@1agh/maude 0.56.0 → 0.58.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 (58) hide show
  1. package/README.md +5 -1
  2. package/apps/studio/acp/bridge.ts +385 -26
  3. package/apps/studio/acp/index.ts +498 -102
  4. package/apps/studio/acp/running.ts +97 -0
  5. package/apps/studio/acp/transcript.ts +64 -0
  6. package/apps/studio/acp/write-scope.ts +459 -0
  7. package/apps/studio/api.ts +69 -4
  8. package/apps/studio/build.ts +28 -1
  9. package/apps/studio/client/app.jsx +187 -39
  10. package/apps/studio/client/panels/ChatPanel.jsx +19 -1
  11. package/apps/studio/client/panels/CloudBar.jsx +72 -13
  12. package/apps/studio/client/panels/PermissionPrompt.jsx +146 -6
  13. package/apps/studio/client/panels/RepoBranchSwitcher.jsx +145 -6
  14. package/apps/studio/client/panels/acp-runtime.js +96 -5
  15. package/apps/studio/client/panels/chat-markdown.jsx +76 -5
  16. package/apps/studio/client/panels/file-preview.jsx +115 -0
  17. package/apps/studio/client/styles/3-shell-maude.css +56 -2
  18. package/apps/studio/client/styles/6-acp-chat.css +79 -0
  19. package/apps/studio/dist/client.bundle.js +1436 -1436
  20. package/apps/studio/dist/comment-mount.js +2 -2
  21. package/apps/studio/dist/styles.css +1 -1
  22. package/apps/studio/http.ts +59 -2
  23. package/apps/studio/input-router.tsx +39 -1
  24. package/apps/studio/server.ts +11 -0
  25. package/apps/studio/sync/connection-state.ts +116 -6
  26. package/apps/studio/sync/index.ts +50 -1
  27. package/apps/studio/sync/presentation.ts +273 -0
  28. package/apps/studio/sync/remote-docs.ts +191 -0
  29. package/apps/studio/sync/status.ts +4 -1
  30. package/apps/studio/test/acp-activity-endpoint.test.ts +183 -0
  31. package/apps/studio/test/acp-branch-guard.test.ts +123 -0
  32. package/apps/studio/test/acp-bridge-lifetime.test.ts +369 -0
  33. package/apps/studio/test/acp-caps-bridge.test.ts +5 -0
  34. package/apps/studio/test/acp-commands.test.ts +5 -0
  35. package/apps/studio/test/acp-elicitation-bridge.test.ts +5 -0
  36. package/apps/studio/test/acp-permission-prompt.test.ts +175 -1
  37. package/apps/studio/test/acp-permission.test.ts +18 -2
  38. package/apps/studio/test/acp-session-allowed-tools.test.ts +62 -14
  39. package/apps/studio/test/acp-usage-bridge.test.ts +5 -0
  40. package/apps/studio/test/acp-write-gate.test.ts +323 -0
  41. package/apps/studio/test/acp-write-scope.test.ts +533 -0
  42. package/apps/studio/test/bundle-smoke.test.ts +35 -18
  43. package/apps/studio/test/canvas-origin-gate.test.ts +7 -0
  44. package/apps/studio/test/cloud-connect-note.test.ts +135 -0
  45. package/apps/studio/test/cloud-endpoints.test.ts +11 -4
  46. package/apps/studio/test/cloud-shell-surfaces.test.ts +5 -2
  47. package/apps/studio/test/config-version.test.ts +88 -0
  48. package/apps/studio/test/fixtures/mock-acp-agent-slow.mjs +45 -0
  49. package/apps/studio/test/fixtures/mock-acp-agent-write.mjs +118 -0
  50. package/apps/studio/test/input-router.test.ts +56 -0
  51. package/apps/studio/test/sync-connect-honesty.test.ts +114 -0
  52. package/apps/studio/test/sync-connection-state.test.ts +45 -1
  53. package/apps/studio/test/sync-presentation.test.ts +185 -0
  54. package/apps/studio/test/sync-remote-docs.test.ts +171 -0
  55. package/apps/studio/test/whats-new.test.ts +13 -1
  56. package/apps/studio/whats-new.json +27 -0
  57. package/apps/studio/whats-new.ts +34 -10
  58. package/package.json +8 -8
@@ -0,0 +1,123 @@
1
+ // feature-acp-write-path-scope Addendum, Task 9 — the branch-switch warning.
2
+ //
3
+ // `RepoBranchSwitcher.jsx` has THREE `window.location.reload()` call sites
4
+ // (`switchDraft`, `createDraft`, and the local-merge fold in `foldDraft`). All
5
+ // three move the worktree, so all three need the gate; covering one and missing
6
+ // two is the easy mistake, which is why the source-shape assertion below exists
7
+ // alongside the copy tests.
8
+ //
9
+ // Why the wording matters enough to test: this is a safety prompt, and Task 8
10
+ // changed what is TRUE about it. Before, the reload killed the running turn, so
11
+ // "this will stop it" was accurate. Now the bridge outlives its socket, so the
12
+ // turn keeps going — into a worktree that has moved under it. "Will stop it"
13
+ // would now be false in the reassuring direction.
14
+
15
+ import { describe, expect, test } from 'bun:test';
16
+ import { readFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+
19
+ import { chatGuardCopy } from '../client/panels/RepoBranchSwitcher.jsx';
20
+
21
+ describe('chatGuardCopy', () => {
22
+ const one = chatGuardCopy({ count: 1, branch: 'draft-a', verb: 'switch to “main”' });
23
+
24
+ test('names the branch, the action, and the real consequence', () => {
25
+ expect(one.title).toBe('A chat is working right now');
26
+ expect(one.body).toContain('draft-a');
27
+ expect(one.body).toContain('switch to “main”');
28
+ expect(one.body).toContain('wrong branch');
29
+ });
30
+
31
+ test('does NOT claim the switch stops the chat (it no longer does — Task 8)', () => {
32
+ const all = `${one.title} ${one.body} ${one.meta}`.toLowerCase();
33
+ expect(all).not.toContain('will stop it');
34
+ // …and it does say the thing that IS true: the agent is actively editing.
35
+ expect(one.body).toContain('editing files on');
36
+ });
37
+
38
+ test('is honest that History cannot undo this', () => {
39
+ // The `_history/` snapshot stack is per-canvas-slug with NO branch
40
+ // awareness, so the "it's reversible" reassurance this whole feature leans
41
+ // on genuinely does not hold across a checkout. Promising rollback here
42
+ // would be the one lie that makes the confirm worse than no confirm.
43
+ expect(one.body).toContain("History can't undo");
44
+ });
45
+
46
+ test('pluralizes when several chats are running', () => {
47
+ expect(chatGuardCopy({ count: 3, branch: 'x', verb: 'y' }).title).toBe(
48
+ '3 chats are working right now'
49
+ );
50
+ });
51
+
52
+ test('the confirm is not the safe default', () => {
53
+ // "Wait" is the cancel; "Do it anyway" is the deliberate, phrased-as-a-risk
54
+ // confirm. A neutral "OK/Cancel" pair would read as routine.
55
+ expect(one.cancel).toBe('Wait');
56
+ expect(one.confirm).toBe('Do it anyway');
57
+ });
58
+ });
59
+
60
+ describe('all THREE reload call sites are gated', () => {
61
+ const src = readFileSync(
62
+ join(import.meta.dir, '..', 'client', 'panels', 'RepoBranchSwitcher.jsx'),
63
+ 'utf8'
64
+ );
65
+
66
+ test('every reload lives in a `do*` action reached only through guardedByChat', () => {
67
+ // Source-shape guard rather than a render test: the failure mode is a
68
+ // FOURTH reload being added later without a gate, which no render test of
69
+ // the existing three would catch.
70
+ const guarded = src.match(/guardedByChat\(/g) ?? [];
71
+ // One definition + three call sites.
72
+ expect(guarded.length).toBeGreaterThanOrEqual(4);
73
+ for (const fn of ['doSwitchDraft', 'doCreateDraft', 'doFoldDraft']) {
74
+ expect(src).toContain(`function ${fn}`);
75
+ }
76
+ });
77
+
78
+ test('the gate asks the SERVER, not local chat state', () => {
79
+ // A bridge can be running DETACHED (post-reload, pre-re-attach) with no
80
+ // client that knows about it — precisely the case the warning is for. Local
81
+ // busy state would answer "nothing is running" exactly when it matters.
82
+ expect(src).toContain('/_api/acp/running');
83
+ });
84
+
85
+ test('a failed probe never BLOCKS a switch', () => {
86
+ // A switch the user asked for must not be hostage to an unrelated fetch
87
+ // error. The catch returns 0 (⇒ proceed), not a thrown error.
88
+ expect(src).toMatch(/catch\s*{[\s\S]*?return 0;/);
89
+ });
90
+ });
91
+
92
+ // SECURITY (security-auditor A6) — cross-PROJECT loopback adjacency.
93
+ //
94
+ // Before the sidecar pool (Addendum Task 10) at most one dev-server ran at a
95
+ // time, so "another Maude instance on another loopback port" was not a state the
96
+ // product produced. The pool makes concurrency DESIGNED-IN: projects A and B now
97
+ // routinely run side by side on different ports, and A's canvas iframe is
98
+ // untrusted content (DDR-054). So the question "can A's canvas reach B's
99
+ // privileged main origin?" went from hypothetical to worth an explicit test.
100
+ //
101
+ // The defence is `sameOriginWrite`'s host+port compare — different instance,
102
+ // different port, different `host`, rejected. Asserting it here so the property
103
+ // is pinned to the pool's introduction rather than left as an inference.
104
+ describe('cross-project origin adjacency (A6)', () => {
105
+ test('a request from ANOTHER instance’s origin is not same-origin', async () => {
106
+ const { sameOriginWrite } = await import('../http.ts');
107
+ const projectB = new Request('http://localhost:4400/_api/acp/running', {
108
+ method: 'POST',
109
+ // Project A's canvas/main origin, aimed at project B's server.
110
+ headers: { origin: 'http://localhost:4399' },
111
+ });
112
+ expect(sameOriginWrite(projectB)).toBe(false);
113
+ });
114
+
115
+ test('a request from the SAME instance is allowed (the pool must not break normal use)', async () => {
116
+ const { sameOriginWrite } = await import('../http.ts');
117
+ const own = new Request('http://localhost:4400/_api/acp/running', {
118
+ method: 'POST',
119
+ headers: { origin: 'http://localhost:4400' },
120
+ });
121
+ expect(sameOriginWrite(own)).toBe(true);
122
+ });
123
+ });
@@ -0,0 +1,369 @@
1
+ // feature-acp-write-path-scope Addendum, Task 8 — the bridge outlives its socket.
2
+ //
3
+ // The bug this closes: `bridges` was keyed by `ws.data.id` and `onClose` called
4
+ // `bridge.stop()` immediately, so ANY socket close killed the running agent.
5
+ // `RepoBranchSwitcher.jsx` calls `window.location.reload()` unconditionally on a
6
+ // branch switch / draft-create / local-merge fold, which meant switching drafts
7
+ // mid-turn silently destroyed the work in flight. It merely LOOKED like a lost
8
+ // place, because the transcript and the ACP sessionId are both persisted.
9
+ //
10
+ // What is asserted here, in the plan's own words:
11
+ // (a) the turn completes after the socket dies,
12
+ // (b) a re-attaching client receives each update EXACTLY ONCE, and
13
+ // (c) no orphaned bridge survives the TTL.
14
+ // Plus the hazard the Addendum names explicitly: a permission request raised
15
+ // while NOBODY is attached must fail closed, never read as consent.
16
+
17
+ import { afterEach, describe, expect, test } from 'bun:test';
18
+ import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
19
+ import { tmpdir } from 'node:os';
20
+ import { join } from 'node:path';
21
+
22
+ import type { ServerWebSocket } from 'bun';
23
+
24
+ import { AcpBridge } from '../acp/bridge.ts';
25
+ import { createAcp, DETACHED_TTL_MS, MAX_DETACHED_BRIDGES } from '../acp/index.ts';
26
+ import type { Context } from '../context.ts';
27
+ import type { WsData } from '../ws.ts';
28
+
29
+ const FIXTURE_SLOW = join(import.meta.dir, 'fixtures', 'mock-acp-agent-slow.mjs');
30
+ const FIXTURE_PERM = join(import.meta.dir, 'fixtures', 'mock-acp-agent-permission.mjs');
31
+ const TEST_ENV_KEYS = ['MAUDE_ACP_ADAPTER_ENTRY', 'MAUDE_ACP_RUNTIME', 'MAUDE_CLAUDE_BIN'];
32
+
33
+ function useMockAgent(fixture: string) {
34
+ process.env.MAUDE_ACP_ADAPTER_ENTRY = fixture;
35
+ process.env.MAUDE_ACP_RUNTIME = process.execPath;
36
+ process.env.MAUDE_CLAUDE_BIN = process.execPath;
37
+ }
38
+
39
+ const dirs: string[] = [];
40
+ function freshCtx(): Context {
41
+ const root = mkdtempSync(join(tmpdir(), 'maude-acp-lifetime-'));
42
+ dirs.push(root);
43
+ mkdirSync(join(root, '.design', '_chat'), { recursive: true });
44
+ return {
45
+ paths: { repoRoot: root, designRoot: join(root, '.design'), designRel: '.design' },
46
+ } as unknown as Context;
47
+ }
48
+
49
+ afterEach(() => {
50
+ for (const key of TEST_ENV_KEYS) delete process.env[key];
51
+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
52
+ });
53
+
54
+ function fakeWs(id: string) {
55
+ const frames: Array<Record<string, unknown>> = [];
56
+ const ws = {
57
+ data: { id } as WsData,
58
+ send: (raw: string) => {
59
+ frames.push(JSON.parse(raw));
60
+ },
61
+ } as unknown as ServerWebSocket<WsData>;
62
+ return { ws, frames };
63
+ }
64
+
65
+ async function until<T>(fn: () => T | undefined, timeoutMs = 15000): Promise<T> {
66
+ const start = performance.now();
67
+ for (;;) {
68
+ const v = fn();
69
+ if (v !== undefined) return v;
70
+ if (performance.now() - start > timeoutMs) throw new Error('timeout waiting for condition');
71
+ await new Promise((r) => setTimeout(r, 20));
72
+ }
73
+ }
74
+
75
+ describe('bridge lifetime — a closed socket no longer kills the turn', () => {
76
+ test('the turn COMPLETES after the socket closes, and a re-attach gets every update exactly once', async () => {
77
+ useMockAgent(FIXTURE_SLOW);
78
+ const ctx = freshCtx();
79
+ const acp = createAcp(ctx);
80
+
81
+ const a = fakeWs('life-a');
82
+ acp.onOpen(a.ws);
83
+ acp.onMessage(a.ws, JSON.stringify({ t: 'prompt', text: 'go', chat: 'c1' }));
84
+
85
+ // Wait until the turn is genuinely streaming, then yank the socket — the
86
+ // exact shape of a `window.location.reload()` landing mid-turn.
87
+ const firstSeq = await until(() => {
88
+ const f = a.frames.find((x) => x.t === 'update' && typeof x.seq === 'number');
89
+ return f ? (f.seq as number) : undefined;
90
+ });
91
+ // `seq` is the transcript LINE, not an agent-update counter — the bootstrap
92
+ // brief, the plugin-autoload audit record and the user's own turn all
93
+ // occupy lines before the first agent chunk. That is deliberate: the client
94
+ // compares it against the line count the HTTP hydration covered, which
95
+ // counts those lines too. An "nth agent update" counter would not line up.
96
+ expect(firstSeq).toBeGreaterThan(0);
97
+ acp.onClose(a.ws);
98
+
99
+ // (a) The bridge SURVIVES the close. Under the old per-socket keying this
100
+ // was already 0 by now, and the agent was dead.
101
+ expect(acp.size()).toBe(1);
102
+
103
+ // The chat's own transcript keeps growing while nobody is attached — the
104
+ // durable record the re-attach replays from.
105
+ await until(async () => {
106
+ const { chatTranscriptSeq } = await import('../acp/transcript.ts');
107
+ return chatTranscriptSeq(ctx.paths.designRoot, 'c1') > firstSeq ? true : undefined;
108
+ });
109
+
110
+ // (b) Re-attach from the seq the client had already hydrated. Everything
111
+ // after it replays; nothing at or before it does.
112
+ const b = fakeWs('life-b');
113
+ acp.onOpen(b.ws);
114
+ acp.onMessage(b.ws, JSON.stringify({ t: 'attach', chat: 'c1', seq: firstSeq }));
115
+ await until(() => b.frames.find((f) => f.t === 'attached'));
116
+
117
+ // Let the turn finish so the replay + live tail are both complete.
118
+ await until(() => b.frames.find((f) => f.t === 'turn-end'), 20000);
119
+
120
+ const seqs = b.frames.filter((f) => f.t === 'update').map((f) => f.seq as number);
121
+ // EXACTLY ONCE: no duplicates …
122
+ expect(new Set(seqs).size).toBe(seqs.length);
123
+ // … and nothing the client already had (that's the whole point of the seam;
124
+ // without it, the replay and the live stream overlap and the user sees the
125
+ // last few seconds twice).
126
+ expect(seqs.every((s) => s > firstSeq)).toBe(true);
127
+ // … and no HOLE either: the seqs are contiguous from firstSeq+1.
128
+ expect(seqs).toEqual(seqs.map((_, i) => firstSeq + 1 + i));
129
+
130
+ acp.onClose(b.ws);
131
+ acp.stopAll();
132
+ }, 40000);
133
+
134
+ test('a DETACHED, idle bridge is reaped — no orphaned subprocess', async () => {
135
+ useMockAgent(FIXTURE_SLOW);
136
+ const ctx = freshCtx();
137
+ const acp = createAcp(ctx);
138
+ const a = fakeWs('reap-a');
139
+ acp.onOpen(a.ws);
140
+ // `warm` establishes a bridge without starting a turn — the "abandoned"
141
+ // shape, as opposed to the "still working" one above.
142
+ acp.onMessage(a.ws, JSON.stringify({ t: 'warm', chat: 'c1' }));
143
+ await until(() => (acp.size() === 1 ? true : undefined));
144
+ acp.onClose(a.ws);
145
+ expect(acp.size()).toBe(1); // detached, not yet reaped
146
+
147
+ // The real TTL is minutes — assert the CONSTANT is sane rather than sleeping
148
+ // through it. The reap PATH itself is covered by stopAll() below and by the
149
+ // ceiling test, which exercises the same `reap()`.
150
+ expect(DETACHED_TTL_MS).toBeGreaterThan(0);
151
+ expect(DETACHED_TTL_MS).toBeLessThanOrEqual(15 * 60_000);
152
+
153
+ acp.stopAll();
154
+ expect(acp.size()).toBe(0);
155
+ }, 30000);
156
+
157
+ test('detached bridges are CAPPED — the least-recently-active is reaped', async () => {
158
+ // Detaching removed the natural reaper that socket-close used to be, so an
159
+ // unbounded set of detached bridges is a process leak (DDR-125 already books
160
+ // "N processes" as the cost of parallel chats). Idle ones are sacrificed
161
+ // first; a detached bridge with a live turn is what we are protecting.
162
+ useMockAgent(FIXTURE_SLOW);
163
+ const ctx = freshCtx();
164
+ const acp = createAcp(ctx);
165
+ const sockets = [];
166
+ for (let i = 0; i <= MAX_DETACHED_BRIDGES; i++) {
167
+ const s = fakeWs(`cap-${i}`);
168
+ sockets.push(s);
169
+ acp.onOpen(s.ws);
170
+ acp.onMessage(s.ws, JSON.stringify({ t: 'warm', chat: `c${i}` }));
171
+ }
172
+ await until(() => (acp.size() === MAX_DETACHED_BRIDGES + 1 ? true : undefined));
173
+ for (const s of sockets) acp.onClose(s.ws);
174
+ expect(acp.size()).toBe(MAX_DETACHED_BRIDGES);
175
+
176
+ acp.stopAll();
177
+ }, 30000);
178
+
179
+ test('re-attaching CANCELS the reaper (a reload is not an abandonment)', async () => {
180
+ useMockAgent(FIXTURE_SLOW);
181
+ const ctx = freshCtx();
182
+ const acp = createAcp(ctx);
183
+ const a = fakeWs('rearm-a');
184
+ acp.onOpen(a.ws);
185
+ acp.onMessage(a.ws, JSON.stringify({ t: 'warm', chat: 'c1' }));
186
+ await until(() => (acp.size() === 1 ? true : undefined));
187
+ acp.onClose(a.ws);
188
+ const b = fakeWs('rearm-b');
189
+ acp.onOpen(b.ws);
190
+ acp.onMessage(b.ws, JSON.stringify({ t: 'attach', chat: 'c1', seq: 0 }));
191
+ const attached = await until(() => b.frames.find((f) => f.t === 'attached'));
192
+ expect(attached.chat).toBe('c1');
193
+ // Same bridge, not a fresh one — the whole point of keying by chat.
194
+ expect(acp.size()).toBe(1);
195
+ acp.stopAll();
196
+ }, 30000);
197
+ });
198
+
199
+ describe('bridge lifetime — a detached bridge must never read as consent', () => {
200
+ test('a permission request raised with NO socket attached fails closed (deny)', async () => {
201
+ // The Addendum names this hazard explicitly: "A detached bridge is a live
202
+ // agent with no UI attached. Any requestPermission raised while nobody is
203
+ // watching must hit the existing timeout → fail-closed deny. 'No client
204
+ // attached' must never be a path to auto-approval — that would re-open,
205
+ // from a new direction, exactly what the write gate closes."
206
+ // Driven at the BRIDGE level with a short timeout override rather than
207
+ // through the manager: the real PERMISSION_TIMEOUT_MS is 120 s, and a test
208
+ // that actually sleeps through it would be a 2-minute test proving a
209
+ // constant. Detachment is modelled the way the manager models it — the
210
+ // request is raised and `broadcast` reaches nobody, i.e. no sink answers.
211
+ useMockAgent(FIXTURE_PERM);
212
+ const updates: Array<{ content?: { text?: string } }> = [];
213
+ const raised: string[] = [];
214
+ const bridge = new AcpBridge({
215
+ repoRoot: freshCtx().paths.repoRoot,
216
+ permissionTimeoutMs: 250,
217
+ onUpdate: (u) => updates.push(u as { content?: { text?: string } }),
218
+ // A DETACHED bridge still RAISES the request (the manager's `broadcast`
219
+ // is what silently drops it when `sinks` is empty) — it just never gets
220
+ // an answer. Nothing here calls resolvePermission.
221
+ onPermissionRequest: (id) => raised.push(id),
222
+ });
223
+ try {
224
+ await bridge.prompt('go', 'c1');
225
+ expect(raised).toHaveLength(1);
226
+ const text = updates.map((u) => u?.content?.text ?? '').join('');
227
+ expect(text).toContain('"outcome":"cancelled"');
228
+ expect(text).not.toContain('selected');
229
+ } finally {
230
+ await bridge.stop();
231
+ }
232
+ }, 30000);
233
+ });
234
+
235
+ describe('bridge lifetime — a socket may only address chats it is attached to', () => {
236
+ // SECURITY. Before bridges were re-keyed by chat, every control-frame lookup
237
+ // was `bridges.get(ws.data.id)` — a socket was STRUCTURALLY incapable of
238
+ // naming another socket's bridge. Re-keying moved the key into the FRAME, and
239
+ // the first cut resolved `chat` against the whole map, silently widening the
240
+ // surface so any socket could cancel another chat's turn or flip its config.
241
+ // The nonce ids make answering another chat's permission impractical to hit
242
+ // blind, but "you'd have to guess a UUID" is a weaker guarantee than "the
243
+ // frame cannot name that bridge at all" — and DDR-125 F1's posture is
244
+ // explicitly the latter. These tests pin the restored property.
245
+ test('a control frame naming ANOTHER chat is refused', async () => {
246
+ useMockAgent(FIXTURE_SLOW);
247
+ const ctx = freshCtx();
248
+ const acp = createAcp(ctx);
249
+
250
+ const a = fakeWs('cross-a');
251
+ acp.onOpen(a.ws);
252
+ acp.onMessage(a.ws, JSON.stringify({ t: 'warm', chat: 'victim' }));
253
+ await until(() => (acp.size() === 1 ? true : undefined));
254
+
255
+ const b = fakeWs('cross-b');
256
+ acp.onOpen(b.ws);
257
+ acp.onMessage(b.ws, JSON.stringify({ t: 'warm', chat: 'attacker' }));
258
+ await until(() => (acp.size() === 2 ? true : undefined));
259
+
260
+ // Socket B names socket A's chat. Must be a no-op, not a cancel.
261
+ expect(() =>
262
+ acp.onMessage(b.ws, JSON.stringify({ t: 'cancel', chat: 'victim' }))
263
+ ).not.toThrow();
264
+ expect(() =>
265
+ acp.onMessage(
266
+ b.ws,
267
+ JSON.stringify({ t: 'permission-response', id: 'x', chat: 'victim', decision: 'allow' })
268
+ )
269
+ ).not.toThrow();
270
+ expect(() =>
271
+ acp.onMessage(
272
+ b.ws,
273
+ JSON.stringify({ t: 'set-mode', chat: 'victim', modeId: 'bypassPermissions' })
274
+ )
275
+ ).not.toThrow();
276
+
277
+ // Both bridges still alive — nothing was cancelled or torn down.
278
+ expect(acp.size()).toBe(2);
279
+ acp.stopAll();
280
+ }, 30000);
281
+
282
+ test('a socket CAN address its own chat by name', async () => {
283
+ // The restriction must not break the normal path — the client echoes `chat`
284
+ // back on every response frame.
285
+ useMockAgent(FIXTURE_SLOW);
286
+ const ctx = freshCtx();
287
+ const acp = createAcp(ctx);
288
+ const a = fakeWs('own-a');
289
+ acp.onOpen(a.ws);
290
+ acp.onMessage(a.ws, JSON.stringify({ t: 'warm', chat: 'mine' }));
291
+ await until(() => (acp.size() === 1 ? true : undefined));
292
+ expect(() => acp.onMessage(a.ws, JSON.stringify({ t: 'cancel', chat: 'mine' }))).not.toThrow();
293
+ expect(acp.size()).toBe(1);
294
+ acp.stopAll();
295
+ }, 30000);
296
+ });
297
+
298
+ describe('bridge lifetime — the attach seq is client-supplied and must be bounded', () => {
299
+ test('hostile seq values (negative, NaN, Infinity, fractional, huge) never throw or over-read', async () => {
300
+ // `frame.seq` flows into readChatLinesAfter. It is floored, clamped at 0,
301
+ // and the read is capped — but the values are attacker-chosen, so pin it.
302
+ useMockAgent(FIXTURE_SLOW);
303
+ const ctx = freshCtx();
304
+ const acp = createAcp(ctx);
305
+ const a = fakeWs('seq-a');
306
+ acp.onOpen(a.ws);
307
+ for (const seq of [-1, -1e9, Number.NaN, Number.POSITIVE_INFINITY, 3.7, 1e15, '5', null]) {
308
+ expect(() =>
309
+ acp.onMessage(a.ws, JSON.stringify({ t: 'attach', chat: 'c1', seq }))
310
+ ).not.toThrow();
311
+ }
312
+ // Every attach still answered — degraded to seq 0, never wedged.
313
+ expect(a.frames.filter((f) => f.t === 'attached').length).toBe(8);
314
+ // A chat with no transcript replays nothing regardless of the seq claimed.
315
+ expect(a.frames.filter((f) => f.t === 'update')).toHaveLength(0);
316
+ acp.stopAll();
317
+ }, 30000);
318
+
319
+ test('a traversal-shaped chat id cannot reach another file', async () => {
320
+ // chatId is sanitized to [a-z0-9_-] before it reaches the transcript path.
321
+ useMockAgent(FIXTURE_SLOW);
322
+ const ctx = freshCtx();
323
+ const acp = createAcp(ctx);
324
+ const a = fakeWs('seq-b');
325
+ acp.onOpen(a.ws);
326
+ expect(() =>
327
+ acp.onMessage(a.ws, JSON.stringify({ t: 'attach', chat: '../../../etc/passwd', seq: 0 }))
328
+ ).not.toThrow();
329
+ const attached = a.frames.find((f) => f.t === 'attached');
330
+ expect(attached?.chat).not.toContain('/');
331
+ expect(attached?.chat).not.toContain('.');
332
+ acp.stopAll();
333
+ }, 30000);
334
+ });
335
+
336
+ describe('set-mode is attachment-scoped too (ethical-hacker A2)', () => {
337
+ test('a socket CANNOT flip another chat into bypassPermissions', async () => {
338
+ // A2 was the one control frame that escaped the attachment-scoping sweep,
339
+ // and the highest-value one to miss: `bypassPermissions` is an advertised
340
+ // mode and short-circuits ADAPTER-side, so `requestPermission` — and with it
341
+ // the entire write gate — never runs. A raw `bridges.get(chat)` let any
342
+ // main-origin socket switch the gate off for a chat it was never attached
343
+ // to, including a DETACHED one with a live turn and nobody watching.
344
+ useMockAgent(FIXTURE_SLOW);
345
+ const ctx = freshCtx();
346
+ const acp = createAcp(ctx);
347
+
348
+ const victim = fakeWs('mode-victim');
349
+ acp.onOpen(victim.ws);
350
+ acp.onMessage(victim.ws, JSON.stringify({ t: 'warm', chat: 'victim' }));
351
+ await until(() => (acp.size() === 1 ? true : undefined));
352
+
353
+ const attacker = fakeWs('mode-attacker');
354
+ acp.onOpen(attacker.ws);
355
+ acp.onMessage(attacker.ws, JSON.stringify({ t: 'warm', chat: 'attacker' }));
356
+ await until(() => (acp.size() === 2 ? true : undefined));
357
+
358
+ expect(() =>
359
+ acp.onMessage(
360
+ attacker.ws,
361
+ JSON.stringify({ t: 'set-mode', chat: 'victim', modeId: 'bypassPermissions' })
362
+ )
363
+ ).not.toThrow();
364
+ // Both bridges intact and the frame was a no-op — the mode change never
365
+ // reached a bridge this socket isn't attached to.
366
+ expect(acp.size()).toBe(2);
367
+ acp.stopAll();
368
+ }, 30000);
369
+ });
@@ -267,6 +267,11 @@ describe('Acp manager — set-mode/set-config frames validate against last-adver
267
267
  );
268
268
  } finally {
269
269
  acp.onClose(a.ws);
270
+ // Task 8 — `onClose` DETACHES now; it no longer stops the bridge (that is
271
+ // the point: a page reload must not kill a running turn). So a test that
272
+ // relied on socket-close for teardown leaks the adapter subprocess for the
273
+ // whole DETACHED_TTL_MS. Tear down explicitly.
274
+ acp.stopAll();
270
275
  await new Promise((r) => setTimeout(r, 50));
271
276
  await rm(designRoot, { recursive: true, force: true });
272
277
  }
@@ -106,6 +106,11 @@ describe('Acp manager — warm frame broadcasts + open replays commands', () =>
106
106
  acp.onClose(b.ws);
107
107
  } finally {
108
108
  acp.onClose(a.ws);
109
+ // Task 8 — `onClose` DETACHES now; it no longer stops the bridge (that is
110
+ // the point: a page reload must not kill a running turn). So a test that
111
+ // relied on socket-close for teardown leaks the adapter subprocess for the
112
+ // whole DETACHED_TTL_MS. Tear down explicitly.
113
+ acp.stopAll();
109
114
  // give teardown a tick to kill the subprocess
110
115
  await new Promise((r) => setTimeout(r, 50));
111
116
  await rm(designRoot, { recursive: true, force: true });
@@ -365,6 +365,11 @@ describe('Acp manager — elicitation-request/-response frames', () => {
365
365
  expect(settledFrame.id).toBe(reqFrame.id);
366
366
  } finally {
367
367
  acp.onClose(a.ws);
368
+ // Task 8 — `onClose` DETACHES now; it no longer stops the bridge (that is
369
+ // the point: a page reload must not kill a running turn). So a test that
370
+ // relied on socket-close for teardown leaks the adapter subprocess for the
371
+ // whole DETACHED_TTL_MS. Tear down explicitly.
372
+ acp.stopAll();
368
373
  await new Promise((r) => setTimeout(r, 50));
369
374
  }
370
375
  }, 20000);