@openparachute/agent 0.2.0 → 0.2.3-rc.10

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 (70) hide show
  1. package/.parachute/module.json +3 -3
  2. package/package.json +8 -1
  3. package/src/agent-defs.ts +9 -0
  4. package/src/auth.ts +182 -14
  5. package/src/backends/registry.ts +65 -27
  6. package/src/daemon.ts +311 -12
  7. package/src/def-vault-triggers.ts +317 -0
  8. package/src/preflight.ts +139 -0
  9. package/src/spawn-agent.ts +16 -0
  10. package/src/step-up.ts +316 -0
  11. package/src/terminal-ui.ts +73 -0
  12. package/src/transports/http-ui.ts +10 -8
  13. package/src/transports/vault.ts +40 -22
  14. package/src/ui-kit.ts +6 -3
  15. package/src/ui-ticket.ts +121 -0
  16. package/web/ui/dist/assets/index-Dhr5Kl_d.css +1 -0
  17. package/web/ui/dist/assets/index-Di5MmFZR.js +60 -0
  18. package/web/ui/dist/index.html +15 -0
  19. package/src/_parked/interactive-spawn.test.ts +0 -324
  20. package/src/_parked/interactive-spawn.ts +0 -701
  21. package/src/agent-defs.test.ts +0 -1504
  22. package/src/agent-mcp-config.test.ts +0 -115
  23. package/src/agents.test.ts +0 -360
  24. package/src/auth.test.ts +0 -46
  25. package/src/backends/attached-queue.test.ts +0 -376
  26. package/src/backends/programmatic.test.ts +0 -1715
  27. package/src/backends/registry.test.ts +0 -1494
  28. package/src/backends/stream-json.test.ts +0 -570
  29. package/src/channel-backend-wiring.test.ts +0 -237
  30. package/src/credentials.test.ts +0 -274
  31. package/src/cron.test.ts +0 -342
  32. package/src/daemon-agent-def-api.test.ts +0 -166
  33. package/src/daemon-agent-defs-api.test.ts +0 -953
  34. package/src/daemon-agent-env-api.test.ts +0 -338
  35. package/src/daemon-attached-queue-store.test.ts +0 -65
  36. package/src/daemon-config-api.test.ts +0 -962
  37. package/src/daemon-jobs-api.test.ts +0 -271
  38. package/src/daemon-vault-chat.test.ts +0 -250
  39. package/src/daemon.test.ts +0 -746
  40. package/src/def-vaults.test.ts +0 -136
  41. package/src/delivery-state.test.ts +0 -110
  42. package/src/effective-env.test.ts +0 -114
  43. package/src/grants.test.ts +0 -638
  44. package/src/hub-jwt.test.ts +0 -161
  45. package/src/jobs.test.ts +0 -245
  46. package/src/mcp-http.test.ts +0 -265
  47. package/src/mint-token.test.ts +0 -152
  48. package/src/module-manifest.test.ts +0 -158
  49. package/src/programmatic-wiring.test.ts +0 -838
  50. package/src/registry.test.ts +0 -227
  51. package/src/resolve-port.test.ts +0 -64
  52. package/src/routing.test.ts +0 -184
  53. package/src/runner.test.ts +0 -506
  54. package/src/sandbox/config.test.ts +0 -150
  55. package/src/sandbox/egress.test.ts +0 -113
  56. package/src/sandbox/live-seatbelt.test.ts +0 -277
  57. package/src/sandbox/mounts.test.ts +0 -154
  58. package/src/sandbox/sandbox.test.ts +0 -168
  59. package/src/services-manifest.test.ts +0 -106
  60. package/src/spa-serve.test.ts +0 -116
  61. package/src/spawn-agent-cli.test.ts +0 -172
  62. package/src/spawn-agent.test.ts +0 -1218
  63. package/src/spawn-deps.test.ts +0 -54
  64. package/src/terminal-assets.test.ts +0 -50
  65. package/src/terminal.test.ts +0 -530
  66. package/src/transports/http-ui.test.ts +0 -455
  67. package/src/transports/telegram.test.ts +0 -174
  68. package/src/transports/vault.test.ts +0 -2011
  69. package/src/ui-kit.test.ts +0 -178
  70. package/web/ui/tsconfig.json +0 -21
@@ -1,338 +0,0 @@
1
- /**
2
- * Integration tests for GET /api/agents/<name>/env — the EFFECTIVE-ENV operability
3
- * endpoint (see what env vars an agent's `claude -p` turn will run with, NAMES ONLY).
4
- *
5
- * The endpoint composes three tagged sources — `default` (operator env.default),
6
- * `channel` (per-agent override env.channels[<agent>]), and `grant:<service>` (service
7
- * env vars an APPROVED grant WOULD inject) — in precedence order channel > default >
8
- * grant, marking shadowed lower-precedence entries `overridden:true`.
9
- *
10
- * Load-bearing assertions (the security posture):
11
- * - VALUES NEVER appear in the response (only names) — across all three layers.
12
- * - grant env names are derived WITHOUT a material fetch (the GrantsClient's
13
- * getMaterial is asserted NEVER called).
14
- * - resilient when the grants/hub is unreachable at instantiate (env layers + a
15
- * degraded grant status still come back; the read never 500s).
16
- *
17
- * Harness mirrors daemon-agent-defs-api.test.ts: the hub JWT validator is stubbed
18
- * (sentinel tokens → fixed scopes); the def-vault REST is an in-memory fake; the state
19
- * dir is sandboxed so the env-store writes never touch the operator's ~/.parachute.
20
- */
21
- import { describe, test, expect, mock, beforeAll, afterAll, beforeEach } from "bun:test";
22
- import { HubJwtError, looksLikeJwt } from "@openparachute/scope-guard";
23
- import { mkdtempSync, rmSync } from "node:fs";
24
- import { tmpdir } from "node:os";
25
- import { join } from "node:path";
26
-
27
- // Sandbox the state dir — the route reads the env store via describeChannelEnv() →
28
- // defaultStateDir(); the tests seed it via setChannelEnvVar(). Pin to a throwaway dir
29
- // so we never touch the operator's real ~/.parachute/agent (feedback_sandbox_destructive_cli).
30
- let stateDir: string;
31
- let priorStateDir: string | undefined;
32
- beforeAll(() => {
33
- priorStateDir = process.env.PARACHUTE_AGENT_STATE_DIR;
34
- stateDir = mkdtempSync(join(tmpdir(), "agent-env-api-state-"));
35
- process.env.PARACHUTE_AGENT_STATE_DIR = stateDir;
36
- });
37
- afterAll(() => {
38
- if (priorStateDir === undefined) delete process.env.PARACHUTE_AGENT_STATE_DIR;
39
- else process.env.PARACHUTE_AGENT_STATE_DIR = priorStateDir;
40
- try {
41
- rmSync(stateDir, { recursive: true, force: true });
42
- } catch {}
43
- });
44
-
45
- const ADMIN_TOKEN = "test-admin-token";
46
- const READ_TOKEN = "test-read-token";
47
- mock.module("./hub-jwt.ts", () => ({
48
- AGENT_AUDIENCE: "agent",
49
- CHANNEL_AUDIENCE: "channel",
50
- async validateHubJwt(token: string) {
51
- const base = { sub: "test", aud: "agent", jti: undefined, clientId: undefined, vaultScope: undefined };
52
- if (token === ADMIN_TOKEN) return { ...base, scopes: ["agent:read", "agent:send", "agent:admin"] };
53
- if (token === READ_TOKEN) return { ...base, scopes: ["agent:read"] };
54
- throw new HubJwtError("issuer", "invalid token");
55
- },
56
- HubJwtError,
57
- looksLikeJwt,
58
- resetJwksCache() {},
59
- resetRevocationCache() {},
60
- }));
61
-
62
- import { createFetchHandler } from "./daemon.ts";
63
- import { ClientRegistry } from "./routing.ts";
64
- import { AgentDefRegistry, type InstantiateDeps } from "./agent-defs.ts";
65
- import { GrantsClient } from "./grants.ts";
66
- import {
67
- setChannelEnvVar,
68
- removeChannelEnvVar,
69
- readCredentialsFile,
70
- } from "./credentials.ts";
71
- import type { Channel } from "./registry.ts";
72
-
73
- const adminAuth = { authorization: "Bearer " + ADMIN_TOKEN } as const;
74
- const readAuth = { authorization: "Bearer " + READ_TOKEN } as const;
75
-
76
- // ---------------------------------------------------------------------------
77
- // A FAKE def-vault REST (in-memory) — the registry's DefVaultClient drives it via an
78
- // injected fetchFn. Only the routes the registry calls (list / patch-status) matter.
79
- // ---------------------------------------------------------------------------
80
- interface FakeNote {
81
- id: string;
82
- content?: string;
83
- tags?: string[];
84
- metadata: Record<string, unknown>;
85
- }
86
- class FakeDefVault {
87
- readonly notes = new Map<string, FakeNote>();
88
- seed(note: FakeNote): void {
89
- this.notes.set(note.id, note);
90
- }
91
- fetch = (async (input: URL | RequestInfo, init?: RequestInit) => {
92
- const url = new URL(typeof input === "string" ? input : (input as Request).url);
93
- const method = (init?.method ?? "GET").toUpperCase();
94
- const m = url.pathname.match(/\/vault\/[^/]+\/api\/notes(?:\/(.+))?$/);
95
- const noteId = m?.[1] ? decodeURIComponent(m[1]) : undefined;
96
- const j = (body: unknown, status = 200) =>
97
- new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
98
- if (method === "GET" && noteId === undefined) return j(Array.from(this.notes.values()));
99
- if (method === "GET" && noteId !== undefined) {
100
- const note = this.notes.get(noteId);
101
- return note ? j(note) : j({ error: "not_found" }, 404);
102
- }
103
- if (method === "PATCH" && noteId !== undefined) {
104
- const note = this.notes.get(noteId);
105
- if (!note) return j({ error: "not_found" }, 404);
106
- const body = JSON.parse(String(init?.body ?? "{}")) as { content?: string; metadata?: Record<string, unknown> };
107
- if (body.content !== undefined) note.content = body.content;
108
- if (body.metadata) note.metadata = { ...note.metadata, ...body.metadata };
109
- return j(note);
110
- }
111
- return j({ error: "unhandled", method, path: url.pathname }, 500);
112
- }) as unknown as typeof fetch;
113
- }
114
-
115
- /** No-op InstantiateDeps — instantiate runs (own-vault) without real channel/spawn I/O. */
116
- function noopDeps(): InstantiateDeps {
117
- return {
118
- ensureChannel: async () => {},
119
- setupAndRegister: async () => {},
120
- deregister: async () => true,
121
- removeChannel: async () => true,
122
- };
123
- }
124
-
125
- /**
126
- * A GrantsClient over a controllable hub fetch. registerGrant returns a status we set
127
- * per connection key (so a `wants:` connection resolves to `approved`/`pending`).
128
- * getMaterial is FORBIDDEN — the read endpoint must never fetch material; if it does,
129
- * the test fails loudly. Records the URLs hit so we can assert no `/material` call.
130
- */
131
- function grantsClientWith(statusByKeyHint: Record<string, string>) {
132
- const calls: string[] = [];
133
- let materialFetched = false;
134
- const fetchFn = (async (input: URL | RequestInfo, init?: RequestInit) => {
135
- const url = new URL(typeof input === "string" ? input : (input as Request).url);
136
- const method = (init?.method ?? "GET").toUpperCase();
137
- calls.push(`${method} ${url.pathname}`);
138
- const j = (body: unknown, status = 200) =>
139
- new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
140
- if (url.pathname.endsWith("/material")) {
141
- materialFetched = true;
142
- return j({ error: "material must never be fetched by a names-only read" }, 500);
143
- }
144
- if (method === "PUT" && url.pathname === "/admin/grants") {
145
- const body = JSON.parse(String(init?.body ?? "{}")) as { agent: string; connection: { kind: string; target: string; inject?: string[] } };
146
- // Re-derive the same key the registry will look up. For a service it's
147
- // `<inject-joined>:<target>`; we key the hint by the bare service target for ease.
148
- const status = statusByKeyHint[body.connection.target] ?? "pending";
149
- return j({ id: `grant-${body.connection.target}`, agent: body.agent, connection: body.connection, status });
150
- }
151
- if (method === "GET" && url.pathname === "/admin/grants") return j({ grants: [] });
152
- if (method === "POST" && url.pathname === "/admin/grants/reconcile") return j({ pruned: 0 });
153
- return j({ error: "unhandled", method, path: url.pathname }, 500);
154
- }) as unknown as typeof fetch;
155
- const client = new GrantsClient({ hubOrigin: "http://hub.test", managerBearer: "mgr", fetchFn });
156
- return { client, calls, get materialFetched() { return materialFetched; } };
157
- }
158
-
159
- function serverWith(channels: Map<string, Channel>, agentDefs?: AgentDefRegistry) {
160
- const registry = new ClientRegistry();
161
- const srv = Bun.serve({
162
- port: 0,
163
- hostname: "127.0.0.1",
164
- idleTimeout: 0,
165
- fetch: createFetchHandler(channels, registry, agentDefs ? { agentDefs } : {}),
166
- });
167
- return { srv, base: `http://127.0.0.1:${srv.port}` };
168
- }
169
-
170
- const emptyChannels = () => new Map<string, Channel>();
171
-
172
- // Clean the env store between tests so layer assertions are deterministic.
173
- function wipeEnvStore() {
174
- const f = readCredentialsFile(stateDir);
175
- for (const n of Object.keys(f.env?.default ?? {})) removeChannelEnvVar(null, n, stateDir);
176
- for (const [ch, vars] of Object.entries(f.env?.channels ?? {})) {
177
- for (const n of Object.keys(vars)) removeChannelEnvVar(ch, n, stateDir);
178
- }
179
- }
180
- beforeEach(() => wipeEnvStore());
181
-
182
- // Secret sentinels — assert these VALUES never appear in any response body.
183
- const SECRET_VALUES = ["ghp_supersecret", "cf_supersecret", "default_secret_val", "grant_token_secret"];
184
- function assertNoSecretValues(bodyText: string) {
185
- for (const v of SECRET_VALUES) expect(bodyText).not.toContain(v);
186
- }
187
-
188
- describe("GET /api/agents/<name>/env — auth + shape", () => {
189
- test("no Authorization → 401 (admin-gated)", async () => {
190
- const { srv, base } = serverWith(emptyChannels());
191
- const res = await fetch(`${base}/api/agents/uni-dev/env`);
192
- expect(res.status).toBe(401);
193
- srv.stop();
194
- });
195
-
196
- test("a read-only token → 403 (admin scope required; authenticated but insufficient)", async () => {
197
- const { srv, base } = serverWith(emptyChannels());
198
- const res = await fetch(`${base}/api/agents/uni-dev/env`, { headers: readAuth });
199
- expect(res.status).toBe(403);
200
- srv.stop();
201
- });
202
-
203
- test("no def registered → env-store layers only + a note (never a 500)", async () => {
204
- setChannelEnvVar(null, "DEFAULT_VAR", "default_secret_val", stateDir);
205
- setChannelEnvVar("uni-dev", "CHANNEL_VAR", "ghp_supersecret", stateDir);
206
- const { srv, base } = serverWith(emptyChannels()); // NO agentDefs wired.
207
- const res = await fetch(`${base}/api/agents/uni-dev/env`, { headers: adminAuth });
208
- expect(res.status).toBe(200);
209
- const text = await res.text();
210
- assertNoSecretValues(text);
211
- const body = JSON.parse(text) as { env: Array<{ name: string; source: string }>; note?: string };
212
- expect(body.note).toBeDefined();
213
- const names = body.env.map((e) => e.name).sort();
214
- expect(names).toEqual(["CHANNEL_VAR", "DEFAULT_VAR"]);
215
- expect(body.env.find((e) => e.name === "DEFAULT_VAR")!.source).toBe("default");
216
- expect(body.env.find((e) => e.name === "CHANNEL_VAR")!.source).toBe("channel");
217
- srv.stop();
218
- });
219
- });
220
-
221
- describe("GET /api/agents/<name>/env — composes all three sources + precedence", () => {
222
- /** Build a registry with one live def for `uni-dev` declaring `env:github`, with the
223
- * grant status the hub reports for it. Returns the registry + the grants probe. */
224
- async function liveDefRegistry(githubGrantStatus: string) {
225
- const fake = new FakeDefVault();
226
- fake.seed({
227
- id: "Agents/uni-dev",
228
- content: "You are uni-dev.",
229
- tags: ["#agent/definition"],
230
- metadata: { name: "uni-dev", backend: "programmatic", mode: "single-threaded", wants: "env:github" },
231
- });
232
- const grants = grantsClientWith({ github: githubGrantStatus });
233
- const reg = new AgentDefRegistry(noopDeps(), {
234
- bindings: [{ vault: "default", vaultUrl: "http://127.0.0.1:1940", token: "vtok" }],
235
- fetchFn: fake.fetch,
236
- grants: grants.client,
237
- });
238
- await reg.loadAll(); // instantiate → registers the grant + resolves status (no material fetch).
239
- return { reg, grants };
240
- }
241
-
242
- test("default + channel + approved-grant env merge, channel wins on collision, grant names derived WITHOUT material fetch, VALUES never returned", async () => {
243
- // Seed the env store: a default-only var, a channel-only var, and a COLLISION on
244
- // GITHUB_TOKEN (both the channel override AND the github grant target the same name).
245
- setChannelEnvVar(null, "DEFAULT_VAR", "default_secret_val", stateDir);
246
- setChannelEnvVar(null, "GITHUB_TOKEN", "default_secret_val", stateDir); // default layer also sets it
247
- setChannelEnvVar("uni-dev", "CHANNEL_VAR", "ghp_supersecret", stateDir);
248
- setChannelEnvVar("uni-dev", "GITHUB_TOKEN", "ghp_supersecret", stateDir); // channel override (wins)
249
-
250
- const { reg, grants } = await liveDefRegistry("approved"); // github grant approved → injects GITHUB_TOKEN
251
- const { srv, base } = serverWith(emptyChannels(), reg);
252
- const res = await fetch(`${base}/api/agents/uni-dev/env`, { headers: adminAuth });
253
- expect(res.status).toBe(200);
254
- const text = await res.text();
255
- // SECURITY: no value ever leaks, from any of the three layers.
256
- assertNoSecretValues(text);
257
- expect(text).not.toContain('"value"');
258
-
259
- const body = JSON.parse(text) as { env: Array<{ name: string; source: string; overridden?: boolean }>; note?: string };
260
- expect(body.note).toBeUndefined(); // a def IS registered → no degraded note.
261
-
262
- // CHANNEL_VAR — channel only.
263
- const channelVar = body.env.filter((e) => e.name === "CHANNEL_VAR");
264
- expect(channelVar).toHaveLength(1);
265
- expect(channelVar[0]!.source).toBe("channel");
266
- expect(channelVar[0]!.overridden).toBeUndefined();
267
-
268
- // DEFAULT_VAR — default only.
269
- const defaultVar = body.env.filter((e) => e.name === "DEFAULT_VAR");
270
- expect(defaultVar).toHaveLength(1);
271
- expect(defaultVar[0]!.source).toBe("default");
272
-
273
- // GITHUB_TOKEN — set in ALL THREE layers; winner is channel, the other two shadowed.
274
- const gh = body.env.filter((e) => e.name === "GITHUB_TOKEN");
275
- expect(gh).toHaveLength(3);
276
- const winner = gh.find((e) => !e.overridden)!;
277
- expect(winner.source).toBe("channel"); // channel > default > grant
278
- const shadowed = gh.filter((e) => e.overridden);
279
- expect(shadowed.map((e) => e.source).sort()).toEqual(["default", "grant:github"]);
280
-
281
- // The grant env NAME was derived (GITHUB_TOKEN, tagged grant:github) — and the
282
- // grants client was NEVER asked for material (only PUT register at instantiate).
283
- expect(grants.materialFetched).toBe(false);
284
- expect(grants.calls.some((c) => c.includes("/material"))).toBe(false);
285
- srv.stop();
286
- });
287
-
288
- test("a PENDING (not approved) grant does NOT contribute an env name", async () => {
289
- const { reg, grants } = await liveDefRegistry("pending"); // github grant pending → no inject
290
- const { srv, base } = serverWith(emptyChannels(), reg);
291
- const res = await fetch(`${base}/api/agents/uni-dev/env`, { headers: adminAuth });
292
- const body = (await res.json()) as { env: Array<{ name: string; source: string }> };
293
- // No grant: layer at all (nothing approved), and no env-store vars seeded.
294
- expect(body.env.filter((e) => e.source.startsWith("grant:"))).toHaveLength(0);
295
- expect(body.env.find((e) => e.name === "GITHUB_TOKEN")).toBeUndefined();
296
- expect(grants.materialFetched).toBe(false);
297
- srv.stop();
298
- });
299
- });
300
-
301
- describe("GET /api/agents/<name>/env — resilient when grants/hub unreachable", () => {
302
- test("a def whose grant registration fails (hub down) still returns env-store layers, no 500", async () => {
303
- // The env store has layers even though the hub is unreachable.
304
- setChannelEnvVar(null, "DEFAULT_VAR", "default_secret_val", stateDir);
305
- setChannelEnvVar("uni-dev", "CHANNEL_VAR", "ghp_supersecret", stateDir);
306
-
307
- const fake = new FakeDefVault();
308
- fake.seed({
309
- id: "Agents/uni-dev",
310
- content: "You are uni-dev.",
311
- tags: ["#agent/definition"],
312
- metadata: { name: "uni-dev", backend: "programmatic", mode: "single-threaded", wants: "env:github" },
313
- });
314
- // A grants client whose hub fetch always throws — registerGrant fails at instantiate,
315
- // so the connection resolves as pending (not approved); the load still succeeds own-vault.
316
- const downFetch = (async () => {
317
- throw new Error("ECONNREFUSED hub down");
318
- }) as unknown as typeof fetch;
319
- const reg = new AgentDefRegistry(noopDeps(), {
320
- bindings: [{ vault: "default", vaultUrl: "http://127.0.0.1:1940", token: "vtok" }],
321
- fetchFn: fake.fetch,
322
- grants: new GrantsClient({ hubOrigin: "http://hub.test", managerBearer: "mgr", fetchFn: downFetch }),
323
- });
324
- await reg.loadAll();
325
-
326
- const { srv, base } = serverWith(emptyChannels(), reg);
327
- const res = await fetch(`${base}/api/agents/uni-dev/env`, { headers: adminAuth });
328
- expect(res.status).toBe(200); // NOT a 500.
329
- const text = await res.text();
330
- assertNoSecretValues(text);
331
- const body = JSON.parse(text) as { env: Array<{ name: string; source: string }> };
332
- // Env-store layers came back even with the hub down; no approved grant → no grant layer.
333
- const names = body.env.map((e) => e.name).sort();
334
- expect(names).toEqual(["CHANNEL_VAR", "DEFAULT_VAR"]);
335
- expect(body.env.filter((e) => e.source.startsWith("grant:"))).toHaveLength(0);
336
- srv.stop();
337
- });
338
- });
@@ -1,65 +0,0 @@
1
- /**
2
- * `attachedQueueStoreFor` — the PRODUCTION adapter that wires a live `VaultTransport`
3
- * into the `AttachedQueueStore` the pull-queue worker uses.
4
- *
5
- * Regression for the agent#101 CAS single-claim guard (PR #116): the adapter MUST
6
- * forward the 4th `ifUpdatedAt` arg to `vt.setInboundStatus`, or the compare-and-set
7
- * silently collapses to `force:true` (last-write-wins) and the double-claim race the
8
- * CAS was built to close re-opens. The unit tests inject a FAKE store that honors all
9
- * four args, so ONLY the live daemon adapter was lossy (a 3-param arrow is assignable
10
- * to the wider interface slot, so the type checker can't catch it). This exercises the
11
- * REAL adapter end-to-end against a `VaultTransport`.
12
- */
13
- import { describe, test, expect, afterEach } from "bun:test";
14
- import { attachedQueueStoreFor } from "./daemon.ts";
15
- import { VaultTransport } from "./transports/vault.ts";
16
- import type { Channel } from "./registry.ts";
17
-
18
- const realFetch = globalThis.fetch;
19
- afterEach(() => {
20
- globalThis.fetch = realFetch;
21
- });
22
-
23
- function vaultChannels(): Map<string, Channel> {
24
- const vault = new VaultTransport({ vault: "default", vaultUrl: "http://127.0.0.1:1940", token: "write-token" });
25
- const channels = new Map<string, Channel>();
26
- channels.set("eng", {
27
- name: "eng",
28
- transport: vault,
29
- entry: { name: "eng", transport: "vault", config: { vault: "default", token: "write-token" } },
30
- });
31
- return channels;
32
- }
33
-
34
- /** Capture the PATCH bodies the vault transport sends. */
35
- function recordPatch(): { bodies: Record<string, unknown>[] } {
36
- const bodies: Record<string, unknown>[] = [];
37
- globalThis.fetch = (async (_url: string | URL | Request, init?: RequestInit) => {
38
- if ((init?.method ?? "GET") === "PATCH") bodies.push(JSON.parse(String(init?.body)) as Record<string, unknown>);
39
- return new Response("{}", { status: 200 });
40
- }) as typeof fetch;
41
- return { bodies };
42
- }
43
-
44
- describe("attachedQueueStoreFor — CAS arg forwarding (agent#101 regression)", () => {
45
- test("setInboundStatus FORWARDS ifUpdatedAt → the vault does a CAS (if_updated_at), not force", async () => {
46
- const store = attachedQueueStoreFor(vaultChannels(), "eng");
47
- expect(store).not.toBeNull();
48
- const { bodies } = recordPatch();
49
- await store!.setInboundStatus("note-1", "in-flight", "2026-06-22T00:00:00.000Z", "2026-06-22T00:00:00.000Z");
50
- expect(bodies).toHaveLength(1);
51
- // The CAS precondition is forwarded (the whole point of the single-claim guard) …
52
- expect(bodies[0]!.if_updated_at).toBe("2026-06-22T00:00:00.000Z");
53
- // … and it is NOT the force/last-write-wins path the dropped-arg bug fell back to.
54
- expect(bodies[0]!.force).toBeUndefined();
55
- });
56
-
57
- test("setInboundStatus WITHOUT ifUpdatedAt → force:true (release/handled/sweep path, unchanged)", async () => {
58
- const store = attachedQueueStoreFor(vaultChannels(), "eng");
59
- const { bodies } = recordPatch();
60
- await store!.setInboundStatus("note-1", "pending", null);
61
- expect(bodies).toHaveLength(1);
62
- expect(bodies[0]!.force).toBe(true);
63
- expect(bodies[0]!.if_updated_at).toBeUndefined();
64
- });
65
- });