@1agh/maude 0.55.0 → 0.57.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 (85) hide show
  1. package/apps/studio/acp/bridge.ts +385 -26
  2. package/apps/studio/acp/index.ts +498 -102
  3. package/apps/studio/acp/running.ts +97 -0
  4. package/apps/studio/acp/transcript.ts +64 -0
  5. package/apps/studio/acp/write-scope.ts +459 -0
  6. package/apps/studio/bin/_smart-frames.mjs +187 -20
  7. package/apps/studio/bin/_smart-frames.test.mjs +59 -4
  8. package/apps/studio/bin/_transcribe.mjs +40 -3
  9. package/apps/studio/bin/smoke.sh +7 -1
  10. package/apps/studio/build.ts +28 -1
  11. package/apps/studio/client/app.jsx +78 -33
  12. package/apps/studio/client/panels/ChatPanel.jsx +19 -1
  13. package/apps/studio/client/panels/CloudBar.jsx +104 -6
  14. package/apps/studio/client/panels/GitPanel.jsx +38 -25
  15. package/apps/studio/client/panels/PermissionPrompt.jsx +146 -6
  16. package/apps/studio/client/panels/RepoBranchSwitcher.jsx +145 -6
  17. package/apps/studio/client/panels/SettingsPanel.jsx +239 -27
  18. package/apps/studio/client/panels/acp-runtime.js +96 -5
  19. package/apps/studio/client/styles/3-shell-maude.css +11 -2
  20. package/apps/studio/client/styles/4-components.css +72 -0
  21. package/apps/studio/client/styles/6-acp-chat.css +51 -0
  22. package/apps/studio/cloud/endpoints.ts +56 -3
  23. package/apps/studio/collab/persistence.ts +29 -2
  24. package/apps/studio/config.schema.json +3 -3
  25. package/apps/studio/context.ts +41 -0
  26. package/apps/studio/dist/client.bundle.js +1330 -1330
  27. package/apps/studio/dist/comment-mount.js +2 -2
  28. package/apps/studio/dist/styles.css +1 -1
  29. package/apps/studio/generation/gemma-models.ts +312 -14
  30. package/apps/studio/generation/prefs.ts +7 -2
  31. package/apps/studio/generation/runtime-probe.ts +50 -0
  32. package/apps/studio/generation/whisper-models.ts +124 -0
  33. package/apps/studio/hmr-broadcast.ts +67 -0
  34. package/apps/studio/http.ts +247 -111
  35. package/apps/studio/input-router.tsx +55 -2
  36. package/apps/studio/server.ts +22 -9
  37. package/apps/studio/sync/autocommit.ts +61 -2
  38. package/apps/studio/sync/cell-pairing.ts +174 -0
  39. package/apps/studio/sync/codec.ts +11 -5
  40. package/apps/studio/sync/connection-state.ts +116 -6
  41. package/apps/studio/sync/index.ts +288 -26
  42. package/apps/studio/sync/limits.ts +49 -0
  43. package/apps/studio/sync/loopback.ts +21 -0
  44. package/apps/studio/sync/presentation.ts +273 -0
  45. package/apps/studio/sync/projection.ts +47 -12
  46. package/apps/studio/sync/remote-docs.ts +191 -0
  47. package/apps/studio/sync/status.ts +4 -1
  48. package/apps/studio/sync/supervisor.ts +178 -0
  49. package/apps/studio/test/acp-activity-endpoint.test.ts +183 -0
  50. package/apps/studio/test/acp-branch-guard.test.ts +123 -0
  51. package/apps/studio/test/acp-bridge-lifetime.test.ts +369 -0
  52. package/apps/studio/test/acp-caps-bridge.test.ts +5 -0
  53. package/apps/studio/test/acp-commands.test.ts +5 -0
  54. package/apps/studio/test/acp-elicitation-bridge.test.ts +5 -0
  55. package/apps/studio/test/acp-permission-prompt.test.ts +175 -1
  56. package/apps/studio/test/acp-permission.test.ts +18 -2
  57. package/apps/studio/test/acp-session-allowed-tools.test.ts +62 -14
  58. package/apps/studio/test/acp-usage-bridge.test.ts +5 -0
  59. package/apps/studio/test/acp-write-gate.test.ts +323 -0
  60. package/apps/studio/test/acp-write-scope.test.ts +533 -0
  61. package/apps/studio/test/bundle-smoke.test.ts +35 -18
  62. package/apps/studio/test/canvas-origin-gate.test.ts +7 -0
  63. package/apps/studio/test/cloud-connect-note.test.ts +135 -0
  64. package/apps/studio/test/cloud-endpoints.test.ts +102 -0
  65. package/apps/studio/test/cloud-shell-surfaces.test.ts +5 -2
  66. package/apps/studio/test/csrf-write-guard.test.ts +19 -2
  67. package/apps/studio/test/fixtures/mock-acp-agent-slow.mjs +45 -0
  68. package/apps/studio/test/fixtures/mock-acp-agent-write.mjs +118 -0
  69. package/apps/studio/test/gemma-models.test.ts +245 -0
  70. package/apps/studio/test/hmr-broadcast.test.ts +57 -1
  71. package/apps/studio/test/input-router.test.ts +95 -0
  72. package/apps/studio/test/shared-doc-cell-pairing.test.ts +639 -0
  73. package/apps/studio/test/sync-autocommit.test.ts +47 -0
  74. package/apps/studio/test/sync-connect-honesty.test.ts +114 -0
  75. package/apps/studio/test/sync-connection-state.test.ts +45 -1
  76. package/apps/studio/test/sync-presentation.test.ts +185 -0
  77. package/apps/studio/test/sync-remote-docs.test.ts +171 -0
  78. package/apps/studio/test/sync-supervisor.test.ts +212 -0
  79. package/apps/studio/test/trusted-request-host.test.ts +66 -0
  80. package/apps/studio/test/whisper-setup.test.ts +97 -0
  81. package/apps/studio/whats-new.json +45 -0
  82. package/apps/studio/ws.ts +9 -1
  83. package/cli/commands/kg.mjs +9 -2
  84. package/package.json +8 -8
  85. package/plugins/design/dependencies.json +21 -3
@@ -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);
@@ -6,8 +6,15 @@
6
6
  // visually-primary button resolves to — a seam no backend test could see.
7
7
 
8
8
  import { describe, expect, test } from 'bun:test';
9
+ import { createElement } from 'react';
10
+ import { renderToStaticMarkup } from 'react-dom/server';
9
11
 
10
- import { pickDefaultAllow, pickDefaultReject } from '../client/panels/PermissionPrompt.jsx';
12
+ import PermissionPrompt, {
13
+ describeOutOfProject,
14
+ pickDefaultAllow,
15
+ pickDefaultReject,
16
+ sanitizePathForDisplay,
17
+ } from '../client/panels/PermissionPrompt.jsx';
11
18
 
12
19
  describe('pickDefaultAllow', () => {
13
20
  test('prefers allow_once over allow_always, regardless of array order', () => {
@@ -75,3 +82,170 @@ describe('pickDefaultReject', () => {
75
82
  expect(pickDefaultReject(null)).toBeNull();
76
83
  });
77
84
  });
85
+
86
+ // feature-acp-write-path-scope Task 4 — the out-of-project WRITE card.
87
+ //
88
+ // Same reasoning as the pickDefaultAllow suite above: the affordance IS the
89
+ // security control. A card that renders the model's own path string, or that
90
+ // still offers an "always allow", is a speed bump rather than a gate — and
91
+ // neither failure is visible to any bridge-side test.
92
+ const OUT_OF_PROJECT = {
93
+ outOfProjectWrite: true,
94
+ resolvedPaths: ['/Users/x/.zshenv'],
95
+ scopeRoot: '/Users/x/git/project',
96
+ reason: 'outside',
97
+ };
98
+
99
+ describe('describeOutOfProject', () => {
100
+ test('absent scope → null (an ordinary permission card is unchanged)', () => {
101
+ expect(describeOutOfProject(undefined)).toBeNull();
102
+ expect(describeOutOfProject(null)).toBeNull();
103
+ // A scope object that isn't explicitly flagged must NOT trigger the copy —
104
+ // the discriminator is checked, not merely the object's presence.
105
+ expect(describeOutOfProject({ resolvedPaths: ['/etc/passwd'] })).toBeNull();
106
+ });
107
+
108
+ test('carries the resolved paths + root verbatim', () => {
109
+ const d = describeOutOfProject(OUT_OF_PROJECT);
110
+ expect(d?.paths).toEqual(['/Users/x/.zshenv']);
111
+ expect(d?.scopeRoot).toBe('/Users/x/git/project');
112
+ expect(d?.lead).toContain('outside this project');
113
+ });
114
+
115
+ test('plural lead for a multi-target write', () => {
116
+ const d = describeOutOfProject({ ...OUT_OF_PROJECT, resolvedPaths: ['/a', '/b'] });
117
+ expect(d?.lead).toContain('files outside this project');
118
+ });
119
+
120
+ test('the fail-closed reasons get their own honest copy, not "outside"', () => {
121
+ // `no-target` and `disagreement` are NOT "the file is outside the project" —
122
+ // saying so would be a claim the server never made. They are "we could not
123
+ // tell what will be written", which is a different thing to ask a human about.
124
+ expect(describeOutOfProject({ ...OUT_OF_PROJECT, reason: 'no-target' })?.lead).toContain(
125
+ 'did not say which one'
126
+ );
127
+ expect(describeOutOfProject({ ...OUT_OF_PROJECT, reason: 'disagreement' })?.lead).toContain(
128
+ 'two different files'
129
+ );
130
+ });
131
+
132
+ test('tolerates a malformed resolvedPaths — never throws', () => {
133
+ expect(describeOutOfProject({ outOfProjectWrite: true })?.paths).toEqual([]);
134
+ expect(
135
+ describeOutOfProject({ outOfProjectWrite: true, resolvedPaths: [null, '', '/ok'] })?.paths
136
+ ).toEqual(['/ok']);
137
+ });
138
+ });
139
+
140
+ describe('PermissionPrompt — render', () => {
141
+ const OPTIONS = [
142
+ { optionId: 'allow_always', kind: 'allow_always', name: 'Always Allow' },
143
+ { optionId: 'allow', kind: 'allow_once', name: 'Allow' },
144
+ { optionId: 'reject', kind: 'reject_once', name: 'Reject' },
145
+ ];
146
+ const render = (request) =>
147
+ renderToStaticMarkup(createElement(PermissionPrompt, { request, onRespond: () => {} }));
148
+
149
+ test('an ORDINARY request renders the generic copy and every offered option', () => {
150
+ const out = render({ id: '1', toolCall: { title: 'Run command' }, options: OPTIONS });
151
+ expect(out).toContain('Claude wants permission to continue');
152
+ expect(out).not.toContain('chat-perm-outside');
153
+ expect(out).toContain('Always Allow');
154
+ });
155
+
156
+ test('an OUT-OF-PROJECT write renders the RESOLVED path, never the model string', () => {
157
+ const out = render({
158
+ id: '1',
159
+ // `rawInput.file_path` is the model-authored string. It reads like a docs
160
+ // edit; only the resolution tells the truth, so the card must show the
161
+ // latter. Same lesson as the deep-link modal's truncated project name.
162
+ toolCall: {
163
+ title: 'Write docs/../../../.zshenv',
164
+ rawInput: { file_path: 'docs/../../../.zshenv' },
165
+ },
166
+ options: OPTIONS,
167
+ scope: OUT_OF_PROJECT,
168
+ });
169
+ expect(out).toContain('/Users/x/.zshenv');
170
+ expect(out).not.toContain('docs/../../../.zshenv');
171
+ expect(out).toContain('outside this project');
172
+ expect(out).toContain('/Users/x/git/project');
173
+ });
174
+
175
+ test('DECISION D — the out-of-project card offers NO "always" option', () => {
176
+ const out = render({
177
+ id: '1',
178
+ toolCall: { title: 'Write' },
179
+ options: OPTIONS,
180
+ scope: OUT_OF_PROJECT,
181
+ });
182
+ expect(out).not.toContain('Always Allow');
183
+ expect(out).toContain('Allow');
184
+ expect(out).toContain('Reject');
185
+ expect(out).toContain('for this request only');
186
+ });
187
+
188
+ test('the out-of-project card is distinguishable, not just differently worded', () => {
189
+ // A card that LOOKS identical to the routine one gets clicked through at the
190
+ // same rate, which is the whole prompt-fatigue failure mode.
191
+ const out = render({
192
+ id: '1',
193
+ toolCall: { title: 'Write' },
194
+ options: OPTIONS,
195
+ scope: OUT_OF_PROJECT,
196
+ });
197
+ expect(out).toContain('chat-perm--outside');
198
+ expect(out).toContain('file outside this project'); // aria-label
199
+ });
200
+ });
201
+
202
+ // SECURITY (security-auditor F3) — the resolved path's non-existent tail is
203
+ // whatever the model asked to create, so it is attacker-influenced text in the
204
+ // one card whose entire job is to be read accurately. React escapes markup; it
205
+ // does NOT neutralize bidi overrides, so a path can be made to READ as harmless
206
+ // while resolving somewhere else. Written as \u escapes on purpose: a literal
207
+ // override in this source would reorder the test file itself in every editor.
208
+ const RLO = '\u202E';
209
+ const PDF = '\u202C';
210
+
211
+ describe('sanitizePathForDisplay (F3)', () => {
212
+ test('neutralizes bidi overrides — the visual-spoofing primitive', () => {
213
+ const out = sanitizePathForDisplay(`/Users/x/safe/${RLO}gnp.esriv${PDF}`);
214
+ expect(out).not.toContain(RLO);
215
+ expect(out).not.toContain(PDF);
216
+ // Replaced, not deleted — a tampered path should look ODD, not just shorter.
217
+ expect(out).toContain('\uFFFD');
218
+ });
219
+
220
+ test('neutralizes C0 controls (newline/CR can hide a whole path segment)', () => {
221
+ const out = sanitizePathForDisplay('/Users/x/a\nb\rc');
222
+ expect(out).not.toMatch(/[\n\r]/);
223
+ });
224
+
225
+ test('also covers zero-width, directional marks and soft hyphen (F3 nit)', () => {
226
+ // Zero-width joiners and directional marks are invisible, so they can split
227
+ // or re-order a path name without leaving any visible trace at all — the
228
+ // same class of trick as the overrides, just quieter.
229
+ const sneaky = '/Users/x/\u200Bzsh\u200Cenv\u061C\u00AD';
230
+ const out = sanitizePathForDisplay(sneaky);
231
+ for (const ch of ['\u200B', '\u200C', '\u061C', '\u00AD']) {
232
+ expect(out).not.toContain(ch);
233
+ }
234
+ });
235
+
236
+ test('leaves an ordinary path completely untouched', () => {
237
+ const p = '/Users/x/git/project/.design/ui/home.tsx';
238
+ expect(sanitizePathForDisplay(p)).toBe(p);
239
+ });
240
+
241
+ test('describeOutOfProject sanitizes BOTH the paths and the scope root', () => {
242
+ const d = describeOutOfProject({
243
+ outOfProjectWrite: true,
244
+ reason: 'outside',
245
+ resolvedPaths: [`/Users/x/${RLO}evil`],
246
+ scopeRoot: `/Users/x/${RLO}root`,
247
+ });
248
+ expect(d.paths[0]).not.toContain(RLO);
249
+ expect(d.scopeRoot).not.toContain(RLO);
250
+ });
251
+ });
@@ -75,7 +75,14 @@ describe('AcpBridge — permission approve/deny (Task B1)', () => {
75
75
  const promptPromise = bridge.prompt('hi', 'c1');
76
76
  const req = await until(() => (requests.length ? requests[0] : undefined));
77
77
  expect(req.toolCallTitle).toBe('Write file');
78
- expect(req.optionIds).toEqual(['allow-once', 'allow-always', 'reject-once']);
78
+ // `allow-always` is ABSENT, and that is the point (feature-acp-write-path-
79
+ // scope Decision D + security-auditor F2). This fixture's tool call is
80
+ // `kind:'edit'` targeting `/tmp/x` — a write-shaped call landing OUTSIDE
81
+ // the bridge's project root — so the bridge strips every `allow_always`
82
+ // option before offering it, and validates any response against that same
83
+ // filtered set. Consent for an out-of-project write is per-call; one click
84
+ // must not be able to install a session-wide standing rule.
85
+ expect(req.optionIds).toEqual(['allow-once', 'reject-once']);
79
86
  expect(transparency.length).toBe(1); // transparency fires unconditionally too
80
87
 
81
88
  bridge.resolvePermission(req.id, 'allow-once');
@@ -191,7 +198,11 @@ describe('Acp manager — permission-request/-response frames (Task B2)', () =>
191
198
  const reqFrame = await until(() => a.frames.find((f) => f.t === 'permission-request'));
192
199
  expect(reqFrame.toolCall).toMatchObject({ title: 'Write file' });
193
200
  const options = reqFrame.options as Array<{ optionId: string }>;
194
- expect(options.map((o) => o.optionId)).toEqual(['allow-once', 'allow-always', 'reject-once']);
201
+ // See the Task B1 test above — `allow-always` is stripped for this
202
+ // out-of-project write-shaped call, and the FRAME carries the filtered
203
+ // set, so the client is shown the real options rather than a cosmetic
204
+ // subset the server would then reject.
205
+ expect(options.map((o) => o.optionId)).toEqual(['allow-once', 'reject-once']);
195
206
 
196
207
  acp.onMessage(
197
208
  a.ws,
@@ -200,6 +211,11 @@ describe('Acp manager — permission-request/-response frames (Task B2)', () =>
200
211
  await until(() => a.frames.find((f) => f.t === 'turn-end'));
201
212
  } finally {
202
213
  acp.onClose(a.ws);
214
+ // Task 8 — `onClose` DETACHES now; it no longer stops the bridge (that is
215
+ // the point: a page reload must not kill a running turn). So a test that
216
+ // relied on socket-close for teardown leaks the adapter subprocess for the
217
+ // whole DETACHED_TTL_MS. Tear down explicitly.
218
+ acp.stopAll();
203
219
  await new Promise((r) => setTimeout(r, 50));
204
220
  }
205
221
  }, 20000);