@stigmer/runner 3.1.1 → 3.1.3

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 (166) hide show
  1. package/dist/.build-fingerprint +1 -1
  2. package/dist/activities/execute-cursor/attachment-resolver.d.ts +49 -8
  3. package/dist/activities/execute-cursor/attachment-resolver.js +83 -26
  4. package/dist/activities/execute-cursor/attachment-resolver.js.map +1 -1
  5. package/dist/activities/execute-cursor/capture-flow.d.ts +18 -0
  6. package/dist/activities/execute-cursor/capture-flow.js +21 -0
  7. package/dist/activities/execute-cursor/capture-flow.js.map +1 -1
  8. package/dist/activities/execute-cursor/cas-observations.d.ts +13 -0
  9. package/dist/activities/execute-cursor/cas-observations.js +39 -5
  10. package/dist/activities/execute-cursor/cas-observations.js.map +1 -1
  11. package/dist/activities/execute-cursor/hook-script.js +19 -1
  12. package/dist/activities/execute-cursor/hook-script.js.map +1 -1
  13. package/dist/activities/execute-cursor/index.d.ts +5 -0
  14. package/dist/activities/execute-cursor/index.js +222 -160
  15. package/dist/activities/execute-cursor/index.js.map +1 -1
  16. package/dist/activities/execute-cursor/message-translator.js +10 -1
  17. package/dist/activities/execute-cursor/message-translator.js.map +1 -1
  18. package/dist/activities/execute-cursor/prompt-builder.d.ts +32 -7
  19. package/dist/activities/execute-cursor/prompt-builder.js +38 -20
  20. package/dist/activities/execute-cursor/prompt-builder.js.map +1 -1
  21. package/dist/activities/execute-cursor/skill-resolver.d.ts +1 -10
  22. package/dist/activities/execute-cursor/skill-resolver.js +3 -55
  23. package/dist/activities/execute-cursor/skill-resolver.js.map +1 -1
  24. package/dist/activities/execute-cursor/stigmer-link.d.ts +35 -0
  25. package/dist/activities/execute-cursor/stigmer-link.js +73 -0
  26. package/dist/activities/execute-cursor/stigmer-link.js.map +1 -0
  27. package/dist/activities/execute-cursor/turn-boundary.d.ts +108 -0
  28. package/dist/activities/execute-cursor/turn-boundary.js +163 -0
  29. package/dist/activities/execute-cursor/turn-boundary.js.map +1 -0
  30. package/dist/activities/execute-cursor/workspace-provision.d.ts +3 -2
  31. package/dist/activities/execute-cursor/workspace-provision.js +5 -3
  32. package/dist/activities/execute-cursor/workspace-provision.js.map +1 -1
  33. package/dist/activities/execute-deep-agent/index.js +89 -5
  34. package/dist/activities/execute-deep-agent/index.js.map +1 -1
  35. package/dist/activities/execute-deep-agent/prompt-builder.d.ts +17 -0
  36. package/dist/activities/execute-deep-agent/prompt-builder.js +16 -0
  37. package/dist/activities/execute-deep-agent/prompt-builder.js.map +1 -1
  38. package/dist/activities/execute-deep-agent/setup.js +22 -16
  39. package/dist/activities/execute-deep-agent/setup.js.map +1 -1
  40. package/dist/activities/execute-deep-agent/streaming-v3.js +6 -1
  41. package/dist/activities/execute-deep-agent/streaming-v3.js.map +1 -1
  42. package/dist/activities/execute-deep-agent/streaming.d.ts +7 -0
  43. package/dist/activities/execute-deep-agent/streaming.js +5 -1
  44. package/dist/activities/execute-deep-agent/streaming.js.map +1 -1
  45. package/dist/config.d.ts +7 -0
  46. package/dist/config.js +9 -0
  47. package/dist/config.js.map +1 -1
  48. package/dist/middleware/approval-gate.js +36 -6
  49. package/dist/middleware/approval-gate.js.map +1 -1
  50. package/dist/runner-manager.d.ts +2 -0
  51. package/dist/runner-manager.js +2 -1
  52. package/dist/runner-manager.js.map +1 -1
  53. package/dist/runner.d.ts +2 -0
  54. package/dist/runner.js +2 -1
  55. package/dist/runner.js.map +1 -1
  56. package/dist/shared/artifact-storage.d.ts +32 -0
  57. package/dist/shared/artifact-storage.js +74 -1
  58. package/dist/shared/artifact-storage.js.map +1 -1
  59. package/dist/shared/filereview/capture.d.ts +18 -1
  60. package/dist/shared/filereview/capture.js +105 -28
  61. package/dist/shared/filereview/capture.js.map +1 -1
  62. package/dist/shared/filereview/cas-substrate.d.ts +9 -0
  63. package/dist/shared/filereview/cas-substrate.js +9 -1
  64. package/dist/shared/filereview/cas-substrate.js.map +1 -1
  65. package/dist/shared/filereview/events.d.ts +16 -0
  66. package/dist/shared/filereview/events.js +37 -0
  67. package/dist/shared/filereview/events.js.map +1 -1
  68. package/dist/shared/filereview/git-substrate.d.ts +42 -0
  69. package/dist/shared/filereview/git-substrate.js +78 -0
  70. package/dist/shared/filereview/git-substrate.js.map +1 -1
  71. package/dist/shared/filereview/index.d.ts +3 -1
  72. package/dist/shared/filereview/index.js +3 -1
  73. package/dist/shared/filereview/index.js.map +1 -1
  74. package/dist/shared/filereview/line-counts.d.ts +48 -0
  75. package/dist/shared/filereview/line-counts.js +72 -0
  76. package/dist/shared/filereview/line-counts.js.map +1 -0
  77. package/dist/shared/filereview/progress.d.ts +96 -0
  78. package/dist/shared/filereview/progress.js +134 -0
  79. package/dist/shared/filereview/progress.js.map +1 -0
  80. package/dist/shared/implement-plan-prompt.d.ts +44 -0
  81. package/dist/shared/implement-plan-prompt.js +98 -0
  82. package/dist/shared/implement-plan-prompt.js.map +1 -0
  83. package/dist/shared/plan-artifact.d.ts +59 -11
  84. package/dist/shared/plan-artifact.js +144 -16
  85. package/dist/shared/plan-artifact.js.map +1 -1
  86. package/dist/shared/plan-mode-prompt.d.ts +32 -0
  87. package/dist/shared/plan-mode-prompt.js +56 -0
  88. package/dist/shared/plan-mode-prompt.js.map +1 -0
  89. package/dist/shared/status.d.ts +11 -0
  90. package/dist/shared/status.js +12 -2
  91. package/dist/shared/status.js.map +1 -1
  92. package/dist/shared/tool-row.d.ts +30 -1
  93. package/dist/shared/tool-row.js +53 -4
  94. package/dist/shared/tool-row.js.map +1 -1
  95. package/dist/shared/workspace/session-root.d.ts +35 -0
  96. package/dist/shared/workspace/session-root.js +53 -0
  97. package/dist/shared/workspace/session-root.js.map +1 -0
  98. package/dist/shared/workspace/workspace-lock.d.ts +86 -0
  99. package/dist/shared/workspace/workspace-lock.js +187 -0
  100. package/dist/shared/workspace/workspace-lock.js.map +1 -0
  101. package/package.json +8 -5
  102. package/src/__tests__/config.test.ts +8 -0
  103. package/src/activities/__tests__/classify-tool-approvals.test.ts +1 -0
  104. package/src/activities/__tests__/discover-mcp-server.test.ts +1 -0
  105. package/src/activities/execute-cursor/__tests__/attachment-resolver.test.ts +161 -0
  106. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +132 -2
  107. package/src/activities/execute-cursor/__tests__/cas-observations.test.ts +55 -0
  108. package/src/activities/execute-cursor/__tests__/delta-enricher.test.ts +68 -0
  109. package/src/activities/execute-cursor/__tests__/hitl-ledger.test.ts +28 -0
  110. package/src/activities/execute-cursor/__tests__/hook-script.test.ts +63 -4
  111. package/src/activities/execute-cursor/__tests__/turn-boundary.test.ts +280 -0
  112. package/src/activities/execute-cursor/__tests__/workspace-provision.test.ts +36 -2
  113. package/src/activities/execute-cursor/attachment-resolver.ts +116 -34
  114. package/src/activities/execute-cursor/capture-flow.ts +32 -0
  115. package/src/activities/execute-cursor/cas-observations.ts +41 -5
  116. package/src/activities/execute-cursor/hook-script.ts +19 -1
  117. package/src/activities/execute-cursor/index.ts +243 -178
  118. package/src/activities/execute-cursor/message-translator.ts +9 -1
  119. package/src/activities/execute-cursor/prompt-builder.ts +60 -22
  120. package/src/activities/execute-cursor/skill-resolver.ts +3 -59
  121. package/src/activities/execute-cursor/stigmer-link.ts +78 -0
  122. package/src/activities/execute-cursor/turn-boundary.ts +274 -0
  123. package/src/activities/execute-cursor/workspace-provision.ts +5 -3
  124. package/src/activities/execute-deep-agent/__tests__/hitl-resume-approve-all.test.ts +7 -2
  125. package/src/activities/execute-deep-agent/__tests__/hitl-resume-history.test.ts +7 -2
  126. package/src/activities/execute-deep-agent/__tests__/index.test.ts +4 -1
  127. package/src/activities/execute-deep-agent/__tests__/prompt-builder.test.ts +99 -0
  128. package/src/activities/execute-deep-agent/__tests__/sequential-gate-resume.test.ts +7 -2
  129. package/src/activities/execute-deep-agent/index.ts +104 -5
  130. package/src/activities/execute-deep-agent/prompt-builder.ts +39 -0
  131. package/src/activities/execute-deep-agent/setup.ts +25 -17
  132. package/src/activities/execute-deep-agent/streaming-v3.ts +6 -1
  133. package/src/activities/execute-deep-agent/streaming.ts +12 -1
  134. package/src/config.ts +17 -0
  135. package/src/middleware/__tests__/approval-gate.test.ts +77 -12
  136. package/src/middleware/approval-gate.ts +39 -7
  137. package/src/runner-manager.ts +6 -1
  138. package/src/runner.ts +6 -1
  139. package/src/shared/__tests__/artifact-storage.test.ts +111 -1
  140. package/src/shared/__tests__/implement-plan-prompt.test.ts +86 -0
  141. package/src/shared/__tests__/plan-artifact.test.ts +142 -9
  142. package/src/shared/__tests__/secret-leak-scan.test.ts +105 -0
  143. package/src/shared/__tests__/status.test.ts +7 -2
  144. package/src/shared/__tests__/tool-row.test.ts +136 -1
  145. package/src/shared/artifact-storage.ts +83 -1
  146. package/src/shared/filereview/__tests__/capture.test.ts +182 -1
  147. package/src/shared/filereview/__tests__/cas-substrate.test.ts +34 -0
  148. package/src/shared/filereview/__tests__/events.test.ts +105 -0
  149. package/src/shared/filereview/__tests__/line-counts.test.ts +73 -0
  150. package/src/shared/filereview/__tests__/progress.test.ts +236 -0
  151. package/src/shared/filereview/capture.ts +134 -30
  152. package/src/shared/filereview/cas-substrate.ts +17 -1
  153. package/src/shared/filereview/events.ts +50 -0
  154. package/src/shared/filereview/git-substrate.ts +108 -0
  155. package/src/shared/filereview/index.ts +22 -1
  156. package/src/shared/filereview/line-counts.ts +83 -0
  157. package/src/shared/filereview/progress.ts +186 -0
  158. package/src/shared/implement-plan-prompt.ts +104 -0
  159. package/src/shared/plan-artifact.ts +152 -16
  160. package/src/shared/plan-mode-prompt.ts +56 -0
  161. package/src/shared/status.ts +11 -1
  162. package/src/shared/tool-row.ts +58 -5
  163. package/src/shared/workspace/__tests__/session-root.test.ts +42 -0
  164. package/src/shared/workspace/__tests__/workspace-lock.test.ts +200 -0
  165. package/src/shared/workspace/session-root.ts +60 -0
  166. package/src/shared/workspace/workspace-lock.ts +241 -0
@@ -6,19 +6,25 @@
6
6
  * parameter). On reinvocation, only the approval decisions are sent.
7
7
  *
8
8
  * Sections (in order, conditionally included):
9
- * 1. Agent instructions (persona/character)
10
- * 2. Available skills metadata
11
- * 3. Sub-agent delegation guidance
12
- * 4. Workspace context (multi-root only; single-dir is redundant with SDK cwd)
13
- * 5. Input files / referenced files
14
- * 6. Response rules (only when agent has no custom instructions)
15
- * 7. User's actual message
9
+ * 1. Interaction-mode / implement-plan directives
10
+ * 2. Agent instructions (persona/character)
11
+ * 3. Available skills metadata
12
+ * 4. Sub-agent delegation guidance
13
+ * 5. Workspace context (multi-root only; single-dir is redundant with SDK cwd)
14
+ * 6. Input files / referenced files
15
+ * 7. Response rules (only when agent has no custom instructions)
16
+ * 8. User's actual message
16
17
  */
17
18
 
18
19
  import { resolve } from "node:path";
19
20
  import type { SubAgent } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/spec_pb";
20
21
  import type { PendingApproval } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/approval_pb";
21
22
  import { ApprovalAction, InteractionMode } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
23
+ import { PLAN_MODE_DIRECTIVE } from "../../shared/plan-mode-prompt.js";
24
+ import {
25
+ buildImplementPlanDirective,
26
+ findApprovedPlanPath,
27
+ } from "../../shared/implement-plan-prompt.js";
22
28
 
23
29
  /**
24
30
  * Marker path segments that identify runner-internal directories. A workspace
@@ -47,6 +53,13 @@ export interface EnhancedPromptOptions {
47
53
  workspaceFileRefs: string[];
48
54
  attachmentPaths: string[];
49
55
  interactionMode?: InteractionMode;
56
+ /**
57
+ * The execution is a Build-from-plan turn (spec.execution_config
58
+ * .build_from_plan): inject the implement-plan directive so the model reads
59
+ * the attached approved plan (or falls back to the conversation's plan).
60
+ * The user message itself is just a short label ("Build from plan").
61
+ */
62
+ buildFromPlan?: boolean;
50
63
  }
51
64
 
52
65
  /**
@@ -63,6 +76,14 @@ export function buildEnhancedPrompt(options: EnhancedPromptOptions): string {
63
76
  sections.push(modePrefix);
64
77
  }
65
78
 
79
+ const implementPlan = formatImplementPlanSection(
80
+ options.buildFromPlan,
81
+ options.attachmentPaths,
82
+ );
83
+ if (implementPlan) {
84
+ sections.push(implementPlan);
85
+ }
86
+
66
87
  if (options.instructions) {
67
88
  sections.push(formatInstructions(options.instructions));
68
89
  }
@@ -348,30 +369,47 @@ export function formatReferencedFiles(refs: string[]): string {
348
369
  /**
349
370
  * Returns a system-level directive when the execution is in Plan mode.
350
371
  * Returns `undefined` for Agent mode (default) since no prefix is needed.
372
+ *
373
+ * The directive body is the harness-agnostic {@link PLAN_MODE_DIRECTIVE}
374
+ * (shared with the native harness) wrapped in this harness's XML-tag section
375
+ * framing. For Cursor this prompt IS the plan-mode enforcement — the Cursor
376
+ * SDK exposes no mode parameter — see the shared module's doc comment.
351
377
  */
352
378
  export function formatInteractionModePrefix(
353
379
  mode: InteractionMode | undefined,
354
380
  ): string | undefined {
355
- if (
356
- mode == null ||
357
- mode === InteractionMode.UNSPECIFIED ||
358
- mode === InteractionMode.AGENT
359
- ) {
381
+ if (mode !== InteractionMode.PLAN) {
360
382
  return undefined;
361
383
  }
362
384
 
363
- if (mode === InteractionMode.PLAN) {
364
- return [
365
- "<interaction_mode>",
366
- "IMPORTANT: You are in Plan mode. Analyze the codebase and produce a detailed plan.",
367
- "Do NOT create, edit, or delete any files. Do NOT run commands that modify the filesystem.",
368
- "Only read, search, and analyze. Your output should be analysis, recommendations, and",
369
- "implementation plans not code changes.",
370
- "</interaction_mode>",
371
- ].join("\n");
385
+ return ["<interaction_mode>", PLAN_MODE_DIRECTIVE, "</interaction_mode>"].join(
386
+ "\n",
387
+ );
388
+ }
389
+
390
+ /**
391
+ * Returns the implement-plan directive section for a Build-from-plan
392
+ * execution, or `undefined` otherwise. The directive body is the shared
393
+ * {@link buildImplementPlanDirective} (same words as the native harness)
394
+ * wrapped in this harness's XML-tag framing; the variant is picked by whether
395
+ * the approved plan document is among the resolved attachment paths.
396
+ *
397
+ * Like the interaction-mode prefix, this rides BOTH prompt paths — the fresh
398
+ * enhanced prompt and a resumed turn's prefix — because build_from_plan is
399
+ * per-execution and the build turn is usually a follow-up on a resumed agent.
400
+ */
401
+ export function formatImplementPlanSection(
402
+ buildFromPlan: boolean | undefined,
403
+ attachmentPaths: string[],
404
+ ): string | undefined {
405
+ if (!buildFromPlan) {
406
+ return undefined;
372
407
  }
373
408
 
374
- return undefined;
409
+ const directive = buildImplementPlanDirective(
410
+ findApprovedPlanPath(attachmentPaths),
411
+ );
412
+ return ["<implement_plan>", directive, "</implement_plan>"].join("\n");
375
413
  }
376
414
 
377
415
  export function formatResponseRules(): string {
@@ -5,11 +5,11 @@
5
5
  * - Writes SKILL.md to .stigmer/skills/{name}/SKILL.md
6
6
  * - Downloads and extracts ZIP artifacts (references/, scripts/, etc.)
7
7
  * - Uses a platform-managed directory outside the workspace
8
- * - Creates a symlink from the workspace to the platform dir
8
+ * - Ensures the workspace `.stigmer` symlink (see stigmer-link.ts)
9
9
  * - Returns metadata for prompt injection
10
10
  */
11
11
 
12
- import { mkdir, writeFile, symlink, readlink, unlink, rm, lstat } from "node:fs/promises";
12
+ import { mkdir, writeFile, rm } from "node:fs/promises";
13
13
  import { join, dirname } from "node:path";
14
14
  import type { StigmerClient } from "../../client/stigmer-client.js";
15
15
  import type { Skill } from "@stigmer/protos/ai/stigmer/agentic/skill/v1/api_pb";
@@ -17,8 +17,8 @@ import type { ApiResourceReference } from "@stigmer/protos/ai/stigmer/commons/ap
17
17
  import type { SkillMetadata } from "./prompt-builder.js";
18
18
  import { getPlatformDir } from "../../shared/workspace/platform-dir.js";
19
19
  import { extractZipFileEntries } from "../../shared/zip-extract.js";
20
+ import { ensureStigmerSymlink, STIGMER_LOCAL_STATE_DIR } from "./stigmer-link.js";
20
21
 
21
- const STIGMER_LOCAL_STATE_DIR = ".stigmer";
22
22
  const SKILLS_SUBDIR = "skills";
23
23
 
24
24
  export interface SkillResolverOptions {
@@ -132,62 +132,6 @@ async function writeSkill(
132
132
  };
133
133
  }
134
134
 
135
- /**
136
- * Ensure .stigmer symlink in the workspace points to the platform dir.
137
- *
138
- * The Cursor SDK reads files from the workspace CWD, so we need the
139
- * .stigmer directory to be accessible there. Unlike the Python runner
140
- * which intercepts file paths, Cursor reads directly from the filesystem.
141
- */
142
- async function ensureStigmerSymlink(
143
- workspaceDir: string,
144
- platformDir: string,
145
- ): Promise<void> {
146
- const linkPath = join(workspaceDir, STIGMER_LOCAL_STATE_DIR);
147
-
148
- try {
149
- const existing = await readlink(linkPath);
150
- if (existing === platformDir) return;
151
- await unlink(linkPath);
152
- } catch (err: any) {
153
- if (err.code === "ENOENT") {
154
- // No existing symlink
155
- } else if (err.code === "EINVAL") {
156
- // Exists but is not a symlink — remove the directory
157
- await rm(linkPath, { recursive: true, force: true });
158
- } else {
159
- throw err;
160
- }
161
- }
162
-
163
- await symlink(platformDir, linkPath, "dir");
164
- }
165
-
166
- /**
167
- * Remove the workspace `.stigmer` symlink created by {@link resolveSkills}.
168
- *
169
- * Called in the activity's finally so attaching a real repo leaves no Stigmer
170
- * symlink behind once the turn ends (issue #173); a multi-turn session recreates
171
- * it on the next turn. Only ever removes a SYMLINK — a real `.stigmer` directory
172
- * (which would be the user's own, not ours) is left untouched. Best-effort.
173
- */
174
- export async function removeStigmerSymlink(workspaceDir: string): Promise<void> {
175
- const linkPath = join(workspaceDir, STIGMER_LOCAL_STATE_DIR);
176
- try {
177
- const stat = await lstat(linkPath);
178
- if (stat.isSymbolicLink()) {
179
- await unlink(linkPath);
180
- }
181
- } catch (err: any) {
182
- if (err?.code !== "ENOENT") {
183
- console.warn(
184
- `removeStigmerSymlink: failed to remove ${linkPath} (non-fatal): ` +
185
- `${err instanceof Error ? err.message : err}`,
186
- );
187
- }
188
- }
189
- }
190
-
191
135
  /**
192
136
  * Clean up platform-managed skill directory for a session.
193
137
  */
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The workspace `.stigmer` symlink — the Cursor harness's bridge from the
3
+ * user's workspace to the session's platform-managed directory
4
+ * (~/.stigmer/sessions/{id}/platform/, see shared/workspace/platform-dir.ts).
5
+ *
6
+ * The Cursor SDK reads files from the workspace CWD, so platform-injected
7
+ * content (skills, attachment inputs) must be reachable there; the symlink is
8
+ * how, without ever writing platform files into the user's repo (issue #173).
9
+ * This mechanism is deliberately harness-local: the native harness routes
10
+ * `.stigmer/` paths through its WorkspaceBackend instead and never symlinks.
11
+ *
12
+ * Both resolvers that populate the platform dir (skills, attachments) call
13
+ * {@link ensureStigmerSymlink}; it is idempotent, so either may run first and
14
+ * an agent with only one kind of content still gets the link. The activity's
15
+ * cleanup calls {@link removeStigmerSymlink} so a real repo is left untouched
16
+ * once the turn ends; a multi-turn session recreates the link on the next turn.
17
+ */
18
+
19
+ import { symlink, readlink, unlink, rm, lstat } from "node:fs/promises";
20
+ import { join } from "node:path";
21
+
22
+ /** The workspace-visible name of the platform namespace. */
23
+ export const STIGMER_LOCAL_STATE_DIR = ".stigmer";
24
+
25
+ /**
26
+ * Ensure the workspace `.stigmer` symlink points to the platform dir.
27
+ * Idempotent: an existing correct link is kept; a stale link (or a non-link
28
+ * left behind by an older runner) is replaced.
29
+ */
30
+ export async function ensureStigmerSymlink(
31
+ workspaceDir: string,
32
+ platformDir: string,
33
+ ): Promise<void> {
34
+ const linkPath = join(workspaceDir, STIGMER_LOCAL_STATE_DIR);
35
+
36
+ try {
37
+ const existing = await readlink(linkPath);
38
+ if (existing === platformDir) return;
39
+ await unlink(linkPath);
40
+ } catch (err: any) {
41
+ if (err.code === "ENOENT") {
42
+ // No existing symlink
43
+ } else if (err.code === "EINVAL") {
44
+ // Exists but is not a symlink — remove the directory
45
+ await rm(linkPath, { recursive: true, force: true });
46
+ } else {
47
+ throw err;
48
+ }
49
+ }
50
+
51
+ await symlink(platformDir, linkPath, "dir");
52
+ }
53
+
54
+ /**
55
+ * Remove the workspace `.stigmer` symlink created by
56
+ * {@link ensureStigmerSymlink}.
57
+ *
58
+ * Called in the activity's finally so attaching a real repo leaves no Stigmer
59
+ * symlink behind once the turn ends (issue #173). Only ever removes a
60
+ * SYMLINK — a real `.stigmer` directory (which would be the user's own, not
61
+ * ours) is left untouched. Best-effort.
62
+ */
63
+ export async function removeStigmerSymlink(workspaceDir: string): Promise<void> {
64
+ const linkPath = join(workspaceDir, STIGMER_LOCAL_STATE_DIR);
65
+ try {
66
+ const stat = await lstat(linkPath);
67
+ if (stat.isSymbolicLink()) {
68
+ await unlink(linkPath);
69
+ }
70
+ } catch (err: any) {
71
+ if (err?.code !== "ENOENT") {
72
+ console.warn(
73
+ `removeStigmerSymlink: failed to remove ${linkPath} (non-fatal): ` +
74
+ `${err instanceof Error ? err.message : err}`,
75
+ );
76
+ }
77
+ }
78
+ }
@@ -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
+ }
@@ -12,14 +12,16 @@ import type { Session } from "@stigmer/protos/ai/stigmer/agentic/session/v1/api_
12
12
  import { WorkspaceProvisioner } from "../../shared/workspace/provisioner.js";
13
13
  import { LocalWorkspaceBackend } from "../../shared/workspace/local-backend.js";
14
14
  import { ensurePlatformDir } from "../../shared/workspace/platform-dir.js";
15
+ import { resolveSessionWorkspaceRoot } from "../../shared/workspace/session-root.js";
15
16
 
16
17
  /**
17
18
  * Provision the session's workspace entries for a LOCAL Cursor agent.
18
19
  *
19
20
  * Clones git-repo entries (using the user's GITHUB_TOKEN from the resolved
20
21
  * execution environment) and mounts local-path entries, then returns the
21
- * directories the agent should operate in. Falls back to the configured
22
- * workspace root when the session declares no workspace entries.
22
+ * directories the agent should operate in. A session with no workspace
23
+ * entries gets its own empty per-session directory (see session-root.ts)
24
+ * never the shared root, which would leak other sessions' files into it.
23
25
  *
24
26
  * provisionGit is idempotent (it reuses an existing clone), so this is safe
25
27
  * to call on every execution, including multi-turn and HITL reinvocations.
@@ -32,7 +34,7 @@ export async function provisionCursorWorkspace(
32
34
  ): Promise<string[]> {
33
35
  const entries = session.spec?.workspaceEntries ?? [];
34
36
  if (entries.length === 0) {
35
- return [config.workspaceRootDir];
37
+ return [await resolveSessionWorkspaceRoot(config.workspaceRootDir, entries, sessionId)];
36
38
  }
37
39
 
38
40
  const platformDir = await ensurePlatformDir(sessionId);
@@ -49,7 +49,9 @@ import type { SetupResult } from "../setup.js";
49
49
  vi.mock("@temporalio/activity", () => ({
50
50
  Context: {
51
51
  current: () => ({
52
- cancellationSignal: { aborted: false },
52
+ // A real AbortSignal: the workspace-lock wait registers abort listeners
53
+ // on it, which a bare `{ aborted: false }` stub cannot satisfy.
54
+ cancellationSignal: new AbortController().signal,
53
55
  heartbeat: vi.fn(),
54
56
  }),
55
57
  },
@@ -258,7 +260,9 @@ function fakeDurableResumeSetup(): SetupResult {
258
260
  },
259
261
  agent: {},
260
262
  session: { spec: { workspaceEntries: [] } },
261
- workspaceBackend: { rootDir: "/tmp/ws" },
263
+ // Unique per test file: the workspace turn lock keys on this path, and a
264
+ // path shared across files would serialize parallel test workers for real.
265
+ workspaceBackend: { rootDir: "/tmp/stigmer-test-ws-hitl-approve-all" },
262
266
  mcpConnection: null,
263
267
  mergedEnvVars: {},
264
268
  secretKeys: new Set<string>(),
@@ -292,6 +296,7 @@ const baseConfig: Config = {
292
296
  checkpointerProxyEndpoint: "http://localhost:7234",
293
297
  primaryModel: "claude-sonnet",
294
298
  cursorStreamStallTimeoutMs: 180000,
299
+ workspaceLockTimeoutMs: 900000,
295
300
  };
296
301
 
297
302
  describe("ExecuteDeepAgent — APPROVE_ALL durable resume preserves leading thinking + first tool call", () => {
@@ -42,7 +42,9 @@ import type { SetupResult } from "../setup.js";
42
42
  vi.mock("@temporalio/activity", () => ({
43
43
  Context: {
44
44
  current: () => ({
45
- cancellationSignal: { aborted: false },
45
+ // A real AbortSignal: the workspace-lock wait registers abort listeners
46
+ // on it, which a bare `{ aborted: false }` stub cannot satisfy.
47
+ cancellationSignal: new AbortController().signal,
46
48
  heartbeat: vi.fn(),
47
49
  }),
48
50
  },
@@ -213,7 +215,9 @@ function fakeDurableResumeSetup(): SetupResult {
213
215
  },
214
216
  agent: {},
215
217
  session: { spec: { workspaceEntries: [] } },
216
- workspaceBackend: { rootDir: "/tmp/ws" },
218
+ // Unique per test file: the workspace turn lock keys on this path, and a
219
+ // path shared across files would serialize parallel test workers for real.
220
+ workspaceBackend: { rootDir: "/tmp/stigmer-test-ws-hitl-history" },
217
221
  mcpConnection: null,
218
222
  mergedEnvVars: {},
219
223
  secretKeys: new Set<string>(),
@@ -246,6 +250,7 @@ const baseConfig: Config = {
246
250
  checkpointerProxyEndpoint: "http://localhost:7234",
247
251
  primaryModel: "claude-sonnet",
248
252
  cursorStreamStallTimeoutMs: 180000,
253
+ workspaceLockTimeoutMs: 900000,
249
254
  };
250
255
 
251
256
  describe("ExecuteDeepAgent — durable-checkpoint resume preserves history", () => {
@@ -8,7 +8,9 @@ import type { Config } from "../../../config.js";
8
8
  vi.mock("@temporalio/activity", () => ({
9
9
  Context: {
10
10
  current: () => ({
11
- cancellationSignal: { aborted: false },
11
+ // A real AbortSignal: the workspace-lock wait registers abort listeners
12
+ // on it, which a bare `{ aborted: false }` stub cannot satisfy.
13
+ cancellationSignal: new AbortController().signal,
12
14
  heartbeat: vi.fn(),
13
15
  }),
14
16
  },
@@ -45,6 +47,7 @@ describe("ExecuteDeepAgent activity", () => {
45
47
  checkpointerProxyEndpoint: null,
46
48
  primaryModel: "gpt-4.1",
47
49
  cursorStreamStallTimeoutMs: 180000,
50
+ workspaceLockTimeoutMs: 900000,
48
51
  };
49
52
 
50
53
  let activities: ReturnType<typeof createDeepAgentActivities>;