dsh-taskbridge 1.8.1 → 1.9.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 (40) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +139 -121
  3. package/antigravity/agents/dsh-taskbridge.md +14 -12
  4. package/antigravity/skills/dsh-taskbridge/SKILL.md +32 -19
  5. package/bin/dsh-delegate-codex-agent.js +9 -4
  6. package/codex/skills/dsh-taskbridge/SKILL.md +131 -0
  7. package/codex/skills/dsh-taskbridge/rules-reference-96027c387cb9b7587efa4aa3836235d86db1108068e007dc08196e807ca25e5d.md +114 -0
  8. package/docs/INTRODUCTION.md +94 -68
  9. package/docs/INTRODUCTION.zh.md +94 -77
  10. package/docs/antigravity-integration.md +6 -1
  11. package/docs/assets/taskbridge-workflow.en.svg +72 -0
  12. package/docs/assets/taskbridge-workflow.zh.png +0 -0
  13. package/docs/claude-code.md +5 -5
  14. package/docs/codex-integration.md +1102 -1076
  15. package/docs/releases/1.9.0.zh.md +31 -0
  16. package/docs/releases/1.9.1.zh.md +14 -0
  17. package/docs/runtime-compatibility.md +7 -9
  18. package/docs/silent-wait.md +17 -26
  19. package/docs/taskbridge-upgrade.md +4 -4
  20. package/lib/client.d.ts +2 -2
  21. package/lib/client.js +7 -7
  22. package/locale/en.json +1 -1
  23. package/locale/zh.json +1 -1
  24. package/package.json +157 -150
  25. package/src/antigravity/installer.js +33 -2
  26. package/src/client/api.js +139 -17
  27. package/src/client/index.jsx +20 -19
  28. package/src/codex/agent-ownership.js +72 -12
  29. package/src/codex/installer.js +4613 -4190
  30. package/src/http/execution-plane.js +17 -0
  31. package/src/http/user-plane.js +6 -0
  32. package/src/index.d.ts +9 -1
  33. package/src/index.js +86 -64
  34. package/src/jobs/engine.js +278 -5
  35. package/src/jobs/history.js +17 -1
  36. package/src/jobs/record-cleanup.js +76 -2
  37. package/src/mcp/server.js +241 -12
  38. package/src/runtime/permissions.js +18 -0
  39. package/src/runtime/worker-prompt.js +13 -9
  40. package/codex/dsh-taskbridge.toml +0 -181
@@ -612,6 +612,25 @@ export class JobEngine {
612
612
  });
613
613
  }
614
614
  const continueFromTaskId = typeof rawContinuation === 'string' ? rawContinuation.trim() : '';
615
+ const rawReuseWorktree = request?.reuseWorktreeFromTaskId;
616
+ if (rawReuseWorktree !== undefined && rawReuseWorktree !== null && typeof rawReuseWorktree !== 'string') {
617
+ throw new JobError(JOB_CODES.isolationRefused, 'reuseWorktreeFromTaskId must be a task id string', {
618
+ field: 'reuseWorktreeFromTaskId',
619
+ requestedType: typeof rawReuseWorktree,
620
+ });
621
+ }
622
+ const reuseWorktreeFromTaskId = typeof rawReuseWorktree === 'string' ? rawReuseWorktree.trim() : '';
623
+ if (continueFromTaskId !== '' && reuseWorktreeFromTaskId !== '') {
624
+ throw new JobError(
625
+ JOB_CODES.isolationRefused,
626
+ 'continueFromTaskId and reuseWorktreeFromTaskId cannot be combined; continueFromTaskId already reuses the parent worktree',
627
+ {
628
+ continueFromTaskId,
629
+ reuseWorktreeFromTaskId,
630
+ cause: 'WORKTREE_REUSE_CONFLICT',
631
+ },
632
+ );
633
+ }
615
634
  const rawPlanNodeId = request?.planNodeId;
616
635
  if (rawPlanNodeId !== undefined && typeof rawPlanNodeId !== 'string') {
617
636
  throw new JobError(JOB_CODES.planRefInvalid, 'planNodeId must be a string', {
@@ -629,6 +648,7 @@ export class JobEngine {
629
648
  }
630
649
  const parentNodeId = typeof rawParentNodeId === 'string' ? rawParentNodeId.trim() : '';
631
650
  this.assertRecordNotBeingRemoved(continueFromTaskId);
651
+ this.assertRecordNotBeingRemoved(reuseWorktreeFromTaskId);
632
652
  this.assertRecordNotBeingRemoved(parentNodeId);
633
653
  const goal = canonicalTaskDescription(request?.goalDescription, TASK_DESCRIPTION_FIELDS.goal, redactText);
634
654
  if (goal.ok === false) {
@@ -648,6 +668,7 @@ export class JobEngine {
648
668
  // Frozen before the first await so the task record states, from the moment it
649
669
  // exists, whether it starts a conversation or continues one.
650
670
  task.continueFromTaskId = continueFromTaskId === '' ? null : continueFromTaskId;
671
+ task.reuseWorktreeFromTaskId = reuseWorktreeFromTaskId === '' ? null : reuseWorktreeFromTaskId;
651
672
  task.planNodeId = planNodeId === '' ? null : planNodeId;
652
673
  task.parentNodeId = parentNodeId === '' ? null : parentNodeId;
653
674
  task.goalDescription = goal.value;
@@ -696,6 +717,7 @@ export class JobEngine {
696
717
  // conversation. Frozen at creation: it is what the run does with its session,
697
718
  // and it must not be re-read after the first await.
698
719
  continueFromTaskId: null,
720
+ reuseWorktreeFromTaskId: null,
699
721
  planNodeId: null,
700
722
  parentNodeId: null,
701
723
  goalDescription: null,
@@ -738,6 +760,8 @@ export class JobEngine {
738
760
  // execution path and conversation, never the internal parent object.
739
761
  continuationParent: null,
740
762
  continuationRecord: null,
763
+ continuationParentUsage: null,
764
+ reuseWorktreeRecord: null,
741
765
  // The parent's Agent Teams facts (`teamFactsOf`), read once during continuation
742
766
  // admission from the same documents whose ownership was just proven. Admission's
743
767
  // effective step decides what may be inherited from them; nothing re-reads history
@@ -891,6 +915,11 @@ export class JobEngine {
891
915
  await this.assertPlanHierarchy(task, sourcePath);
892
916
  this.assertLive(task, 'plan-hierarchy');
893
917
  }
918
+ if (task.reuseWorktreeFromTaskId !== null) {
919
+ task.phase = 'worktree-reuse';
920
+ await this.assertWorktreeReuse(task, sourcePath);
921
+ this.assertLive(task, 'worktree-reuse');
922
+ }
894
923
 
895
924
  // ---- 3. one immutable settings snapshot ----------------------------------
896
925
  task.phase = 'settings';
@@ -947,6 +976,15 @@ export class JobEngine {
947
976
  overrides.agentTeams = inheritedTeam.value;
948
977
  teamChoiceOrigin = 'continuation';
949
978
  }
979
+ } else if (task.reuseWorktreeRecord !== null) {
980
+ if (overrides.isolation !== undefined && overrides.isolation !== 'worktree') {
981
+ throw new JobError(JOB_CODES.isolationRefused, 'reuseWorktreeFromTaskId requires worktree isolation', {
982
+ reuseWorktreeFromTaskId: task.reuseWorktreeFromTaskId,
983
+ requestedIsolation: overrides.isolation,
984
+ cause: 'WORKTREE_REUSE_ISOLATION_CONFLICT',
985
+ });
986
+ }
987
+ overrides.isolation = 'worktree';
950
988
  }
951
989
  // The operator's NEW-TASK default fills an absent choice for a NEW task only.
952
990
  //
@@ -1077,9 +1115,11 @@ export class JobEngine {
1077
1115
  const prepared = await this.guardPreflight(
1078
1116
  task,
1079
1117
  'worktree',
1080
- () => this.withPreparationTurn(task, () => (task.continuationRecord === null
1081
- ? this.prepareWorktree(task)
1082
- : this.reuseContinuationWorktree(task))),
1118
+ () => this.withPreparationTurn(task, () => (task.continuationRecord !== null
1119
+ ? this.reuseContinuationWorktree(task)
1120
+ : (task.reuseWorktreeRecord !== null
1121
+ ? this.reuseTaskWorktree(task)
1122
+ : this.prepareWorktree(task)))),
1083
1123
  {
1084
1124
  // A tree that finished after this start was abandoned still exists on
1085
1125
  // disk. It is recorded and marked complete, never deleted or merged: it
@@ -1089,7 +1129,7 @@ export class JobEngine {
1089
1129
  );
1090
1130
  task.worktree = prepared;
1091
1131
  task.executionPath = prepared.workspacePath;
1092
- task.reusedWorktree = task.continuationRecord !== null;
1132
+ task.reusedWorktree = task.continuationRecord !== null || task.reuseWorktreeRecord !== null;
1093
1133
  this.assertLive(task, 'worktree');
1094
1134
  if (!task.leases.some((lease) => lease.mode === LOCK_MODES.exclusive && samePath(lease.path, task.executionPath))) {
1095
1135
  // A follow-up drives the directory its parent ran in, so this keeps two
@@ -2073,8 +2113,10 @@ export class JobEngine {
2073
2113
  // supplies its stored `team`/`agentTeamsOrigin`, and the identity map (read once,
2074
2114
  // below) supplies the chain's decision when an older row predates those fields.
2075
2115
  let durableTeamRecord = {};
2116
+ let parentUsage = null;
2076
2117
  if (parent !== null) {
2077
2118
  if (parent.connectionId !== caller) throw this.absentContinuation(parentId);
2119
+ parentUsage = parent.execution?.usage ?? null;
2078
2120
  row = {
2079
2121
  state: parent.state,
2080
2122
  sourcePath: parent.sourcePath,
@@ -2091,6 +2133,7 @@ export class JobEngine {
2091
2133
  } else {
2092
2134
  const durable = await this.durableParent(task, parentId, caller);
2093
2135
  if (durable === null) throw this.absentContinuation(parentId);
2136
+ parentUsage = durable.execution?.usage ?? null;
2094
2137
  row = {
2095
2138
  state: durable.state ?? null,
2096
2139
  sourcePath: durable.sourcePath ?? null,
@@ -2147,6 +2190,7 @@ export class JobEngine {
2147
2190
  // isolation and worktree steps read to resume the parent instead of starting over.
2148
2191
  task.continuationParent = parent;
2149
2192
  task.continuationRecord = task.continuationIdentity;
2193
+ task.continuationParentUsage = parentUsage;
2150
2194
  // The parent's Agent Teams facts, taken from the same two documents that were just
2151
2195
  // proven. Admission reads them once here, so a later step never re-reads history or
2152
2196
  // the identity map for a decision it must not re-derive.
@@ -2596,6 +2640,153 @@ export class JobEngine {
2596
2640
  return { ...tree, workspacePath, reused: true };
2597
2641
  }
2598
2642
 
2643
+ /**
2644
+ * Prove that this caller owns the upstream isolated task named by
2645
+ * `reuseWorktreeFromTaskId`, and that its managed worktree may be reused by a
2646
+ * new independent subtask (with its own fresh DSH Session) under the same
2647
+ * source repository.
2648
+ * @param {object} task - pending record with `reuseWorktreeFromTaskId`.
2649
+ * @param {string} sourcePath - resolved source repository path.
2650
+ * @returns {Promise<void>} resolves when the worktree reuse is admitted.
2651
+ */
2652
+ async assertWorktreeReuse(task, sourcePath) {
2653
+ const sourceTaskId = task.reuseWorktreeFromTaskId;
2654
+ const caller = typeof task.connectionId === 'string' && task.connectionId !== '' ? task.connectionId : null;
2655
+ if (caller === null) throw this.absentContinuation(sourceTaskId);
2656
+ const refuse = (message, cause, extra = {}) => new JobError(JOB_CODES.isolationRefused, message, redactDeep({
2657
+ reuseWorktreeFromTaskId: sourceTaskId,
2658
+ requested: 'worktree',
2659
+ cause,
2660
+ ...extra,
2661
+ }));
2662
+
2663
+ const parent = this.tasks.get(sourceTaskId) ?? null;
2664
+ let row;
2665
+ if (parent !== null) {
2666
+ if (parent.connectionId !== caller) throw this.absentContinuation(sourceTaskId);
2667
+ row = {
2668
+ state: parent.state,
2669
+ sourcePath: parent.sourcePath,
2670
+ sourcePathDigest: pathDigest(parent.sourcePath),
2671
+ executionWorkspacePath: parent.executionPath,
2672
+ executionPathDigest: pathDigest(parent.executionPath),
2673
+ isolation: parent.effective?.worker?.isolation ?? null,
2674
+ worktreeId: parent.worktree?.taskId ?? parent.taskId,
2675
+ worktreeState: parent.worktree?.state ?? null,
2676
+ };
2677
+ } else {
2678
+ const durable = await this.durableParent(task, sourceTaskId, caller);
2679
+ if (durable === null) throw this.absentContinuation(sourceTaskId);
2680
+ let storedIdentity = null;
2681
+ const store = this.deps?.sessionStore ?? null;
2682
+ if (store !== null && typeof store.get === 'function') {
2683
+ try {
2684
+ storedIdentity = await this.guardPreflight(task, 'worktree-reuse-identity', () => store.get(sourceTaskId));
2685
+ } catch (error) {
2686
+ if (error instanceof JobError) throw error;
2687
+ storedIdentity = null;
2688
+ }
2689
+ }
2690
+ row = {
2691
+ state: durable.state ?? null,
2692
+ sourcePath: storedIdentity?.sourcePath ?? durable.sourcePath ?? null,
2693
+ sourcePathDigest: storedIdentity?.sourcePathDigest ?? durable.sourcePathDigest ?? null,
2694
+ executionWorkspacePath: storedIdentity?.executionPath ?? durable.executionWorkspacePath ?? null,
2695
+ executionPathDigest: storedIdentity?.executionPathDigest ?? durable.executionPathDigest ?? null,
2696
+ isolation: durable.isolation ?? storedIdentity?.isolation ?? null,
2697
+ worktreeId: storedIdentity?.worktreeId ?? durable.worktree?.taskId ?? sourceTaskId,
2698
+ worktreeState: storedIdentity?.worktreeState ?? durable.worktree?.state ?? null,
2699
+ };
2700
+ }
2701
+
2702
+ if (row.state !== TASK_STATES.awaitingHostReview) {
2703
+ const message = row.state === TASK_STATES.pending || row.state === TASK_STATES.running
2704
+ ? 'the named upstream task is still running, so its worktree cannot be reused yet'
2705
+ : 'the named upstream task did not finish in awaiting-host-review, so its worktree cannot be reused';
2706
+ throw refuse(message, 'WORKTREE_REUSE_STATE_INVALID', { upstreamState: row.state ?? null });
2707
+ }
2708
+ if (row.isolation !== 'worktree') {
2709
+ throw refuse('the named upstream task did not use a managed worktree', 'WORKTREE_REUSE_NOT_ISOLATED', {
2710
+ upstreamIsolation: row.isolation ?? null,
2711
+ });
2712
+ }
2713
+ if (!recordedDirectoryIs({ path: row.sourcePath, digest: row.sourcePathDigest }, sourcePath)) {
2714
+ throw refuse('the named upstream task belongs to another source repository', 'WORKTREE_REUSE_SOURCE_MISMATCH');
2715
+ }
2716
+ if (typeof row.executionWorkspacePath !== 'string' || row.executionWorkspacePath.trim() === ''
2717
+ || recordedPathIsMasked(row.executionWorkspacePath)) {
2718
+ throw refuse('the named upstream task has no usable worktree path to reuse', 'WORKTREE_REUSE_PATH_UNAVAILABLE');
2719
+ }
2720
+
2721
+ task.reuseWorktreeRecord = {
2722
+ taskId: sourceTaskId,
2723
+ sourcePath,
2724
+ executionPath: row.executionWorkspacePath,
2725
+ worktreeId: row.worktreeId ?? sourceTaskId,
2726
+ worktreeState: row.worktreeState ?? null,
2727
+ isolation: 'worktree',
2728
+ };
2729
+ }
2730
+
2731
+ /**
2732
+ * Resolve and validate the existing managed worktree named by
2733
+ * `reuseWorktreeFromTaskId` for a new independent subtask.
2734
+ * @param {object} task - pending task with `reuseWorktreeRecord`.
2735
+ * @returns {Promise<object>} the existing tree metadata.
2736
+ */
2737
+ async reuseTaskWorktree(task) {
2738
+ const identity = task.reuseWorktreeRecord;
2739
+ const manager = this.deps?.worktrees ?? null;
2740
+ const refuse = (message, cause) => new JobError(JOB_CODES.isolationRefused, message, {
2741
+ reuseWorktreeFromTaskId: task.reuseWorktreeFromTaskId,
2742
+ requested: 'worktree',
2743
+ cause,
2744
+ });
2745
+ if (identity?.isolation !== 'worktree') {
2746
+ throw refuse('the named upstream task did not use a managed worktree', 'WORKTREE_REUSE_NOT_ISOLATED');
2747
+ }
2748
+ if (manager === null || typeof manager.get !== 'function') {
2749
+ throw refuse('the managed worktree service is unavailable, so the upstream tree cannot be reused', 'WORKTREE_SERVICE_UNAVAILABLE');
2750
+ }
2751
+ const expectedTreeId = identity.worktreeId ?? identity.taskId;
2752
+ let tree;
2753
+ try {
2754
+ tree = manager.get(identity.executionPath);
2755
+ if (tree === null && typeof manager.recover === 'function') {
2756
+ tree = await manager.recover({
2757
+ taskId: expectedTreeId,
2758
+ sourcePath: identity.sourcePath,
2759
+ workspacePath: identity.executionPath,
2760
+ state: identity.worktreeState,
2761
+ signal: task.controller.signal,
2762
+ });
2763
+ }
2764
+ } catch (error) {
2765
+ throw refuse('the managed worktree service refused to report the upstream tree', typeof error?.code === 'string' ? error.code : 'WORKTREE_REGISTRY_FAILED');
2766
+ }
2767
+ if (tree === null || typeof tree !== 'object') {
2768
+ throw refuse('the upstream worktree is no longer registered; a new tree will not be substituted', 'WORKTREE_REUSE_ABSENT');
2769
+ }
2770
+ if (!samePath(tree.workspacePath, identity.executionPath)
2771
+ || !samePath(tree.sourcePath, identity.sourcePath)
2772
+ || (typeof expectedTreeId === 'string' && expectedTreeId !== '' && tree.taskId !== expectedTreeId)
2773
+ || tree.state === 'disposed'
2774
+ || tree.isolated !== true
2775
+ || tree.detached !== true) {
2776
+ throw refuse('the registered worktree does not match the upstream task', 'WORKTREE_REUSE_MISMATCH');
2777
+ }
2778
+ let workspacePath;
2779
+ try {
2780
+ workspacePath = await resolveWorkspacePath(identity.executionPath);
2781
+ } catch {
2782
+ throw refuse('the upstream worktree path is no longer available', 'WORKTREE_REUSE_PATH_UNAVAILABLE');
2783
+ }
2784
+ if (!samePath(workspacePath, identity.executionPath)) {
2785
+ throw refuse('the upstream worktree path resolves to a different directory', 'WORKTREE_REUSE_PATH_MISMATCH');
2786
+ }
2787
+ return { ...tree, workspacePath, reused: true, reusedFromTaskId: task.reuseWorktreeFromTaskId };
2788
+ }
2789
+
2599
2790
  /**
2600
2791
  * Decide whether a named task thread may be joined, from the live facts of one parent.
2601
2792
  *
@@ -3059,6 +3250,7 @@ export class JobEngine {
3059
3250
  decision: request?.decision,
3060
3251
  reason: request?.reason,
3061
3252
  ...(request?.fingerprint === undefined ? {} : { fingerprint: request.fingerprint }),
3253
+ ...(request?.scope === undefined ? {} : { scope: request.scope }),
3062
3254
  });
3063
3255
  } catch (error) {
3064
3256
  if (error instanceof PermissionError) {
@@ -3960,12 +4152,13 @@ export class JobEngine {
3960
4152
  task.native.settled = true;
3961
4153
  }
3962
4154
 
4155
+ const usage = enrichUsageReceipt(run.usage, task.continuationParentUsage);
3963
4156
  task.execution = {
3964
4157
  workspacePath: task.executionPath,
3965
4158
  outcome: run.outcome,
3966
4159
  text: run.text,
3967
4160
  reasoningOnly: run.reasoningOnly,
3968
- usage: run.usage,
4161
+ usage,
3969
4162
  turnEnd: run.turnEnd,
3970
4163
  agentId: run.agentId,
3971
4164
  sessionId: run.sessionId,
@@ -5354,6 +5547,42 @@ export class JobEngine {
5354
5547
  return this.tasks.get(taskId)?.cleanupSettled === true;
5355
5548
  }
5356
5549
 
5550
+ /**
5551
+ * Managed worktree paths already claimed by live pending/running tasks that
5552
+ * have validated reuse/continuation admission but may not yet have switched
5553
+ * `executionPath` away from `sourcePath`.
5554
+ * @returns {string[]} claimed worktree paths.
5555
+ */
5556
+ reservedWorktreePathsForCleanup() {
5557
+ const paths = [];
5558
+ for (const task of this.tasks.values()) {
5559
+ if (task.state !== TASK_STATES.pending && task.state !== TASK_STATES.running) continue;
5560
+ const claimed = task.reuseWorktreeRecord?.executionPath ?? task.continuationRecord?.executionPath ?? null;
5561
+ if (typeof claimed === 'string' && claimed.trim() !== '') paths.push(claimed);
5562
+ }
5563
+ return paths;
5564
+ }
5565
+
5566
+ /**
5567
+ * Session and workspace identities already claimed by live pending/running
5568
+ * continuation tasks that have passed admission lookup but may not yet have
5569
+ * recorded `execution`.
5570
+ * @returns {{ sessionIds: string[], workspaceIds: string[] }} claimed identities.
5571
+ */
5572
+ reservedContinuationRefsForCleanup() {
5573
+ const sessionIds = [];
5574
+ const workspaceIds = [];
5575
+ for (const task of this.tasks.values()) {
5576
+ if (task.state !== TASK_STATES.pending && task.state !== TASK_STATES.running) continue;
5577
+ const cont = task.continuationRecord;
5578
+ if (cont !== null && typeof cont === 'object') {
5579
+ if (typeof cont.sessionId === 'string' && cont.sessionId.trim() !== '') sessionIds.push(cont.sessionId.trim());
5580
+ if (typeof cont.workspaceId === 'string' && cont.workspaceId.trim() !== '') workspaceIds.push(cont.workspaceId.trim());
5581
+ }
5582
+ }
5583
+ return { sessionIds, workspaceIds };
5584
+ }
5585
+
5357
5586
  // Hold these ids between the final check and the removal from disk and memory.
5358
5587
  reserveCleanupIds(taskIds) {
5359
5588
  for (const id of taskIds) this.cleanupIds.add(id);
@@ -5477,6 +5706,9 @@ export class JobEngine {
5477
5706
  // Frozen on the task at creation, so the record states the intent even when
5478
5707
  // the run never got as far as driving a conversation.
5479
5708
  continueFromTaskId: task.continueFromTaskId ?? null,
5709
+ ...(typeof task.reuseWorktreeFromTaskId === 'string' && task.reuseWorktreeFromTaskId !== ''
5710
+ ? { reuseWorktreeFromTaskId: task.reuseWorktreeFromTaskId }
5711
+ : {}),
5480
5712
  ...(typeof task.planNodeId === 'string' && task.planNodeId !== ''
5481
5713
  ? { planNodeId: task.planNodeId }
5482
5714
  : {}),
@@ -5925,3 +6157,44 @@ function summarizedTeam(team) {
5925
6157
  reason: typeof team.reason === 'string' ? diagnostic(team.reason, 200) : null,
5926
6158
  };
5927
6159
  }
6160
+
6161
+ /**
6162
+ * Attach bounded `delta` and `cumulative` token counter blocks to a worker usage receipt
6163
+ * while keeping the original top-level counters intact for backward compatibility.
6164
+ * @param {object | null | undefined} rawUsage - current run usage.
6165
+ * @param {object | null | undefined} previousUsage - parent run usage on a continuation, or null.
6166
+ * @returns {object | null} enriched usage receipt, or null when absent.
6167
+ */
6168
+ function enrichUsageReceipt(rawUsage, previousUsage = null) {
6169
+ if (rawUsage === null || rawUsage === undefined || typeof rawUsage !== 'object') return rawUsage ?? null;
6170
+ const counter = (value) => (typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null);
6171
+ const current = {
6172
+ inputTokens: counter(rawUsage.inputTokens),
6173
+ outputTokens: counter(rawUsage.outputTokens),
6174
+ totalTokens: counter(rawUsage.totalTokens),
6175
+ reasoningTokens: counter(rawUsage.reasoningTokens),
6176
+ };
6177
+ const prevSource = previousUsage && typeof previousUsage === 'object'
6178
+ ? (previousUsage.cumulative && typeof previousUsage.cumulative === 'object' ? previousUsage.cumulative : previousUsage)
6179
+ : null;
6180
+ const deltaOf = (key) => {
6181
+ const cur = current[key];
6182
+ if (cur === null) return null;
6183
+ if (prevSource === null) return cur;
6184
+ const prev = counter(prevSource[key]);
6185
+ if (prev === null) return cur;
6186
+ return cur >= prev ? cur - prev : cur;
6187
+ };
6188
+ const delta = {
6189
+ inputTokens: deltaOf('inputTokens'),
6190
+ outputTokens: deltaOf('outputTokens'),
6191
+ totalTokens: deltaOf('totalTokens'),
6192
+ reasoningTokens: deltaOf('reasoningTokens'),
6193
+ };
6194
+ const cumulative = { ...current };
6195
+ return {
6196
+ ...current,
6197
+ delta,
6198
+ cumulative,
6199
+ };
6200
+ }
@@ -749,6 +749,7 @@ function projectView(view, maxEntryBytes, options = {}) {
749
749
  // Both are omitted when absent, so a load does not rewrite a document to add the new keys.
750
750
  const title = titleText(view.title, ctx);
751
751
  const continueFrom = continuationRef(view.continueFromTaskId, taskId);
752
+ const reuseWorktreeFrom = continuationRef(view.reuseWorktreeFromTaskId, taskId);
752
753
  const planNodeId = continuationRef(view.planNodeId, taskId);
753
754
  const parentNodeId = continuationRef(view.parentNodeId, taskId);
754
755
  const goalDescription = descriptionText(
@@ -759,6 +760,7 @@ function projectView(view, maxEntryBytes, options = {}) {
759
760
  state: view.state,
760
761
  ...(title === '' ? {} : { title }),
761
762
  ...(continueFrom === null ? {} : { continueFromTaskId: continueFrom }),
763
+ ...(reuseWorktreeFrom === null ? {} : { reuseWorktreeFromTaskId: reuseWorktreeFrom }),
762
764
  ...(planNodeId === null ? {} : { planNodeId }),
763
765
  ...(parentNodeId === null ? {} : { parentNodeId }),
764
766
  // Only present when the commander stated a goal: nothing is derived from the prompt.
@@ -969,6 +971,10 @@ function worktreeView(value) {
969
971
  completedAt: time(value.completedAt),
970
972
  sourcePreexistingChanges: count(value.sourcePreexistingChanges),
971
973
  disposable: value.disposable === true,
974
+ ...(value.reused === true ? { reused: true } : {}),
975
+ ...(typeof value.reusedFromTaskId === 'string' && value.reusedFromTaskId.trim() !== ''
976
+ ? { reusedFromTaskId: label(value.reusedFromTaskId) }
977
+ : {}),
972
978
  };
973
979
  }
974
980
 
@@ -1083,7 +1089,7 @@ function conversationView(value) {
1083
1089
  * @returns {object | null} usage counters. Only finite non-negative numbers are
1084
1090
  * kept; `redactDeep` masks any counter-named field that is not one.
1085
1091
  */
1086
- function usageView(value) {
1092
+ function usageCounters(value) {
1087
1093
  if (!isPlainObject(value)) return null;
1088
1094
  const out = {};
1089
1095
  for (const key of [
@@ -1097,6 +1103,16 @@ function usageView(value) {
1097
1103
  return Object.keys(out).length === 0 ? null : out;
1098
1104
  }
1099
1105
 
1106
+ function usageView(value) {
1107
+ const out = usageCounters(value);
1108
+ if (out === null) return null;
1109
+ const delta = usageCounters(value.delta);
1110
+ if (delta !== null) setOwn(out, 'delta', delta);
1111
+ const cumulative = usageCounters(value.cumulative);
1112
+ if (cumulative !== null) setOwn(out, 'cumulative', cumulative);
1113
+ return out;
1114
+ }
1115
+
1100
1116
  /** @returns {object | null} bounded result from a legacy model review. */
1101
1117
  function reviewView(value, ctx) {
1102
1118
  if (!isPlainObject(value)) return null;
@@ -97,6 +97,7 @@ function cleanupContext(engine, archived, plans) {
97
97
  const tasks = new Map([...archivedById, ...liveById]);
98
98
  const continuations = new Map();
99
99
  const taskChildren = new Map();
100
+ const liveReuseChildren = new Map();
100
101
  const planParents = new Set(plans.map((node) => node.parentNodeId));
101
102
  const remember = (map, parent, child) => {
102
103
  if (typeof parent !== 'string' || parent === '' || parent === child) return;
@@ -108,10 +109,15 @@ function cleanupContext(engine, archived, plans) {
108
109
  remember(taskChildren, row.parentNodeId, row.taskId);
109
110
  remember(taskChildren, row.planNodeId, row.taskId);
110
111
  }
112
+ for (const row of tasks.values()) {
113
+ if (!FINISHED.has(row.state)) {
114
+ remember(liveReuseChildren, row.reuseWorktreeFromTaskId, row.taskId);
115
+ }
116
+ }
111
117
  const tree = buildTaskTree({ planNodes: plans, tasks: [...tasks.values()] });
112
118
  const byChain = new Map();
113
119
  for (const root of tree.roots) collectChains(root, byChain);
114
- return { byChain, liveById, archivedById, continuations, taskChildren, planParents, engine };
120
+ return { byChain, liveById, archivedById, continuations, taskChildren, liveReuseChildren, planParents, engine };
115
121
  }
116
122
 
117
123
  function blockersFor(chain, context) {
@@ -132,6 +138,9 @@ function blockersFor(chain, context) {
132
138
  for (const child of context.taskChildren.get(taskId) ?? []) {
133
139
  if (!members.has(child)) blockers.add(CLEANUP_CODES.hierarchyChildren);
134
140
  }
141
+ for (const child of context.liveReuseChildren.get(taskId) ?? []) {
142
+ if (!members.has(child)) blockers.add(CLEANUP_CODES.hierarchyChildren);
143
+ }
135
144
  if (context.planParents.has(taskId)) blockers.add(CLEANUP_CODES.planChildren);
136
145
  }
137
146
  return [...blockers];
@@ -348,6 +357,44 @@ async function tryDeleteHostWorkspace(deps, workspaceId) {
348
357
  return false;
349
358
  }
350
359
 
360
+ function collectReservedReuseRefs(rows, knownRowsById, sessionByTask, engine) {
361
+ const paths = [];
362
+ const sessionIds = [];
363
+ const workspaceIds = [];
364
+ const upstreamTaskIds = new Set();
365
+ if (typeof engine?.reservedWorktreePathsForCleanup === 'function') {
366
+ for (const candidate of engine.reservedWorktreePathsForCleanup()) {
367
+ if (typeof candidate === 'string' && candidate.trim() !== '') paths.push(candidate.trim());
368
+ }
369
+ }
370
+ if (typeof engine?.reservedContinuationRefsForCleanup === 'function') {
371
+ const refs = engine.reservedContinuationRefsForCleanup();
372
+ for (const id of Array.isArray(refs?.sessionIds) ? refs.sessionIds : []) {
373
+ if (typeof id === 'string' && id.trim() !== '') sessionIds.push(id.trim());
374
+ }
375
+ for (const id of Array.isArray(refs?.workspaceIds) ? refs.workspaceIds : []) {
376
+ if (typeof id === 'string' && id.trim() !== '') workspaceIds.push(id.trim());
377
+ }
378
+ }
379
+ for (const row of rows) {
380
+ if (FINISHED.has(row?.state)) continue;
381
+ const reuseId = firstNonEmpty(row?.reuseWorktreeFromTaskId);
382
+ const contId = firstNonEmpty(row?.continueFromTaskId);
383
+ const upstreamId = firstNonEmpty(reuseId, contId);
384
+ if (upstreamId === null) continue;
385
+ upstreamTaskIds.add(upstreamId);
386
+ const upstreamFacts = extractTaskFacts(knownRowsById.get(upstreamId) ?? null, sessionByTask.get(upstreamId) ?? null);
387
+ if (upstreamFacts.executionPath !== null) {
388
+ const execKey = sessionPathKey(upstreamFacts.executionPath);
389
+ const sourceKey = sessionPathKey(upstreamFacts.sourcePath);
390
+ if (execKey !== null && execKey !== sourceKey) paths.push(upstreamFacts.executionPath);
391
+ }
392
+ if (upstreamFacts.workspaceId !== null) workspaceIds.push(upstreamFacts.workspaceId);
393
+ if (contId !== null && upstreamFacts.sessionId !== null) sessionIds.push(upstreamFacts.sessionId);
394
+ }
395
+ return { paths, sessionIds, workspaceIds, upstreamTaskIds };
396
+ }
397
+
351
398
  async function performLinkedCleanup(deps, { options, deletedTaskIds, deletedRows, remainingRows, plans }) {
352
399
  const deletedSet = new Set(deletedTaskIds);
353
400
  let sessionRows = [];
@@ -359,6 +406,11 @@ async function performLinkedCleanup(deps, { options, deletedTaskIds, deletedRows
359
406
  }
360
407
  }
361
408
  const sessionByTask = new Map(sessionRows.map((row) => [row.taskId, row]));
409
+ const knownRowsById = new Map(
410
+ [...deletedRows, ...remainingRows]
411
+ .filter((row) => typeof row?.taskId === 'string' && row.taskId !== '')
412
+ .map((row) => [row.taskId, row]),
413
+ );
362
414
 
363
415
  const activeSessionIds = new Set();
364
416
  const activeWorkspaceIds = new Set();
@@ -370,6 +422,13 @@ async function performLinkedCleanup(deps, { options, deletedTaskIds, deletedRows
370
422
  const execKey = sessionPathKey(facts.executionPath);
371
423
  if (execKey !== null) activeExecKeys.add(execKey);
372
424
  }
425
+ const reservedLinked = collectReservedReuseRefs(remainingRows, knownRowsById, sessionByTask, deps?.engine);
426
+ for (const sid of reservedLinked.sessionIds) activeSessionIds.add(sid);
427
+ for (const wid of reservedLinked.workspaceIds) activeWorkspaceIds.add(wid);
428
+ for (const reservedPath of reservedLinked.paths) {
429
+ const reservedKey = sessionPathKey(reservedPath);
430
+ if (reservedKey !== null) activeExecKeys.add(reservedKey);
431
+ }
373
432
 
374
433
  const deletedFacts = deletedTaskIds.map((taskId) => {
375
434
  const row = deletedRows.find((item) => item?.taskId === taskId) ?? { taskId };
@@ -527,6 +586,11 @@ export async function runOrphanCleanup(deps, body) {
527
586
  const activeExecPaths = [];
528
587
  const knownSourcePaths = new Set();
529
588
 
589
+ const knownRowsById = new Map(
590
+ allExisting
591
+ .filter((row) => typeof row?.taskId === 'string' && row.taskId !== '')
592
+ .map((row) => [row.taskId, row]),
593
+ );
530
594
  for (const row of allExisting) {
531
595
  const facts = extractTaskFacts(row, sessionByTask.get(row.taskId));
532
596
  if (facts.sessionId !== null) activeSessionIds.add(facts.sessionId);
@@ -538,8 +602,18 @@ export async function runOrphanCleanup(deps, body) {
538
602
  if (key !== null) activeExecKeys.add(key);
539
603
  }
540
604
  }
605
+ const reservedOrphan = collectReservedReuseRefs(allExisting, knownRowsById, sessionByTask, deps?.engine);
606
+ for (const sid of reservedOrphan.sessionIds) activeSessionIds.add(sid);
607
+ for (const wid of reservedOrphan.workspaceIds) activeWorkspaceIds.add(wid);
608
+ for (const reservedPath of reservedOrphan.paths) {
609
+ activeExecPaths.push(reservedPath);
610
+ const key = sessionPathKey(reservedPath);
611
+ if (key !== null) activeExecKeys.add(key);
612
+ }
541
613
 
542
- const orphanRows = sessionRows.filter((row) => typeof row?.taskId === 'string' && !existingTaskIds.has(row.taskId));
614
+ const orphanRows = sessionRows.filter(
615
+ (row) => typeof row?.taskId === 'string' && !existingTaskIds.has(row.taskId) && !reservedOrphan.upstreamTaskIds.has(row.taskId),
616
+ );
543
617
  const orphanTaskIds = orphanRows.map((row) => row.taskId);
544
618
 
545
619
  const archivedSessionIds = [];