@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
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Session workspace-root resolution — shared by both executors (Cursor and
3
+ * deep-agent) so their placement rules can never drift.
4
+ *
5
+ * SessionSpec.workspace_entries promises: "When empty, the session uses an
6
+ * empty workspace directory." Handing every no-entry session the shared
7
+ * `config.workspaceRootDir` broke that contract twice over: a "new" session
8
+ * started amid every prior session's leftovers, and — under the per-workspace
9
+ * turn lock (workspace-lock.ts) — unrelated no-entry sessions would falsely
10
+ * serialize against each other. A per-session directory honors the contract,
11
+ * isolates the default quickstart case, and removes the false contention.
12
+ *
13
+ * Sessions WITH entries keep the shared root: their content identity is the
14
+ * entry source (a git URL clones idempotently, a localPath IS the user's
15
+ * directory), and cross-session sharing of that content is intentional —
16
+ * that sharing is exactly what the turn lock serializes.
17
+ */
18
+ /**
19
+ * Resolve (and create) the working-tree root for a session.
20
+ *
21
+ * - No workspace entries → `{workspaceRootDir}/sessions/{sessionId}`, created
22
+ * on demand. Deterministic from sessionId alone, so it is stable across
23
+ * turns, HITL reinvocations, and Temporal retries with no persisted state.
24
+ * - One or more entries → the shared `workspaceRootDir`, where the
25
+ * provisioner materializes each entry (in place, or per-entry subdirs).
26
+ *
27
+ * The `sessions/` namespace lives under the configured workspace root (the
28
+ * volume operators size and mount for workspace content), not under $HOME.
29
+ * It can coexist with a single-entry clone at the root: cloneInPlace
30
+ * (sources/git.ts) tolerates non-empty targets, colliding only if the repo
31
+ * itself ships a root-level `sessions` path — a strictly smaller surface
32
+ * than the old behavior, where any file a no-entry session dropped at the
33
+ * root could break the checkout.
34
+ */
35
+ export declare function resolveSessionWorkspaceRoot(workspaceRootDir: string, workspaceEntries: readonly unknown[], sessionId: string): Promise<string>;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Session workspace-root resolution — shared by both executors (Cursor and
3
+ * deep-agent) so their placement rules can never drift.
4
+ *
5
+ * SessionSpec.workspace_entries promises: "When empty, the session uses an
6
+ * empty workspace directory." Handing every no-entry session the shared
7
+ * `config.workspaceRootDir` broke that contract twice over: a "new" session
8
+ * started amid every prior session's leftovers, and — under the per-workspace
9
+ * turn lock (workspace-lock.ts) — unrelated no-entry sessions would falsely
10
+ * serialize against each other. A per-session directory honors the contract,
11
+ * isolates the default quickstart case, and removes the false contention.
12
+ *
13
+ * Sessions WITH entries keep the shared root: their content identity is the
14
+ * entry source (a git URL clones idempotently, a localPath IS the user's
15
+ * directory), and cross-session sharing of that content is intentional —
16
+ * that sharing is exactly what the turn lock serializes.
17
+ */
18
+ import { join } from "node:path";
19
+ import { mkdir } from "node:fs/promises";
20
+ /**
21
+ * Resolve (and create) the working-tree root for a session.
22
+ *
23
+ * - No workspace entries → `{workspaceRootDir}/sessions/{sessionId}`, created
24
+ * on demand. Deterministic from sessionId alone, so it is stable across
25
+ * turns, HITL reinvocations, and Temporal retries with no persisted state.
26
+ * - One or more entries → the shared `workspaceRootDir`, where the
27
+ * provisioner materializes each entry (in place, or per-entry subdirs).
28
+ *
29
+ * The `sessions/` namespace lives under the configured workspace root (the
30
+ * volume operators size and mount for workspace content), not under $HOME.
31
+ * It can coexist with a single-entry clone at the root: cloneInPlace
32
+ * (sources/git.ts) tolerates non-empty targets, colliding only if the repo
33
+ * itself ships a root-level `sessions` path — a strictly smaller surface
34
+ * than the old behavior, where any file a no-entry session dropped at the
35
+ * root could break the checkout.
36
+ */
37
+ export async function resolveSessionWorkspaceRoot(workspaceRootDir, workspaceEntries, sessionId) {
38
+ if (workspaceEntries.length > 0) {
39
+ return workspaceRootDir;
40
+ }
41
+ if (!sessionId) {
42
+ // Same invariant as resolvePlatformOptions: an empty sessionId would
43
+ // collapse every no-entry session onto one directory — the exact leakage
44
+ // this function exists to prevent.
45
+ throw new Error("resolveSessionWorkspaceRoot: sessionId is required for a session with " +
46
+ "no workspace entries; an empty value would collapse every such session " +
47
+ "onto one shared directory.");
48
+ }
49
+ const sessionRoot = join(workspaceRootDir, "sessions", sessionId);
50
+ await mkdir(sessionRoot, { recursive: true });
51
+ return sessionRoot;
52
+ }
53
+ //# sourceMappingURL=session-root.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-root.js","sourceRoot":"","sources":["../../../src/shared/workspace/session-root.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AAEzC;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAC/C,gBAAwB,EACxB,gBAAoC,EACpC,SAAiB;IAEjB,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAChC,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IACD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,qEAAqE;QACrE,yEAAyE;QACzE,mCAAmC;QACnC,MAAM,IAAI,KAAK,CACb,wEAAwE;YACxE,yEAAyE;YACzE,4BAA4B,CAC7B,CAAC;IACJ,CAAC;IACD,MAAM,WAAW,GAAG,IAAI,CAAC,gBAAgB,EAAE,UAAU,EAAE,SAAS,CAAC,CAAC;IAClE,MAAM,KAAK,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,CAAC,CAAC;IAC9C,OAAO,WAAW,CAAC;AACrB,CAAC"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Per-workspace turn lock — serializes agent-execution turns that share a
3
+ * working tree.
4
+ *
5
+ * Why this exists: the file-review substrate (shared/filereview) computes a
6
+ * turn's change set as `git diff baselineTree candidateTree`, where both trees
7
+ * are live snapshots of the working directory at turn start/end. That model is
8
+ * correct for a single writer, but nothing scopes a working tree to one
9
+ * execution: sessions declaring the same `localPath` (or sharing the runner's
10
+ * `workspaceRootDir`) resolve to the SAME directory, and the runner happily
11
+ * runs activities concurrently. A concurrent turn's write landing between
12
+ * another turn's baseline and candidate gets misattributed to that other turn
13
+ * (observed in prod: aex_01kwpzhmvbvwqdez9cb331nekr reviewed a notes.md it
14
+ * never wrote). The same race lets a reject-reconcile in one session silently
15
+ * revert a file another session's user just approved.
16
+ *
17
+ * Why a FILE lock and not in-process/server-side coordination: the shared
18
+ * resource is a directory on one host. A `localPath` entry resolves to the
19
+ * user's literal directory in ANY runner process on the machine — the CLI
20
+ * daemon and the desktop app's embedded runner can contend on one tree while
21
+ * answering to DIFFERENT control planes, so no single server can see all
22
+ * contenders and no in-process mutex can exclude a sibling process. Mutual
23
+ * exclusion must live where the collision happens: the filesystem.
24
+ *
25
+ * Mechanics (proper-lockfile):
26
+ * - The lock artifact lives under `~/.stigmer/workspace-locks/{key}.lock`,
27
+ * NEVER inside the user's workspace (issue #173: attaching a real repo must
28
+ * leave no Stigmer droppings). The key is sha256(realpath(workspaceRoot)),
29
+ * so symlink aliases of one directory converge on one lock — the same
30
+ * keying pattern as getHitlGateDir in platform-dir.ts.
31
+ * - While held, proper-lockfile refreshes the artifact's mtime on an interval;
32
+ * if the holder process dies, refreshing stops and the artifact goes stale,
33
+ * so the next waiter simply takes over. A crashed runner can never deadlock
34
+ * a workspace, and no human ever has to delete a lock file.
35
+ * - Deadlock-free by construction: an activity holds at most ONE lock (its
36
+ * primary workspace root), and a turn that pauses for human approval ENDS
37
+ * its activity — releasing the lock — so a change set sitting unreviewed
38
+ * never blocks the workspace.
39
+ */
40
+ /**
41
+ * Default bound on how long an execution waits for a contended workspace
42
+ * before failing with {@link WorkspaceLockTimeoutError}. Generous — an agent
43
+ * turn legitimately runs for minutes — but finite, so a pathological holder
44
+ * produces an explicit, actionable failure instead of an invisible hang.
45
+ */
46
+ export declare const DEFAULT_WORKSPACE_LOCK_TIMEOUT_MS: number;
47
+ /** The acquisition wait exceeded its bound — the workspace stayed busy. */
48
+ export declare class WorkspaceLockTimeoutError extends Error {
49
+ constructor(workspaceRoot: string, waitedMs: number);
50
+ }
51
+ /** The acquisition wait was cancelled (e.g. the user cancelled the execution). */
52
+ export declare class WorkspaceLockCancelledError extends Error {
53
+ constructor(workspaceRoot: string);
54
+ }
55
+ export interface AcquireWorkspaceLockOptions {
56
+ /**
57
+ * Invoked once, when the first acquisition attempt finds the workspace
58
+ * held by another turn — the hook for surfacing a visible "waiting for
59
+ * workspace" state to the user. Never invoked on an uncontended acquire.
60
+ */
61
+ readonly onWaiting?: () => void | Promise<void>;
62
+ /** Invoked on every poll while waiting (Temporal activity liveness). */
63
+ readonly heartbeat?: () => void;
64
+ /** Aborts the wait immediately (Temporal activity cancellation). */
65
+ readonly signal?: AbortSignal;
66
+ /** Max wait before {@link WorkspaceLockTimeoutError}. */
67
+ readonly timeoutMs?: number;
68
+ /** Poll interval override (tests). */
69
+ readonly pollIntervalMs?: number;
70
+ /** Staleness bound override (tests). */
71
+ readonly staleMs?: number;
72
+ /** Lock-artifact directory override (tests). */
73
+ readonly lockDir?: string;
74
+ }
75
+ /** Idempotent releaser returned by {@link acquireWorkspaceLock}. */
76
+ export type ReleaseWorkspaceLock = () => Promise<void>;
77
+ /**
78
+ * Acquire the exclusive turn lock for a workspace working tree, waiting (with
79
+ * heartbeats and cancellation) while another turn holds it.
80
+ *
81
+ * The caller must hold the lock across the turn's ENTIRE tree-mutating window
82
+ * — decision reconcile, HITL gate install, the agent's own writes, and the
83
+ * candidate capture — and release it in a `finally` as the last
84
+ * workspace-touching step.
85
+ */
86
+ export declare function acquireWorkspaceLock(workspaceRoot: string, options?: AcquireWorkspaceLockOptions): Promise<ReleaseWorkspaceLock>;
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Per-workspace turn lock — serializes agent-execution turns that share a
3
+ * working tree.
4
+ *
5
+ * Why this exists: the file-review substrate (shared/filereview) computes a
6
+ * turn's change set as `git diff baselineTree candidateTree`, where both trees
7
+ * are live snapshots of the working directory at turn start/end. That model is
8
+ * correct for a single writer, but nothing scopes a working tree to one
9
+ * execution: sessions declaring the same `localPath` (or sharing the runner's
10
+ * `workspaceRootDir`) resolve to the SAME directory, and the runner happily
11
+ * runs activities concurrently. A concurrent turn's write landing between
12
+ * another turn's baseline and candidate gets misattributed to that other turn
13
+ * (observed in prod: aex_01kwpzhmvbvwqdez9cb331nekr reviewed a notes.md it
14
+ * never wrote). The same race lets a reject-reconcile in one session silently
15
+ * revert a file another session's user just approved.
16
+ *
17
+ * Why a FILE lock and not in-process/server-side coordination: the shared
18
+ * resource is a directory on one host. A `localPath` entry resolves to the
19
+ * user's literal directory in ANY runner process on the machine — the CLI
20
+ * daemon and the desktop app's embedded runner can contend on one tree while
21
+ * answering to DIFFERENT control planes, so no single server can see all
22
+ * contenders and no in-process mutex can exclude a sibling process. Mutual
23
+ * exclusion must live where the collision happens: the filesystem.
24
+ *
25
+ * Mechanics (proper-lockfile):
26
+ * - The lock artifact lives under `~/.stigmer/workspace-locks/{key}.lock`,
27
+ * NEVER inside the user's workspace (issue #173: attaching a real repo must
28
+ * leave no Stigmer droppings). The key is sha256(realpath(workspaceRoot)),
29
+ * so symlink aliases of one directory converge on one lock — the same
30
+ * keying pattern as getHitlGateDir in platform-dir.ts.
31
+ * - While held, proper-lockfile refreshes the artifact's mtime on an interval;
32
+ * if the holder process dies, refreshing stops and the artifact goes stale,
33
+ * so the next waiter simply takes over. A crashed runner can never deadlock
34
+ * a workspace, and no human ever has to delete a lock file.
35
+ * - Deadlock-free by construction: an activity holds at most ONE lock (its
36
+ * primary workspace root), and a turn that pauses for human approval ENDS
37
+ * its activity — releasing the lock — so a change set sitting unreviewed
38
+ * never blocks the workspace.
39
+ */
40
+ import { join, resolve } from "node:path";
41
+ import { homedir } from "node:os";
42
+ import { createHash } from "node:crypto";
43
+ import { mkdir, realpath } from "node:fs/promises";
44
+ import lockfile from "proper-lockfile";
45
+ /** How long a waiter polls between acquisition attempts. */
46
+ const DEFAULT_POLL_INTERVAL_MS = 1_000;
47
+ /**
48
+ * Default bound on how long an execution waits for a contended workspace
49
+ * before failing with {@link WorkspaceLockTimeoutError}. Generous — an agent
50
+ * turn legitimately runs for minutes — but finite, so a pathological holder
51
+ * produces an explicit, actionable failure instead of an invisible hang.
52
+ */
53
+ export const DEFAULT_WORKSPACE_LOCK_TIMEOUT_MS = 15 * 60 * 1_000;
54
+ /**
55
+ * How long a lock artifact may go un-refreshed before waiters treat the
56
+ * holder as dead and take over. proper-lockfile refreshes at stale/2, so a
57
+ * live holder can never be usurped; only a crashed process trips this.
58
+ */
59
+ const DEFAULT_STALE_MS = 10_000;
60
+ /** The acquisition wait exceeded its bound — the workspace stayed busy. */
61
+ export class WorkspaceLockTimeoutError extends Error {
62
+ constructor(workspaceRoot, waitedMs) {
63
+ super(`Workspace is in use by another session: ${workspaceRoot} ` +
64
+ `(waited ${Math.round(waitedMs / 1000)}s). Another agent execution is ` +
65
+ `operating on this workspace directory; retry after it finishes.`);
66
+ this.name = "WorkspaceLockTimeoutError";
67
+ }
68
+ }
69
+ /** The acquisition wait was cancelled (e.g. the user cancelled the execution). */
70
+ export class WorkspaceLockCancelledError extends Error {
71
+ constructor(workspaceRoot) {
72
+ super(`Workspace lock wait cancelled for ${workspaceRoot}`);
73
+ this.name = "WorkspaceLockCancelledError";
74
+ }
75
+ }
76
+ /** Runner-owned home for lock artifacts (HOME override honored, as in platform-dir.ts). */
77
+ function defaultLockDir() {
78
+ const home = process.env.HOME || process.env.USERPROFILE || homedir();
79
+ return join(home, ".stigmer", "workspace-locks");
80
+ }
81
+ /**
82
+ * Acquire the exclusive turn lock for a workspace working tree, waiting (with
83
+ * heartbeats and cancellation) while another turn holds it.
84
+ *
85
+ * The caller must hold the lock across the turn's ENTIRE tree-mutating window
86
+ * — decision reconcile, HITL gate install, the agent's own writes, and the
87
+ * candidate capture — and release it in a `finally` as the last
88
+ * workspace-touching step.
89
+ */
90
+ export async function acquireWorkspaceLock(workspaceRoot, options = {}) {
91
+ const { onWaiting, heartbeat, signal, timeoutMs = DEFAULT_WORKSPACE_LOCK_TIMEOUT_MS, pollIntervalMs = DEFAULT_POLL_INTERVAL_MS, staleMs = DEFAULT_STALE_MS, lockDir = defaultLockDir(), } = options;
92
+ // Resolve symlink aliases so every path spelling of one directory contends
93
+ // on one lock. The resolved path is also what we hand proper-lockfile as
94
+ // the target (with realpath:false — already resolved here). A root that
95
+ // does not exist yet cannot be realpath'd, so it locks on its canonical
96
+ // absolute spelling instead — proper-lockfile never touches the target
97
+ // itself (the artifact lives at lockfilePath), so the lock still works.
98
+ const resolvedRoot = await realpath(workspaceRoot).catch(() => resolve(workspaceRoot));
99
+ const key = createHash("sha256").update(resolvedRoot).digest("hex").slice(0, 16);
100
+ await mkdir(lockDir, { recursive: true });
101
+ const lockfilePath = join(lockDir, `${key}.lock`);
102
+ const startedAt = Date.now();
103
+ let waitingReported = false;
104
+ for (;;) {
105
+ if (signal?.aborted) {
106
+ throw new WorkspaceLockCancelledError(resolvedRoot);
107
+ }
108
+ try {
109
+ const release = await lockfile.lock(resolvedRoot, {
110
+ lockfilePath,
111
+ realpath: false,
112
+ stale: staleMs,
113
+ // No library-side retries: the wait loop below owns retry policy so it
114
+ // can heartbeat, report waiting, honor cancellation, and bound the wait.
115
+ retries: 0,
116
+ // A compromised lock (artifact vanished / refresh missed its staleness
117
+ // window under extreme event-loop stall) must not crash the worker
118
+ // process — the default behavior throws uncaught. Log loudly and let
119
+ // the turn finish: the exposure is bounded to pre-lock semantics.
120
+ onCompromised: (err) => {
121
+ console.error(`[workspace-lock] lock on ${resolvedRoot} compromised mid-turn ` +
122
+ `(continuing unlocked): ${err}`);
123
+ },
124
+ });
125
+ if (waitingReported) {
126
+ console.log(`[workspace-lock] acquired ${resolvedRoot} after waiting ` +
127
+ `${Date.now() - startedAt}ms`);
128
+ }
129
+ // Idempotent wrapper: the executors release in a `finally` that also
130
+ // runs on paths where an earlier error may already have torn the lock
131
+ // down; a double release (or a release racing staleness takeover) must
132
+ // never mask the turn's real outcome.
133
+ let released = false;
134
+ return async () => {
135
+ if (released)
136
+ return;
137
+ released = true;
138
+ try {
139
+ await release();
140
+ }
141
+ catch (err) {
142
+ console.warn(`[workspace-lock] release of ${resolvedRoot} failed (ignored): ${err}`);
143
+ }
144
+ };
145
+ }
146
+ catch (err) {
147
+ if (!isLockHeldError(err))
148
+ throw err;
149
+ }
150
+ if (!waitingReported) {
151
+ waitingReported = true;
152
+ console.log(`[workspace-lock] ${resolvedRoot} is held by another turn; waiting`);
153
+ try {
154
+ await onWaiting?.();
155
+ }
156
+ catch (err) {
157
+ console.warn(`[workspace-lock] onWaiting callback failed (non-fatal): ${err}`);
158
+ }
159
+ }
160
+ const waitedMs = Date.now() - startedAt;
161
+ if (waitedMs + pollIntervalMs > timeoutMs) {
162
+ throw new WorkspaceLockTimeoutError(resolvedRoot, waitedMs);
163
+ }
164
+ heartbeat?.();
165
+ await sleepAbortable(pollIntervalMs, signal);
166
+ }
167
+ }
168
+ /** proper-lockfile signals "already held" with code ELOCKED. */
169
+ function isLockHeldError(err) {
170
+ return typeof err === "object" && err !== null &&
171
+ err.code === "ELOCKED";
172
+ }
173
+ /** Sleep that wakes immediately when the signal aborts (wait stays responsive). */
174
+ function sleepAbortable(ms, signal) {
175
+ return new Promise((resolve) => {
176
+ const timer = setTimeout(() => {
177
+ signal?.removeEventListener("abort", onAbort);
178
+ resolve();
179
+ }, ms);
180
+ const onAbort = () => {
181
+ clearTimeout(timer);
182
+ resolve();
183
+ };
184
+ signal?.addEventListener("abort", onAbort, { once: true });
185
+ });
186
+ }
187
+ //# sourceMappingURL=workspace-lock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workspace-lock.js","sourceRoot":"","sources":["../../../src/shared/workspace/workspace-lock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AAEH,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AACnD,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AAEvC,4DAA4D;AAC5D,MAAM,wBAA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,GAAG,KAAK,IAAI;QAC3C,GAA0B,CAAC,IAAI,KAAK,SAAS,CAAC;AACnD,CAAC;AAED,mFAAmF;AACnF,SAAS,cAAc,CAAC,EAAU,EAAE,MAAoB;IACtD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE;YAC5B,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC9C,OAAO,EAAE,CAAC;QACZ,CAAC,EAAE,EAAE,CAAC,CAAC;QACP,MAAM,OAAO,GAAG,GAAG,EAAE;YACnB,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC;QACF,MAAM,EAAE,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;IAC7D,CAAC,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stigmer/runner",
3
- "version": "3.1.1",
3
+ "version": "3.1.3",
4
4
  "description": "Embeddable Temporal worker for the Stigmer AI agent platform — handles agent execution, workflow orchestration, and MCP server management",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -77,16 +77,15 @@
77
77
  "@langchain/langgraph": "^1.3.0",
78
78
  "@langchain/mcp-adapters": "^1.1.3",
79
79
  "@langchain/openai": "^1.4.0",
80
- "zod-to-json-schema": "^3.24.0",
81
80
  "@opentelemetry/api": "^1.9.0",
82
81
  "@opentelemetry/core": "^2.0.0",
83
82
  "@opentelemetry/exporter-metrics-otlp-grpc": "^0.218.0",
84
- "@opentelemetry/sdk-metrics": "^2.0.0",
85
83
  "@opentelemetry/exporter-trace-otlp-grpc": "^0.218.0",
86
84
  "@opentelemetry/resources": "^2.0.0",
85
+ "@opentelemetry/sdk-metrics": "^2.0.0",
87
86
  "@opentelemetry/sdk-trace-base": "^2.0.0",
88
87
  "@opentelemetry/sdk-trace-node": "^2.0.0",
89
- "@stigmer/protos": "3.1.1",
88
+ "@stigmer/protos": "3.1.3",
90
89
  "@temporalio/activity": "^1.11.0",
91
90
  "@temporalio/client": "^1.11.0",
92
91
  "@temporalio/common": "^1.11.0",
@@ -94,14 +93,18 @@
94
93
  "@temporalio/worker": "^1.11.0",
95
94
  "@temporalio/workflow": "^1.16.2",
96
95
  "deepagents": "^1.10.0",
96
+ "diff": "^8.0.4",
97
97
  "jq-wasm": "^1.1.0-jq-1.8.1",
98
98
  "js-yaml": "^4.1.1",
99
+ "proper-lockfile": "^4.1.2",
99
100
  "semver": "^7.8.0",
100
- "zod": "^3.25.0"
101
+ "zod": "^3.25.0",
102
+ "zod-to-json-schema": "^3.24.0"
101
103
  },
102
104
  "devDependencies": {
103
105
  "@temporalio/testing": "^1.16.2",
104
106
  "@types/js-yaml": "^4.0.9",
107
+ "@types/proper-lockfile": "^4.1.4",
105
108
  "@types/semver": "^7.7.1",
106
109
  "esbuild": "^0.28.0",
107
110
  "tsx": "^4.21.0",
@@ -33,6 +33,7 @@ describe("loadConfig", () => {
33
33
  expect(config.proxyEndpoint).toBeNull();
34
34
  expect(config.maxConcurrentActivities).toBe(5);
35
35
  expect(config.cursorStreamStallTimeoutMs).toBe(180000);
36
+ expect(config.workspaceLockTimeoutMs).toBe(900000);
36
37
  });
37
38
 
38
39
  it("respects CURSOR_STREAM_STALL_TIMEOUT_MS", () => {
@@ -42,6 +43,13 @@ describe("loadConfig", () => {
42
43
  expect(config.cursorStreamStallTimeoutMs).toBe(90000);
43
44
  });
44
45
 
46
+ it("respects WORKSPACE_LOCK_TIMEOUT_MS", () => {
47
+ process.env.CURSOR_API_KEY = "test-key";
48
+ process.env.WORKSPACE_LOCK_TIMEOUT_MS = "60000";
49
+ const config = loadConfig();
50
+ expect(config.workspaceLockTimeoutMs).toBe(60000);
51
+ });
52
+
45
53
  it("respects STIGMER_TASK_QUEUE", () => {
46
54
  process.env.STIGMER_TASK_QUEUE = "runner:abc123";
47
55
  process.env.CURSOR_API_KEY = "test-key";
@@ -622,6 +622,7 @@ function makeConfig() {
622
622
  checkpointerProxyEndpoint: null,
623
623
  primaryModel: "gpt-4.1",
624
624
  cursorStreamStallTimeoutMs: 180000,
625
+ workspaceLockTimeoutMs: 900000,
625
626
  };
626
627
  }
627
628
 
@@ -601,6 +601,7 @@ function makeConfig() {
601
601
  checkpointerProxyEndpoint: null,
602
602
  primaryModel: "gpt-4.1",
603
603
  cursorStreamStallTimeoutMs: 180000,
604
+ workspaceLockTimeoutMs: 900000,
604
605
  };
605
606
  }
606
607
 
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Tests for the Cursor harness's attachment resolver.
3
+ *
4
+ * The load-bearing behaviors: storage-key attachments materialize under the
5
+ * platform inputs dir (the universal path — every server-created attachment
6
+ * carries a storage key), the workspace `.stigmer` symlink exists even when
7
+ * the agent has no skills, and any attachment that cannot be materialized
8
+ * fails the resolution loudly (the silent-skip regression behind "plan file
9
+ * wasn't found").
10
+ */
11
+
12
+ import { describe, it, expect, beforeEach, afterEach } from "vitest";
13
+ import { mkdtempSync, writeFileSync, readFileSync, rmSync, lstatSync, readlinkSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { tmpdir } from "node:os";
16
+ import { resolveAttachments, AttachmentResolutionError } from "../attachment-resolver.js";
17
+ import { getPlatformDir } from "../../../shared/workspace/platform-dir.js";
18
+ import { makeInMemoryArtifactStorage } from "../../../__test-utils__/fake-artifact-storage.js";
19
+
20
+ function makeAttachment(overrides: Partial<{
21
+ filename: string;
22
+ storageKey: string;
23
+ mountPath: string;
24
+ contentType: string;
25
+ extract: boolean;
26
+ localPath: string;
27
+ }> = {}) {
28
+ return {
29
+ filename: overrides.filename ?? "plan.md",
30
+ storageKey: overrides.storageKey ?? "attachments/01ABC/plan.md",
31
+ mountPath: overrides.mountPath ?? "",
32
+ contentType: overrides.contentType ?? "text/markdown",
33
+ extract: overrides.extract ?? false,
34
+ localPath: overrides.localPath ?? "",
35
+ $typeName: "ai.stigmer.agentic.agentexecution.v1.Attachment" as const,
36
+ $unknown: undefined,
37
+ } as any;
38
+ }
39
+
40
+ describe("resolveAttachments", () => {
41
+ let workspaceDir: string;
42
+ let sessionId: string;
43
+ let platformDir: string;
44
+
45
+ beforeEach(() => {
46
+ workspaceDir = mkdtempSync(join(tmpdir(), "attach-ws-"));
47
+ sessionId = `test-session-${Date.now()}-${Math.random().toString(36).slice(2)}`;
48
+ platformDir = getPlatformDir(sessionId);
49
+ });
50
+
51
+ afterEach(() => {
52
+ rmSync(platformDir, { recursive: true, force: true });
53
+ rmSync(workspaceDir, { recursive: true, force: true });
54
+ });
55
+
56
+ function options(overrides: Partial<Parameters<typeof resolveAttachments>[1]> = {}) {
57
+ return {
58
+ sessionId,
59
+ primaryWorkspaceDir: workspaceDir,
60
+ mode: "local" as const,
61
+ storage: undefined,
62
+ ...overrides,
63
+ };
64
+ }
65
+
66
+ it("returns [] and touches nothing for an execution without attachments", async () => {
67
+ const result = await resolveAttachments([], options());
68
+
69
+ expect(result).toEqual([]);
70
+ expect(() => lstatSync(join(workspaceDir, ".stigmer"))).toThrow();
71
+ });
72
+
73
+ it("downloads a storage-key attachment into .stigmer/inputs (the uploadAttachment path)", async () => {
74
+ const { storage } = makeInMemoryArtifactStorage();
75
+ await storage.upload("attachments/01ABC/plan.md", Buffer.from("# The Plan"), "text/markdown");
76
+
77
+ const result = await resolveAttachments([makeAttachment()], options({ storage }));
78
+
79
+ expect(result).toEqual([
80
+ { filename: "plan.md", relativePath: ".stigmer/inputs/plan.md" },
81
+ ]);
82
+ expect(readFileSync(join(platformDir, "inputs", "plan.md"), "utf-8")).toBe("# The Plan");
83
+ });
84
+
85
+ it("ensures the workspace .stigmer symlink even when the agent has no skills", async () => {
86
+ // The regression this guards: only the skill resolver created the link,
87
+ // so a skill-less agent's attachments were written but unreachable.
88
+ const { storage } = makeInMemoryArtifactStorage();
89
+ await storage.upload("attachments/01ABC/plan.md", Buffer.from("# The Plan"), "text/markdown");
90
+
91
+ await resolveAttachments([makeAttachment()], options({ storage }));
92
+
93
+ const linkPath = join(workspaceDir, ".stigmer");
94
+ expect(lstatSync(linkPath).isSymbolicLink()).toBe(true);
95
+ expect(readlinkSync(linkPath)).toBe(platformDir);
96
+ // The resolved relative path actually dangles nowhere: it reads through
97
+ // the link to the platform dir.
98
+ expect(readFileSync(join(workspaceDir, ".stigmer", "inputs", "plan.md"), "utf-8")).toBe("# The Plan");
99
+ });
100
+
101
+ it("copies a localPath attachment directly in local mode (no storage round-trip)", async () => {
102
+ const srcPath = join(workspaceDir, "src.csv");
103
+ writeFileSync(srcPath, "a,b,c");
104
+
105
+ const result = await resolveAttachments(
106
+ [makeAttachment({ filename: "data.csv", storageKey: "", localPath: srcPath })],
107
+ options(),
108
+ );
109
+
110
+ expect(result).toEqual([
111
+ { filename: "data.csv", relativePath: ".stigmer/inputs/data.csv" },
112
+ ]);
113
+ expect(readFileSync(join(platformDir, "inputs", "data.csv"), "utf-8")).toBe("a,b,c");
114
+ });
115
+
116
+ it("ignores localPath in cloud mode and downloads by storage key", async () => {
117
+ const { storage } = makeInMemoryArtifactStorage();
118
+ await storage.upload("attachments/01ABC/plan.md", Buffer.from("from storage"), "text/markdown");
119
+
120
+ const result = await resolveAttachments(
121
+ [makeAttachment({ localPath: "/nonexistent/host/path.md" })],
122
+ options({ mode: "cloud", storage }),
123
+ );
124
+
125
+ expect(result).toHaveLength(1);
126
+ expect(readFileSync(join(platformDir, "inputs", "plan.md"), "utf-8")).toBe("from storage");
127
+ });
128
+
129
+ it("fails loudly when the storage download fails (no silent skip)", async () => {
130
+ const { storage } = makeInMemoryArtifactStorage();
131
+ // Nothing uploaded — the download will throw.
132
+
133
+ await expect(
134
+ resolveAttachments([makeAttachment()], options({ storage })),
135
+ ).rejects.toThrow(AttachmentResolutionError);
136
+ });
137
+
138
+ it("fails loudly when a storage-backed attachment arrives with no usable storage", async () => {
139
+ await expect(
140
+ resolveAttachments([makeAttachment()], options({ storage: undefined })),
141
+ ).rejects.toThrow(/artifact storage is unavailable/);
142
+ });
143
+
144
+ it("fails loudly on an attachment with neither localPath nor storageKey", async () => {
145
+ await expect(
146
+ resolveAttachments(
147
+ [makeAttachment({ storageKey: "", localPath: "" })],
148
+ options(),
149
+ ),
150
+ ).rejects.toThrow(/missing storageKey/);
151
+ });
152
+
153
+ it("fails loudly when the local file cannot be read", async () => {
154
+ await expect(
155
+ resolveAttachments(
156
+ [makeAttachment({ storageKey: "", localPath: join(workspaceDir, "missing.md") })],
157
+ options(),
158
+ ),
159
+ ).rejects.toThrow(AttachmentResolutionError);
160
+ });
161
+ });