@1agh/maude 0.48.0 → 0.49.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 (33) hide show
  1. package/apps/studio/api.ts +18 -2
  2. package/apps/studio/assets-s3.ts +291 -0
  3. package/apps/studio/collab/origins.ts +150 -0
  4. package/apps/studio/collab/protocol.ts +36 -9
  5. package/apps/studio/collab/room.ts +124 -0
  6. package/apps/studio/context.ts +9 -0
  7. package/apps/studio/dist/client.bundle.js +1 -1
  8. package/apps/studio/dist/comment-mount.js +2 -2
  9. package/apps/studio/http.ts +45 -0
  10. package/apps/studio/server.ts +75 -2
  11. package/apps/studio/sync/autocommit.ts +299 -0
  12. package/apps/studio/sync/doc-name.ts +228 -0
  13. package/apps/studio/sync/index.ts +95 -1
  14. package/apps/studio/sync/workspace-signin.ts +301 -0
  15. package/apps/studio/test/assets-s3.test.ts +249 -0
  16. package/apps/studio/test/canvas-origin-gate.test.ts +7 -0
  17. package/apps/studio/test/collab-origin-gate.test.ts +323 -0
  18. package/apps/studio/test/sync-autocommit.test.ts +334 -0
  19. package/apps/studio/test/sync-doc-name.test.ts +281 -0
  20. package/apps/studio/test/workspace-containment.test.ts +258 -0
  21. package/apps/studio/test/workspace-signin.test.ts +270 -0
  22. package/apps/studio/use-collab.tsx +28 -1
  23. package/apps/studio/workspace-mode.ts +210 -0
  24. package/apps/studio/ws.ts +11 -2
  25. package/cli/commands/hub-workspace.mjs +341 -0
  26. package/cli/commands/hub.mjs +325 -3
  27. package/cli/commands/hub.test.mjs +14 -1
  28. package/cli/lib/cell-plan.mjs +302 -0
  29. package/cli/lib/cell-plan.test.mjs +225 -0
  30. package/cli/lib/gitignore-block.mjs +12 -1
  31. package/cli/lib/workspace-plan.mjs +422 -0
  32. package/cli/lib/workspace-plan.test.mjs +223 -0
  33. package/package.json +8 -8
@@ -0,0 +1,323 @@
1
+ // Unit: the DDR-122 follow-up origin gate — untrusted canvas-realm doc ops may
2
+ // never write the canvas SOURCE lanes (html / css / meta / syncMeta), while the
3
+ // lanes the canvas legitimately co-authors (comments / annotations /
4
+ // presentation) keep working for same-machine boards.
5
+ //
6
+ // Cloud Phase 1 Task 3. See apps/studio/collab/origins.ts for the threat model
7
+ // and for why the gate needs a mirror doc rather than update-byte inspection.
8
+
9
+ import { describe, expect, test } from 'bun:test';
10
+
11
+ import * as encoding from 'lib0/encoding';
12
+ import { writeUpdate } from 'y-protocols/sync';
13
+ import * as Y from 'yjs';
14
+
15
+ import {
16
+ isBodyLane,
17
+ isCanvasAuthorableLane,
18
+ isTrustedOrigin,
19
+ laneVocabulary,
20
+ markTrustedOrigin,
21
+ rootTypesTouched,
22
+ SHELL_EDIT_ORIGIN,
23
+ touchesBodyLane,
24
+ } from '../collab/origins.ts';
25
+ import { MESSAGE_SYNC } from '../collab/protocol.ts';
26
+ import { createRoom, type RoomCallbacks, type RoomConn } from '../collab/room.ts';
27
+
28
+ const MESSAGE_SYNC_UPDATE = 2; // y-protocols/sync messageYjsUpdate
29
+
30
+ function makeConn(id: string, realm?: 'main' | 'canvas'): RoomConn & { recv: Uint8Array[] } {
31
+ const recv: Uint8Array[] = [];
32
+ return {
33
+ id,
34
+ ...(realm ? { realm } : {}),
35
+ send(payload: Uint8Array) {
36
+ recv.push(payload);
37
+ },
38
+ recv,
39
+ };
40
+ }
41
+
42
+ function makeCallbacks(): RoomCallbacks {
43
+ return {
44
+ seed() {
45
+ /* nothing on disk */
46
+ },
47
+ persistJson() {
48
+ /* no-op */
49
+ },
50
+ persistBinary() {
51
+ /* no-op */
52
+ },
53
+ };
54
+ }
55
+
56
+ /** Frame a raw Y update as a y-websocket MESSAGE_SYNC / update frame. */
57
+ function syncUpdateFrame(update: Uint8Array): Uint8Array {
58
+ const encoder = encoding.createEncoder();
59
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
60
+ writeUpdate(encoder, update);
61
+ return encoding.toUint8Array(encoder);
62
+ }
63
+
64
+ /**
65
+ * Build the frame a malicious (or merely careless) canvas peer would send: it
66
+ * mirrors the room's current state, mutates locally, and ships the delta —
67
+ * exactly what `use-collab.tsx` does, minus lock 1.
68
+ */
69
+ function peerDelta(room: { doc: Y.Doc }, mutate: (doc: Y.Doc) => void): Uint8Array {
70
+ const peer = new Y.Doc();
71
+ Y.applyUpdate(peer, Y.encodeStateAsUpdate(room.doc));
72
+ const before = Y.encodeStateVector(peer);
73
+ mutate(peer);
74
+ return Y.encodeStateAsUpdate(peer, before);
75
+ }
76
+
77
+ describe('origins — lane vocabulary + trusted sentinels', () => {
78
+ test('body lanes and canvas-authorable lanes are disjoint and complete', () => {
79
+ const { body, canvasAuthorable } = laneVocabulary();
80
+ expect(body).toEqual(['css', 'html', 'meta', 'syncMeta']);
81
+ expect(canvasAuthorable).toEqual(['annotations', 'comments', 'presentation']);
82
+ for (const lane of body) {
83
+ expect(isBodyLane(lane)).toBe(true);
84
+ expect(isCanvasAuthorableLane(lane)).toBe(false);
85
+ }
86
+ for (const lane of canvasAuthorable) {
87
+ expect(isBodyLane(lane)).toBe(false);
88
+ expect(isCanvasAuthorableLane(lane)).toBe(true);
89
+ }
90
+ });
91
+
92
+ test('a forged origin object is NOT trusted; only the real sentinel is', () => {
93
+ expect(isTrustedOrigin(SHELL_EDIT_ORIGIN)).toBe(true);
94
+ // The exact shape of the sentinel, rebuilt by an attacker who read the source.
95
+ expect(isTrustedOrigin({ maudeOrigin: 'shell-edit' })).toBe(false);
96
+ expect(isTrustedOrigin('shell-edit')).toBe(false);
97
+ expect(isTrustedOrigin(null)).toBe(false);
98
+ expect(isTrustedOrigin(undefined)).toBe(false);
99
+ });
100
+
101
+ test('markTrustedOrigin registers a frozen object and returns it', () => {
102
+ const sentinel = markTrustedOrigin(Object.freeze({ maudeOrigin: 'test' }));
103
+ expect(isTrustedOrigin(sentinel)).toBe(true);
104
+ });
105
+
106
+ test('rootTypesTouched resolves nested types up to their root', () => {
107
+ const doc = new Y.Doc();
108
+ const seen: Set<string>[] = [];
109
+ doc.on('afterTransaction', (tr: Y.Transaction) => {
110
+ if (tr.origin === 'probe') seen.push(rootTypesTouched(tr));
111
+ });
112
+ doc.transact(() => {
113
+ const nested = new Y.Map<string>();
114
+ doc.getArray<Y.Map<string>>('comments').push([nested]);
115
+ nested.set('text', 'hi');
116
+ }, 'probe');
117
+ expect(seen.length).toBe(1);
118
+ expect([...(seen[0] ?? [])]).toEqual(['comments']);
119
+ });
120
+
121
+ test('touchesBodyLane discriminates body writes from comment writes', () => {
122
+ const doc = new Y.Doc();
123
+ const verdicts: boolean[] = [];
124
+ doc.on('afterTransaction', (tr: Y.Transaction) => {
125
+ if (tr.origin === 'probe') verdicts.push(touchesBodyLane(tr));
126
+ });
127
+ doc.transact(() => doc.getArray('comments').push([{ id: 'c1' }]), 'probe');
128
+ doc.transact(() => doc.getText('html').insert(0, '<b>x</b>'), 'probe');
129
+ // An insert into EXISTING text — the case whose target lane is absent from
130
+ // the update bytes (origins.ts § "why a mirror doc").
131
+ doc.transact(() => doc.getText('html').insert(3, 'evil'), 'probe');
132
+ expect(verdicts).toEqual([false, true, true]);
133
+ });
134
+ });
135
+
136
+ describe('room origin gate — canvas realm', () => {
137
+ test('REJECTS a canvas-realm write to the body lane; doc untouched, not broadcast', async () => {
138
+ const room = createRoom('ui-screen', makeCallbacks());
139
+ const shell = makeConn('shell', 'main');
140
+ const canvas = makeConn('canvas', 'canvas');
141
+ await room.connect(shell);
142
+ await room.connect(canvas);
143
+ shell.recv.length = 0;
144
+
145
+ // Seed a body through the trusted path so the attack is an insert into
146
+ // EXISTING text — the case update-byte inspection cannot classify.
147
+ room.doc.transact(() => room.doc.getText('html').insert(0, '<main>ok</main>'), 'sync-agent');
148
+ shell.recv.length = 0;
149
+ canvas.recv.length = 0;
150
+
151
+ const evil = peerDelta(room, (d) => d.getText('html').insert(6, 'PWNED'));
152
+ room.receive(canvas, syncUpdateFrame(evil));
153
+
154
+ expect(room.doc.getText('html').toString()).toBe('<main>ok</main>');
155
+ expect(room.gateRefusals()).toBe(1);
156
+ // Nothing reached the other peer.
157
+ expect(shell.recv.length).toBe(0);
158
+ // The refused peer got a corrective full-state frame instead.
159
+ expect(canvas.recv.length).toBe(1);
160
+ await room.destroy();
161
+ });
162
+
163
+ test('REJECTS canvas-realm writes to css, meta and syncMeta too', async () => {
164
+ for (const [lane, mutate] of [
165
+ ['css', (d: Y.Doc) => d.getText('css').insert(0, '.evil{}')],
166
+ ['meta', (d: Y.Doc) => d.getText('meta').insert(0, '{"evil":1}')],
167
+ ['syncMeta', (d: Y.Doc) => d.getMap('syncMeta').set('bodyEditAt', 1)],
168
+ ] as const) {
169
+ const room = createRoom(`lane-${lane}`, makeCallbacks());
170
+ const canvas = makeConn('canvas', 'canvas');
171
+ await room.connect(canvas);
172
+ room.receive(canvas, syncUpdateFrame(peerDelta(room, mutate)));
173
+ expect(room.gateRefusals()).toBe(1);
174
+ expect(Y.encodeStateAsUpdate(room.doc).length).toBe(
175
+ Y.encodeStateAsUpdate(new Y.Doc()).length
176
+ );
177
+ await room.destroy();
178
+ }
179
+ });
180
+
181
+ test('ALLOWS canvas-realm comments + annotations (same-machine boards keep working)', async () => {
182
+ const room = createRoom('board', makeCallbacks());
183
+ const shell = makeConn('shell', 'main');
184
+ const canvas = makeConn('canvas', 'canvas');
185
+ await room.connect(shell);
186
+ await room.connect(canvas);
187
+ shell.recv.length = 0;
188
+
189
+ room.receive(
190
+ canvas,
191
+ syncUpdateFrame(
192
+ peerDelta(room, (d) => {
193
+ d.getArray('comments').push([{ id: 'c1', text: 'from the canvas' }]);
194
+ d.getMap('annotations').set('svg', '<svg><rect/></svg>');
195
+ })
196
+ )
197
+ );
198
+
199
+ expect(room.doc.getArray('comments').toArray()).toEqual([
200
+ { id: 'c1', text: 'from the canvas' },
201
+ ]);
202
+ expect(room.doc.getMap('annotations').get('svg')).toBe('<svg><rect/></svg>');
203
+ expect(room.gateRefusals()).toBe(0);
204
+ // And it DID reach the other peer.
205
+ expect(shell.recv.length).toBeGreaterThan(0);
206
+ await room.destroy();
207
+ });
208
+
209
+ test('a mixed frame is refused WHOLESALE — no partial application of the good half', async () => {
210
+ const room = createRoom('mixed', makeCallbacks());
211
+ const canvas = makeConn('canvas', 'canvas');
212
+ await room.connect(canvas);
213
+
214
+ room.receive(
215
+ canvas,
216
+ syncUpdateFrame(
217
+ peerDelta(room, (d) => {
218
+ d.getArray('comments').push([{ id: 'decoy' }]);
219
+ d.getText('html').insert(0, 'PWNED');
220
+ })
221
+ )
222
+ );
223
+
224
+ expect(room.gateRefusals()).toBe(1);
225
+ expect(room.doc.getArray('comments').length).toBe(0);
226
+ expect(room.doc.getText('html').toString()).toBe('');
227
+ await room.destroy();
228
+ });
229
+
230
+ test('the gate SURVIVES a refusal — the next honest canvas frame still applies', async () => {
231
+ const room = createRoom('recover', makeCallbacks());
232
+ const canvas = makeConn('canvas', 'canvas');
233
+ await room.connect(canvas);
234
+
235
+ room.receive(canvas, syncUpdateFrame(peerDelta(room, (d) => d.getText('html').insert(0, 'x'))));
236
+ expect(room.gateRefusals()).toBe(1);
237
+
238
+ room.receive(
239
+ canvas,
240
+ syncUpdateFrame(peerDelta(room, (d) => d.getArray('comments').push([{ id: 'after' }])))
241
+ );
242
+ expect(room.gateRefusals()).toBe(1);
243
+ expect(room.doc.getArray('comments').toArray()).toEqual([{ id: 'after' }]);
244
+ await room.destroy();
245
+ });
246
+
247
+ test('the MAIN realm is ungated — the shell may still write the body', async () => {
248
+ const room = createRoom('shell-write', makeCallbacks());
249
+ const shell = makeConn('shell', 'main');
250
+ await room.connect(shell);
251
+
252
+ room.receive(shell, syncUpdateFrame(peerDelta(room, (d) => d.getText('html').insert(0, 'ok'))));
253
+
254
+ expect(room.doc.getText('html').toString()).toBe('ok');
255
+ expect(room.gateRefusals()).toBe(0);
256
+ await room.destroy();
257
+ });
258
+
259
+ test('a conn with no realm defaults to trusted (pre-existing callers unchanged)', async () => {
260
+ const room = createRoom('legacy', makeCallbacks());
261
+ const legacy = makeConn('legacy');
262
+ await room.connect(legacy);
263
+
264
+ room.receive(
265
+ legacy,
266
+ syncUpdateFrame(peerDelta(room, (d) => d.getText('html').insert(0, 'ok')))
267
+ );
268
+
269
+ expect(room.doc.getText('html').toString()).toBe('ok');
270
+ expect(room.gateRefusals()).toBe(0);
271
+ await room.destroy();
272
+ });
273
+
274
+ test('awareness frames from the canvas realm pass through the gate untouched', async () => {
275
+ const room = createRoom('presence', makeCallbacks());
276
+ const canvas = makeConn('canvas', 'canvas');
277
+ await room.connect(canvas);
278
+
279
+ // A well-formed awareness frame from a peer's own Awareness instance.
280
+ const peerDoc = new Y.Doc();
281
+ const { Awareness, encodeAwarenessUpdate } = await import('y-protocols/awareness');
282
+ const peerAwareness = new Awareness(peerDoc);
283
+ peerAwareness.setLocalState({ name: 'canvas peer' });
284
+ const encoder = encoding.createEncoder();
285
+ encoding.writeVarUint(encoder, 1 /* MESSAGE_AWARENESS */);
286
+ encoding.writeVarUint8Array(
287
+ encoder,
288
+ encodeAwarenessUpdate(peerAwareness, [peerAwareness.clientID])
289
+ );
290
+ room.receive(canvas, encoding.toUint8Array(encoder));
291
+
292
+ expect(room.awareness.getStates().get(peerAwareness.clientID)).toEqual({ name: 'canvas peer' });
293
+ expect(room.gateRefusals()).toBe(0);
294
+ await room.destroy();
295
+ });
296
+
297
+ test('a malformed sync frame from the canvas realm mutates nothing and leaves the room usable', async () => {
298
+ const room = createRoom('garbage', makeCallbacks());
299
+ const canvas = makeConn('canvas', 'canvas');
300
+ await room.connect(canvas);
301
+
302
+ const encoder = encoding.createEncoder();
303
+ encoding.writeVarUint(encoder, MESSAGE_SYNC);
304
+ encoding.writeVarUint(encoder, MESSAGE_SYNC_UPDATE);
305
+ encoding.writeVarUint8Array(encoder, new Uint8Array([0xff, 0xff, 0xff, 0xff]));
306
+ // yjs swallows an undecodable update internally rather than throwing, so
307
+ // this is not a *gate* refusal — it never becomes a transaction at all, on
308
+ // the mirror or on the room doc. Assert the property that matters: nothing
309
+ // applied, no crash, and the gate still works afterwards.
310
+ room.receive(canvas, encoding.toUint8Array(encoder));
311
+
312
+ expect(Y.encodeStateAsUpdate(room.doc).length).toBe(Y.encodeStateAsUpdate(new Y.Doc()).length);
313
+
314
+ room.receive(canvas, syncUpdateFrame(peerDelta(room, (d) => d.getText('html').insert(0, 'x'))));
315
+ expect(room.gateRefusals()).toBe(1);
316
+ room.receive(
317
+ canvas,
318
+ syncUpdateFrame(peerDelta(room, (d) => d.getArray('comments').push([{ id: 'ok' }])))
319
+ );
320
+ expect(room.doc.getArray('comments').toArray()).toEqual([{ id: 'ok' }]);
321
+ await room.destroy();
322
+ });
323
+ });
@@ -0,0 +1,334 @@
1
+ // Cloud Phase 3 Task 1 — autosave as append-only git commits.
2
+ //
3
+ // Driven against a REAL git repository in a temp dir, not a mocked runner. The
4
+ // properties that matter (authorship survives, history is never rewritten, a
5
+ // no-op write produces no commit) are properties of git's actual behaviour, and
6
+ // a mock would only prove that the arguments match what I expected them to be.
7
+
8
+ import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
9
+
10
+ import { spawn } from 'node:child_process';
11
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import path from 'node:path';
14
+
15
+ import {
16
+ commitMessage,
17
+ createAutoCommit,
18
+ formatAuthor,
19
+ type GitRunner,
20
+ pushMirror,
21
+ sanitizeAttribution,
22
+ UNKNOWN_AUTHOR,
23
+ } from '../sync/autocommit.ts';
24
+
25
+ const git: GitRunner = (args, { cwd }) =>
26
+ new Promise((resolve) => {
27
+ const child = spawn('git', args, {
28
+ cwd,
29
+ env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null' },
30
+ });
31
+ let stdout = '';
32
+ let stderr = '';
33
+ child.stdout.on('data', (d) => {
34
+ stdout += d;
35
+ });
36
+ child.stderr.on('data', (d) => {
37
+ stderr += d;
38
+ });
39
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr }));
40
+ });
41
+
42
+ let repo: string;
43
+
44
+ async function initRepo(): Promise<string> {
45
+ const dir = mkdtempSync(path.join(tmpdir(), 'maude-autocommit-'));
46
+ await git(['init', '--initial-branch=main'], { cwd: dir });
47
+ await git(['config', 'user.name', 'Seed'], { cwd: dir });
48
+ await git(['config', 'user.email', 'seed@example.com'], { cwd: dir });
49
+ mkdirSync(path.join(dir, '.design', 'ui'), { recursive: true });
50
+ writeFileSync(path.join(dir, '.design', 'ui', 'Screen.tsx'), 'export default () => null;\n');
51
+ await git(['add', '-A'], { cwd: dir });
52
+ await git(['commit', '-m', 'seed'], { cwd: dir });
53
+ return dir;
54
+ }
55
+
56
+ const ALICE = { name: 'Alice Novák', email: 'alice@example.com' };
57
+ const BOB = { name: 'Bob', email: 'bob@example.com' };
58
+ const REL = '.design/ui/Screen.tsx';
59
+
60
+ const write = (rel: string, body: string) => writeFileSync(path.join(repo, rel), body);
61
+ const log = async (fmt: string) =>
62
+ (await git(['log', `--pretty=format:${fmt}`], { cwd: repo })).stdout.split('\n').filter(Boolean);
63
+
64
+ beforeEach(async () => {
65
+ repo = await initRepo();
66
+ });
67
+
68
+ afterEach(() => {
69
+ if (repo) rmSync(repo, { recursive: true, force: true });
70
+ });
71
+
72
+ describe('attribution', () => {
73
+ test('a missing author is UNKNOWN, never the bot', () => {
74
+ // Attributing an anonymous human's work to the server makes `git blame` lie
75
+ // in a way that is hard to notice later. "Unknown" is honest and visibly
76
+ // wrong.
77
+ expect(sanitizeAttribution(null)).toEqual(UNKNOWN_AUTHOR);
78
+ expect(sanitizeAttribution(undefined)).toEqual(UNKNOWN_AUTHOR);
79
+ expect(sanitizeAttribution({ name: '', email: '' })).toEqual(UNKNOWN_AUTHOR);
80
+ });
81
+
82
+ test('presence-supplied identity cannot forge commit trailers', () => {
83
+ // Presence arrives over a semi-trusted hub (DDR-054): a name is
84
+ // attacker-influenceable text, and `--author` takes `Name <email>`.
85
+ const evil = sanitizeAttribution({
86
+ name: 'Real Person <real@example.com>\nSigned-off-by: Someone Else',
87
+ email: 'a@b.com\r\nCo-Authored-By: Nobody',
88
+ });
89
+ expect(evil.name).not.toContain('\n');
90
+ expect(evil.name).not.toContain('<');
91
+ expect(evil.name).not.toContain('>');
92
+ expect(evil.email).not.toContain('\r');
93
+ expect(formatAuthor(evil)).toMatch(/^[^<>\n]+ <[^<>\n]+>$/);
94
+ });
95
+
96
+ test('names are bounded so one peer cannot bloat every commit', () => {
97
+ const long = sanitizeAttribution({ name: 'x'.repeat(500), email: 'y'.repeat(500) });
98
+ expect(long.name.length).toBeLessThanOrEqual(96);
99
+ expect(long.email.length).toBeLessThanOrEqual(96);
100
+ });
101
+
102
+ test('unicode names survive intact — this is a real person, not a slug', () => {
103
+ expect(sanitizeAttribution(ALICE).name).toBe('Alice Novák');
104
+ });
105
+ });
106
+
107
+ describe('commit message', () => {
108
+ test('names the canvas rather than saying "autosave"', () => {
109
+ // 400 identical subjects is the same as no history.
110
+ const one = commitMessage(['.design/ui/Screen.tsx'], ALICE);
111
+ expect(one.split('\n')[0]).toBe('design: update Screen');
112
+ expect(one).toContain('Alice Novák <alice@example.com>');
113
+ expect(one).toContain('append-only');
114
+ });
115
+
116
+ test('a multi-file commit summarizes and lists', () => {
117
+ const many = commitMessage(
118
+ ['.design/ui/Screen.tsx', '.design/ui/Settings.tsx', '.design/ui/Screen.meta.json'],
119
+ ALICE
120
+ );
121
+ // Screen.tsx + Screen.meta.json are ONE canvas — a subject that said
122
+ // "3 canvases" would overstate what changed on every single commit.
123
+ expect(many.split('\n')[0]).toBe('design: update 2 canvases');
124
+ expect(many).toContain('- Screen');
125
+ expect(many).toContain('- Settings');
126
+ expect(many).not.toContain('- Screen.meta');
127
+ });
128
+ });
129
+
130
+ describe('committing, against a real repo', () => {
131
+ test('an edit becomes a commit authored by the HUMAN, committed by the bot', async () => {
132
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
133
+ write(REL, 'export default () => <main>alice was here</main>;\n');
134
+ auto.note(REL, ALICE);
135
+
136
+ const outcome = await auto.flush();
137
+ expect(outcome?.ok).toBe(true);
138
+
139
+ // This is the point of using git's author/committer split at all: blame
140
+ // answers "who designed this", not "the server did".
141
+ expect(await log('%an|%ae')).toEqual([
142
+ 'Alice Novák|alice@example.com',
143
+ 'Seed|seed@example.com',
144
+ ]);
145
+ expect((await log('%cn'))[0]).toBe('Maude Workspace');
146
+ expect((await log('%s'))[0]).toBe('design: update Screen');
147
+ });
148
+
149
+ test('edits COALESCE — a typing session is one commit, not four hundred', async () => {
150
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
151
+ for (let i = 0; i < 20; i++) {
152
+ write(REL, `export default () => <main>v${i}</main>;\n`);
153
+ auto.note(REL, ALICE);
154
+ }
155
+ await auto.flush();
156
+ expect((await log('%s')).length).toBe(2); // seed + one autosave
157
+ });
158
+
159
+ test('a no-op write produces NO commit', async () => {
160
+ // An echo, or a write of identical bytes. Committing it would be noise.
161
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
162
+ auto.note(REL, ALICE);
163
+ const outcome = await auto.flush();
164
+ expect(outcome?.ok).toBe(false);
165
+ expect(outcome && !outcome.ok && outcome.reason).toBe('nothing-to-commit');
166
+ expect((await log('%s')).length).toBe(1);
167
+ });
168
+
169
+ test('only the NOTED files are staged — an unrelated dirty file is left alone', async () => {
170
+ // `git add -A` in a workspace would sweep in whatever else is in the tree.
171
+ // The cell must never commit something it wasn't told about.
172
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
173
+ write(REL, 'export default () => <main>noted</main>;\n');
174
+ writeFileSync(path.join(repo, 'UNRELATED.md'), 'not part of the design\n');
175
+ auto.note(REL, ALICE);
176
+ await auto.flush();
177
+
178
+ const show = await git(['show', '--name-only', '--pretty=format:', 'HEAD'], { cwd: repo });
179
+ expect(show.stdout.trim()).toBe(REL);
180
+ const status = await git(['status', '--porcelain'], { cwd: repo });
181
+ expect(status.stdout).toContain('UNRELATED.md');
182
+ });
183
+
184
+ test('history is APPEND-ONLY — an earlier state is still reachable', async () => {
185
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
186
+ write(REL, 'export default () => <main>first</main>;\n');
187
+ auto.note(REL, ALICE);
188
+ await auto.flush();
189
+ const firstSha = (await log('%H'))[0];
190
+
191
+ write(REL, 'export default () => <main>second</main>;\n');
192
+ auto.note(REL, BOB);
193
+ await auto.flush();
194
+
195
+ // The old content is still there — the guarantee that makes a cell's
196
+ // autosave safe to trust with someone's only copy.
197
+ const old = await git(['show', `${firstSha}:${REL}`], { cwd: repo });
198
+ expect(old.stdout).toContain('first');
199
+ expect((await log('%s')).length).toBe(3);
200
+ expect(await log('%an')).toEqual(['Bob', 'Alice Novák', 'Seed']);
201
+ });
202
+
203
+ test('two peers editing before quiescence produce one commit, attributed to the last', async () => {
204
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
205
+ write(REL, 'export default () => <main>alice</main>;\n');
206
+ auto.note(REL, ALICE);
207
+ write(path.join('.design', 'ui', 'Second.tsx'), '');
208
+ writeFileSync(path.join(repo, '.design/ui/Second.tsx'), 'export default () => null;\n');
209
+ auto.note('.design/ui/Second.tsx', BOB);
210
+ await auto.flush();
211
+
212
+ expect((await log('%an'))[0]).toBe('Bob');
213
+ expect((await log('%s'))[0]).toBe('design: update 2 canvases');
214
+ });
215
+
216
+ test('a git failure RE-QUEUES the change instead of dropping it', async () => {
217
+ // The bytes are already on disk, so a git error must not remove the change
218
+ // from history permanently — making the commit a precondition of the save
219
+ // would turn a transient error into data loss.
220
+ let failNext = true;
221
+ const flaky: GitRunner = async (args, opts) => {
222
+ if (args.includes('commit') && failNext) {
223
+ failNext = false;
224
+ return { code: 1, stdout: '', stderr: 'simulated git failure' };
225
+ }
226
+ return git(args, opts);
227
+ };
228
+ const auto = createAutoCommit({ repoRoot: repo, run: flaky, debounceMs: 5, log: silent() });
229
+ write(REL, 'export default () => <main>retry me</main>;\n');
230
+ auto.note(REL, ALICE);
231
+
232
+ const first = await auto.flush();
233
+ expect(first?.ok).toBe(false);
234
+ expect(auto.pending()).toEqual([REL]);
235
+
236
+ const second = await auto.flush();
237
+ expect(second?.ok).toBe(true);
238
+ expect((await log('%s')).length).toBe(2);
239
+ });
240
+
241
+ test('flush with nothing pending is a no-op, not an empty commit', async () => {
242
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
243
+ expect(await auto.flush()).toBe(null);
244
+ expect((await log('%s')).length).toBe(1);
245
+ });
246
+
247
+ test('stop() prevents further scheduling', async () => {
248
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
249
+ auto.stop();
250
+ write(REL, 'export default () => <main>after stop</main>;\n');
251
+ auto.note(REL, ALICE);
252
+ expect(auto.pending()).toEqual([]);
253
+ });
254
+ });
255
+
256
+ describe('mirror push — never rewrites someone else’s work', () => {
257
+ test('a non-fast-forward push is REPORTED as rejected, never forced', async () => {
258
+ // The cell has no way to know whether merging a stranger's commits is
259
+ // right, so it stops and surfaces it. DDR-119's hazard, arriving from the
260
+ // other direction.
261
+ const remote = mkdtempSync(path.join(tmpdir(), 'maude-remote-'));
262
+ await git(['init', '--bare', '--initial-branch=main'], { cwd: remote });
263
+ await git(['remote', 'add', 'origin', remote], { cwd: repo });
264
+ await git(['push', 'origin', 'main'], { cwd: repo });
265
+
266
+ // Someone else pushes first, from a separate clone.
267
+ const other = mkdtempSync(path.join(tmpdir(), 'maude-other-'));
268
+ await git(['clone', remote, other], { cwd: path.dirname(other) });
269
+ await git(['config', 'user.name', 'Other'], { cwd: other });
270
+ await git(['config', 'user.email', 'other@example.com'], { cwd: other });
271
+ writeFileSync(path.join(other, 'theirs.txt'), 'their work\n');
272
+ await git(['add', '-A'], { cwd: other });
273
+ await git(['commit', '-m', 'their work'], { cwd: other });
274
+ await git(['push', 'origin', 'main'], { cwd: other });
275
+
276
+ // Now the cell has a diverging commit.
277
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
278
+ write(REL, 'export default () => <main>ours</main>;\n');
279
+ auto.note(REL, ALICE);
280
+ await auto.flush();
281
+
282
+ const res = await pushMirror({ repoRoot: repo, run: git, branch: 'main', log: silent() });
283
+ expect(res.ok).toBe(false);
284
+ expect(res.rejected).toBe(true);
285
+
286
+ // Their commit is still the remote's tip — nothing of theirs was destroyed.
287
+ const remoteLog = await git(['log', '--pretty=format:%s', 'main'], { cwd: remote });
288
+ expect(remoteLog.stdout.split('\n')[0]).toBe('their work');
289
+
290
+ rmSync(remote, { recursive: true, force: true });
291
+ rmSync(other, { recursive: true, force: true });
292
+ });
293
+
294
+ test('a fast-forward push succeeds', async () => {
295
+ const remote = mkdtempSync(path.join(tmpdir(), 'maude-remote-ok-'));
296
+ await git(['init', '--bare', '--initial-branch=main'], { cwd: remote });
297
+ await git(['remote', 'add', 'origin', remote], { cwd: repo });
298
+ await git(['push', 'origin', 'main'], { cwd: repo });
299
+
300
+ const auto = createAutoCommit({ repoRoot: repo, run: git, debounceMs: 5, log: silent() });
301
+ write(REL, 'export default () => <main>ours</main>;\n');
302
+ auto.note(REL, ALICE);
303
+ await auto.flush();
304
+
305
+ const res = await pushMirror({ repoRoot: repo, run: git, branch: 'main', log: silent() });
306
+ expect(res.ok).toBe(true);
307
+ expect(res.rejected).toBe(false);
308
+
309
+ rmSync(remote, { recursive: true, force: true });
310
+ });
311
+
312
+ test('pushMirror never passes a force flag', async () => {
313
+ // Pinned as an argv assertion: the guarantee is the ABSENCE of a flag, and
314
+ // absence is exactly what a future edit could add without any test noticing.
315
+ const seen: string[][] = [];
316
+ await pushMirror({
317
+ repoRoot: repo,
318
+ branch: 'main',
319
+ run: async (args) => {
320
+ seen.push(args);
321
+ return { code: 0, stdout: '', stderr: '' };
322
+ },
323
+ log: silent(),
324
+ });
325
+ const flat = seen.flat();
326
+ expect(flat.some((a) => /^--force/.test(a))).toBe(false);
327
+ expect(flat.some((a) => a.startsWith('+'))).toBe(false);
328
+ expect(flat).toContain('refs/heads/main:refs/heads/main');
329
+ });
330
+ });
331
+
332
+ function silent() {
333
+ return { warn: () => {}, error: () => {}, log: () => {} };
334
+ }