-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsync.js
More file actions
executable file
·381 lines (320 loc) · 12.4 KB
/
sync.js
File metadata and controls
executable file
·381 lines (320 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
#!/usr/bin/env node
/**
* Claude-TaskWarrior Sync Engine
* Advanced synchronization between Claude's TodoWrite tool and TaskWarrior
*
* Features:
* - Bidirectional sync
* - Conflict resolution
* - Data validation
* - Backup integration
* - Multi-project support
*/
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
class ClaudeTaskWarriorSync {
constructor() {
this.defaultProject = 'claude-session';
this.backupDir = process.env.HOME + '/.claude-taskwarrior-backups';
this.configFile = process.env.HOME + '/.claude-taskwarrior.conf';
this.ensureBackupDir();
this.loadConfig();
}
ensureBackupDir() {
if (!fs.existsSync(this.backupDir)) {
fs.mkdirSync(this.backupDir, { recursive: true });
}
}
loadConfig() {
if (fs.existsSync(this.configFile)) {
const config = fs.readFileSync(this.configFile, 'utf8');
const lines = config.split('\n');
for (const line of lines) {
if (line.startsWith('PROJECT=')) {
this.defaultProject = line.split('=')[1];
}
}
}
}
/**
* Import Claude todos to TaskWarrior
*/
importTodos(projectName, todosJson) {
const project = projectName || this.defaultProject;
try {
const todos = JSON.parse(todosJson);
console.log(`🔄 Importing ${todos.length} todos to TaskWarrior project: ${project}`);
// Validate todos structure
this.validateTodos(todos);
// Create backup before import
this.createBackup(project, 'pre-import');
let importedCount = 0;
let errorCount = 0;
for (const todo of todos) {
try {
const taskId = this.addTaskToWarrior(todo, project);
if (taskId && todo.status === 'completed') {
this.markTaskCompleted(taskId);
} else if (taskId && todo.status === 'in_progress') {
this.markTaskStarted(taskId);
}
importedCount++;
console.log(` ✓ ${todo.content}`);
} catch (error) {
errorCount++;
console.error(` ✗ Failed: ${todo.content} (${error.message})`);
}
}
console.log(`\n📊 Import Summary:`);
console.log(` Imported: ${importedCount}`);
console.log(` Errors: ${errorCount}`);
console.log(` Project: ${project}`);
return { imported: importedCount, errors: errorCount };
} catch (error) {
console.error(`❌ Import failed: ${error.message}`);
throw error;
}
}
/**
* Export TaskWarrior tasks to Claude format
*/
exportTodos(projectName) {
const project = projectName || this.defaultProject;
try {
// Check if project has tasks
const taskCount = this.getTaskCount(project);
if (taskCount === 0) {
return JSON.stringify([], null, 2);
}
// Export tasks from TaskWarrior
const result = execSync(`task project:${project} export`, { encoding: 'utf8' });
const tasks = JSON.parse(result);
// Convert to Claude format
const todos = tasks.map(task => this.convertTaskToTodo(task));
// Sort by priority and status
todos.sort((a, b) => {
const priorityOrder = { 'high': 0, 'medium': 1, 'low': 2 };
const statusOrder = { 'in_progress': 0, 'pending': 1, 'completed': 2 };
// First by status, then by priority
const statusDiff = statusOrder[a.status] - statusOrder[b.status];
if (statusDiff !== 0) return statusDiff;
return priorityOrder[a.priority] - priorityOrder[b.priority];
});
console.error(`📤 Exported ${todos.length} tasks from project: ${project}`);
return JSON.stringify(todos, null, 2);
} catch (error) {
console.error(`❌ Export failed: ${error.message}`);
return JSON.stringify([], null, 2);
}
}
/**
* Add a single task to TaskWarrior
*/
addTaskToWarrior(todo, project) {
const priority = this.mapPriority(todo.priority);
const description = todo.content.replace(/"/g, '\\"');
// Build task command
let cmd = `task add project:${project} priority:${priority}`;
// Add tags if any
if (todo.tags && Array.isArray(todo.tags)) {
cmd += ` +${todo.tags.join(' +')}`;
}
// Add due date if specified
if (todo.due) {
cmd += ` due:${todo.due}`;
}
cmd += ` "${description}"`;
try {
const result = execSync(cmd, { encoding: 'utf8' });
const match = result.match(/Created task (\d+)/);
return match ? match[1] : null;
} catch (error) {
throw new Error(`TaskWarrior add failed: ${error.message}`);
}
}
/**
* Mark task as completed
*/
markTaskCompleted(taskId) {
try {
execSync(`echo "yes" | task ${taskId} done`, { encoding: 'utf8' });
} catch (error) {
console.warn(`Could not mark task ${taskId} as completed: ${error.message}`);
}
}
/**
* Mark task as started
*/
markTaskStarted(taskId) {
try {
execSync(`task ${taskId} start`, { encoding: 'utf8' });
} catch (error) {
console.warn(`Could not start task ${taskId}: ${error.message}`);
}
}
/**
* Convert TaskWarrior task to Claude todo format
*/
convertTaskToTodo(task) {
return {
id: `tw-${task.uuid.slice(0, 8)}`,
content: task.description,
status: this.mapTaskStatus(task.status, task.start),
priority: this.unmapPriority(task.priority),
created: task.entry ? new Date(task.entry).toISOString() : undefined,
modified: task.modified ? new Date(task.modified).toISOString() : undefined,
due: task.due ? new Date(task.due).toISOString().split('T')[0] : undefined,
tags: task.tags || undefined
};
}
/**
* Map Claude priority to TaskWarrior priority
*/
mapPriority(claudePriority) {
const mapping = {
'high': 'H',
'medium': 'M',
'low': 'L'
};
return mapping[claudePriority] || 'M';
}
/**
* Map TaskWarrior priority to Claude priority
*/
unmapPriority(taskPriority) {
const mapping = {
'H': 'high',
'M': 'medium',
'L': 'low'
};
return mapping[taskPriority] || 'medium';
}
/**
* Map TaskWarrior status to Claude status
*/
mapTaskStatus(taskStatus, startTime) {
if (taskStatus === 'completed') return 'completed';
if (taskStatus === 'pending' && startTime) return 'in_progress';
return 'pending';
}
/**
* Get task count for a project
*/
getTaskCount(project) {
try {
const result = execSync(`task project:${project} count`, { encoding: 'utf8' });
return parseInt(result.trim()) || 0;
} catch (error) {
return 0;
}
}
/**
* Create backup of current tasks
*/
createBackup(project, suffix = '') {
try {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const filename = `backup-${project}-${timestamp}${suffix ? '-' + suffix : ''}.json`;
const backupPath = path.join(this.backupDir, filename);
const result = execSync(`task project:${project} export`, { encoding: 'utf8' });
fs.writeFileSync(backupPath, result);
console.log(`💾 Backup created: ${filename}`);
return backupPath;
} catch (error) {
console.warn(`⚠️ Backup failed: ${error.message}`);
return null;
}
}
/**
* Validate todos structure
*/
validateTodos(todos) {
if (!Array.isArray(todos)) {
throw new Error('Todos must be an array');
}
for (const [index, todo] of todos.entries()) {
if (!todo.content || typeof todo.content !== 'string') {
throw new Error(`Todo ${index}: content is required and must be a string`);
}
if (!todo.status || !['pending', 'in_progress', 'completed'].includes(todo.status)) {
throw new Error(`Todo ${index}: status must be pending, in_progress, or completed`);
}
if (!todo.priority || !['high', 'medium', 'low'].includes(todo.priority)) {
throw new Error(`Todo ${index}: priority must be high, medium, or low`);
}
}
}
/**
* Get summary statistics
*/
getSummary(projectName) {
const project = projectName || this.defaultProject;
try {
const pending = this.getTaskCount(project + ' status:pending');
const completed = this.getTaskCount(project + ' status:completed');
const inProgress = execSync(`task project:${project} +ACTIVE count`, { encoding: 'utf8' }).trim();
return {
project,
total: pending + completed + parseInt(inProgress || 0),
pending,
completed,
in_progress: parseInt(inProgress || 0)
};
} catch (error) {
return {
project,
total: 0,
pending: 0,
completed: 0,
in_progress: 0,
error: error.message
};
}
}
}
// CLI interface
if (require.main === module) {
const sync = new ClaudeTaskWarriorSync();
const command = process.argv[2];
const projectName = process.argv[3];
const data = process.argv[4] || process.argv[3]; // Support both project+data and just data
try {
switch (command) {
case 'import':
if (!data || (!projectName && !data.startsWith('['))) {
console.error('Usage: node sync.js import [project] \'[{"id":"...","content":"..."}]\'');
process.exit(1);
}
const importProject = projectName && !projectName.startsWith('[') ? projectName : null;
const importData = importProject ? data : projectName;
sync.importTodos(importProject, importData);
break;
case 'export':
console.log(sync.exportTodos(projectName));
break;
case 'summary':
const summary = sync.getSummary(projectName);
console.log(JSON.stringify(summary, null, 2));
break;
case 'backup':
sync.createBackup(projectName || sync.defaultProject, 'manual');
break;
default:
console.log('Claude-TaskWarrior Sync Engine');
console.log('Usage: node sync.js [import|export|summary|backup] [project] [data]');
console.log('');
console.log('Commands:');
console.log(' import [project] \'[json]\' Import Claude todos to TaskWarrior');
console.log(' export [project] Export TaskWarrior tasks to Claude format');
console.log(' summary [project] Show project statistics');
console.log(' backup [project] Create manual backup');
process.exit(1);
}
} catch (error) {
console.error(`❌ Error: ${error.message}`);
process.exit(1);
}
}
module.exports = ClaudeTaskWarriorSync;