@stigmer/runner 3.1.2 → 3.1.4

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 (127) hide show
  1. package/dist/.build-fingerprint +1 -1
  2. package/dist/activities/execute-cursor/attachment-resolver.d.ts +1 -1
  3. package/dist/activities/execute-cursor/attachment-resolver.js +1 -1
  4. package/dist/activities/execute-cursor/capture-flow.d.ts +29 -0
  5. package/dist/activities/execute-cursor/capture-flow.js +59 -0
  6. package/dist/activities/execute-cursor/capture-flow.js.map +1 -1
  7. package/dist/activities/execute-cursor/command-provenance.d.ts +11 -25
  8. package/dist/activities/execute-cursor/command-provenance.js +25 -115
  9. package/dist/activities/execute-cursor/command-provenance.js.map +1 -1
  10. package/dist/activities/execute-cursor/index.js +358 -557
  11. package/dist/activities/execute-cursor/index.js.map +1 -1
  12. package/dist/activities/execute-cursor/todo-tracker.d.ts +6 -1
  13. package/dist/activities/execute-cursor/todo-tracker.js +15 -43
  14. package/dist/activities/execute-cursor/todo-tracker.js.map +1 -1
  15. package/dist/activities/execute-cursor/turn-boundary.d.ts +108 -0
  16. package/dist/activities/execute-cursor/turn-boundary.js +163 -0
  17. package/dist/activities/execute-cursor/turn-boundary.js.map +1 -0
  18. package/dist/activities/execute-cursor/turn-stream.d.ts +141 -0
  19. package/dist/activities/execute-cursor/turn-stream.js +249 -0
  20. package/dist/activities/execute-cursor/turn-stream.js.map +1 -0
  21. package/dist/activities/execute-deep-agent/command-provenance.d.ts +61 -0
  22. package/dist/activities/execute-deep-agent/command-provenance.js +72 -0
  23. package/dist/activities/execute-deep-agent/command-provenance.js.map +1 -0
  24. package/dist/activities/execute-deep-agent/index.js +73 -4
  25. package/dist/activities/execute-deep-agent/index.js.map +1 -1
  26. package/dist/activities/execute-deep-agent/status-builder.js +8 -1
  27. package/dist/activities/execute-deep-agent/status-builder.js.map +1 -1
  28. package/dist/activities/execute-deep-agent/streaming-v3.js +6 -1
  29. package/dist/activities/execute-deep-agent/streaming-v3.js.map +1 -1
  30. package/dist/activities/execute-deep-agent/streaming.d.ts +7 -0
  31. package/dist/activities/execute-deep-agent/streaming.js +5 -1
  32. package/dist/activities/execute-deep-agent/streaming.js.map +1 -1
  33. package/dist/activities/execute-deep-agent/v3-status-builder.js +12 -1
  34. package/dist/activities/execute-deep-agent/v3-status-builder.js.map +1 -1
  35. package/dist/otel.js +10 -0
  36. package/dist/otel.js.map +1 -1
  37. package/dist/shared/filereview/capture.d.ts +18 -1
  38. package/dist/shared/filereview/capture.js +105 -28
  39. package/dist/shared/filereview/capture.js.map +1 -1
  40. package/dist/shared/filereview/cas-progress.d.ts +63 -0
  41. package/dist/shared/filereview/cas-progress.js +128 -0
  42. package/dist/shared/filereview/cas-progress.js.map +1 -0
  43. package/dist/shared/filereview/cas-substrate.d.ts +38 -0
  44. package/dist/shared/filereview/cas-substrate.js +48 -15
  45. package/dist/shared/filereview/cas-substrate.js.map +1 -1
  46. package/dist/shared/filereview/command-provenance.d.ts +93 -0
  47. package/dist/shared/filereview/command-provenance.js +132 -0
  48. package/dist/shared/filereview/command-provenance.js.map +1 -0
  49. package/dist/shared/filereview/events.d.ts +16 -0
  50. package/dist/shared/filereview/events.js +37 -0
  51. package/dist/shared/filereview/events.js.map +1 -1
  52. package/dist/shared/filereview/git-substrate.d.ts +48 -0
  53. package/dist/shared/filereview/git-substrate.js +78 -0
  54. package/dist/shared/filereview/git-substrate.js.map +1 -1
  55. package/dist/shared/filereview/index.d.ts +5 -2
  56. package/dist/shared/filereview/index.js +5 -2
  57. package/dist/shared/filereview/index.js.map +1 -1
  58. package/dist/shared/filereview/line-counts.d.ts +48 -0
  59. package/dist/shared/filereview/line-counts.js +72 -0
  60. package/dist/shared/filereview/line-counts.js.map +1 -0
  61. package/dist/shared/filereview/progress.d.ts +167 -0
  62. package/dist/shared/filereview/progress.js +196 -0
  63. package/dist/shared/filereview/progress.js.map +1 -0
  64. package/dist/shared/implement-plan-prompt.d.ts +6 -4
  65. package/dist/shared/implement-plan-prompt.js +38 -6
  66. package/dist/shared/implement-plan-prompt.js.map +1 -1
  67. package/dist/shared/plan-artifact.d.ts +59 -11
  68. package/dist/shared/plan-artifact.js +144 -16
  69. package/dist/shared/plan-artifact.js.map +1 -1
  70. package/dist/shared/plan-mode-prompt.d.ts +15 -4
  71. package/dist/shared/plan-mode-prompt.js +28 -5
  72. package/dist/shared/plan-mode-prompt.js.map +1 -1
  73. package/dist/shared/todos.d.ts +56 -0
  74. package/dist/shared/todos.js +98 -0
  75. package/dist/shared/todos.js.map +1 -0
  76. package/dist/shared/tool-row.d.ts +16 -0
  77. package/dist/shared/tool-row.js +31 -0
  78. package/dist/shared/tool-row.js.map +1 -1
  79. package/package.json +3 -2
  80. package/src/__tests__/otel-turn-span.test.ts +61 -0
  81. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +7 -0
  82. package/src/activities/execute-cursor/__tests__/delta-enricher.test.ts +68 -0
  83. package/src/activities/execute-cursor/__tests__/progress-substrate.test.ts +169 -0
  84. package/src/activities/execute-cursor/__tests__/turn-boundary.test.ts +280 -0
  85. package/src/activities/execute-cursor/__tests__/turn-stream.test.ts +349 -0
  86. package/src/activities/execute-cursor/attachment-resolver.ts +1 -1
  87. package/src/activities/execute-cursor/capture-flow.ts +78 -0
  88. package/src/activities/execute-cursor/command-provenance.ts +25 -120
  89. package/src/activities/execute-cursor/index.ts +419 -602
  90. package/src/activities/execute-cursor/todo-tracker.ts +17 -59
  91. package/src/activities/execute-cursor/turn-boundary.ts +274 -0
  92. package/src/activities/execute-cursor/turn-stream.ts +418 -0
  93. package/src/activities/execute-deep-agent/__tests__/command-provenance.test.ts +252 -0
  94. package/src/activities/execute-deep-agent/__tests__/prompt-builder.test.ts +11 -0
  95. package/src/activities/execute-deep-agent/__tests__/status-builder.test.ts +78 -0
  96. package/src/activities/execute-deep-agent/__tests__/v3-status-builder.test.ts +105 -1
  97. package/src/activities/execute-deep-agent/command-provenance.ts +102 -0
  98. package/src/activities/execute-deep-agent/index.ts +91 -4
  99. package/src/activities/execute-deep-agent/status-builder.ts +9 -0
  100. package/src/activities/execute-deep-agent/streaming-v3.ts +6 -1
  101. package/src/activities/execute-deep-agent/streaming.ts +12 -1
  102. package/src/activities/execute-deep-agent/v3-status-builder.ts +13 -0
  103. package/src/otel.ts +8 -0
  104. package/src/shared/__tests__/implement-plan-prompt.test.ts +40 -2
  105. package/src/shared/__tests__/plan-artifact.test.ts +142 -9
  106. package/src/shared/__tests__/todos.test.ts +216 -0
  107. package/src/shared/filereview/__tests__/capture.test.ts +182 -1
  108. package/src/shared/filereview/__tests__/cas-progress.test.ts +228 -0
  109. package/src/shared/filereview/__tests__/cas-substrate.test.ts +100 -0
  110. package/src/shared/filereview/__tests__/command-provenance.test.ts +252 -0
  111. package/src/shared/filereview/__tests__/events.test.ts +105 -0
  112. package/src/shared/filereview/__tests__/line-counts.test.ts +73 -0
  113. package/src/shared/filereview/__tests__/progress.test.ts +338 -0
  114. package/src/shared/filereview/capture.ts +134 -30
  115. package/src/shared/filereview/cas-progress.ts +170 -0
  116. package/src/shared/filereview/cas-substrate.ts +79 -18
  117. package/src/shared/filereview/command-provenance.ts +180 -0
  118. package/src/shared/filereview/events.ts +50 -0
  119. package/src/shared/filereview/git-substrate.ts +114 -0
  120. package/src/shared/filereview/index.ts +36 -1
  121. package/src/shared/filereview/line-counts.ts +83 -0
  122. package/src/shared/filereview/progress.ts +310 -0
  123. package/src/shared/implement-plan-prompt.ts +39 -8
  124. package/src/shared/plan-artifact.ts +152 -16
  125. package/src/shared/plan-mode-prompt.ts +28 -5
  126. package/src/shared/todos.ts +126 -0
  127. package/src/shared/tool-row.ts +34 -0
@@ -12,34 +12,22 @@
12
12
  * parallel extraction into the proto map that downstream consumers
13
13
  * (React TodoList, CLI emitTodoEvents) already know how to render.
14
14
  *
15
+ * The payload-to-map mapping lives in the harness-agnostic `applyTodoUpdate`
16
+ * (shared/todos.ts), shared with the native v2/v3 status builders so no two
17
+ * writers of `status.todos` can drift. This class owns only the Cursor-specific
18
+ * concerns: which events carry todos, parsing the SDK's args shape, and the
19
+ * dirty/force-flush signal.
20
+ *
15
21
  * Follows the same single-responsibility pattern as DeltaEnricher:
16
22
  * the orchestrator (execute-cursor.ts) wires it into the event loop.
17
23
  */
18
24
 
19
- import { create } from "@bufbuild/protobuf";
20
- import { TodoItemSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/todo_pb";
21
25
  import type { TodoItem } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/todo_pb";
22
- import { TodoStatus } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
23
26
  import type { SDKMessage } from "@cursor/sdk";
24
- import { utcTimestamp } from "./message-translator.js";
27
+ import { applyTodoUpdate } from "../../shared/todos.js";
25
28
 
26
29
  const TODO_TOOL_NAMES = new Set(["TodoWrite", "updateTodos"]);
27
30
 
28
- const STATUS_MAP: Record<string, TodoStatus> = {
29
- pending: TodoStatus.TODO_PENDING,
30
- in_progress: TodoStatus.TODO_IN_PROGRESS,
31
- inprogress: TodoStatus.TODO_IN_PROGRESS,
32
- completed: TodoStatus.TODO_COMPLETED,
33
- cancelled: TodoStatus.TODO_CANCELLED,
34
- };
35
-
36
- interface RawTodoItem {
37
- id?: string;
38
- content?: string;
39
- status?: string;
40
- created_at?: string;
41
- }
42
-
43
31
  export class TodoTracker {
44
32
  private readonly todos: { [key: string]: TodoItem };
45
33
  private _isDirty = false;
@@ -60,43 +48,19 @@ export class TodoTracker {
60
48
  const args = this.parseArgs(event.args);
61
49
  if (!args) return;
62
50
 
63
- const rawTodos = args.todos as RawTodoItem[] | undefined;
64
- if (!Array.isArray(rawTodos) || rawTodos.length === 0) {
65
- if (args.merge !== true) {
66
- this.clearMap();
67
- this._isDirty = true;
68
- }
69
- return;
70
- }
71
-
72
- const merge = args.merge === true;
73
- const now = utcTimestamp();
74
-
75
- if (!merge) {
76
- this.clearMap();
51
+ const changed = applyTodoUpdate(this.todos, args.todos, {
52
+ merge: args.merge === true,
53
+ });
54
+ if (changed) {
55
+ this._isDirty = true;
77
56
  }
78
57
 
79
- for (let i = 0; i < rawTodos.length; i++) {
80
- const raw = rawTodos[i];
81
- const id = raw.id || `todo-${i}`;
82
- const statusStr = (raw.status ?? "pending").toLowerCase();
83
- const status = STATUS_MAP[statusStr] ?? TodoStatus.TODO_PENDING;
84
-
85
- const existing = merge ? this.todos[id] : undefined;
86
-
87
- this.todos[id] = create(TodoItemSchema, {
88
- id,
89
- content: raw.content ?? "",
90
- status,
91
- createdAt: existing?.createdAt || raw.created_at || now,
92
- updatedAt: now,
93
- });
58
+ if (Array.isArray(args.todos) && args.todos.length > 0) {
59
+ console.log(
60
+ `TodoTracker: processed ${args.todos.length} todo(s) from ${event.name} ` +
61
+ `(merge=${args.merge === true})`,
62
+ );
94
63
  }
95
-
96
- this._isDirty = true;
97
- console.log(
98
- `TodoTracker: processed ${rawTodos.length} todo(s) from ${event.name} (merge=${merge})`,
99
- );
100
64
  }
101
65
 
102
66
  get isDirty(): boolean {
@@ -124,10 +88,4 @@ export class TodoTracker {
124
88
 
125
89
  return null;
126
90
  }
127
-
128
- private clearMap(): void {
129
- for (const key of Object.keys(this.todos)) {
130
- delete this.todos[key];
131
- }
132
- }
133
91
  }
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The Cursor harness's turn boundary — the single post-run pipeline that turns
3
+ * a finished agent run into the durable review surfaces:
4
+ *
5
+ * 1. read the denial ledger the preToolUse hook appended this turn;
6
+ * 2. derive the approved-command provenance (DD-28 auto-keep facts);
7
+ * 3. capture the turn's net file change set to the file_review ledger
8
+ * (CANDIDATE_CAPTURED) and stamp the flowed edit rows;
9
+ * 4. reconcile denied tool calls to WAITING_APPROVAL gate rows and redact the
10
+ * model's provisional post-denial narration.
11
+ *
12
+ * Extracted from the activity entry point (index.ts Phase 12) so it is directly
13
+ * unit-testable AND re-enterable: the poisoned-handle / transport-timeout
14
+ * recoveries re-run the agent with a fresh handle AFTER the primary boundary
15
+ * already ran, so their edits must flow through this exact pipeline again or
16
+ * they silently escape review (production case aex_01kws27q1e2esvkqjpvectttxf,
17
+ * where a Build-from-plan retry created a file with no review gate).
18
+ *
19
+ * Re-entry is safe by construction: a retry is only reachable when the primary
20
+ * boundary captured nothing (a captured change pauses the turn before
21
+ * run.wait() is ever consulted), `stampFlowedFileEditRows` skips already-stamped
22
+ * rows, and the denial ledger is per-turn append-only.
23
+ *
24
+ * The caller owns everything around the boundary: the stream epilogue
25
+ * (accumulator/enricher finalize), the WAITING_FOR_APPROVAL phase flip +
26
+ * persist, and the terminal result mapping.
27
+ */
28
+
29
+ import type { AgentExecutionStatus } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/api_pb";
30
+ import type { SubAgentExecution } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/subagent_pb";
31
+ import { collectSubAgentToolCallIds } from "../../shared/tool-row.js";
32
+ import { LocalWorkspaceBackend } from "../../shared/workspace/local-backend.js";
33
+ import type { ArtifactStorage } from "../../shared/artifact-storage.js";
34
+ import type { MergedToolPolicy } from "../../shared/approval-policy.js";
35
+ import { primaryToken, readDenialLedger, type ApprovalGrant } from "./approval-state.js";
36
+ import { deriveTurnCommandProvenance } from "./command-provenance.js";
37
+ import { captureTurnToLedger } from "./capture-flow.js";
38
+ import {
39
+ clearProvisionalPostDenialNarration,
40
+ reconcileDeniedToolCalls,
41
+ } from "./message-translator.js";
42
+
43
+ // How long the boundary waits for the first-denial-stop's run.cancel() to
44
+ // settle before reading the final denial ledger and capturing the turn's tree.
45
+ // Long enough for the SDK's normal teardown, short enough that a wedged cancel
46
+ // cannot noticeably delay the approval pause the user is already waiting on.
47
+ const FIRST_DENIAL_CANCEL_TIMEOUT_MS = 5_000;
48
+
49
+ export interface TurnBoundaryOptions {
50
+ /** Mutated in place: gate rows overlaid, edit rows stamped, narration redacted. */
51
+ readonly status: AgentExecutionStatus;
52
+ readonly executionId: string;
53
+ /** This turn's change set id (`{executionId}:{turnSeq}`). */
54
+ readonly changeSetId: string;
55
+ /** Session HITL dir holding the denial ledger + CAS sidecar; undefined → no gate installed. */
56
+ readonly hitlDir: string | undefined;
57
+ /** Whether this turn runs apply-then-review capture (vs. the deny-gate fallback). */
58
+ readonly captureMode: boolean;
59
+ /**
60
+ * The baseline authored at turn start — the git tree sha for a git workspace,
61
+ * or "" (empty, but authored) for a non-git one. `undefined` means no baseline
62
+ * was authored this turn, which skips capture entirely; a plain truthiness
63
+ * check would wrongly skip the non-git capture.
64
+ */
65
+ readonly baselineTree: string | undefined;
66
+ readonly primaryWorkspaceDir: string;
67
+ /** True for a git work tree; false for a CAS-only non-git workspace. */
68
+ readonly gitWorkspace: boolean;
69
+ /**
70
+ * Index of the first message produced by THIS turn's stream — the positional
71
+ * turn boundary the approved-command provenance (DD-28) scopes to.
72
+ */
73
+ readonly turnStartMessageIndex: number;
74
+ /** Reinvocation grants; their tokens map back to the consent rows for DD-28. */
75
+ readonly approvalGrants: ApprovalGrant[] | undefined;
76
+ /** spec.auto_approve_all — qualifies every command as consented for DD-28. */
77
+ readonly globalBypass: boolean;
78
+ /**
79
+ * Sub-agent executions that existed BEFORE this turn's stream (cloned in on
80
+ * resume); their rows are skipped when stamping so a resume never re-stamps a
81
+ * prior turn's sub-agent rows.
82
+ */
83
+ readonly seededSubAgents: readonly SubAgentExecution[];
84
+ /** CAS blob store for gitignored/non-git captures; undefined → git-only capture. */
85
+ readonly artifactStorage: ArtifactStorage | undefined;
86
+ /** Merged approval policies, threaded to the denied-call reconcile for gate provenance. */
87
+ readonly mergedPolicies: Map<string, MergedToolPolicy>;
88
+ /**
89
+ * The first-denial-stop's run.cancel() promise, when a denial stopped this
90
+ * run. Awaited (timeboxed) before the ledger read: run.cancel() races the
91
+ * SDK's auto-execution — until it lands, the agent process may still attempt
92
+ * a post-denial workaround whose hook denial would land AFTER a premature
93
+ * ledger read (the row then never collapses and renders as RUNNING forever —
94
+ * production case aex_01kwj07f7g23c3wp9sn8496z5g), or a late tool could
95
+ * mutate the tree mid-capture. Omit when no denial stopped the run (the
96
+ * normal completion path and the recovery retries, which have no early stop).
97
+ */
98
+ readonly denialCancelSettled?: Promise<void>;
99
+ }
100
+
101
+ export interface TurnBoundaryResult {
102
+ /**
103
+ * True when the turn must pause for human review — at least one gated tool
104
+ * call or one captured file change. The caller flips the phase to
105
+ * WAITING_FOR_APPROVAL, persists, and returns without consulting run.wait().
106
+ */
107
+ readonly waiting: boolean;
108
+ /** File changes authored to the file_review ledger this call (0 = no candidate). */
109
+ readonly capturedChangeCount: number;
110
+ /** Denied tool calls reconciled to WAITING_APPROVAL gate rows this call. */
111
+ readonly deniedToolCallCount: number;
112
+ }
113
+
114
+ /**
115
+ * Run the turn boundary: author this turn's change set to the file_review
116
+ * ledger and overlay the hook's denials as approval gates. Mutates
117
+ * `opts.status` in place and reports whether the turn must pause.
118
+ *
119
+ * The hook records each denial to the ledger; we mark the corresponding tool
120
+ * calls WAITING_APPROVAL. The backend projects pending_approvals from that
121
+ * tool-call status (PendingApprovalComputer), so — exactly like the native
122
+ * harness — the approval surface is driven entirely by tool-call status. We
123
+ * deliberately do NOT set status.pendingApprovals here: any value would be
124
+ * discarded by the backend's recompute on the next updateStatus.
125
+ */
126
+ export async function runTurnBoundary(opts: TurnBoundaryOptions): Promise<TurnBoundaryResult> {
127
+ const {
128
+ status,
129
+ executionId,
130
+ changeSetId,
131
+ hitlDir,
132
+ captureMode,
133
+ baselineTree,
134
+ primaryWorkspaceDir,
135
+ gitWorkspace,
136
+ turnStartMessageIndex,
137
+ approvalGrants,
138
+ globalBypass,
139
+ seededSubAgents,
140
+ artifactStorage,
141
+ mergedPolicies,
142
+ denialCancelSettled,
143
+ } = opts;
144
+
145
+ // The timebox keeps a wedged cancel from hanging the pause; the reconcile
146
+ // trims below remain the backstop for that degraded case.
147
+ if (denialCancelSettled) {
148
+ await Promise.race([
149
+ denialCancelSettled,
150
+ new Promise<void>((resolve) => {
151
+ const timer = setTimeout(resolve, FIRST_DENIAL_CANCEL_TIMEOUT_MS);
152
+ timer.unref();
153
+ }),
154
+ ]);
155
+ }
156
+ const deniedLedger = await readDenialLedger(hitlDir ?? "");
157
+
158
+ // Capture mode: author the net change set to the file_review ledger as the
159
+ // CANDIDATE_CAPTURED event (projected server-side to a file_change_set
160
+ // AWAITING_REVIEW — the single review surface). The runner-owned gate files
161
+ // are excluded from the capture. The agent's edits are LEFT applied on the
162
+ // working tree (Cursor parity — the user reviews the real change; nothing is
163
+ // committed and the next turn is blocked until approval, and a reject snaps
164
+ // each file back on resume). Runs BEFORE the denial reconcile so a denied
165
+ // (gitignored) write stays on the deny-gate path while every flowed edit is
166
+ // captured to the ledger.
167
+ let capturedChangeCount = 0;
168
+ if (captureMode && baselineTree !== undefined && primaryWorkspaceDir) {
169
+ const deniedTokens = new Set(deniedLedger.map((e) => e.token));
170
+ // Approved-command turn facts (DD-28): when every mutation-capable call
171
+ // this turn was a consented shell command, attach the provenance so the
172
+ // backend can verify the cited consent rows and auto-keep the set instead
173
+ // of arming a second gate. Fail-closed: any non-qualifying turn attaches
174
+ // nothing and reviews manually exactly as before.
175
+ const commandProvenance = deriveTurnCommandProvenance({
176
+ messages: status.messages,
177
+ turnStartIndex: turnStartMessageIndex,
178
+ deniedTokens,
179
+ grantTokenToConsentId: new Map(
180
+ (approvalGrants ?? []).map((g) => [
181
+ primaryToken(g.key, g.salient, g.contentDigest),
182
+ g.sourceToolCallId,
183
+ ]),
184
+ ),
185
+ globalBypass,
186
+ });
187
+ if (commandProvenance) {
188
+ console.log(
189
+ `ExecuteCursor capture: turn qualifies for approved-command auto-keep ` +
190
+ `(consent rows: ${commandProvenance.consentToolCallIds.join(",") || "(auto_approve_all)"}); ` +
191
+ `attaching provenance to candidate (execution=${executionId})`,
192
+ );
193
+ }
194
+ const captured = await captureTurnToLedger({
195
+ status,
196
+ gitRoot: primaryWorkspaceDir,
197
+ executionId,
198
+ changeSetId,
199
+ baselineTree,
200
+ messages: status.messages,
201
+ deniedTokens,
202
+ commandProvenance,
203
+ // Scope sub-agent row stamping to this turn: the seeded prior sub-agents
204
+ // (cloned in on resume) are the "before this turn" rows to skip.
205
+ priorSubAgentToolCallIds: collectSubAgentToolCallIds(seededSubAgents),
206
+ // The CAS half: read the sidecar the hook staged this turn and compose it
207
+ // into the change set. hitlDir + storage are present when captureIgnored
208
+ // was on (a git tree's gitignored writes, or ALL writes in a non-git
209
+ // workspace). In a git tree this composes with the git diff (HYBRID); in a
210
+ // non-git workspace it IS the whole change set (CAS-only).
211
+ hitlDir,
212
+ storage: artifactStorage,
213
+ gitWorkspace,
214
+ });
215
+ capturedChangeCount = captured.length;
216
+ if (capturedChangeCount > 0) {
217
+ console.log(
218
+ `ExecuteCursor capture: ${capturedChangeCount} file change(s) authored to the ` +
219
+ `file_review ledger (change_set=${changeSetId}), working tree left applied ` +
220
+ `for review (execution=${executionId})`,
221
+ );
222
+ }
223
+ }
224
+
225
+ // The gate reads each denied file's pre-edit `before` from the workspace the
226
+ // runner is co-located with (local FS for OSS; the sandbox in cloud), so a
227
+ // whole-file rewrite gate renders a true before/after diff. The tool was
228
+ // DENIED, so disk still holds the old content. User files are never platform
229
+ // paths, so no platformDir routing is needed here.
230
+ const gateWorkspaceBackend = new LocalWorkspaceBackend(primaryWorkspaceDir);
231
+ const deniedToolCalls = await reconcileDeniedToolCalls(
232
+ status.messages,
233
+ deniedLedger,
234
+ mergedPolicies,
235
+ gateWorkspaceBackend,
236
+ );
237
+ // Observability: a synthesized placeholder (id `approval:*`) means a denial
238
+ // correlated to NO streamed tool call in either the exact or the normalized
239
+ // pass. After the normalized-path fallback this should be ~0; a non-zero rate
240
+ // is the early-warning signal of a NEW identity drift (the gate would then
241
+ // show "No preview available" with no diff). Logged, not thrown — the
242
+ // synthesized gate still safely surfaces the approval.
243
+ const synthesizedGateCount = deniedToolCalls.filter((tc) =>
244
+ tc.id.startsWith("approval:"),
245
+ ).length;
246
+ if (synthesizedGateCount > 0) {
247
+ console.warn(
248
+ `ExecuteCursor reconcile synthesized ${synthesizedGateCount} placeholder gate(s) ` +
249
+ `with no correlated stream call (execution=${executionId}); ` +
250
+ `possible hook/stream identity drift — gate(s) will lack a diff`,
251
+ );
252
+ }
253
+ if (deniedToolCalls.length > 0) {
254
+ // Deterministic clean-pause: a turn that pauses for approval must read as
255
+ // the same shape the native harness produces — pre-tool text + the gated
256
+ // tool calls — never the model's provisional reaction to Cursor's deny
257
+ // (e.g. "blocked by a hook; enable it in your Cursor settings"). We blank
258
+ // that reaction in place (keeping the message count, so the finalize stays
259
+ // append-only) rather than removing it. See
260
+ // clearProvisionalPostDenialNarration for the full rationale.
261
+ const redactedNarration = clearProvisionalPostDenialNarration(status.messages, deniedToolCalls);
262
+ if (redactedNarration.length > 0) {
263
+ console.log(
264
+ `ExecuteCursor redacted ${redactedNarration.length} provisional post-denial narration message(s) before pausing for approval`,
265
+ );
266
+ }
267
+ }
268
+
269
+ return {
270
+ waiting: deniedToolCalls.length > 0 || capturedChangeCount > 0,
271
+ capturedChangeCount,
272
+ deniedToolCallCount: deniedToolCalls.length,
273
+ };
274
+ }