@nebutra/agent-runtime 0.2.0

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 (179) hide show
  1. package/.turbo/turbo-build.log +115 -0
  2. package/.turbo/turbo-test.log +44 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/CHANGELOG.md +253 -0
  5. package/LICENSE +676 -0
  6. package/README.md +50 -0
  7. package/dist/adapters/dispatcher-sse.d.ts +68 -0
  8. package/dist/adapters/dispatcher-sse.js +11 -0
  9. package/dist/adapters/dispatcher-sse.js.map +1 -0
  10. package/dist/adapters/index.d.ts +12 -0
  11. package/dist/adapters/index.js +21 -0
  12. package/dist/adapters/index.js.map +1 -0
  13. package/dist/adapters/mcp-catalog.d.ts +58 -0
  14. package/dist/adapters/mcp-catalog.js +9 -0
  15. package/dist/adapters/mcp-catalog.js.map +1 -0
  16. package/dist/adapters/prisma-rollout.d.ts +60 -0
  17. package/dist/adapters/prisma-rollout.js +7 -0
  18. package/dist/adapters/prisma-rollout.js.map +1 -0
  19. package/dist/chunk-24ZXP7FI.js +93 -0
  20. package/dist/chunk-24ZXP7FI.js.map +1 -0
  21. package/dist/chunk-2DA6Q6TN.js +126 -0
  22. package/dist/chunk-2DA6Q6TN.js.map +1 -0
  23. package/dist/chunk-37BBB2P2.js +73 -0
  24. package/dist/chunk-37BBB2P2.js.map +1 -0
  25. package/dist/chunk-57W3AR43.js +52 -0
  26. package/dist/chunk-57W3AR43.js.map +1 -0
  27. package/dist/chunk-5N4644PB.js +67 -0
  28. package/dist/chunk-5N4644PB.js.map +1 -0
  29. package/dist/chunk-5YS7WAPS.js +177 -0
  30. package/dist/chunk-5YS7WAPS.js.map +1 -0
  31. package/dist/chunk-6EGG2OZC.js +13 -0
  32. package/dist/chunk-6EGG2OZC.js.map +1 -0
  33. package/dist/chunk-7BUOF367.js +126 -0
  34. package/dist/chunk-7BUOF367.js.map +1 -0
  35. package/dist/chunk-BJBBR3QA.js +121 -0
  36. package/dist/chunk-BJBBR3QA.js.map +1 -0
  37. package/dist/chunk-CGRCUKGT.js +73 -0
  38. package/dist/chunk-CGRCUKGT.js.map +1 -0
  39. package/dist/chunk-FUG5DT2C.js +75 -0
  40. package/dist/chunk-FUG5DT2C.js.map +1 -0
  41. package/dist/chunk-LO24VOA3.js +199 -0
  42. package/dist/chunk-LO24VOA3.js.map +1 -0
  43. package/dist/chunk-MUF7ZZTO.js +57 -0
  44. package/dist/chunk-MUF7ZZTO.js.map +1 -0
  45. package/dist/chunk-NN7DATXA.js +46 -0
  46. package/dist/chunk-NN7DATXA.js.map +1 -0
  47. package/dist/chunk-PGGWSUTM.js +33 -0
  48. package/dist/chunk-PGGWSUTM.js.map +1 -0
  49. package/dist/chunk-RDKYDMXT.js +135 -0
  50. package/dist/chunk-RDKYDMXT.js.map +1 -0
  51. package/dist/chunk-YYFPDBJG.js +63 -0
  52. package/dist/chunk-YYFPDBJG.js.map +1 -0
  53. package/dist/chunk-ZMYX5VBU.js +135 -0
  54. package/dist/chunk-ZMYX5VBU.js.map +1 -0
  55. package/dist/chunk-ZTSKS42I.js +131 -0
  56. package/dist/chunk-ZTSKS42I.js.map +1 -0
  57. package/dist/commands.d.ts +74 -0
  58. package/dist/commands.js +10 -0
  59. package/dist/commands.js.map +1 -0
  60. package/dist/definitions.d.ts +94 -0
  61. package/dist/definitions.js +15 -0
  62. package/dist/definitions.js.map +1 -0
  63. package/dist/dispatcher.d.ts +50 -0
  64. package/dist/dispatcher.js +8 -0
  65. package/dist/dispatcher.js.map +1 -0
  66. package/dist/durable-turn.d.ts +58 -0
  67. package/dist/durable-turn.js +9 -0
  68. package/dist/durable-turn.js.map +1 -0
  69. package/dist/hook-pipeline.d.ts +114 -0
  70. package/dist/hook-pipeline.js +13 -0
  71. package/dist/hook-pipeline.js.map +1 -0
  72. package/dist/index.d.ts +1874 -0
  73. package/dist/index.js +3117 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/loop.d.ts +78 -0
  76. package/dist/loop.js +9 -0
  77. package/dist/loop.js.map +1 -0
  78. package/dist/mcp-bridge.d.ts +48 -0
  79. package/dist/mcp-bridge.js +8 -0
  80. package/dist/mcp-bridge.js.map +1 -0
  81. package/dist/model.d.ts +154 -0
  82. package/dist/model.js +9 -0
  83. package/dist/model.js.map +1 -0
  84. package/dist/policy.d.ts +130 -0
  85. package/dist/policy.js +23 -0
  86. package/dist/policy.js.map +1 -0
  87. package/dist/protocol.d.ts +170 -0
  88. package/dist/protocol.js +15 -0
  89. package/dist/protocol.js.map +1 -0
  90. package/dist/rollout-store-persistent.d.ts +48 -0
  91. package/dist/rollout-store-persistent.js +9 -0
  92. package/dist/rollout-store-persistent.js.map +1 -0
  93. package/dist/rollout.d.ts +82 -0
  94. package/dist/rollout.js +15 -0
  95. package/dist/rollout.js.map +1 -0
  96. package/dist/sandbox.d.ts +65 -0
  97. package/dist/sandbox.js +15 -0
  98. package/dist/sandbox.js.map +1 -0
  99. package/dist/skills.d.ts +93 -0
  100. package/dist/skills.js +10 -0
  101. package/dist/skills.js.map +1 -0
  102. package/dist/subagents.d.ts +129 -0
  103. package/dist/subagents.js +21 -0
  104. package/dist/subagents.js.map +1 -0
  105. package/dist/tools.d.ts +77 -0
  106. package/dist/tools.js +9 -0
  107. package/dist/tools.js.map +1 -0
  108. package/package.json +74 -0
  109. package/src/adapters/dispatcher-sse.test.ts +218 -0
  110. package/src/adapters/dispatcher-sse.ts +222 -0
  111. package/src/adapters/index.ts +18 -0
  112. package/src/adapters/mcp-catalog.test.ts +213 -0
  113. package/src/adapters/mcp-catalog.ts +188 -0
  114. package/src/adapters/prisma-rollout.test.ts +153 -0
  115. package/src/adapters/prisma-rollout.ts +104 -0
  116. package/src/agent-runtime.test.ts +176 -0
  117. package/src/artifact-stream.test.ts +330 -0
  118. package/src/artifact-stream.ts +453 -0
  119. package/src/channel-gateway.test.ts +432 -0
  120. package/src/channel-gateway.ts +357 -0
  121. package/src/code-review.test.ts +501 -0
  122. package/src/code-review.ts +495 -0
  123. package/src/command-suggestions.test.ts +251 -0
  124. package/src/command-suggestions.ts +338 -0
  125. package/src/commands.test.ts +184 -0
  126. package/src/commands.ts +140 -0
  127. package/src/commit-message.test.ts +249 -0
  128. package/src/commit-message.ts +180 -0
  129. package/src/context-compaction.test.ts +522 -0
  130. package/src/context-compaction.ts +434 -0
  131. package/src/definitions.test.ts +78 -0
  132. package/src/definitions.ts +190 -0
  133. package/src/deployment-status.test.ts +215 -0
  134. package/src/deployment-status.ts +227 -0
  135. package/src/design-context.test.ts +195 -0
  136. package/src/design-context.ts +198 -0
  137. package/src/dispatcher.test.ts +234 -0
  138. package/src/dispatcher.ts +189 -0
  139. package/src/durable-turn.test.ts +209 -0
  140. package/src/durable-turn.ts +135 -0
  141. package/src/edit-planner.test.ts +204 -0
  142. package/src/edit-planner.ts +325 -0
  143. package/src/fuzzy-match.test.ts +311 -0
  144. package/src/fuzzy-match.ts +444 -0
  145. package/src/hook-pipeline.test.ts +279 -0
  146. package/src/hook-pipeline.ts +373 -0
  147. package/src/inbound-admission.test.ts +394 -0
  148. package/src/inbound-admission.ts +246 -0
  149. package/src/index.ts +47 -0
  150. package/src/loop.test.ts +161 -0
  151. package/src/loop.ts +211 -0
  152. package/src/mcp-bridge.test.ts +165 -0
  153. package/src/mcp-bridge.ts +76 -0
  154. package/src/memory-provider.test.ts +232 -0
  155. package/src/memory-provider.ts +257 -0
  156. package/src/model.ts +168 -0
  157. package/src/permission-ruleset.test.ts +301 -0
  158. package/src/permission-ruleset.ts +200 -0
  159. package/src/policy.ts +151 -0
  160. package/src/project-repo.test.ts +232 -0
  161. package/src/project-repo.ts +311 -0
  162. package/src/protocol.ts +159 -0
  163. package/src/rollout-store-persistent.test.ts +217 -0
  164. package/src/rollout-store-persistent.ts +166 -0
  165. package/src/rollout.ts +150 -0
  166. package/src/sandbox.ts +113 -0
  167. package/src/session-share.test.ts +360 -0
  168. package/src/session-share.ts +310 -0
  169. package/src/skill-distillation.test.ts +177 -0
  170. package/src/skill-distillation.ts +369 -0
  171. package/src/skills.test.ts +277 -0
  172. package/src/skills.ts +255 -0
  173. package/src/subagents.test.ts +290 -0
  174. package/src/subagents.ts +332 -0
  175. package/src/tools.ts +126 -0
  176. package/src/workbench.test.ts +0 -0
  177. package/src/workbench.ts +0 -0
  178. package/tsconfig.json +12 -0
  179. package/tsup.config.ts +33 -0
@@ -0,0 +1,176 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { z } from "zod";
3
+ import { isTurnTerminal, mergeTurnConfig, type TurnConfig } from "./model";
4
+ import { DEFAULT_CAPABILITY_POLICY, DENIED, isApproval, resolveRuleDecision } from "./policy";
5
+ import { METHOD_REGISTRY, resolveScope, scopeKey } from "./protocol";
6
+ import {
7
+ InMemoryRolloutStore,
8
+ PERSISTED_OUTPUT_MAX_BYTES,
9
+ replay,
10
+ sanitizeForPersist,
11
+ } from "./rollout";
12
+ import {
13
+ assertSafePosture,
14
+ createHttpSandbox,
15
+ NoExecutorConfiguredError,
16
+ REFUSING_SANDBOX,
17
+ SandboxDelegationError,
18
+ } from "./sandbox";
19
+ import { ToolRegistry } from "./tools";
20
+
21
+ const baseConfig: TurnConfig = {
22
+ model: "m",
23
+ provider: "p",
24
+ approvalPolicy: "on_request",
25
+ capabilityPolicy: "external_sandbox",
26
+ };
27
+
28
+ describe("model", () => {
29
+ it("merges overrides immutably", () => {
30
+ const merged = mergeTurnConfig(baseConfig, { model: "x" });
31
+ expect(merged.model).toBe("x");
32
+ expect(baseConfig.model).toBe("m");
33
+ });
34
+ it("detects terminal turn events", () => {
35
+ expect(
36
+ isTurnTerminal({
37
+ type: "turn.completed",
38
+ usage: { inputTokens: 0, cachedInputTokens: 0, outputTokens: 0, reasoningOutputTokens: 0 },
39
+ }),
40
+ ).toBe(true);
41
+ expect(isTurnTerminal({ type: "turn.started" })).toBe(false);
42
+ });
43
+ });
44
+
45
+ describe("policy", () => {
46
+ it("defaults to external_sandbox posture", () => {
47
+ expect(DEFAULT_CAPABILITY_POLICY.kind).toBe("external_sandbox");
48
+ });
49
+ it("forbidden rule auto-rejects regardless of policy", () => {
50
+ expect(resolveRuleDecision("forbidden", { kind: "on_request" })).toBe("auto_reject");
51
+ });
52
+ it("prompt rule under never policy auto-rejects", () => {
53
+ expect(resolveRuleDecision("prompt", { kind: "never" })).toBe("auto_reject");
54
+ });
55
+ it("prompt rule under granular respects the rules gate", () => {
56
+ expect(
57
+ resolveRuleDecision("prompt", {
58
+ kind: "granular",
59
+ config: {
60
+ sandboxApproval: true,
61
+ rules: false,
62
+ skillApproval: false,
63
+ requestPermissions: false,
64
+ mcpElicitations: true,
65
+ },
66
+ }),
67
+ ).toBe("auto_reject");
68
+ });
69
+ it("denied is not an approval", () => {
70
+ expect(isApproval(DENIED)).toBe(false);
71
+ expect(isApproval({ kind: "approved_for_session" })).toBe(true);
72
+ });
73
+ });
74
+
75
+ describe("protocol", () => {
76
+ it("scope key is tenant-prefixed and thread-isolated", () => {
77
+ const a = resolveScope(METHOD_REGISTRY.turnStart, "t1", { threadId: "th1" });
78
+ const b = resolveScope(METHOD_REGISTRY.turnStart, "t2", { threadId: "th1" });
79
+ expect(scopeKey(a)).not.toBe(scopeKey(b)); // cross-tenant never shares a lane
80
+ expect(scopeKey(a)).toContain("t:t1");
81
+ });
82
+ it("thread-scoped method without threadId fails closed", () => {
83
+ expect(() => resolveScope(METHOD_REGISTRY.turnStart, "t1", {})).toThrow();
84
+ });
85
+ });
86
+
87
+ describe("rollout", () => {
88
+ it("caps oversized command output", () => {
89
+ const big = "x".repeat(PERSISTED_OUTPUT_MAX_BYTES + 100);
90
+ const out = sanitizeForPersist({
91
+ id: "1",
92
+ type: "command_execution",
93
+ command: "c",
94
+ aggregatedOutput: big,
95
+ status: "completed",
96
+ });
97
+ expect((out as { aggregatedOutput: string }).aggregatedOutput.length).toBeLessThan(big.length);
98
+ });
99
+ it("replays an append-only log into derived state, bounded by compaction", async () => {
100
+ const store = new InMemoryRolloutStore();
101
+ const at = new Date().toISOString();
102
+ await store.append({
103
+ tenantId: "t",
104
+ threadId: "th",
105
+ type: "session_meta",
106
+ config: baseConfig,
107
+ at,
108
+ });
109
+ await store.append({
110
+ tenantId: "t",
111
+ threadId: "th",
112
+ type: "event",
113
+ at,
114
+ event: { type: "item.completed", item: { id: "i1", type: "agent_message", text: "hi" } },
115
+ });
116
+ await store.append({
117
+ tenantId: "t",
118
+ threadId: "th",
119
+ type: "compacted",
120
+ summary: "summary",
121
+ droppedThrough: "i1",
122
+ at,
123
+ });
124
+ const proj = replay(await store.read("t", "th"));
125
+ expect(proj?.compactionSummary).toBe("summary");
126
+ expect(proj?.items).toHaveLength(0);
127
+ });
128
+ });
129
+
130
+ describe("sandbox", () => {
131
+ it("refuses execution by default (no in-process untrusted exec)", async () => {
132
+ await expect(
133
+ REFUSING_SANDBOX.exec({
134
+ tenantId: "t",
135
+ threadId: "th",
136
+ command: "rm -rf /",
137
+ capabilityPolicy: DEFAULT_CAPABILITY_POLICY,
138
+ }),
139
+ ).rejects.toBeInstanceOf(NoExecutorConfiguredError);
140
+ });
141
+ it("refuses danger_full_access without explicit opt-in", () => {
142
+ expect(() => assertSafePosture({ kind: "danger_full_access" })).toThrow();
143
+ expect(() => assertSafePosture({ kind: "danger_full_access" }, true)).not.toThrow();
144
+ });
145
+ it("surfaces a fail-closed isolator refusal as an error, never a fake result", async () => {
146
+ const fakeFetch = (async () =>
147
+ new Response(JSON.stringify({ error: "execution_refused" }), {
148
+ status: 403,
149
+ })) as unknown as typeof fetch;
150
+ const sandbox = createHttpSandbox("http://isolator:8020", fakeFetch);
151
+ await expect(
152
+ sandbox.exec({
153
+ tenantId: "org_a",
154
+ threadId: "th_1",
155
+ command: "rm -rf /",
156
+ capabilityPolicy: DEFAULT_CAPABILITY_POLICY,
157
+ }),
158
+ ).rejects.toBeInstanceOf(SandboxDelegationError);
159
+ });
160
+ });
161
+
162
+ describe("tools", () => {
163
+ it("validates input and dispatches with tenant context", async () => {
164
+ const reg = new ToolRegistry();
165
+ reg.register(
166
+ { name: "echo", description: "echo", inputSchema: z.object({ v: z.string() }) },
167
+ async (input: { v: string }, ctx) => `${ctx.tenantId}:${input.v}`,
168
+ );
169
+ expect(await reg.dispatch("echo", { v: "hi" }, { tenantId: "t1", threadId: "th" })).toBe(
170
+ "t1:hi",
171
+ );
172
+ await expect(
173
+ reg.dispatch("echo", { v: 1 }, { tenantId: "t1", threadId: "th" }),
174
+ ).rejects.toBeTruthy();
175
+ });
176
+ });
@@ -0,0 +1,330 @@
1
+ import { describe, expect, it, vi } from "vitest";
2
+ import {
3
+ type ActionPorts,
4
+ ActionRunner,
5
+ ArtifactStreamParser,
6
+ type PlanAction,
7
+ stripFencedWrapper,
8
+ unescapeEntities,
9
+ } from "./artifact-stream";
10
+
11
+ // ── Pure helpers ─────────────────────────────────────────────────────────────
12
+
13
+ describe("stripFencedWrapper", () => {
14
+ it("strips a single ```lang fenced wrapper", () => {
15
+ expect(stripFencedWrapper("```ts\nconst a = 1;\n```")).toBe("const a = 1;");
16
+ });
17
+
18
+ it("strips a bare ``` fence", () => {
19
+ expect(stripFencedWrapper("```\nhello\n```")).toBe("hello");
20
+ });
21
+
22
+ it("leaves unfenced content untouched", () => {
23
+ expect(stripFencedWrapper("plain text")).toBe("plain text");
24
+ });
25
+
26
+ it("does not strip inner fences (single wrapper only)", () => {
27
+ const input = "```md\nuse ```code``` here\n```";
28
+ expect(stripFencedWrapper(input)).toBe("use ```code``` here");
29
+ });
30
+ });
31
+
32
+ describe("unescapeEntities", () => {
33
+ it("unescapes < and >", () => {
34
+ expect(unescapeEntities("a &lt;tag&gt; b")).toBe("a <tag> b");
35
+ });
36
+
37
+ it("is a no-op without entities", () => {
38
+ expect(unescapeEntities("nothing here")).toBe("nothing here");
39
+ });
40
+ });
41
+
42
+ // ── Parser ───────────────────────────────────────────────────────────────────
43
+
44
+ function collector() {
45
+ const events: string[] = [];
46
+ return {
47
+ events,
48
+ onArtifactOpen: vi.fn((e) => events.push(`open:${e.artifactId}:${e.title}`)),
49
+ onArtifactClose: vi.fn((e) => events.push(`close:${e.artifactId}`)),
50
+ onActionOpen: vi.fn((e) => events.push(`aopen:${e.actionId}:${e.action.type}`)),
51
+ onActionStream: vi.fn((e) => events.push(`astream:${e.actionId}`)),
52
+ onActionClose: vi.fn((e) => events.push(`aclose:${e.actionId}:${e.action.type}`)),
53
+ };
54
+ }
55
+
56
+ const CTX = { tenantId: "org_123" };
57
+
58
+ describe("ArtifactStreamParser", () => {
59
+ it("parses a single-action artifact in one chunk", () => {
60
+ const c = collector();
61
+ const p = new ArtifactStreamParser(c);
62
+ p.parse(
63
+ "m1",
64
+ CTX,
65
+ `<artifact id="a1" title="Build">` +
66
+ `<action type="file" filePath="src/x.ts">const x = 1;</action></artifact>`,
67
+ );
68
+
69
+ expect(c.onArtifactOpen).toHaveBeenCalledWith(
70
+ expect.objectContaining({
71
+ tenantId: "org_123",
72
+ messageId: "m1",
73
+ artifactId: "a1",
74
+ title: "Build",
75
+ }),
76
+ );
77
+ expect(c.onActionClose).toHaveBeenCalledWith(
78
+ expect.objectContaining({
79
+ tenantId: "org_123",
80
+ action: { type: "file", filePath: "src/x.ts", content: "const x = 1;" },
81
+ }),
82
+ );
83
+ expect(c.onArtifactClose).toHaveBeenCalledTimes(1);
84
+ });
85
+
86
+ it("handles a tag split across two chunks without dup emit", () => {
87
+ const c = collector();
88
+ const p = new ArtifactStreamParser(c);
89
+ p.parse("m1", CTX, `<artifact id="a1" title="Sp`);
90
+ p.parse("m1", CTX, `lit"><action type="shell">npm i</acti`);
91
+ p.parse("m1", CTX, `on></artifact>`);
92
+
93
+ expect(c.onArtifactOpen).toHaveBeenCalledTimes(1);
94
+ expect(c.onArtifactOpen).toHaveBeenCalledWith(
95
+ expect.objectContaining({ artifactId: "a1", title: "Split" }),
96
+ );
97
+ expect(c.onActionClose).toHaveBeenCalledTimes(1);
98
+ expect(c.onActionClose).toHaveBeenCalledWith(
99
+ expect.objectContaining({ action: { type: "shell", content: "npm i" } }),
100
+ );
101
+ expect(c.onArtifactClose).toHaveBeenCalledTimes(1);
102
+ });
103
+
104
+ it("streams partial content via onActionStream then final via onActionClose", () => {
105
+ const c = collector();
106
+ const p = new ArtifactStreamParser(c);
107
+ p.parse("m1", CTX, `<artifact id="a1" title="T"><action type="file" filePath="f">par`);
108
+ p.parse("m1", CTX, `tial</action></artifact>`);
109
+
110
+ expect(c.onActionStream).toHaveBeenCalled();
111
+ expect(c.onActionClose).toHaveBeenCalledWith(
112
+ expect.objectContaining({ action: { type: "file", filePath: "f", content: "partial" } }),
113
+ );
114
+ });
115
+
116
+ it("strips a fenced wrapper and unescapes entities in action content", () => {
117
+ const c = collector();
118
+ const p = new ArtifactStreamParser(c);
119
+ p.parse(
120
+ "m1",
121
+ CTX,
122
+ '<artifact id="a1" title="T"><action type="file" filePath="f">' +
123
+ "```ts\nconst t = &lt;X&gt;();\n```" +
124
+ "</action></artifact>",
125
+ );
126
+
127
+ expect(c.onActionClose).toHaveBeenCalledWith(
128
+ expect.objectContaining({
129
+ action: { type: "file", filePath: "f", content: "const t = <X>();" },
130
+ }),
131
+ );
132
+ });
133
+
134
+ it("preserves order of multiple actions in one artifact", () => {
135
+ const c = collector();
136
+ const p = new ArtifactStreamParser(c);
137
+ p.parse(
138
+ "m1",
139
+ CTX,
140
+ `<artifact id="a1" title="Multi">` +
141
+ `<action type="file" filePath="a.ts">A</action>` +
142
+ `<action type="shell">npm test</action>` +
143
+ `<action type="start">npm run dev</action>` +
144
+ `</artifact>`,
145
+ );
146
+
147
+ const opens = c.events.filter((e) => e.startsWith("aclose:"));
148
+ expect(opens).toEqual(["aclose:0:file", "aclose:1:shell", "aclose:2:start"]);
149
+ });
150
+
151
+ it("parses a data action with operation + projectId", () => {
152
+ const c = collector();
153
+ const p = new ArtifactStreamParser(c);
154
+ p.parse(
155
+ "m1",
156
+ CTX,
157
+ `<artifact id="a1" title="T"><action type="data" operation="migration" projectId="p1">SQL</action></artifact>`,
158
+ );
159
+
160
+ expect(c.onActionClose).toHaveBeenCalledWith(
161
+ expect.objectContaining({
162
+ action: { type: "data", operation: "migration", projectId: "p1", content: "SQL" },
163
+ }),
164
+ );
165
+ });
166
+
167
+ it("isolates state per messageId", () => {
168
+ const c = collector();
169
+ const p = new ArtifactStreamParser(c);
170
+ p.parse("m1", CTX, `<artifact id="a1" title="One">`);
171
+ p.parse("m2", CTX, `<artifact id="b1" title="Two">`);
172
+ p.parse("m1", CTX, `<action type="shell">x</action></artifact>`);
173
+ p.parse("m2", CTX, `<action type="shell">y</action></artifact>`);
174
+
175
+ expect(c.onArtifactOpen).toHaveBeenCalledWith(expect.objectContaining({ artifactId: "a1" }));
176
+ expect(c.onArtifactOpen).toHaveBeenCalledWith(expect.objectContaining({ artifactId: "b1" }));
177
+ expect(c.onActionClose).toHaveBeenCalledTimes(2);
178
+ });
179
+
180
+ it("fails closed on empty tenantId", () => {
181
+ const c = collector();
182
+ const p = new ArtifactStreamParser(c);
183
+ expect(() => p.parse("m1", { tenantId: "" }, '<artifact id="a" title="T">')).toThrow();
184
+ });
185
+ });
186
+
187
+ // ── Runner ───────────────────────────────────────────────────────────────────
188
+
189
+ function ports() {
190
+ const p = {
191
+ writeFile: vi.fn(async (_a: PlanAction, _c: { tenantId: string }) => undefined),
192
+ runShell: vi.fn(async (_a: PlanAction, _c: { tenantId: string }) => ({
193
+ exitCode: 0,
194
+ output: "ok",
195
+ })),
196
+ dataOp: vi.fn(async (_a: PlanAction, _c: { tenantId: string }) => undefined),
197
+ };
198
+ return p as typeof p & ActionPorts;
199
+ }
200
+
201
+ const fileAction: PlanAction = { type: "file", filePath: "a.ts", content: "x" };
202
+ const shellAction: PlanAction = { type: "shell", content: "npm i" };
203
+
204
+ describe("ActionRunner — state machine", () => {
205
+ it("transitions pending -> running -> complete", async () => {
206
+ const r = new ActionRunner(ports(), CTX);
207
+ r.register("0", fileAction);
208
+ expect(r.get("0").status).toBe("pending");
209
+ await r.runAction("0");
210
+ expect(r.get("0").status).toBe("complete");
211
+ expect(r.get("0").executed).toBe(true);
212
+ });
213
+
214
+ it("delegates file write to injected port (no in-proc exec)", async () => {
215
+ const p = ports();
216
+ const r = new ActionRunner(p, CTX);
217
+ r.register("0", fileAction);
218
+ await r.runAction("0");
219
+ expect(p.writeFile).toHaveBeenCalledWith(
220
+ fileAction,
221
+ expect.objectContaining({ tenantId: "org_123" }),
222
+ );
223
+ });
224
+
225
+ it("delegates shell to injected port", async () => {
226
+ const p = ports();
227
+ const r = new ActionRunner(p, CTX);
228
+ r.register("0", shellAction);
229
+ await r.runAction("0");
230
+ expect(p.runShell).toHaveBeenCalledWith(
231
+ shellAction,
232
+ expect.objectContaining({ tenantId: "org_123" }),
233
+ );
234
+ });
235
+
236
+ it("delegates data action to dataOp port", async () => {
237
+ const p = ports();
238
+ const r = new ActionRunner(p, CTX);
239
+ const dataAction: PlanAction = { type: "data", operation: "query", content: "SELECT 1" };
240
+ r.register("0", dataAction);
241
+ await r.runAction("0");
242
+ expect(p.dataOp).toHaveBeenCalledWith(
243
+ dataAction,
244
+ expect.objectContaining({ tenantId: "org_123" }),
245
+ );
246
+ });
247
+
248
+ it("transitions to failed when a port throws", async () => {
249
+ const p = ports();
250
+ p.runShell.mockRejectedValueOnce(new Error("boom"));
251
+ const r = new ActionRunner(p, CTX);
252
+ r.register("0", shellAction);
253
+ await r.runAction("0");
254
+ expect(r.get("0").status).toBe("failed");
255
+ expect(r.get("0").error).toContain("boom");
256
+ });
257
+
258
+ it("throws on illegal transition (run an already complete action)", async () => {
259
+ const r = new ActionRunner(ports(), CTX);
260
+ r.register("0", fileAction);
261
+ await r.runAction("0");
262
+ await expect(r.runAction("0")).rejects.toThrow();
263
+ });
264
+
265
+ it("abort allowed from pending", () => {
266
+ const r = new ActionRunner(ports(), CTX);
267
+ r.register("0", fileAction);
268
+ r.abort("0");
269
+ expect(r.get("0").status).toBe("aborted");
270
+ });
271
+
272
+ it("abort rejected from complete", async () => {
273
+ const r = new ActionRunner(ports(), CTX);
274
+ r.register("0", fileAction);
275
+ await r.runAction("0");
276
+ expect(() => r.abort("0")).toThrow();
277
+ });
278
+ });
279
+
280
+ describe("ActionRunner — queue", () => {
281
+ it("runs actions in submission order", async () => {
282
+ const p = ports();
283
+ const order: string[] = [];
284
+ p.writeFile.mockImplementation(async (a: PlanAction) => {
285
+ order.push((a as { filePath: string }).filePath);
286
+ });
287
+ const r = new ActionRunner(p, CTX);
288
+ r.register("0", { type: "file", filePath: "first", content: "" });
289
+ r.register("1", { type: "file", filePath: "second", content: "" });
290
+ await r.runQueue();
291
+ expect(order).toEqual(["first", "second"]);
292
+ });
293
+
294
+ it("a failed required action halts the queue", async () => {
295
+ const p = ports();
296
+ p.runShell.mockRejectedValueOnce(new Error("fail"));
297
+ const r = new ActionRunner(p, CTX);
298
+ r.register("0", shellAction);
299
+ r.register("1", fileAction);
300
+ await r.runQueue();
301
+ expect(r.get("0").status).toBe("failed");
302
+ expect(r.get("1").status).toBe("pending");
303
+ expect(p.writeFile).not.toHaveBeenCalled();
304
+ });
305
+
306
+ it("continueOnError keeps draining the queue", async () => {
307
+ const p = ports();
308
+ p.runShell.mockRejectedValueOnce(new Error("fail"));
309
+ const r = new ActionRunner(p, CTX);
310
+ r.register("0", shellAction);
311
+ r.register("1", fileAction);
312
+ await r.runQueue({ continueOnError: true });
313
+ expect(r.get("0").status).toBe("failed");
314
+ expect(r.get("1").status).toBe("complete");
315
+ });
316
+ });
317
+
318
+ describe("ActionRunner — tenant isolation", () => {
319
+ it("fails closed on empty tenantId", () => {
320
+ expect(() => new ActionRunner(ports(), { tenantId: "" })).toThrow();
321
+ });
322
+
323
+ it("cross-tenant action map access is impossible", () => {
324
+ const a = new ActionRunner(ports(), { tenantId: "org_a" });
325
+ a.register("0", fileAction);
326
+ const b = new ActionRunner(ports(), { tenantId: "org_b" });
327
+ expect(() => b.get("0")).toThrow();
328
+ expect(a.get("0").status).toBe("pending");
329
+ });
330
+ });