dsh-taskbridge 1.7.1 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -21
  3. package/README.md +733 -877
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +32 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +181 -631
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +122 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +2 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/conversation-placement.md +7 -6
  17. package/docs/plugin-market.md +30 -30
  18. package/docs/redaction-contract.md +170 -170
  19. package/docs/releases/1.7.0.zh.md +11 -11
  20. package/docs/releases/1.8.0.zh.md +16 -0
  21. package/docs/releases/1.8.1.zh.md +24 -0
  22. package/docs/runtime-compatibility.md +1 -1
  23. package/docs/taskbridge-upgrade.md +28 -28
  24. package/docs/taskdispatch-upgrade.md +25 -25
  25. package/docs/workspace-contract.md +538 -538
  26. package/docs/workspace-grouping.md +126 -126
  27. package/icon.svg +1 -1
  28. package/lib/client.d.ts +804 -699
  29. package/lib/client.js +7 -7
  30. package/locale/en.json +1 -1
  31. package/locale/zh.json +1 -1
  32. package/package.json +150 -144
  33. package/src/antigravity/installer.js +1068 -0
  34. package/src/antigravity/seam.js +142 -0
  35. package/src/auth/fence.js +361 -361
  36. package/src/auth/grants.js +789 -789
  37. package/src/client/api.js +266 -3
  38. package/src/client/index.jsx +224 -11
  39. package/src/client/sidebar.jsx +862 -862
  40. package/src/client/styles.js +624 -624
  41. package/src/client/task-cleanup.js +429 -304
  42. package/src/client/task-records-table.jsx +217 -217
  43. package/src/client/task-view.js +307 -307
  44. package/src/client/workspace-groups.js +482 -482
  45. package/src/client/workspaces-browser.jsx +770 -770
  46. package/src/codex/agent-ownership.js +270 -270
  47. package/src/codex/installer.js +6 -0
  48. package/src/codex/toml.js +784 -784
  49. package/src/config/defaults.js +11 -15
  50. package/src/config/redact.js +245 -245
  51. package/src/config/store.js +186 -186
  52. package/src/credentials/seam.js +202 -202
  53. package/src/http/respond.js +6 -5
  54. package/src/http/user-plane.js +83 -1
  55. package/src/index.js +25 -0
  56. package/src/jobs/diagnostics.js +15 -15
  57. package/src/jobs/engine.js +1 -0
  58. package/src/jobs/history.js +1 -1
  59. package/src/jobs/plan-store.js +1103 -1020
  60. package/src/jobs/record-cleanup.js +452 -7
  61. package/src/jobs/review-note.js +63 -63
  62. package/src/jobs/task-descriptions.js +82 -82
  63. package/src/jobs/task-display.js +73 -73
  64. package/src/jobs/task-tree.js +786 -786
  65. package/src/jobs/title.js +134 -134
  66. package/src/mcp/continuation.js +317 -317
  67. package/src/mcp/server.js +34 -27
  68. package/src/mcp/wait.js +34 -15
  69. package/src/model/connectivity.js +371 -371
  70. package/src/model/discovery.js +582 -582
  71. package/src/model/native-catalog.js +68 -68
  72. package/src/model/openai-adapter.js +671 -671
  73. package/src/model/probe.js +264 -264
  74. package/src/model/providers.js +756 -756
  75. package/src/model/routing.js +321 -321
  76. package/src/runtime/agent-runner.js +1 -0
  77. package/src/runtime/permissions.js +1619 -1619
  78. package/src/runtime/question-call.js +162 -162
  79. package/src/runtime/questions.js +909 -909
  80. package/src/runtime/session-placement.js +36 -1
  81. package/src/runtime/worker-prompt.js +61 -55
  82. package/src/workspace/audit.js +775 -775
  83. package/src/workspace/preflight.js +424 -424
  84. package/src/workspace/worktrees.js +833 -679
@@ -1,786 +1,786 @@
1
- // Deterministic, runtime-agnostic task tree and continuation-chain projection.
2
- //
3
- // Zero Node-only imports so both the server planes and the browser bundle can use
4
- // the exact same relational rules:
5
- // 1. `continueFromTaskId` links rectification rounds of ONE work item only;
6
- // 2. `planNodeId` binds an execution chain to an unexecuted/planned node;
7
- // 3. `parentNodeId` builds the multi-level goal -> subtask -> step hierarchy;
8
- // 4. Titles, timestamps, models and prompts are NEVER used to infer relationships;
9
- // 5. Missing parents/plans become explicit orphans (never dropped or title-merged),
10
- // and corrupted parent/continuation cycles are broken deterministically.
11
-
12
- const PATH_MASK_SEGMENT = 'masks-user-profile-segment';
13
- const SHA256_DIGEST_RE = /^sha256:[0-9a-f]{64}$/u;
14
- export const UNVERIFIED_PROJECT_KEY = 'unverified';
15
-
16
- export function isMaskedPathString(value) {
17
- if (typeof value !== 'string') return false;
18
- return value.split(/[\\/]+/u).some((part) => part.trim() === PATH_MASK_SEGMENT);
19
- }
20
-
21
- export function normalizePathComparisonKey(value, options = {}) {
22
- if (typeof value !== 'string') return null;
23
- const trimmed = value.trim();
24
- if (trimmed === '' || isMaskedPathString(trimmed)) return null;
25
- const stripped = trimmed.length > 1 ? trimmed.replace(/[\\/]+$/u, '') : trimmed;
26
- const caseInsensitive = options.caseInsensitive ?? /^[A-Za-z]:[\\/]/u.test(stripped);
27
- return caseInsensitive ? stripped.toLowerCase() : stripped;
28
- }
29
-
30
- function cleanRef(value, selfId = null) {
31
- if (typeof value !== 'string') return null;
32
- const trimmed = value.trim();
33
- if (trimmed === '' || trimmed === selfId) return null;
34
- return trimmed;
35
- }
36
-
37
- function shortTaskLabel(id) {
38
- if (typeof id !== 'string' || id === '') return 'unknown';
39
- const stripped = id.startsWith('task-') ? id.slice(5) : id;
40
- return stripped.slice(0, 8);
41
- }
42
-
43
- export function explicitContinuationOf(task) {
44
- if (!isObject(task)) return null;
45
- const selfId = typeof task.taskId === 'string' ? task.taskId.trim() : null;
46
- const direct = cleanRef(task.continueFromTaskId, selfId);
47
- if (direct !== null) return direct;
48
- const placed = cleanRef(task.execution?.conversation?.continuedFromTaskId, selfId);
49
- return placed;
50
- }
51
-
52
- /**
53
- * Group flat task views into continuation chains using explicit `continueFromTaskId` only.
54
- * @param {object[]} tasks - live + archived task views.
55
- * @returns {object[]} ordered chains.
56
- */
57
- export function groupContinuationChains(tasks = []) {
58
- const byId = new Map();
59
- for (const raw of Array.isArray(tasks) ? tasks : []) {
60
- if (!isObject(raw) || typeof raw.taskId !== 'string' || raw.taskId.trim() === '') continue;
61
- const taskId = raw.taskId.trim();
62
- if (!byId.has(taskId)) byId.set(taskId, raw);
63
- }
64
-
65
- // Build explicit parent link `childId -> parentTaskId` with self-loop guard.
66
- const parentOf = new Map();
67
- const brokenByTask = new Map();
68
- for (const [taskId, task] of byId.entries()) {
69
- const rawCont = typeof task.continueFromTaskId === 'string' ? task.continueFromTaskId.trim() : '';
70
- if (rawCont !== '' && rawCont === taskId) {
71
- brokenByTask.set(taskId, { cycleTaskId: taskId, reason: 'cycle-broken' });
72
- continue;
73
- }
74
- const target = explicitContinuationOf(task);
75
- if (target === null) continue;
76
- if (!byId.has(target)) {
77
- brokenByTask.set(taskId, { missingTaskId: target, reason: 'missing-task' });
78
- continue;
79
- }
80
- parentOf.set(taskId, target);
81
- }
82
-
83
- // Detect and break cycles in `parentOf` deterministically (earliest createdAt/taskId becomes root).
84
- const state = new Map(); // 0/undef = unvisited, 1 = visiting, 2 = done
85
- for (const startId of byId.keys()) {
86
- if ((state.get(startId) ?? 0) !== 0) continue;
87
- const trail = [];
88
- const indexInTrail = new Map();
89
- let cur = startId;
90
- while (cur !== null && cur !== undefined) {
91
- const st = state.get(cur) ?? 0;
92
- if (st === 2) break;
93
- if (st === 1) {
94
- const cycleStart = indexInTrail.get(cur) ?? 0;
95
- const cycleIds = trail.slice(cycleStart);
96
- cycleIds.sort((a, b) => compareTasksChronologically(byId.get(a), byId.get(b)));
97
- const chosenRoot = cycleIds[0];
98
- const brokenTarget = parentOf.get(chosenRoot);
99
- parentOf.delete(chosenRoot);
100
- brokenByTask.set(chosenRoot, { cycleTaskId: brokenTarget, reason: 'cycle-broken' });
101
- break;
102
- }
103
- state.set(cur, 1);
104
- indexInTrail.set(cur, trail.length);
105
- trail.push(cur);
106
- cur = parentOf.get(cur) ?? null;
107
- }
108
- for (const id of trail) state.set(id, 2);
109
- }
110
-
111
- // Group children under each chain's root task.
112
- const childrenOf = new Map();
113
- for (const [childId, pId] of parentOf.entries()) {
114
- if (!childrenOf.has(pId)) childrenOf.set(pId, []);
115
- childrenOf.get(pId).push(childId);
116
- }
117
- for (const list of childrenOf.values()) {
118
- list.sort((a, b) => compareTasksChronologically(byId.get(a), byId.get(b)));
119
- }
120
-
121
- const roots = [];
122
- for (const taskId of byId.keys()) {
123
- if (!parentOf.has(taskId)) roots.push(taskId);
124
- }
125
- roots.sort((a, b) => compareTasksChronologically(byId.get(a), byId.get(b)));
126
-
127
- const chains = [];
128
- for (const rootId of roots) {
129
- const rounds = [];
130
- let hasParallelContinuations = false;
131
- const collect = (id) => {
132
- const task = byId.get(id);
133
- rounds.push(task);
134
- const kids = childrenOf.get(id) ?? [];
135
- if (kids.length > 1) hasParallelContinuations = true;
136
- for (const kid of kids) collect(kid);
137
- };
138
- collect(rootId);
139
-
140
- const rootTask = rounds[0];
141
- const latestTask = rounds[rounds.length - 1];
142
-
143
- // Hierarchy identity comes from explicit fields only, never guessed.
144
- let planNodeId = null;
145
- let parentNodeId = null;
146
- let hierarchyMismatch = false;
147
- for (const r of rounds) {
148
- const rPlan = cleanRef(r.planNodeId, r.taskId);
149
- const rParent = cleanRef(r.parentNodeId, r.taskId);
150
- if (rPlan !== null) {
151
- if (planNodeId === null) planNodeId = rPlan;
152
- else if (planNodeId !== rPlan) hierarchyMismatch = true;
153
- }
154
- if (rParent !== null) {
155
- if (parentNodeId === null) parentNodeId = rParent;
156
- else if (parentNodeId !== rParent) hierarchyMismatch = true;
157
- }
158
- }
159
-
160
- // Keep the original task name when a continuation uses a different round title.
161
- const recordedTitle = firstNonEmptyTitle(rounds);
162
- const titleMissing = recordedTitle === null;
163
- const displayTitle = titleMissing
164
- ? `未记录标题 (${shortTaskLabel(rootId)})`
165
- : recordedTitle;
166
-
167
- const goalDescription = firstNonEmptyDescription(rounds, 'goalDescription');
168
- const latestAcceptedOrReviewed = [...rounds].reverse().find(
169
- (r) => acceptanceVerdictOf(r.hostAcceptance) !== null,
170
- ) ?? null;
171
- const completionSummary = typeof latestAcceptedOrReviewed?.hostAcceptance?.completionSummary === 'string'
172
- && latestAcceptedOrReviewed.hostAcceptance.completionSummary.trim() !== ''
173
- ? latestAcceptedOrReviewed.hostAcceptance.completionSummary.trim()
174
- : null;
175
-
176
- chains.push({
177
- chainId: rootId,
178
- rootTaskId: rootId,
179
- latestTaskId: latestTask.taskId,
180
- taskIds: rounds.map((r) => r.taskId),
181
- roundCount: rounds.length,
182
- rounds,
183
- title: recordedTitle,
184
- titleMissing,
185
- displayTitle,
186
- goalDescription,
187
- completionSummary,
188
- planNodeId,
189
- parentNodeId,
190
- hierarchyRecorded: planNodeId !== null || parentNodeId !== null,
191
- hierarchyMismatch,
192
- hasParallelContinuations,
193
- brokenContinuation: brokenByTask.get(rootId) ?? null,
194
- nodeStatus: deriveChainStatus(rounds, new Set(rounds.map((round) => parentOf.get(round.taskId)))),
195
- createdAt: finiteNumber(rootTask.createdAt) ?? 0,
196
- updatedAt: maxTimestampOfRounds(rounds),
197
- sourcePath: rootTask.sourcePath ??
198
- (rootTask.isolation !== 'worktree' && (rootTask.isolation === 'shared' || rootTask.executionWorkspacePath == null)
199
- ? rootTask.workspacePath : null) ?? null,
200
- sourcePathDigest: isDigest(rootTask.sourcePathDigest) ? rootTask.sourcePathDigest : null,
201
- });
202
- }
203
-
204
- return chains;
205
- }
206
-
207
- /**
208
- * Derive conservative status for a task continuation chain (foundation for G04).
209
- * Execution finishing (`awaiting-host-review`) is NEVER reported as `accepted`.
210
- */
211
- export function deriveChainStatus(rounds, continuedTaskIds = new Set(rounds.map(explicitContinuationOf))) {
212
- if (rounds.length === 0) return 'planned';
213
- const statuses = new Set();
214
- for (const round of rounds) {
215
- if (round.state === 'running' && (round.phase === 'awaiting-permission' || round.permission?.waiting === true)) {
216
- return 'awaiting-permission';
217
- }
218
- if (round.state === 'running' && (round.phase === 'awaiting-question' || round.question?.waiting === true)) {
219
- statuses.add('awaiting-question');
220
- } else if (round.state === 'pending' || round.state === 'running') {
221
- statuses.add('running');
222
- } else if (round.state === 'awaiting-host-review' && !isSavedAcceptance(round)) {
223
- statuses.add('awaiting-host-review');
224
- } else if (!continuedTaskIds.has(round.taskId)) {
225
- const terminal = ['failed', 'cancelled', 'interrupted'].includes(round.state) ? round.state : 'unknown';
226
- statuses.add(round.state === 'awaiting-host-review' ? acceptanceVerdictOf(round.hostAcceptance) : terminal);
227
- }
228
- }
229
- const attention = ['awaiting-question', 'running', 'failed', 'changes-requested', 'awaiting-host-review', 'interrupted', 'cancelled', 'unknown'];
230
- return attention.find((status) => statuses.has(status)) ?? (statuses.has('accepted') ? 'accepted' : 'unknown');
231
- }
232
-
233
- function acceptanceVerdictOf(acceptance) {
234
- if (!isObject(acceptance)) return null;
235
- const raw = acceptance.state ?? acceptance.decision ?? null;
236
- if (raw === 'accepted' || raw === 'changes-requested') return raw;
237
- if (typeof acceptance.accepted === 'boolean') {
238
- return acceptance.accepted ? 'accepted' : 'changes-requested';
239
- }
240
- return null;
241
- }
242
-
243
- function isSavedAcceptance(task) {
244
- if (acceptanceVerdictOf(task?.hostAcceptance) === null) return false;
245
- if (task.reviewPersistence && typeof task.reviewPersistence.state === 'string') {
246
- if (task.reviewPersistence.state !== 'saved' && task.reviewPersistence.state !== 'none') {
247
- return false;
248
- }
249
- }
250
- return true;
251
- }
252
-
253
- /**
254
- * Build the complete multi-level goal/subtask tree and project index.
255
- * @param {{ planNodes?: object[], tasks?: object[] }} input - loaded plan nodes and tasks.
256
- * @returns {object} structured tree, flat index, orphans, projects and counts.
257
- */
258
- export function buildTaskTree(input = {}) {
259
- const rawPlans = Array.isArray(input.planNodes) ? input.planNodes : [];
260
- const rawTasks = Array.isArray(input.tasks) ? input.tasks : [];
261
-
262
- const chains = groupContinuationChains(rawTasks);
263
- const projectResolver = createProjectResolver(rawPlans, chains);
264
-
265
- const planWrappers = new Map();
266
- const orderedPlans = [...rawPlans]
267
- .filter((p) => isObject(p) && typeof p.nodeId === 'string' && p.nodeId.trim() !== '')
268
- .sort(comparePlanRecords);
269
-
270
- for (const plan of orderedPlans) {
271
- const nodeId = plan.nodeId.trim();
272
- if (planWrappers.has(nodeId)) continue;
273
- const parentNodeId = typeof plan.parentNodeId === 'string' && plan.parentNodeId.trim() !== ''
274
- ? plan.parentNodeId.trim()
275
- : null;
276
- const project = projectResolver.resolve(plan.sourcePath ?? null, plan.sourcePathDigest ?? null);
277
- const completionSummary = typeof plan.hostAcceptance?.completionSummary === 'string'
278
- && plan.hostAcceptance.completionSummary.trim() !== ''
279
- ? plan.hostAcceptance.completionSummary.trim()
280
- : null;
281
- planWrappers.set(nodeId, {
282
- kind: 'plan',
283
- nodeId,
284
- parentNodeId,
285
- title: plan.title,
286
- displayTitle: plan.title,
287
- titleMissing: false,
288
- goalDescription: typeof plan.goalDescription === 'string' ? plan.goalDescription : null,
289
- completionSummary,
290
- hostAcceptance: plan.hostAcceptance ?? null,
291
- reviewHistory: Array.isArray(plan.reviewHistory) ? plan.reviewHistory : [],
292
- sequence: Number.isSafeInteger(plan.sequence) ? plan.sequence : 0,
293
- createdAt: finiteNumber(plan.createdAt) ?? 0,
294
- updatedAt: finiteNumber(plan.updatedAt) ?? finiteNumber(plan.createdAt) ?? 0,
295
- sourcePath: plan.sourcePath ?? null,
296
- sourcePathDigest: isDigest(plan.sourcePathDigest) ? plan.sourcePathDigest : null,
297
- projectKey: project.projectKey,
298
- executions: [],
299
- children: [],
300
- orphan: null,
301
- executed: false,
302
- nodeStatus: 'planned',
303
- depth: 1,
304
- });
305
- }
306
-
307
- // Lookup table for valid parent targets: plan nodeId -> wrapper, taskId -> wrapper.
308
- const parentLookup = new Map();
309
- for (const [nodeId, wrapper] of planWrappers.entries()) {
310
- parentLookup.set(nodeId, wrapper);
311
- }
312
-
313
- const taskNodes = [];
314
- for (const chain of chains) {
315
- if (chain.planNodeId !== null) {
316
- const targetPlan = planWrappers.get(chain.planNodeId) ?? null;
317
- if (targetPlan !== null) {
318
- targetPlan.executions.push(chain);
319
- targetPlan.executed = true;
320
- if (chain.updatedAt > targetPlan.updatedAt) targetPlan.updatedAt = chain.updatedAt;
321
- // Any child task naming a taskId in this chain resolves to this plan node in the tree.
322
- for (const tId of chain.taskIds) {
323
- if (!parentLookup.has(tId)) parentLookup.set(tId, targetPlan);
324
- }
325
- continue;
326
- }
327
- // Missing planNodeId -> preserve as root-level orphan task node, never drop or guess!
328
- const project = projectResolver.resolve(chain.sourcePath, chain.sourcePathDigest);
329
- const orphanNode = makeTaskTreeNode(chain, project.projectKey, {
330
- isOrphan: true,
331
- kind: 'missing-plan-node',
332
- missingNodeId: chain.planNodeId,
333
- });
334
- taskNodes.push(orphanNode);
335
- for (const tId of chain.taskIds) {
336
- if (!parentLookup.has(tId)) parentLookup.set(tId, orphanNode);
337
- }
338
- continue;
339
- }
340
-
341
- const project = projectResolver.resolve(chain.sourcePath, chain.sourcePathDigest);
342
- const taskNode = makeTaskTreeNode(chain, project.projectKey, null);
343
- taskNodes.push(taskNode);
344
- for (const tId of chain.taskIds) {
345
- if (!parentLookup.has(tId)) parentLookup.set(tId, taskNode);
346
- }
347
- }
348
-
349
- // Combine all structural nodes (plan nodes + standalone/child task nodes).
350
- const allNodes = [...planWrappers.values(), ...taskNodes];
351
- const nodeByPrimaryId = new Map(allNodes.map((n) => [n.nodeId, n]));
352
-
353
- // Resolve each node's parent wrapper, detecting self-loops and missing parents.
354
- const resolvedParent = new Map();
355
- for (const node of allNodes) {
356
- if (node.orphan !== null) {
357
- // Already marked orphan (e.g. missing-plan-node) -> stays at root.
358
- resolvedParent.set(node.nodeId, null);
359
- continue;
360
- }
361
- const rawParentId = node.parentNodeId;
362
- if (rawParentId === null) {
363
- resolvedParent.set(node.nodeId, null);
364
- continue;
365
- }
366
- const target = parentLookup.get(rawParentId) ?? null;
367
- if (target === null) {
368
- node.orphan = {
369
- isOrphan: true,
370
- kind: 'missing-parent',
371
- missingParentId: rawParentId,
372
- };
373
- resolvedParent.set(node.nodeId, null);
374
- continue;
375
- }
376
- if (target.nodeId === node.nodeId) {
377
- node.orphan = {
378
- isOrphan: true,
379
- kind: 'cycle-broken',
380
- cycleParentId: rawParentId,
381
- };
382
- resolvedParent.set(node.nodeId, null);
383
- continue;
384
- }
385
- resolvedParent.set(node.nodeId, target.nodeId);
386
- }
387
-
388
- // Detect and break multi-node parent cycles deterministically.
389
- const visitState = new Map();
390
- for (const node of allNodes) {
391
- if ((visitState.get(node.nodeId) ?? 0) !== 0) continue;
392
- const trail = [];
393
- const pos = new Map();
394
- let curId = node.nodeId;
395
- while (curId !== null && curId !== undefined) {
396
- const st = visitState.get(curId) ?? 0;
397
- if (st === 2) break;
398
- if (st === 1) {
399
- const startIdx = pos.get(curId) ?? 0;
400
- const cycleIds = trail.slice(startIdx);
401
- // Detach the earliest node's upward back-edge so the earliest node stays root and
402
- // newer nodes in the cycle remain descendants beneath it.
403
- cycleIds.sort((a, b) => compareStructuralNodes(nodeByPrimaryId.get(a), nodeByPrimaryId.get(b)));
404
- const rootToDetachId = cycleIds[0];
405
- const rootNode = nodeByPrimaryId.get(rootToDetachId);
406
- const cycleTarget = rootNode.parentNodeId;
407
- resolvedParent.set(rootToDetachId, null);
408
- rootNode.orphan = {
409
- isOrphan: true,
410
- kind: 'cycle-broken',
411
- cycleParentId: cycleTarget,
412
- };
413
- break;
414
- }
415
- visitState.set(curId, 1);
416
- pos.set(curId, trail.length);
417
- trail.push(curId);
418
- curId = resolvedParent.get(curId) ?? null;
419
- }
420
- for (const id of trail) visitState.set(id, 2);
421
- }
422
-
423
- // Attach children to resolved parents and collect roots.
424
- const roots = [];
425
- for (const node of allNodes) {
426
- const pId = resolvedParent.get(node.nodeId) ?? null;
427
- if (pId === null) {
428
- roots.push(node);
429
- } else {
430
- const parent = nodeByPrimaryId.get(pId);
431
- parent.children.push(node);
432
- }
433
- }
434
-
435
- // Sort children at each level, compute depths and roll up node statuses bottom-up.
436
- const sortAndFinalize = (list, depth) => {
437
- list.sort(compareStructuralNodes);
438
- for (const node of list) {
439
- node.depth = depth;
440
- if (node.children.length > 0) {
441
- sortAndFinalize(node.children, depth + 1);
442
- }
443
- if (node.kind === 'plan' || node.children.length > 0) {
444
- finalizeNodeStatus(node);
445
- }
446
- }
447
- };
448
- sortAndFinalize(roots, 1);
449
-
450
- // Build flat pre-order index and orphan summary.
451
- const flatNodes = [];
452
- const orphans = [];
453
- const walkFlat = (node, resolvedParentId) => {
454
- const roundCount = node.kind === 'plan'
455
- ? node.executions.reduce((sum, ch) => sum + ch.roundCount, 0)
456
- : node.chain.roundCount;
457
- flatNodes.push({
458
- nodeId: node.nodeId,
459
- kind: node.kind,
460
- parentNodeId: node.parentNodeId,
461
- resolvedParentNodeId: resolvedParentId,
462
- depth: node.depth,
463
- title: node.title,
464
- displayTitle: node.displayTitle,
465
- titleMissing: node.titleMissing,
466
- goalDescription: node.goalDescription,
467
- completionSummary: node.completionSummary,
468
- executed: node.executed,
469
- nodeStatus: node.nodeStatus,
470
- roundCount,
471
- childCount: node.children.length,
472
- orphan: node.orphan,
473
- projectKey: node.projectKey,
474
- });
475
- if (node.orphan !== null) {
476
- orphans.push({ nodeId: node.nodeId, kind: node.kind, orphan: node.orphan });
477
- }
478
- for (const child of node.children) {
479
- walkFlat(child, node.nodeId);
480
- }
481
- };
482
- for (const root of roots) walkFlat(root, null);
483
-
484
- const projects = projectResolver.summarize(roots, allNodes);
485
- const unexecutedPlanNodes = [...planWrappers.values()].filter(
486
- (p) => p.executions.length === 0 && p.children.every((c) => !c.executed),
487
- ).length;
488
-
489
- return {
490
- roots,
491
- flatNodes,
492
- orphans,
493
- projects,
494
- counts: {
495
- planNodes: planWrappers.size,
496
- taskRecords: rawTasks.length,
497
- taskChains: chains.length,
498
- roots: roots.length,
499
- orphans: orphans.length,
500
- unexecutedPlanNodes,
501
- },
502
- };
503
- }
504
-
505
- function makeTaskTreeNode(chain, projectKey, orphan) {
506
- return {
507
- kind: 'task',
508
- nodeId: chain.rootTaskId,
509
- parentNodeId: chain.parentNodeId,
510
- title: chain.title,
511
- displayTitle: chain.displayTitle,
512
- titleMissing: chain.titleMissing,
513
- goalDescription: chain.goalDescription,
514
- completionSummary: chain.completionSummary,
515
- hostAcceptance: chain.rounds[chain.rounds.length - 1]?.hostAcceptance ?? null,
516
- createdAt: chain.createdAt,
517
- updatedAt: chain.updatedAt,
518
- sourcePath: chain.sourcePath,
519
- sourcePathDigest: chain.sourcePathDigest,
520
- projectKey,
521
- chain,
522
- rounds: chain.rounds,
523
- children: [],
524
- orphan,
525
- standalone: chain.planNodeId === null && chain.parentNodeId === null,
526
- executed: true,
527
- nodeStatus: chain.nodeStatus,
528
- depth: 1,
529
- };
530
- }
531
-
532
- function finalizeNodeStatus(node) {
533
- const isPlan = node.kind === 'plan';
534
- const executions = isPlan ? node.executions : [node.chain];
535
- const hasExecutions = executions.length > 0;
536
- node.executed = hasExecutions || node.children.some((child) => child.executed);
537
-
538
- const allSub = [
539
- ...executions.map((chain) => chain.nodeStatus),
540
- ...node.children.map((child) => child.nodeStatus),
541
- ];
542
-
543
- for (const urgent of ['awaiting-permission', 'awaiting-question', 'running', 'failed', 'changes-requested', 'awaiting-host-review', 'interrupted', 'cancelled']) {
544
- if (allSub.includes(urgent)) {
545
- node.nodeStatus = urgent;
546
- return;
547
- }
548
- }
549
-
550
- const allAccepted = allSub.every((status) => status === 'accepted');
551
- if (!isPlan) {
552
- // The chain keeps its own verdict; the tree node also represents its children.
553
- if (node.chain.nodeStatus === 'accepted' && !allAccepted) {
554
- node.nodeStatus = 'in-progress';
555
- }
556
- return;
557
- }
558
-
559
- if (acceptanceVerdictOf(node.hostAcceptance) === 'changes-requested') {
560
- node.nodeStatus = 'changes-requested';
561
- return;
562
- }
563
- if (node.hostAcceptance?.accepted === true) {
564
- node.nodeStatus = allAccepted ? 'accepted' : 'in-progress';
565
- return;
566
- }
567
-
568
- // If executions exist without a plan-level review, reflect the latest execution chain status:
569
- if (hasExecutions && node.children.length === 0) {
570
- node.nodeStatus = node.executions[node.executions.length - 1].nodeStatus;
571
- return;
572
- }
573
-
574
- if (allSub.length > 0 && allAccepted) {
575
- // All children accepted, awaiting final goal review by commander (G04 rule).
576
- node.nodeStatus = 'children-accepted';
577
- return;
578
- }
579
- if (allSub.some((st) => st === 'accepted' || st === 'children-accepted' || st === 'in-progress')) {
580
- node.nodeStatus = 'in-progress';
581
- return;
582
- }
583
- node.nodeStatus = 'planned';
584
- }
585
-
586
- function createProjectResolver(planNodes, chains) {
587
- // Map normalized unmasked path -> verified digest when both are present, so legacy records
588
- // carrying the same unmasked path join the exact same project bucket.
589
- const normToDigest = new Map();
590
- const projectsByKey = new Map();
591
-
592
- const observe = (sourcePath, sourcePathDigest) => {
593
- const norm = normalizePathComparisonKey(sourcePath);
594
- const digest = isDigest(sourcePathDigest) ? sourcePathDigest : null;
595
- if (norm !== null && digest !== null && !normToDigest.has(norm)) {
596
- normToDigest.set(norm, digest);
597
- }
598
- };
599
- for (const p of planNodes) {
600
- if (isObject(p)) observe(p.sourcePath, p.sourcePathDigest);
601
- }
602
- for (const c of chains) observe(c.sourcePath, c.sourcePathDigest);
603
-
604
- const ensureEntry = (projectKey, sourcePath, unverified) => {
605
- let entry = projectsByKey.get(projectKey);
606
- if (entry === undefined) {
607
- entry = {
608
- projectKey,
609
- name: unverified ? '来源未确认' : folderNameOf(sourcePath) ?? '已验证项目',
610
- sourcePath: unverified ? null : (isMaskedPathString(sourcePath) ? null : sourcePath),
611
- shortPath: null,
612
- unverified,
613
- };
614
- projectsByKey.set(projectKey, entry);
615
- } else if (entry.sourcePath === null && !unverified && typeof sourcePath === 'string' && !isMaskedPathString(sourcePath)) {
616
- entry.sourcePath = sourcePath;
617
- entry.name = folderNameOf(sourcePath) ?? entry.name;
618
- }
619
- return entry;
620
- };
621
-
622
- const resolve = (sourcePath, sourcePathDigest) => {
623
- const norm = normalizePathComparisonKey(sourcePath);
624
- const digest = isDigest(sourcePathDigest) ? sourcePathDigest : (norm !== null ? (normToDigest.get(norm) ?? null) : null);
625
- if (digest !== null) {
626
- return ensureEntry(digest, typeof sourcePath === 'string' ? sourcePath.trim() : null, false);
627
- }
628
- if (norm !== null) {
629
- return ensureEntry(`path:${norm}`, sourcePath.trim(), false);
630
- }
631
- return ensureEntry(UNVERIFIED_PROJECT_KEY, null, true);
632
- };
633
-
634
- const summarize = (roots, allNodes) => {
635
- // Disambiguate same-name projects by computing trailing path segments!
636
- const byName = new Map();
637
- for (const entry of projectsByKey.values()) {
638
- if (entry.unverified) continue;
639
- if (!byName.has(entry.name)) byName.set(entry.name, []);
640
- byName.get(entry.name).push(entry);
641
- }
642
- for (const group of byName.values()) {
643
- if (group.length <= 1) {
644
- if (group.length === 1 && group[0].sourcePath !== null) {
645
- group[0].shortPath = trailingSegments(group[0].sourcePath, 2);
646
- }
647
- continue;
648
- }
649
- assignDisambiguatedPaths(group);
650
- }
651
-
652
- const rootIdsByProject = new Map();
653
- const countByProject = new Map();
654
- for (const r of roots) {
655
- if (!rootIdsByProject.has(r.projectKey)) rootIdsByProject.set(r.projectKey, []);
656
- rootIdsByProject.get(r.projectKey).push(r.nodeId);
657
- }
658
- for (const n of allNodes) {
659
- countByProject.set(n.projectKey, (countByProject.get(n.projectKey) ?? 0) + 1);
660
- }
661
-
662
- const list = [];
663
- for (const entry of projectsByKey.values()) {
664
- const nodeCount = countByProject.get(entry.projectKey) ?? 0;
665
- if (nodeCount === 0) continue;
666
- list.push({
667
- projectKey: entry.projectKey,
668
- name: entry.name,
669
- shortPath: entry.shortPath,
670
- sourcePath: entry.sourcePath,
671
- unverified: entry.unverified,
672
- rootNodeIds: rootIdsByProject.get(entry.projectKey) ?? [],
673
- nodeCount,
674
- });
675
- }
676
- list.sort((a, b) => {
677
- if (a.unverified !== b.unverified) return a.unverified ? 1 : -1;
678
- if (a.name !== b.name) return a.name < b.name ? -1 : 1;
679
- return a.projectKey < b.projectKey ? -1 : a.projectKey > b.projectKey ? 1 : 0;
680
- });
681
- return list;
682
- };
683
-
684
- return { resolve, summarize };
685
- }
686
-
687
- function assignDisambiguatedPaths(entries) {
688
- for (let depth = 2; depth <= 8; depth += 1) {
689
- const seen = new Map();
690
- let collision = false;
691
- for (const entry of entries) {
692
- const candidate = entry.sourcePath !== null
693
- ? trailingSegments(entry.sourcePath, depth)
694
- : `${entry.name}#${entry.projectKey.slice(-6)}`;
695
- if (seen.has(candidate)) collision = true;
696
- seen.set(candidate, entry);
697
- entry.shortPath = candidate;
698
- }
699
- if (!collision) return;
700
- }
701
- }
702
-
703
- function folderNameOf(pathValue) {
704
- if (typeof pathValue !== 'string' || pathValue.trim() === '' || isMaskedPathString(pathValue)) return null;
705
- const parts = pathValue.trim().replace(/[\\/]+$/u, '').split(/[\\/]+/u).filter(Boolean);
706
- return parts.length > 0 ? parts[parts.length - 1] : null;
707
- }
708
-
709
- function trailingSegments(pathValue, count) {
710
- const parts = pathValue.trim().replace(/[\\/]+$/u, '').split(/[\\/]+/u).filter(Boolean);
711
- return parts.slice(-count).join('/');
712
- }
713
-
714
- function firstNonEmptyTitle(rounds) {
715
- for (const round of rounds) {
716
- const t = round.title;
717
- if (typeof t === 'string' && t.trim() !== '') return t.trim();
718
- }
719
- return null;
720
- }
721
-
722
- function firstNonEmptyDescription(rounds, field) {
723
- for (const r of rounds) {
724
- const val = r?.[field];
725
- if (typeof val === 'string' && val.trim() !== '') return val.trim();
726
- }
727
- return null;
728
- }
729
-
730
- function maxTimestampOfRounds(rounds) {
731
- let max = 0;
732
- for (const r of rounds) {
733
- for (const candidate of [r.activity?.lastActivityAt, r.endedAt, r.startedAt, r.createdAt,
734
- r.hostAcceptance?.acceptedAt, r.hostAcceptance?.decidedAt]) {
735
- const num = finiteNumber(candidate);
736
- if (num !== null && num > max) max = num;
737
- }
738
- }
739
- return max;
740
- }
741
-
742
- function compareTasksChronologically(a, b) {
743
- const left = finiteNumber(a?.createdAt) ?? 0;
744
- const right = finiteNumber(b?.createdAt) ?? 0;
745
- if (left !== right) return left - right;
746
- const idA = typeof a?.taskId === 'string' ? a.taskId : '';
747
- const idB = typeof b?.taskId === 'string' ? b.taskId : '';
748
- return idA < idB ? -1 : idA > idB ? 1 : 0;
749
- }
750
-
751
- function comparePlanRecords(a, b) {
752
- const seqA = Number.isSafeInteger(a?.sequence) ? a.sequence : 0;
753
- const seqB = Number.isSafeInteger(b?.sequence) ? b.sequence : 0;
754
- if (seqA !== seqB) return seqA - seqB;
755
- const left = finiteNumber(a?.createdAt) ?? 0;
756
- const right = finiteNumber(b?.createdAt) ?? 0;
757
- if (left !== right) return left - right;
758
- const idA = typeof a?.nodeId === 'string' ? a.nodeId : '';
759
- const idB = typeof b?.nodeId === 'string' ? b.nodeId : '';
760
- return idA < idB ? -1 : idA > idB ? 1 : 0;
761
- }
762
-
763
- function compareStructuralNodes(a, b) {
764
- // Preserve plan sibling order first when both carry explicit plan sequences; otherwise chronological.
765
- if (a?.kind === 'plan' && b?.kind === 'plan') {
766
- return comparePlanRecords(a, b);
767
- }
768
- const left = finiteNumber(a?.createdAt) ?? 0;
769
- const right = finiteNumber(b?.createdAt) ?? 0;
770
- if (left !== right) return left - right;
771
- const idA = typeof a?.nodeId === 'string' ? a.nodeId : '';
772
- const idB = typeof b?.nodeId === 'string' ? b.nodeId : '';
773
- return idA < idB ? -1 : idA > idB ? 1 : 0;
774
- }
775
-
776
- function isDigest(value) {
777
- return typeof value === 'string' && SHA256_DIGEST_RE.test(value);
778
- }
779
-
780
- function finiteNumber(value) {
781
- return typeof value === 'number' && Number.isFinite(value) ? value : null;
782
- }
783
-
784
- function isObject(value) {
785
- return value !== null && typeof value === 'object' && !Array.isArray(value);
786
- }
1
+ // Deterministic, runtime-agnostic task tree and continuation-chain projection.
2
+ //
3
+ // Zero Node-only imports so both the server planes and the browser bundle can use
4
+ // the exact same relational rules:
5
+ // 1. `continueFromTaskId` links rectification rounds of ONE work item only;
6
+ // 2. `planNodeId` binds an execution chain to an unexecuted/planned node;
7
+ // 3. `parentNodeId` builds the multi-level goal -> subtask -> step hierarchy;
8
+ // 4. Titles, timestamps, models and prompts are NEVER used to infer relationships;
9
+ // 5. Missing parents/plans become explicit orphans (never dropped or title-merged),
10
+ // and corrupted parent/continuation cycles are broken deterministically.
11
+
12
+ const PATH_MASK_SEGMENT = 'masks-user-profile-segment';
13
+ const SHA256_DIGEST_RE = /^sha256:[0-9a-f]{64}$/u;
14
+ export const UNVERIFIED_PROJECT_KEY = 'unverified';
15
+
16
+ export function isMaskedPathString(value) {
17
+ if (typeof value !== 'string') return false;
18
+ return value.split(/[\\/]+/u).some((part) => part.trim() === PATH_MASK_SEGMENT);
19
+ }
20
+
21
+ export function normalizePathComparisonKey(value, options = {}) {
22
+ if (typeof value !== 'string') return null;
23
+ const trimmed = value.trim();
24
+ if (trimmed === '' || isMaskedPathString(trimmed)) return null;
25
+ const stripped = trimmed.length > 1 ? trimmed.replace(/[\\/]+$/u, '') : trimmed;
26
+ const caseInsensitive = options.caseInsensitive ?? /^[A-Za-z]:[\\/]/u.test(stripped);
27
+ return caseInsensitive ? stripped.toLowerCase() : stripped;
28
+ }
29
+
30
+ function cleanRef(value, selfId = null) {
31
+ if (typeof value !== 'string') return null;
32
+ const trimmed = value.trim();
33
+ if (trimmed === '' || trimmed === selfId) return null;
34
+ return trimmed;
35
+ }
36
+
37
+ function shortTaskLabel(id) {
38
+ if (typeof id !== 'string' || id === '') return 'unknown';
39
+ const stripped = id.startsWith('task-') ? id.slice(5) : id;
40
+ return stripped.slice(0, 8);
41
+ }
42
+
43
+ export function explicitContinuationOf(task) {
44
+ if (!isObject(task)) return null;
45
+ const selfId = typeof task.taskId === 'string' ? task.taskId.trim() : null;
46
+ const direct = cleanRef(task.continueFromTaskId, selfId);
47
+ if (direct !== null) return direct;
48
+ const placed = cleanRef(task.execution?.conversation?.continuedFromTaskId, selfId);
49
+ return placed;
50
+ }
51
+
52
+ /**
53
+ * Group flat task views into continuation chains using explicit `continueFromTaskId` only.
54
+ * @param {object[]} tasks - live + archived task views.
55
+ * @returns {object[]} ordered chains.
56
+ */
57
+ export function groupContinuationChains(tasks = []) {
58
+ const byId = new Map();
59
+ for (const raw of Array.isArray(tasks) ? tasks : []) {
60
+ if (!isObject(raw) || typeof raw.taskId !== 'string' || raw.taskId.trim() === '') continue;
61
+ const taskId = raw.taskId.trim();
62
+ if (!byId.has(taskId)) byId.set(taskId, raw);
63
+ }
64
+
65
+ // Build explicit parent link `childId -> parentTaskId` with self-loop guard.
66
+ const parentOf = new Map();
67
+ const brokenByTask = new Map();
68
+ for (const [taskId, task] of byId.entries()) {
69
+ const rawCont = typeof task.continueFromTaskId === 'string' ? task.continueFromTaskId.trim() : '';
70
+ if (rawCont !== '' && rawCont === taskId) {
71
+ brokenByTask.set(taskId, { cycleTaskId: taskId, reason: 'cycle-broken' });
72
+ continue;
73
+ }
74
+ const target = explicitContinuationOf(task);
75
+ if (target === null) continue;
76
+ if (!byId.has(target)) {
77
+ brokenByTask.set(taskId, { missingTaskId: target, reason: 'missing-task' });
78
+ continue;
79
+ }
80
+ parentOf.set(taskId, target);
81
+ }
82
+
83
+ // Detect and break cycles in `parentOf` deterministically (earliest createdAt/taskId becomes root).
84
+ const state = new Map(); // 0/undef = unvisited, 1 = visiting, 2 = done
85
+ for (const startId of byId.keys()) {
86
+ if ((state.get(startId) ?? 0) !== 0) continue;
87
+ const trail = [];
88
+ const indexInTrail = new Map();
89
+ let cur = startId;
90
+ while (cur !== null && cur !== undefined) {
91
+ const st = state.get(cur) ?? 0;
92
+ if (st === 2) break;
93
+ if (st === 1) {
94
+ const cycleStart = indexInTrail.get(cur) ?? 0;
95
+ const cycleIds = trail.slice(cycleStart);
96
+ cycleIds.sort((a, b) => compareTasksChronologically(byId.get(a), byId.get(b)));
97
+ const chosenRoot = cycleIds[0];
98
+ const brokenTarget = parentOf.get(chosenRoot);
99
+ parentOf.delete(chosenRoot);
100
+ brokenByTask.set(chosenRoot, { cycleTaskId: brokenTarget, reason: 'cycle-broken' });
101
+ break;
102
+ }
103
+ state.set(cur, 1);
104
+ indexInTrail.set(cur, trail.length);
105
+ trail.push(cur);
106
+ cur = parentOf.get(cur) ?? null;
107
+ }
108
+ for (const id of trail) state.set(id, 2);
109
+ }
110
+
111
+ // Group children under each chain's root task.
112
+ const childrenOf = new Map();
113
+ for (const [childId, pId] of parentOf.entries()) {
114
+ if (!childrenOf.has(pId)) childrenOf.set(pId, []);
115
+ childrenOf.get(pId).push(childId);
116
+ }
117
+ for (const list of childrenOf.values()) {
118
+ list.sort((a, b) => compareTasksChronologically(byId.get(a), byId.get(b)));
119
+ }
120
+
121
+ const roots = [];
122
+ for (const taskId of byId.keys()) {
123
+ if (!parentOf.has(taskId)) roots.push(taskId);
124
+ }
125
+ roots.sort((a, b) => compareTasksChronologically(byId.get(a), byId.get(b)));
126
+
127
+ const chains = [];
128
+ for (const rootId of roots) {
129
+ const rounds = [];
130
+ let hasParallelContinuations = false;
131
+ const collect = (id) => {
132
+ const task = byId.get(id);
133
+ rounds.push(task);
134
+ const kids = childrenOf.get(id) ?? [];
135
+ if (kids.length > 1) hasParallelContinuations = true;
136
+ for (const kid of kids) collect(kid);
137
+ };
138
+ collect(rootId);
139
+
140
+ const rootTask = rounds[0];
141
+ const latestTask = rounds[rounds.length - 1];
142
+
143
+ // Hierarchy identity comes from explicit fields only, never guessed.
144
+ let planNodeId = null;
145
+ let parentNodeId = null;
146
+ let hierarchyMismatch = false;
147
+ for (const r of rounds) {
148
+ const rPlan = cleanRef(r.planNodeId, r.taskId);
149
+ const rParent = cleanRef(r.parentNodeId, r.taskId);
150
+ if (rPlan !== null) {
151
+ if (planNodeId === null) planNodeId = rPlan;
152
+ else if (planNodeId !== rPlan) hierarchyMismatch = true;
153
+ }
154
+ if (rParent !== null) {
155
+ if (parentNodeId === null) parentNodeId = rParent;
156
+ else if (parentNodeId !== rParent) hierarchyMismatch = true;
157
+ }
158
+ }
159
+
160
+ // Keep the original task name when a continuation uses a different round title.
161
+ const recordedTitle = firstNonEmptyTitle(rounds);
162
+ const titleMissing = recordedTitle === null;
163
+ const displayTitle = titleMissing
164
+ ? `未记录标题 (${shortTaskLabel(rootId)})`
165
+ : recordedTitle;
166
+
167
+ const goalDescription = firstNonEmptyDescription(rounds, 'goalDescription');
168
+ const latestAcceptedOrReviewed = [...rounds].reverse().find(
169
+ (r) => acceptanceVerdictOf(r.hostAcceptance) !== null,
170
+ ) ?? null;
171
+ const completionSummary = typeof latestAcceptedOrReviewed?.hostAcceptance?.completionSummary === 'string'
172
+ && latestAcceptedOrReviewed.hostAcceptance.completionSummary.trim() !== ''
173
+ ? latestAcceptedOrReviewed.hostAcceptance.completionSummary.trim()
174
+ : null;
175
+
176
+ chains.push({
177
+ chainId: rootId,
178
+ rootTaskId: rootId,
179
+ latestTaskId: latestTask.taskId,
180
+ taskIds: rounds.map((r) => r.taskId),
181
+ roundCount: rounds.length,
182
+ rounds,
183
+ title: recordedTitle,
184
+ titleMissing,
185
+ displayTitle,
186
+ goalDescription,
187
+ completionSummary,
188
+ planNodeId,
189
+ parentNodeId,
190
+ hierarchyRecorded: planNodeId !== null || parentNodeId !== null,
191
+ hierarchyMismatch,
192
+ hasParallelContinuations,
193
+ brokenContinuation: brokenByTask.get(rootId) ?? null,
194
+ nodeStatus: deriveChainStatus(rounds, new Set(rounds.map((round) => parentOf.get(round.taskId)))),
195
+ createdAt: finiteNumber(rootTask.createdAt) ?? 0,
196
+ updatedAt: maxTimestampOfRounds(rounds),
197
+ sourcePath: rootTask.sourcePath ??
198
+ (rootTask.isolation !== 'worktree' && (rootTask.isolation === 'shared' || rootTask.executionWorkspacePath == null)
199
+ ? rootTask.workspacePath : null) ?? null,
200
+ sourcePathDigest: isDigest(rootTask.sourcePathDigest) ? rootTask.sourcePathDigest : null,
201
+ });
202
+ }
203
+
204
+ return chains;
205
+ }
206
+
207
+ /**
208
+ * Derive conservative status for a task continuation chain (foundation for G04).
209
+ * Execution finishing (`awaiting-host-review`) is NEVER reported as `accepted`.
210
+ */
211
+ export function deriveChainStatus(rounds, continuedTaskIds = new Set(rounds.map(explicitContinuationOf))) {
212
+ if (rounds.length === 0) return 'planned';
213
+ const statuses = new Set();
214
+ for (const round of rounds) {
215
+ if (round.state === 'running' && (round.phase === 'awaiting-permission' || round.permission?.waiting === true)) {
216
+ return 'awaiting-permission';
217
+ }
218
+ if (round.state === 'running' && (round.phase === 'awaiting-question' || round.question?.waiting === true)) {
219
+ statuses.add('awaiting-question');
220
+ } else if (round.state === 'pending' || round.state === 'running') {
221
+ statuses.add('running');
222
+ } else if (round.state === 'awaiting-host-review' && !isSavedAcceptance(round)) {
223
+ statuses.add('awaiting-host-review');
224
+ } else if (!continuedTaskIds.has(round.taskId)) {
225
+ const terminal = ['failed', 'cancelled', 'interrupted'].includes(round.state) ? round.state : 'unknown';
226
+ statuses.add(round.state === 'awaiting-host-review' ? acceptanceVerdictOf(round.hostAcceptance) : terminal);
227
+ }
228
+ }
229
+ const attention = ['awaiting-question', 'running', 'failed', 'changes-requested', 'awaiting-host-review', 'interrupted', 'cancelled', 'unknown'];
230
+ return attention.find((status) => statuses.has(status)) ?? (statuses.has('accepted') ? 'accepted' : 'unknown');
231
+ }
232
+
233
+ function acceptanceVerdictOf(acceptance) {
234
+ if (!isObject(acceptance)) return null;
235
+ const raw = acceptance.state ?? acceptance.decision ?? null;
236
+ if (raw === 'accepted' || raw === 'changes-requested') return raw;
237
+ if (typeof acceptance.accepted === 'boolean') {
238
+ return acceptance.accepted ? 'accepted' : 'changes-requested';
239
+ }
240
+ return null;
241
+ }
242
+
243
+ function isSavedAcceptance(task) {
244
+ if (acceptanceVerdictOf(task?.hostAcceptance) === null) return false;
245
+ if (task.reviewPersistence && typeof task.reviewPersistence.state === 'string') {
246
+ if (task.reviewPersistence.state !== 'saved' && task.reviewPersistence.state !== 'none') {
247
+ return false;
248
+ }
249
+ }
250
+ return true;
251
+ }
252
+
253
+ /**
254
+ * Build the complete multi-level goal/subtask tree and project index.
255
+ * @param {{ planNodes?: object[], tasks?: object[] }} input - loaded plan nodes and tasks.
256
+ * @returns {object} structured tree, flat index, orphans, projects and counts.
257
+ */
258
+ export function buildTaskTree(input = {}) {
259
+ const rawPlans = Array.isArray(input.planNodes) ? input.planNodes : [];
260
+ const rawTasks = Array.isArray(input.tasks) ? input.tasks : [];
261
+
262
+ const chains = groupContinuationChains(rawTasks);
263
+ const projectResolver = createProjectResolver(rawPlans, chains);
264
+
265
+ const planWrappers = new Map();
266
+ const orderedPlans = [...rawPlans]
267
+ .filter((p) => isObject(p) && typeof p.nodeId === 'string' && p.nodeId.trim() !== '')
268
+ .sort(comparePlanRecords);
269
+
270
+ for (const plan of orderedPlans) {
271
+ const nodeId = plan.nodeId.trim();
272
+ if (planWrappers.has(nodeId)) continue;
273
+ const parentNodeId = typeof plan.parentNodeId === 'string' && plan.parentNodeId.trim() !== ''
274
+ ? plan.parentNodeId.trim()
275
+ : null;
276
+ const project = projectResolver.resolve(plan.sourcePath ?? null, plan.sourcePathDigest ?? null);
277
+ const completionSummary = typeof plan.hostAcceptance?.completionSummary === 'string'
278
+ && plan.hostAcceptance.completionSummary.trim() !== ''
279
+ ? plan.hostAcceptance.completionSummary.trim()
280
+ : null;
281
+ planWrappers.set(nodeId, {
282
+ kind: 'plan',
283
+ nodeId,
284
+ parentNodeId,
285
+ title: plan.title,
286
+ displayTitle: plan.title,
287
+ titleMissing: false,
288
+ goalDescription: typeof plan.goalDescription === 'string' ? plan.goalDescription : null,
289
+ completionSummary,
290
+ hostAcceptance: plan.hostAcceptance ?? null,
291
+ reviewHistory: Array.isArray(plan.reviewHistory) ? plan.reviewHistory : [],
292
+ sequence: Number.isSafeInteger(plan.sequence) ? plan.sequence : 0,
293
+ createdAt: finiteNumber(plan.createdAt) ?? 0,
294
+ updatedAt: finiteNumber(plan.updatedAt) ?? finiteNumber(plan.createdAt) ?? 0,
295
+ sourcePath: plan.sourcePath ?? null,
296
+ sourcePathDigest: isDigest(plan.sourcePathDigest) ? plan.sourcePathDigest : null,
297
+ projectKey: project.projectKey,
298
+ executions: [],
299
+ children: [],
300
+ orphan: null,
301
+ executed: false,
302
+ nodeStatus: 'planned',
303
+ depth: 1,
304
+ });
305
+ }
306
+
307
+ // Lookup table for valid parent targets: plan nodeId -> wrapper, taskId -> wrapper.
308
+ const parentLookup = new Map();
309
+ for (const [nodeId, wrapper] of planWrappers.entries()) {
310
+ parentLookup.set(nodeId, wrapper);
311
+ }
312
+
313
+ const taskNodes = [];
314
+ for (const chain of chains) {
315
+ if (chain.planNodeId !== null) {
316
+ const targetPlan = planWrappers.get(chain.planNodeId) ?? null;
317
+ if (targetPlan !== null) {
318
+ targetPlan.executions.push(chain);
319
+ targetPlan.executed = true;
320
+ if (chain.updatedAt > targetPlan.updatedAt) targetPlan.updatedAt = chain.updatedAt;
321
+ // Any child task naming a taskId in this chain resolves to this plan node in the tree.
322
+ for (const tId of chain.taskIds) {
323
+ if (!parentLookup.has(tId)) parentLookup.set(tId, targetPlan);
324
+ }
325
+ continue;
326
+ }
327
+ // Missing planNodeId -> preserve as root-level orphan task node, never drop or guess!
328
+ const project = projectResolver.resolve(chain.sourcePath, chain.sourcePathDigest);
329
+ const orphanNode = makeTaskTreeNode(chain, project.projectKey, {
330
+ isOrphan: true,
331
+ kind: 'missing-plan-node',
332
+ missingNodeId: chain.planNodeId,
333
+ });
334
+ taskNodes.push(orphanNode);
335
+ for (const tId of chain.taskIds) {
336
+ if (!parentLookup.has(tId)) parentLookup.set(tId, orphanNode);
337
+ }
338
+ continue;
339
+ }
340
+
341
+ const project = projectResolver.resolve(chain.sourcePath, chain.sourcePathDigest);
342
+ const taskNode = makeTaskTreeNode(chain, project.projectKey, null);
343
+ taskNodes.push(taskNode);
344
+ for (const tId of chain.taskIds) {
345
+ if (!parentLookup.has(tId)) parentLookup.set(tId, taskNode);
346
+ }
347
+ }
348
+
349
+ // Combine all structural nodes (plan nodes + standalone/child task nodes).
350
+ const allNodes = [...planWrappers.values(), ...taskNodes];
351
+ const nodeByPrimaryId = new Map(allNodes.map((n) => [n.nodeId, n]));
352
+
353
+ // Resolve each node's parent wrapper, detecting self-loops and missing parents.
354
+ const resolvedParent = new Map();
355
+ for (const node of allNodes) {
356
+ if (node.orphan !== null) {
357
+ // Already marked orphan (e.g. missing-plan-node) -> stays at root.
358
+ resolvedParent.set(node.nodeId, null);
359
+ continue;
360
+ }
361
+ const rawParentId = node.parentNodeId;
362
+ if (rawParentId === null) {
363
+ resolvedParent.set(node.nodeId, null);
364
+ continue;
365
+ }
366
+ const target = parentLookup.get(rawParentId) ?? null;
367
+ if (target === null) {
368
+ node.orphan = {
369
+ isOrphan: true,
370
+ kind: 'missing-parent',
371
+ missingParentId: rawParentId,
372
+ };
373
+ resolvedParent.set(node.nodeId, null);
374
+ continue;
375
+ }
376
+ if (target.nodeId === node.nodeId) {
377
+ node.orphan = {
378
+ isOrphan: true,
379
+ kind: 'cycle-broken',
380
+ cycleParentId: rawParentId,
381
+ };
382
+ resolvedParent.set(node.nodeId, null);
383
+ continue;
384
+ }
385
+ resolvedParent.set(node.nodeId, target.nodeId);
386
+ }
387
+
388
+ // Detect and break multi-node parent cycles deterministically.
389
+ const visitState = new Map();
390
+ for (const node of allNodes) {
391
+ if ((visitState.get(node.nodeId) ?? 0) !== 0) continue;
392
+ const trail = [];
393
+ const pos = new Map();
394
+ let curId = node.nodeId;
395
+ while (curId !== null && curId !== undefined) {
396
+ const st = visitState.get(curId) ?? 0;
397
+ if (st === 2) break;
398
+ if (st === 1) {
399
+ const startIdx = pos.get(curId) ?? 0;
400
+ const cycleIds = trail.slice(startIdx);
401
+ // Detach the earliest node's upward back-edge so the earliest node stays root and
402
+ // newer nodes in the cycle remain descendants beneath it.
403
+ cycleIds.sort((a, b) => compareStructuralNodes(nodeByPrimaryId.get(a), nodeByPrimaryId.get(b)));
404
+ const rootToDetachId = cycleIds[0];
405
+ const rootNode = nodeByPrimaryId.get(rootToDetachId);
406
+ const cycleTarget = rootNode.parentNodeId;
407
+ resolvedParent.set(rootToDetachId, null);
408
+ rootNode.orphan = {
409
+ isOrphan: true,
410
+ kind: 'cycle-broken',
411
+ cycleParentId: cycleTarget,
412
+ };
413
+ break;
414
+ }
415
+ visitState.set(curId, 1);
416
+ pos.set(curId, trail.length);
417
+ trail.push(curId);
418
+ curId = resolvedParent.get(curId) ?? null;
419
+ }
420
+ for (const id of trail) visitState.set(id, 2);
421
+ }
422
+
423
+ // Attach children to resolved parents and collect roots.
424
+ const roots = [];
425
+ for (const node of allNodes) {
426
+ const pId = resolvedParent.get(node.nodeId) ?? null;
427
+ if (pId === null) {
428
+ roots.push(node);
429
+ } else {
430
+ const parent = nodeByPrimaryId.get(pId);
431
+ parent.children.push(node);
432
+ }
433
+ }
434
+
435
+ // Sort children at each level, compute depths and roll up node statuses bottom-up.
436
+ const sortAndFinalize = (list, depth) => {
437
+ list.sort(compareStructuralNodes);
438
+ for (const node of list) {
439
+ node.depth = depth;
440
+ if (node.children.length > 0) {
441
+ sortAndFinalize(node.children, depth + 1);
442
+ }
443
+ if (node.kind === 'plan' || node.children.length > 0) {
444
+ finalizeNodeStatus(node);
445
+ }
446
+ }
447
+ };
448
+ sortAndFinalize(roots, 1);
449
+
450
+ // Build flat pre-order index and orphan summary.
451
+ const flatNodes = [];
452
+ const orphans = [];
453
+ const walkFlat = (node, resolvedParentId) => {
454
+ const roundCount = node.kind === 'plan'
455
+ ? node.executions.reduce((sum, ch) => sum + ch.roundCount, 0)
456
+ : node.chain.roundCount;
457
+ flatNodes.push({
458
+ nodeId: node.nodeId,
459
+ kind: node.kind,
460
+ parentNodeId: node.parentNodeId,
461
+ resolvedParentNodeId: resolvedParentId,
462
+ depth: node.depth,
463
+ title: node.title,
464
+ displayTitle: node.displayTitle,
465
+ titleMissing: node.titleMissing,
466
+ goalDescription: node.goalDescription,
467
+ completionSummary: node.completionSummary,
468
+ executed: node.executed,
469
+ nodeStatus: node.nodeStatus,
470
+ roundCount,
471
+ childCount: node.children.length,
472
+ orphan: node.orphan,
473
+ projectKey: node.projectKey,
474
+ });
475
+ if (node.orphan !== null) {
476
+ orphans.push({ nodeId: node.nodeId, kind: node.kind, orphan: node.orphan });
477
+ }
478
+ for (const child of node.children) {
479
+ walkFlat(child, node.nodeId);
480
+ }
481
+ };
482
+ for (const root of roots) walkFlat(root, null);
483
+
484
+ const projects = projectResolver.summarize(roots, allNodes);
485
+ const unexecutedPlanNodes = [...planWrappers.values()].filter(
486
+ (p) => p.executions.length === 0 && p.children.every((c) => !c.executed),
487
+ ).length;
488
+
489
+ return {
490
+ roots,
491
+ flatNodes,
492
+ orphans,
493
+ projects,
494
+ counts: {
495
+ planNodes: planWrappers.size,
496
+ taskRecords: rawTasks.length,
497
+ taskChains: chains.length,
498
+ roots: roots.length,
499
+ orphans: orphans.length,
500
+ unexecutedPlanNodes,
501
+ },
502
+ };
503
+ }
504
+
505
+ function makeTaskTreeNode(chain, projectKey, orphan) {
506
+ return {
507
+ kind: 'task',
508
+ nodeId: chain.rootTaskId,
509
+ parentNodeId: chain.parentNodeId,
510
+ title: chain.title,
511
+ displayTitle: chain.displayTitle,
512
+ titleMissing: chain.titleMissing,
513
+ goalDescription: chain.goalDescription,
514
+ completionSummary: chain.completionSummary,
515
+ hostAcceptance: chain.rounds[chain.rounds.length - 1]?.hostAcceptance ?? null,
516
+ createdAt: chain.createdAt,
517
+ updatedAt: chain.updatedAt,
518
+ sourcePath: chain.sourcePath,
519
+ sourcePathDigest: chain.sourcePathDigest,
520
+ projectKey,
521
+ chain,
522
+ rounds: chain.rounds,
523
+ children: [],
524
+ orphan,
525
+ standalone: chain.planNodeId === null && chain.parentNodeId === null,
526
+ executed: true,
527
+ nodeStatus: chain.nodeStatus,
528
+ depth: 1,
529
+ };
530
+ }
531
+
532
+ function finalizeNodeStatus(node) {
533
+ const isPlan = node.kind === 'plan';
534
+ const executions = isPlan ? node.executions : [node.chain];
535
+ const hasExecutions = executions.length > 0;
536
+ node.executed = hasExecutions || node.children.some((child) => child.executed);
537
+
538
+ const allSub = [
539
+ ...executions.map((chain) => chain.nodeStatus),
540
+ ...node.children.map((child) => child.nodeStatus),
541
+ ];
542
+
543
+ for (const urgent of ['awaiting-permission', 'awaiting-question', 'running', 'failed', 'changes-requested', 'awaiting-host-review', 'interrupted', 'cancelled']) {
544
+ if (allSub.includes(urgent)) {
545
+ node.nodeStatus = urgent;
546
+ return;
547
+ }
548
+ }
549
+
550
+ const allAccepted = allSub.every((status) => status === 'accepted');
551
+ if (!isPlan) {
552
+ // The chain keeps its own verdict; the tree node also represents its children.
553
+ if (node.chain.nodeStatus === 'accepted' && !allAccepted) {
554
+ node.nodeStatus = 'in-progress';
555
+ }
556
+ return;
557
+ }
558
+
559
+ if (acceptanceVerdictOf(node.hostAcceptance) === 'changes-requested') {
560
+ node.nodeStatus = 'changes-requested';
561
+ return;
562
+ }
563
+ if (node.hostAcceptance?.accepted === true) {
564
+ node.nodeStatus = allAccepted ? 'accepted' : 'in-progress';
565
+ return;
566
+ }
567
+
568
+ // If executions exist without a plan-level review, reflect the latest execution chain status:
569
+ if (hasExecutions && node.children.length === 0) {
570
+ node.nodeStatus = node.executions[node.executions.length - 1].nodeStatus;
571
+ return;
572
+ }
573
+
574
+ if (allSub.length > 0 && allAccepted) {
575
+ // All children accepted, awaiting final goal review by commander (G04 rule).
576
+ node.nodeStatus = 'children-accepted';
577
+ return;
578
+ }
579
+ if (allSub.some((st) => st === 'accepted' || st === 'children-accepted' || st === 'in-progress')) {
580
+ node.nodeStatus = 'in-progress';
581
+ return;
582
+ }
583
+ node.nodeStatus = 'planned';
584
+ }
585
+
586
+ function createProjectResolver(planNodes, chains) {
587
+ // Map normalized unmasked path -> verified digest when both are present, so legacy records
588
+ // carrying the same unmasked path join the exact same project bucket.
589
+ const normToDigest = new Map();
590
+ const projectsByKey = new Map();
591
+
592
+ const observe = (sourcePath, sourcePathDigest) => {
593
+ const norm = normalizePathComparisonKey(sourcePath);
594
+ const digest = isDigest(sourcePathDigest) ? sourcePathDigest : null;
595
+ if (norm !== null && digest !== null && !normToDigest.has(norm)) {
596
+ normToDigest.set(norm, digest);
597
+ }
598
+ };
599
+ for (const p of planNodes) {
600
+ if (isObject(p)) observe(p.sourcePath, p.sourcePathDigest);
601
+ }
602
+ for (const c of chains) observe(c.sourcePath, c.sourcePathDigest);
603
+
604
+ const ensureEntry = (projectKey, sourcePath, unverified) => {
605
+ let entry = projectsByKey.get(projectKey);
606
+ if (entry === undefined) {
607
+ entry = {
608
+ projectKey,
609
+ name: unverified ? '来源未确认' : folderNameOf(sourcePath) ?? '已验证项目',
610
+ sourcePath: unverified ? null : (isMaskedPathString(sourcePath) ? null : sourcePath),
611
+ shortPath: null,
612
+ unverified,
613
+ };
614
+ projectsByKey.set(projectKey, entry);
615
+ } else if (entry.sourcePath === null && !unverified && typeof sourcePath === 'string' && !isMaskedPathString(sourcePath)) {
616
+ entry.sourcePath = sourcePath;
617
+ entry.name = folderNameOf(sourcePath) ?? entry.name;
618
+ }
619
+ return entry;
620
+ };
621
+
622
+ const resolve = (sourcePath, sourcePathDigest) => {
623
+ const norm = normalizePathComparisonKey(sourcePath);
624
+ const digest = isDigest(sourcePathDigest) ? sourcePathDigest : (norm !== null ? (normToDigest.get(norm) ?? null) : null);
625
+ if (digest !== null) {
626
+ return ensureEntry(digest, typeof sourcePath === 'string' ? sourcePath.trim() : null, false);
627
+ }
628
+ if (norm !== null) {
629
+ return ensureEntry(`path:${norm}`, sourcePath.trim(), false);
630
+ }
631
+ return ensureEntry(UNVERIFIED_PROJECT_KEY, null, true);
632
+ };
633
+
634
+ const summarize = (roots, allNodes) => {
635
+ // Disambiguate same-name projects by computing trailing path segments!
636
+ const byName = new Map();
637
+ for (const entry of projectsByKey.values()) {
638
+ if (entry.unverified) continue;
639
+ if (!byName.has(entry.name)) byName.set(entry.name, []);
640
+ byName.get(entry.name).push(entry);
641
+ }
642
+ for (const group of byName.values()) {
643
+ if (group.length <= 1) {
644
+ if (group.length === 1 && group[0].sourcePath !== null) {
645
+ group[0].shortPath = trailingSegments(group[0].sourcePath, 2);
646
+ }
647
+ continue;
648
+ }
649
+ assignDisambiguatedPaths(group);
650
+ }
651
+
652
+ const rootIdsByProject = new Map();
653
+ const countByProject = new Map();
654
+ for (const r of roots) {
655
+ if (!rootIdsByProject.has(r.projectKey)) rootIdsByProject.set(r.projectKey, []);
656
+ rootIdsByProject.get(r.projectKey).push(r.nodeId);
657
+ }
658
+ for (const n of allNodes) {
659
+ countByProject.set(n.projectKey, (countByProject.get(n.projectKey) ?? 0) + 1);
660
+ }
661
+
662
+ const list = [];
663
+ for (const entry of projectsByKey.values()) {
664
+ const nodeCount = countByProject.get(entry.projectKey) ?? 0;
665
+ if (nodeCount === 0) continue;
666
+ list.push({
667
+ projectKey: entry.projectKey,
668
+ name: entry.name,
669
+ shortPath: entry.shortPath,
670
+ sourcePath: entry.sourcePath,
671
+ unverified: entry.unverified,
672
+ rootNodeIds: rootIdsByProject.get(entry.projectKey) ?? [],
673
+ nodeCount,
674
+ });
675
+ }
676
+ list.sort((a, b) => {
677
+ if (a.unverified !== b.unverified) return a.unverified ? 1 : -1;
678
+ if (a.name !== b.name) return a.name < b.name ? -1 : 1;
679
+ return a.projectKey < b.projectKey ? -1 : a.projectKey > b.projectKey ? 1 : 0;
680
+ });
681
+ return list;
682
+ };
683
+
684
+ return { resolve, summarize };
685
+ }
686
+
687
+ function assignDisambiguatedPaths(entries) {
688
+ for (let depth = 2; depth <= 8; depth += 1) {
689
+ const seen = new Map();
690
+ let collision = false;
691
+ for (const entry of entries) {
692
+ const candidate = entry.sourcePath !== null
693
+ ? trailingSegments(entry.sourcePath, depth)
694
+ : `${entry.name}#${entry.projectKey.slice(-6)}`;
695
+ if (seen.has(candidate)) collision = true;
696
+ seen.set(candidate, entry);
697
+ entry.shortPath = candidate;
698
+ }
699
+ if (!collision) return;
700
+ }
701
+ }
702
+
703
+ function folderNameOf(pathValue) {
704
+ if (typeof pathValue !== 'string' || pathValue.trim() === '' || isMaskedPathString(pathValue)) return null;
705
+ const parts = pathValue.trim().replace(/[\\/]+$/u, '').split(/[\\/]+/u).filter(Boolean);
706
+ return parts.length > 0 ? parts[parts.length - 1] : null;
707
+ }
708
+
709
+ function trailingSegments(pathValue, count) {
710
+ const parts = pathValue.trim().replace(/[\\/]+$/u, '').split(/[\\/]+/u).filter(Boolean);
711
+ return parts.slice(-count).join('/');
712
+ }
713
+
714
+ function firstNonEmptyTitle(rounds) {
715
+ for (const round of rounds) {
716
+ const t = round.title;
717
+ if (typeof t === 'string' && t.trim() !== '') return t.trim();
718
+ }
719
+ return null;
720
+ }
721
+
722
+ function firstNonEmptyDescription(rounds, field) {
723
+ for (const r of rounds) {
724
+ const val = r?.[field];
725
+ if (typeof val === 'string' && val.trim() !== '') return val.trim();
726
+ }
727
+ return null;
728
+ }
729
+
730
+ function maxTimestampOfRounds(rounds) {
731
+ let max = 0;
732
+ for (const r of rounds) {
733
+ for (const candidate of [r.activity?.lastActivityAt, r.endedAt, r.startedAt, r.createdAt,
734
+ r.hostAcceptance?.acceptedAt, r.hostAcceptance?.decidedAt]) {
735
+ const num = finiteNumber(candidate);
736
+ if (num !== null && num > max) max = num;
737
+ }
738
+ }
739
+ return max;
740
+ }
741
+
742
+ function compareTasksChronologically(a, b) {
743
+ const left = finiteNumber(a?.createdAt) ?? 0;
744
+ const right = finiteNumber(b?.createdAt) ?? 0;
745
+ if (left !== right) return left - right;
746
+ const idA = typeof a?.taskId === 'string' ? a.taskId : '';
747
+ const idB = typeof b?.taskId === 'string' ? b.taskId : '';
748
+ return idA < idB ? -1 : idA > idB ? 1 : 0;
749
+ }
750
+
751
+ function comparePlanRecords(a, b) {
752
+ const seqA = Number.isSafeInteger(a?.sequence) ? a.sequence : 0;
753
+ const seqB = Number.isSafeInteger(b?.sequence) ? b.sequence : 0;
754
+ if (seqA !== seqB) return seqA - seqB;
755
+ const left = finiteNumber(a?.createdAt) ?? 0;
756
+ const right = finiteNumber(b?.createdAt) ?? 0;
757
+ if (left !== right) return left - right;
758
+ const idA = typeof a?.nodeId === 'string' ? a.nodeId : '';
759
+ const idB = typeof b?.nodeId === 'string' ? b.nodeId : '';
760
+ return idA < idB ? -1 : idA > idB ? 1 : 0;
761
+ }
762
+
763
+ function compareStructuralNodes(a, b) {
764
+ // Preserve plan sibling order first when both carry explicit plan sequences; otherwise chronological.
765
+ if (a?.kind === 'plan' && b?.kind === 'plan') {
766
+ return comparePlanRecords(a, b);
767
+ }
768
+ const left = finiteNumber(a?.createdAt) ?? 0;
769
+ const right = finiteNumber(b?.createdAt) ?? 0;
770
+ if (left !== right) return left - right;
771
+ const idA = typeof a?.nodeId === 'string' ? a.nodeId : '';
772
+ const idB = typeof b?.nodeId === 'string' ? b.nodeId : '';
773
+ return idA < idB ? -1 : idA > idB ? 1 : 0;
774
+ }
775
+
776
+ function isDigest(value) {
777
+ return typeof value === 'string' && SHA256_DIGEST_RE.test(value);
778
+ }
779
+
780
+ function finiteNumber(value) {
781
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
782
+ }
783
+
784
+ function isObject(value) {
785
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
786
+ }