-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsync.ts
More file actions
809 lines (735 loc) · 24.1 KB
/
sync.ts
File metadata and controls
809 lines (735 loc) · 24.1 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
import { Octokit } from "@octokit/rest";
import type { GithubMetadata, Task, TaskStore } from "../../types.js";
import type { GitHubRepo } from "./remote.js";
import type { HierarchicalTask } from "./issue-markdown.js";
import {
collectDescendants,
renderHierarchicalIssueBody,
renderTaskMetadataComments,
} from "./issue-markdown.js";
import { parseRootTaskMetadata } from "./issue-parsing.js";
import { isCommitOnRemote } from "../git-utils.js";
import type { SyncResult } from "../sync/registry.js";
/**
* Progress callback for sync operations.
*/
export interface SyncProgress {
/** Current task index (1-based) */
current: number;
/** Total number of tasks */
total: number;
/** Task being processed */
task: Task;
/** Current phase of the sync */
phase: "checking" | "creating" | "updating" | "skipped";
}
/**
* Cached issue data for efficient sync operations.
* Contains all data needed for change detection without re-fetching.
*/
export interface CachedIssue {
number: number;
title: string;
body: string;
state: "open" | "closed";
labels: string[];
}
export interface GitHubSyncServiceOptions {
/** GitHub repository (inferred from git remote) */
repo: GitHubRepo;
/** GitHub personal access token */
token: string;
/** Label prefix for dex tasks (default: "dex") */
labelPrefix?: string;
/** Storage path for task files (default: ".dex") */
storagePath?: string;
}
export interface SyncAllOptions {
/** Callback for progress updates */
onProgress?: (progress: SyncProgress) => void;
/** Whether to skip unchanged tasks (default: true) */
skipUnchanged?: boolean;
}
/**
* GitHub Sync Service
*
* Provides one-way sync of tasks to GitHub Issues.
* File storage remains the source of truth.
*
* Behavior:
* - Top-level tasks (no parent_id) → Create/update GitHub Issue
* - Subtasks → Embedded in parent issue body as markdown
* - Completed tasks → Issue closed only when pushed to remote
* - Pending tasks → Issue open
*
* Sync-on-push: GitHub issues are only closed when the task completion has been
* pushed to origin/HEAD. This prevents issues from being prematurely closed
* before code changes are pushed.
*/
export class GitHubSyncService {
/** Integration ID for the SyncRegistry */
readonly id = "github" as const;
/** Human-readable name for display */
readonly displayName = "GitHub";
private octokit: Octokit;
private owner: string;
private repo: string;
private labelPrefix: string;
private storagePath: string;
constructor(options: GitHubSyncServiceOptions) {
this.octokit = new Octokit({ auth: options.token });
this.owner = options.repo.owner;
this.repo = options.repo.repo;
this.labelPrefix = options.labelPrefix || "dex";
this.storagePath = options.storagePath || ".dex";
}
/**
* Get the repository this service syncs to.
*/
getRepo(): GitHubRepo {
return { owner: this.owner, repo: this.repo };
}
/**
* Get the full repo string (owner/repo format).
*/
getRepoString(): string {
return `${this.owner}/${this.repo}`;
}
/**
* Get the remote ID (issue number) for a task from its metadata.
* Returns null if the task hasn't been synced to GitHub.
* Supports both new format (metadata.github.issueNumber) and legacy format (metadata.github_issue_number).
*/
getRemoteId(task: Task): number | null {
return getGitHubIssueNumber(task);
}
/**
* Get the URL to the GitHub issue for a task.
* Returns null if the task hasn't been synced to GitHub.
* Supports both new format (metadata.github.issueUrl) and legacy format.
*/
getRemoteUrl(task: Task): string | null {
// New format
if (task.metadata?.github?.issueUrl) {
return task.metadata.github.issueUrl;
}
// Legacy format - construct from issue number if we have it
const issueNumber = this.getRemoteId(task);
if (issueNumber) {
return `https://github.com/${this.owner}/${this.repo}/issues/${issueNumber}`;
}
return null;
}
/**
* Close the GitHub issue for a task (e.g., when the task is deleted locally).
* If the task has no associated issue, this is a no-op.
*/
async closeRemote(task: Task): Promise<void> {
const issueNumber = this.getRemoteId(task);
if (!issueNumber) return;
await this.octokit.issues.update({
owner: this.owner,
repo: this.repo,
issue_number: issueNumber,
state: "closed",
});
}
/**
* Sync a single task to GitHub.
* For subtasks, syncs the parent issue instead.
* Returns sync result with github metadata.
*/
async syncTask(task: Task, store: TaskStore): Promise<SyncResult | null> {
// If this is a subtask, sync the parent instead
if (task.parent_id) {
const parent = store.tasks.find((t) => t.id === task.parent_id);
if (parent) {
return this.syncTask(parent, store);
}
return null;
}
return this.syncParentTask(task, store);
}
/**
* Sync all tasks to GitHub.
* Returns array of sync results.
*/
async syncAll(
store: TaskStore,
options: SyncAllOptions = {},
): Promise<SyncResult[]> {
const { onProgress, skipUnchanged = true } = options;
const results: SyncResult[] = [];
const parentTasks = store.tasks.filter((t) => !t.parent_id);
const total = parentTasks.length;
// Fetch all issues once at start for efficient lookups
const issueCache = await this.fetchAllDexIssues();
for (let i = 0; i < parentTasks.length; i++) {
const parent = parentTasks[i];
// Report checking phase
onProgress?.({
current: i + 1,
total,
task: parent,
phase: "checking",
});
const result = await this.syncParentTask(parent, store, {
skipUnchanged,
onProgress,
currentIndex: i + 1,
total,
issueCache,
});
if (result) {
results.push(result);
}
}
return results;
}
/**
* Build a SyncResult for an existing issue.
*/
private buildSyncResult(
taskId: string,
issueNumber: number,
created: boolean,
state: "open" | "closed",
skipped?: boolean,
): SyncResult {
return {
taskId,
metadata: {
issueNumber,
issueUrl: `https://github.com/${this.owner}/${this.repo}/issues/${issueNumber}`,
repo: this.getRepoString(),
state,
},
created,
skipped,
};
}
/**
* Sync a parent task (with all descendants) to GitHub.
* Returns sync result with github metadata.
*/
private async syncParentTask(
parent: Task,
store: TaskStore,
options: {
skipUnchanged?: boolean;
onProgress?: (progress: SyncProgress) => void;
currentIndex?: number;
total?: number;
issueCache?: Map<string, CachedIssue>;
} = {},
): Promise<SyncResult | null> {
const {
skipUnchanged = true,
onProgress,
currentIndex = 1,
total = 1,
issueCache,
} = options;
// Collect ALL descendants, not just immediate children
// Apply push-check: subtasks only show as completed when their commit is pushed
const descendants = collectDescendants(store.tasks, parent.id).map(
(item) => ({
...item,
task: { ...item.task, completed: this.shouldMarkCompleted(item.task) },
}),
);
// Check for existing issue: first metadata, then cache, then API fallback
let issueNumber = getGitHubIssueNumber(parent);
if (!issueNumber && issueCache) {
const cached = issueCache.get(parent.id);
if (cached) {
issueNumber = cached.number;
}
}
if (!issueNumber) {
// Fallback for single-task sync (no cache)
issueNumber = await this.findIssueByTaskId(parent.id);
}
// Determine if task should be marked completed based on remote state
const shouldClose = this.shouldMarkCompleted(parent, store);
// Determine expected state for GitHub issue
const expectedState = shouldClose ? "closed" : "open";
if (issueNumber) {
// Fast path: skip completed tasks that are already synced as closed.
// The stored state check ensures tasks completed locally (but synced while open) are re-synced.
const storedState = parent.metadata?.github?.state;
if (
skipUnchanged &&
expectedState === "closed" &&
storedState === "closed"
) {
onProgress?.({
current: currentIndex,
total,
task: parent,
phase: "skipped",
});
return this.buildSyncResult(
parent.id,
issueNumber,
false,
expectedState,
true,
);
}
// Get cached data for change detection and current state
// IMPORTANT: When state is unknown (no cache), use undefined to preserve remote state
// This prevents reopening closed issues when syncing a single task without cache
const cached = issueCache?.get(parent.id);
let currentState: "open" | "closed" | undefined = cached?.state;
// Check if remote is newer than local (staleness detection)
// If so, pull remote state to local instead of pushing
if (cached?.body) {
const remoteMetadata = parseRootTaskMetadata(cached.body);
if (remoteMetadata?.updated_at && parent.updated_at) {
const remoteUpdated = new Date(remoteMetadata.updated_at).getTime();
const localUpdated = new Date(parent.updated_at).getTime();
if (remoteUpdated > localUpdated) {
// Remote is newer - pull remote state to local
const localUpdates: Partial<Task> = {
updated_at: remoteMetadata.updated_at,
};
// Pull completion state if remote is completed
if (remoteMetadata.completed && !parent.completed) {
localUpdates.completed = true;
localUpdates.completed_at = remoteMetadata.completed_at;
localUpdates.result = remoteMetadata.result;
localUpdates.started_at = remoteMetadata.started_at;
}
// Pull commit metadata if present in remote
// Only set the commit field - don't spread parent.metadata as it may contain
// stale integration metadata that would overwrite fresh state in saveMetadata
if (remoteMetadata.commit?.sha && !parent.metadata?.commit?.sha) {
localUpdates.metadata = {
commit: remoteMetadata.commit,
};
}
onProgress?.({
current: currentIndex,
total,
task: parent,
phase: "skipped", // We're not pushing, we're pulling
});
return {
taskId: parent.id,
metadata: {
issueNumber,
issueUrl: `https://github.com/${this.owner}/${this.repo}/issues/${issueNumber}`,
repo: this.getRepoString(),
state: currentState,
},
created: false,
skipped: true,
localUpdates,
pulledFromRemote: true,
};
}
}
}
// Check if we can skip this update by comparing with GitHub
if (skipUnchanged) {
const expectedBody = this.renderBody(parent, descendants);
const expectedLabels = this.buildLabels(parent, shouldClose);
let hasChanges: boolean;
if (cached) {
hasChanges = this.hasIssueChangedFromCache(
cached,
parent.name,
expectedBody,
expectedLabels,
shouldClose,
);
} else {
// No cache - need to fetch from API to get current state
const changeResult = await this.getIssueChangeResult(
issueNumber,
parent.name,
expectedBody,
expectedLabels,
shouldClose,
);
hasChanges = changeResult.hasChanges;
currentState = changeResult.currentState;
}
if (!hasChanges) {
onProgress?.({
current: currentIndex,
total,
task: parent,
phase: "skipped",
});
return this.buildSyncResult(
parent.id,
issueNumber,
false,
expectedState,
true,
);
}
} else if (!cached) {
// skipUnchanged is false and no cache - still need to fetch current state
// to avoid accidentally reopening closed issues
currentState = await this.fetchIssueState(issueNumber);
}
onProgress?.({
current: currentIndex,
total,
task: parent,
phase: "updating",
});
await this.updateIssue(
parent,
descendants,
issueNumber,
shouldClose,
currentState,
);
return this.buildSyncResult(parent.id, issueNumber, false, expectedState);
} else {
onProgress?.({
current: currentIndex,
total,
task: parent,
phase: "creating",
});
const metadata = await this.createIssue(parent, descendants, shouldClose);
return { taskId: parent.id, metadata, created: true };
}
}
/**
* Compare issue data against expected values.
* Returns true if any field differs (issue needs updating).
*/
private issueNeedsUpdate(
issue: { title: string; body: string; state: string; labels: string[] },
expectedTitle: string,
expectedBody: string,
expectedLabels: string[],
shouldClose: boolean,
): boolean {
if (issue.title !== expectedTitle) return true;
if (issue.body.trim() !== expectedBody.trim()) return true;
const expectedState = shouldClose ? "closed" : "open";
if (issue.state !== expectedState) return true;
const sortedLabels = [...issue.labels].sort();
const sortedExpected = [...expectedLabels].sort();
return JSON.stringify(sortedLabels) !== JSON.stringify(sortedExpected);
}
/**
* Check if an issue has changed and get its current state.
* Returns both change detection result and current state for safe updates.
* When we can't fetch the issue, currentState is undefined to preserve remote state.
*/
private async getIssueChangeResult(
issueNumber: number,
expectedTitle: string,
expectedBody: string,
expectedLabels: string[],
shouldClose: boolean,
): Promise<{
hasChanges: boolean;
currentState: "open" | "closed" | undefined;
}> {
try {
const { data: issue } = await this.octokit.issues.get({
owner: this.owner,
repo: this.repo,
issue_number: issueNumber,
});
const labels = (issue.labels || [])
.map((l) => (typeof l === "string" ? l : l.name || ""))
.filter((l) => l.startsWith(this.labelPrefix));
const hasChanges = this.issueNeedsUpdate(
{
title: issue.title,
body: issue.body || "",
state: issue.state,
labels,
},
expectedTitle,
expectedBody,
expectedLabels,
shouldClose,
);
return {
hasChanges,
currentState: issue.state as "open" | "closed",
};
} catch {
// If we can't fetch the issue, assume it needs updating
// but use undefined state to preserve whatever the remote state is
return { hasChanges: true, currentState: undefined };
}
}
/**
* Fetch only the state of an issue (for when we need to avoid reopening).
* Returns undefined if the issue can't be fetched.
*/
private async fetchIssueState(
issueNumber: number,
): Promise<"open" | "closed" | undefined> {
try {
const { data: issue } = await this.octokit.issues.get({
owner: this.owner,
repo: this.repo,
issue_number: issueNumber,
});
return issue.state as "open" | "closed";
} catch {
return undefined;
}
}
/**
* Check if an issue has changed compared to what we would push using cached data.
* Synchronous version of hasIssueChanged for use with issue cache.
* Returns true if the issue needs updating.
*/
private hasIssueChangedFromCache(
cached: CachedIssue,
expectedTitle: string,
expectedBody: string,
expectedLabels: string[],
shouldClose: boolean,
): boolean {
return this.issueNeedsUpdate(
{
title: cached.title,
body: cached.body,
state: cached.state,
labels: cached.labels,
},
expectedTitle,
expectedBody,
expectedLabels,
shouldClose,
);
}
/**
* Create a new GitHub issue for a task.
* Returns the github metadata for the created issue.
* Issue is created as closed if shouldClose is true.
*/
private async createIssue(
parent: Task,
descendants: HierarchicalTask[],
shouldClose: boolean,
): Promise<GithubMetadata> {
const body = this.renderBody(parent, descendants);
const { data: issue } = await this.octokit.issues.create({
owner: this.owner,
repo: this.repo,
title: parent.name,
body,
labels: this.buildLabels(parent, shouldClose),
});
// Close issue if task completion has been pushed to remote
if (shouldClose) {
await this.octokit.issues.update({
owner: this.owner,
repo: this.repo,
issue_number: issue.number,
state: "closed",
});
}
// Add result as comment if present and closed
if (parent.result && shouldClose) {
await this.octokit.issues.createComment({
owner: this.owner,
repo: this.repo,
issue_number: issue.number,
body: `## Result\n\n${parent.result}`,
});
}
return {
issueNumber: issue.number,
issueUrl: issue.html_url,
repo: this.getRepoString(),
state: shouldClose ? "closed" : "open",
};
}
/**
* Update an existing GitHub issue.
*
* @param currentState - The current state of the issue on GitHub.
* undefined means we don't know the current state.
* Used to prevent reopening closed issues.
*/
private async updateIssue(
parent: Task,
descendants: HierarchicalTask[],
issueNumber: number,
shouldClose: boolean,
currentState: "open" | "closed" | undefined,
): Promise<void> {
const body = this.renderBody(parent, descendants);
// Determine the state to set:
// - If shouldClose is true, always close (even if already closed)
// - If shouldClose is false and currently open, keep open
// - If shouldClose is false and currently closed, DON'T reopen
// - If shouldClose is false and state is unknown (undefined), don't set state
// (this preserves whatever the remote state is, preventing accidental reopening)
let state: "open" | "closed" | undefined;
if (shouldClose) {
state = "closed";
} else if (currentState === "open") {
state = "open";
}
// If currentState is "closed" or undefined and shouldClose is false, don't set state
// (keeps the issue in its current state, doesn't reopen it)
await this.octokit.issues.update({
owner: this.owner,
repo: this.repo,
issue_number: issueNumber,
title: parent.name,
body,
labels: this.buildLabels(parent, shouldClose),
...(state !== undefined && { state }),
});
}
/**
* Render the issue body with hierarchical task tree.
* Includes root task metadata encoded in HTML comments for round-trip support.
*/
private renderBody(task: Task, descendants: HierarchicalTask[]): string {
const rootMeta = renderTaskMetadataComments(task, "task");
const body = renderHierarchicalIssueBody(task.description, descendants);
return `${rootMeta.join("\n")}\n${body}`;
}
/**
* Build labels for a task.
*/
private buildLabels(task: Task, shouldClose: boolean): string[] {
return [
this.labelPrefix,
`${this.labelPrefix}:priority-${task.priority}`,
`${this.labelPrefix}:${shouldClose ? "completed" : "pending"}`,
];
}
/**
* Determine if a task should be marked as completed in GitHub.
*
* - If task has a commit SHA: only mark completed if that commit is pushed to origin
* - If task has no commit SHA: don't mark completed (can't verify work is merged)
*
* This ensures GitHub issues are only closed when the actual work has been pushed.
* Tasks completed with --no-commit will remain open in GitHub until manually closed.
*/
private shouldMarkCompleted(task: Task, store?: TaskStore): boolean {
// Task must be locally completed first
if (!task.completed) {
return false;
}
// If task has a commit SHA, verify it's been pushed
const commitSha = task.metadata?.commit?.sha;
if (commitSha) {
return isCommitOnRemote(commitSha);
}
// For parent tasks (with store context): check if all descendants have verified commits
if (store) {
const descendants = collectDescendants(store.tasks, task.id);
if (descendants.length > 0) {
// Parent is "completed" only when ALL descendants have verified commits on remote
return descendants.every((d) => this.shouldMarkCompleted(d.task));
}
}
// Leaf task with no commit SHA - can't verify, don't close the issue
return false;
}
/**
* Look up a task by its local ID in GitHub issues.
* Used to find existing issues for tasks that don't have metadata yet.
* Uses pagination to handle repos with >100 dex issues.
*/
async findIssueByTaskId(taskId: string): Promise<number | null> {
try {
const issues = await this.octokit.paginate(
this.octokit.issues.listForRepo,
{
owner: this.owner,
repo: this.repo,
labels: this.labelPrefix,
state: "all",
per_page: 100,
},
);
for (const issue of issues) {
if (issue.pull_request) continue;
if (this.extractTaskIdFromBody(issue.body || "") === taskId) {
return issue.number;
}
}
return null;
} catch {
return null;
}
}
/**
* Fetch all dex-labeled issues with pagination support.
* Returns a Map keyed by task ID containing all data needed for change detection.
*/
async fetchAllDexIssues(): Promise<Map<string, CachedIssue>> {
const result = new Map<string, CachedIssue>();
const issues = await this.octokit.paginate(
this.octokit.issues.listForRepo,
{
owner: this.owner,
repo: this.repo,
labels: this.labelPrefix,
state: "all",
per_page: 100,
},
);
for (const issue of issues) {
if (issue.pull_request) continue;
const taskId = this.extractTaskIdFromBody(issue.body || "");
if (taskId) {
result.set(taskId, {
number: issue.number,
title: issue.title,
body: issue.body || "",
state: issue.state as "open" | "closed",
labels: (issue.labels || [])
.map((l) => (typeof l === "string" ? l : l.name || ""))
.filter((l) => l.startsWith(this.labelPrefix)),
});
}
}
return result;
}
/**
* Extract task ID from issue body.
* Supports both new format (<!-- dex:task:id:{taskId} -->) and legacy format (<!-- dex:task:{taskId} -->).
*/
private extractTaskIdFromBody(body: string): string | null {
// Check new format: <!-- dex:task:id:{taskId} -->
const newMatch = body.match(/<!-- dex:task:id:([a-z0-9]+) -->/);
if (newMatch) return newMatch[1];
// Check legacy format: <!-- dex:task:{taskId} -->
const legacyMatch = body.match(/<!-- dex:task:([a-z0-9]+) -->/);
if (legacyMatch) return legacyMatch[1];
return null;
}
}
/**
* Extract GitHub issue number from task metadata.
* Returns null if not synced yet.
* Supports both new format (metadata.github.issueNumber) and legacy format (metadata.github_issue_number).
*/
export function getGitHubIssueNumber(task: Task): number | null {
// New format
if (task.metadata?.github?.issueNumber) {
return task.metadata.github.issueNumber;
}
// Legacy format (from older imports)
const legacyNumber = (task.metadata as Record<string, unknown> | undefined)
?.github_issue_number;
if (typeof legacyNumber === "number") {
return legacyNumber;
}
return null;
}