@1agh/maude 2.1.0 → 2.1.1

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 (100) hide show
  1. package/apps/studio/access/request.ts +1 -0
  2. package/apps/studio/actions/agents.ts +27 -0
  3. package/apps/studio/actions/defs/app.ts +28 -1
  4. package/apps/studio/actions/defs/sync.ts +4 -0
  5. package/apps/studio/actions.manifest.json +60 -2
  6. package/apps/studio/actions.parity.json +13 -1
  7. package/apps/studio/bin/_curl-local.mjs +7 -4
  8. package/apps/studio/client/app.jsx +16 -4
  9. package/apps/studio/client/home/HomeAccountsRow.jsx +221 -0
  10. package/apps/studio/client/home/HomeConnection.jsx +111 -0
  11. package/apps/studio/client/home/home-accounts-model.js +110 -1
  12. package/apps/studio/client/home/home-api.js +6 -2
  13. package/apps/studio/client/home/home-app.jsx +74 -12
  14. package/apps/studio/client/home/home-model.js +40 -1
  15. package/apps/studio/client/home/home-where-model.js +105 -0
  16. package/apps/studio/client/home/home.css +233 -1
  17. package/apps/studio/client/hooks/use-palette-and-panels.jsx +3 -1
  18. package/apps/studio/client/hooks/use-tabs.jsx +11 -4
  19. package/apps/studio/client/panels/TeamProjects.jsx +137 -134
  20. package/apps/studio/client/share-link.js +12 -0
  21. package/apps/studio/client/styles/_index.css +4 -0
  22. package/apps/studio/client/v2/diagnostics/diagnostics-host.jsx +1 -0
  23. package/apps/studio/client/v2/diagnostics/diagnostics-model.js +32 -2
  24. package/apps/studio/client/v2/diagnostics/diagnostics-sheet.jsx +35 -8
  25. package/apps/studio/client/v2/diagnostics/diagnostics.css +34 -0
  26. package/apps/studio/client/v2/diagnostics/sync-details/sync-details-model.js +94 -3
  27. package/apps/studio/client/v2/diagnostics/sync-details/sync-details.jsx +187 -4
  28. package/apps/studio/client/v2/link-server/LinkServerDialog.jsx +492 -0
  29. package/apps/studio/client/v2/link-server/LinkServerHost.jsx +42 -0
  30. package/apps/studio/client/v2/link-server/link-server-api.js +142 -0
  31. package/apps/studio/client/v2/link-server/link-server-model.js +438 -0
  32. package/apps/studio/client/v2/link-server/link-server.css +109 -0
  33. package/apps/studio/client/v2/onboarding/AdvancedSheets.jsx +31 -86
  34. package/apps/studio/client/v2/onboarding/onboarding-model.js +1 -18
  35. package/apps/studio/client/v2/search/search-keywords.js +3 -2
  36. package/apps/studio/client/v2/settings/account.jsx +4 -2
  37. package/apps/studio/client/v2/settings/advanced-section.jsx +245 -148
  38. package/apps/studio/client/v2/settings/connection-row.jsx +3 -59
  39. package/apps/studio/client/v2/settings/connections-section.jsx +118 -425
  40. package/apps/studio/client/v2/settings/general-section.jsx +138 -43
  41. package/apps/studio/client/v2/settings/project-sync-settings.jsx +4 -3
  42. package/apps/studio/client/v2/settings/reset-section.jsx +14 -3
  43. package/apps/studio/client/v2/settings/settings-card.jsx +142 -0
  44. package/apps/studio/client/v2/settings/settings-cards.js +220 -0
  45. package/apps/studio/client/v2/settings/settings-handlers.js +7 -6
  46. package/apps/studio/client/v2/settings/settings-model.js +91 -31
  47. package/apps/studio/client/v2/settings/settings-sheet.jsx +25 -6
  48. package/apps/studio/client/v2/settings/settings.css +374 -64
  49. package/apps/studio/client/v2/settings/this-project-card.jsx +730 -0
  50. package/apps/studio/client/v2/settings/this-project-model.js +172 -0
  51. package/apps/studio/client/v2/settings/use-connections.js +3 -2
  52. package/apps/studio/client/v2/settings/use-open-card.js +37 -0
  53. package/apps/studio/client/v2/shell/connection-state.js +197 -0
  54. package/apps/studio/client/v2/shell/menu-runner.js +7 -2
  55. package/apps/studio/client/v2/shell/project-account-bus.js +36 -0
  56. package/apps/studio/client/v2/shell/project-account-card.jsx +357 -148
  57. package/apps/studio/client/v2/shell/project-account-model.js +272 -149
  58. package/apps/studio/client/v2/shell/project-account-toast.js +66 -0
  59. package/apps/studio/client/v2/shell/project-account.css +237 -0
  60. package/apps/studio/client/v2/shell/share-cluster-host.jsx +166 -83
  61. package/apps/studio/client/v2/shell/shell-parity.js +3 -2
  62. package/apps/studio/client/v2/shell/shell-parity.json +40 -26
  63. package/apps/studio/client/v2/shell/use-account.js +2 -0
  64. package/apps/studio/client/v2/signin/use-signin.js +1 -1
  65. package/apps/studio/cloud/endpoints.ts +29 -4
  66. package/apps/studio/dist/client.bundle.js +834 -834
  67. package/apps/studio/dist/styles.css +1 -1
  68. package/apps/studio/home/accounts.ts +30 -11
  69. package/apps/studio/home/cloud.ts +6 -1
  70. package/apps/studio/home/hub-health.ts +76 -0
  71. package/apps/studio/home/routes.ts +9 -3
  72. package/apps/studio/http.ts +8 -0
  73. package/apps/studio/migrate/hub.ts +8 -1
  74. package/apps/studio/routes/hub-link-folder.ts +334 -0
  75. package/apps/studio/routes/hub-signin.ts +78 -1
  76. package/apps/studio/routes/index.ts +4 -0
  77. package/apps/studio/routes/sync.ts +22 -4
  78. package/apps/studio/shell/api-key.ts +11 -0
  79. package/apps/studio/sync/accepted-cold-start.ts +144 -8
  80. package/apps/studio/sync/action-stage.ts +18 -1
  81. package/apps/studio/sync/ctl-heal.ts +58 -0
  82. package/apps/studio/sync/file-ledger.ts +38 -4
  83. package/apps/studio/sync/file-plane.ts +226 -19
  84. package/apps/studio/sync/held-deletes.ts +86 -5
  85. package/apps/studio/sync/hub-link.ts +8 -0
  86. package/apps/studio/sync/index.ts +68 -4
  87. package/apps/studio/sync/link-consent.ts +22 -75
  88. package/apps/studio/sync/link-survey.ts +252 -0
  89. package/apps/studio/sync/local-kernel.ts +16 -1
  90. package/apps/studio/sync/seed-progress.ts +12 -0
  91. package/apps/studio/sync/source-recovery.ts +18 -2
  92. package/apps/studio/sync/status.ts +11 -1
  93. package/apps/studio/sync/writer-registry.ts +5 -0
  94. package/apps/studio/whats-new.json +18 -0
  95. package/cli/lib/bash-guard.mjs +19 -0
  96. package/cli/lib/design-help.gen.mjs +1 -1
  97. package/package.json +9 -8
  98. package/apps/studio/client/v2/onboarding/HubSheet.jsx +0 -212
  99. package/apps/studio/client/v2/shell/account-card-model.js +0 -114
  100. package/apps/studio/client/v2/shell/account-card.jsx +0 -189
@@ -4,6 +4,13 @@
4
4
  // POST /_api/hub-signin/poll { id } → { ok, pending } | { ok, url, user } | { ok:false, error }
5
5
  // POST /_api/hub-signin/cancel { id } → { ok }
6
6
  // GET /_api/hub-signin/return ?state&code | ?state&error (the browser's hop back from the hub)
7
+ // POST /_api/hub-signin/check { url } → { ok, reachable, url, version } | { ok:false, reason, error }
8
+ //
9
+ // 2.1.1 T5 — "Link your server" checks the address as it is typed: `check` is Home's `/_home/hub/test`
10
+ // (home/hub.ts `createHomeHub().test`) for a project tab — ONE tokenless GET <server>/health, no
11
+ // redirect followed, no credential, only `{ ok, version }` reflected back. `start` takes an invite
12
+ // (the key, or the server's own `/join/<key>` link, which must name the same server — home/hub.ts
13
+ // `hubInviteToken`), so the invite opens the server's own invite page here as it does on Home.
7
14
  //
8
15
  // MAIN ORIGIN ONLY: these mint and store a team-server credential, which the untrusted canvas
9
16
  // origin (DDR-054) must never reach. `guardTableRoute` applies the CSRF + DNS-rebind gates to all
@@ -16,6 +23,9 @@
16
23
  // A cell never serves these (apps/hub/src/studio-manifest.mjs: REFUSED) — a cell holds no team
17
24
  // server credential of its own.
18
25
 
26
+ import { isHomePort, isLoopbackAddress, isTokenBridgePort } from '../bin/_curl-local.mjs';
27
+ import { classifyAddress } from '../bin/_fetch-asset.mjs';
28
+ import { createHomeHub, hubAddress, hubInviteToken } from '../home/hub.ts';
19
29
  import {
20
30
  createHubBrowserSignIn,
21
31
  type HubBrowserSignIn,
@@ -29,6 +39,39 @@ export interface HubSigninRouteDeps {
29
39
  /** The team server this project syncs with — a renewed sign-in for it cycles sync. */
30
40
  linkedHubUrl?: () => string | null | undefined;
31
41
  restartSync?: () => Promise<unknown> | undefined;
42
+ /** The address check's network seam (tests); default `fetch`. */
43
+ fetchImpl?: typeof fetch;
44
+ /** 2.1.1 T8 — a loopback port the check never reaches (default: the app's Home server and token
45
+ * bridge, from the app-owned run files — the same ports the loopback helper refuses). */
46
+ refusedLocalPort?: (port: number) => boolean;
47
+ }
48
+
49
+ /**
50
+ * 2.1.1 T8 — where the address check never sends its GET: an IP literal in a private, link-local or
51
+ * reserved range, and, on loopback, this Mac's own app services (Home, the token bridge). A loopback
52
+ * team server for local development stays allowed. Host NAMES are not resolved here (no DNS lookup on
53
+ * a person's keystroke); the check reflects only `{ ok, version }`. Returns a refusal reason or null.
54
+ */
55
+ export function checkTargetRefusal(
56
+ url: string,
57
+ refusedLocalPort: (port: number) => boolean = (p) => isHomePort(p) || isTokenBridgePort(p)
58
+ ): string | null {
59
+ let u: URL;
60
+ try {
61
+ u = new URL(url);
62
+ } catch {
63
+ return 'bad-address';
64
+ }
65
+ const host = u.hostname.replace(/^\[|\]$/g, '');
66
+ const loopback = host === 'localhost' || isLoopbackAddress(host);
67
+ if (loopback) {
68
+ const port = Number(u.port || (u.protocol === 'https:' ? 443 : 80));
69
+ return refusedLocalPort(port) ? 'local-service' : null;
70
+ }
71
+ const reason = classifyAddress(host);
72
+ // a public IP literal and every host name pass; any classified range is refused
73
+ if (reason === null || reason === 'not an ip address') return null;
74
+ return 'private-address';
32
75
  }
33
76
 
34
77
  async function body(req: Request): Promise<Record<string, unknown>> {
@@ -64,6 +107,8 @@ export function createHubSigninRoutes(deps: HubSigninRouteDeps = {}): RouteSpec[
64
107
  if (sameServer(deps.linkedHubUrl?.(), url)) await deps.restartSync?.();
65
108
  },
66
109
  });
110
+ // the check only: Home's tokenless probe (no redirect, no ambient credentials)
111
+ const checker = createHomeHub(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {});
67
112
  return [
68
113
  {
69
114
  method: 'POST',
@@ -72,7 +117,22 @@ export function createHubSigninRoutes(deps: HubSigninRouteDeps = {}): RouteSpec[
72
117
  readOnly: 'allowed',
73
118
  async handle(req) {
74
119
  const b = await body(req);
75
- const r = await signIn.start(b.url, new URL(req.url).origin);
120
+ // 2.1.1 N5 — the same target refusal as `/check`: start probes the server too
121
+ const target = hubAddress(b.url);
122
+ if (target.ok && checkTargetRefusal(target.url, deps.refusedLocalPort))
123
+ return json(
124
+ { ok: false, reason: 'bad-address', error: "That isn't a team server address." },
125
+ 400
126
+ );
127
+ let invite: string | undefined;
128
+ if (b.invite !== undefined && b.invite !== null && b.invite !== '') {
129
+ const at = hubAddress(b.url);
130
+ if (!at.ok) return json({ ok: false, error: at.error }, 400);
131
+ const t = hubInviteToken(b.invite, at.url);
132
+ if (!t.ok) return json({ ok: false, error: t.error }, 400);
133
+ invite = t.value;
134
+ }
135
+ const r = await signIn.start(b.url, new URL(req.url).origin, invite ? { invite } : {});
76
136
  return r.ok
77
137
  ? json(r)
78
138
  : json(
@@ -100,6 +160,23 @@ export function createHubSigninRoutes(deps: HubSigninRouteDeps = {}): RouteSpec[
100
160
  return json({ ok: true });
101
161
  },
102
162
  },
163
+ {
164
+ method: 'POST',
165
+ path: '/_api/hub-signin/check',
166
+ origin: 'main',
167
+ readOnly: 'allowed',
168
+ async handle(req) {
169
+ const b = await body(req);
170
+ const a = hubAddress(b.url);
171
+ if (a.ok && checkTargetRefusal(a.url, deps.refusedLocalPort))
172
+ return json(
173
+ { ok: false, reason: 'bad-address', error: "That isn't a team server address." },
174
+ 400
175
+ );
176
+ const r = await checker.test(b);
177
+ return json(r.body, r.status);
178
+ },
179
+ },
103
180
  {
104
181
  method: 'GET',
105
182
  // A literal (the route scrapers read `path:` strings) — HUB_SIGNIN_RETURN_PATH, asserted by the test.
@@ -45,6 +45,7 @@ import { createGenerateRoutes, type GenerateRouteDeps } from './generate.ts';
45
45
  import { createHandoffRoutes, type HandoffRouteDeps } from './handoff.ts';
46
46
  import { createHelpGuidesRoutes, type HelpGuidesDeps } from './help-guides.ts';
47
47
  import { createHistoryRoutes, type HistoryRouteDeps } from './history.ts';
48
+ import { createHubLinkFolderRoutes, type HubLinkFolderDeps } from './hub-link-folder.ts';
48
49
  import { createHubSigninRoutes, type HubSigninRouteDeps } from './hub-signin.ts';
49
50
  import { createImportLinkRoutes, type ImportLinkRouteDeps } from './import-link.ts';
50
51
  import { createKindRoutes } from './kinds.ts';
@@ -143,6 +144,8 @@ export interface RouteDeps {
143
144
  connections?: ConnectionsRouteDeps;
144
145
  /** Issue #204 — `/_api/hub-signin/*` (main origin): sign in to a team server on its own page */
145
146
  hubSignin?: HubSigninRouteDeps;
147
+ /** 2.1.1 — `POST /_api/hub/link-folder` (main origin, window only): THIS folder joins the person's team server */
148
+ hubLinkFolder?: HubLinkFolderDeps;
146
149
  /** S8.19 — `GET /_api/asset-state` (main origin): disk + upload queue + hub presence */
147
150
  assetState?: AssetStateRouteDeps;
148
151
  /** S8.13 — `POST /_api/assets/trash` (main origin, Can edit on the project): assets + sidecars to `_trash/`;
@@ -274,6 +277,7 @@ export function allSpecs(deps: RouteDeps): RouteSpec[] {
274
277
  ...(deps.helpGuides ? createHelpGuidesRoutes(deps.helpGuides) : []),
275
278
  ...(deps.connections ? createConnectionsRoutes(deps.connections) : []),
276
279
  ...createHubSigninRoutes(deps.hubSignin ?? {}),
280
+ ...(deps.hubLinkFolder ? createHubLinkFolderRoutes(deps.hubLinkFolder) : []),
277
281
  ...createAssetStateRoutes(deps.assetState ?? { service: () => null }),
278
282
  ...(deps.assetTrash ? createAssetTrashRoutes(deps.assetTrash) : []),
279
283
  // P8 round 7 — POST /_api/assets/rename (routes/asset-rename.ts): the same deps and verdict as Move to trash
@@ -7,8 +7,8 @@
7
7
  // uses that will not reach the workspace, each with its reason; a disk read)
8
8
  // POST /_api/sync/code-consent/set { allow } → { ok, consent } · 403 window-only / read-only ·
9
9
  // 409 not-linked / not-signed-in / cell
10
- // POST /_api/sync/held-deletes { answer: delete|keep, folder? } → { ok, how, count } · 403
11
- // window-only / read-only / not-owner · 409 not-linked / nothing-held / busy
10
+ // POST /_api/sync/held-deletes { answer: delete|keep|remove-here|keep-here, folder?, digest } → { ok, how, count } · 403
11
+ // window-only / read-only / not-owner · 409 not-linked / nothing-held / busy / changed
12
12
  // POST /_api/sync/adopt-held { path, sha256 } → { ok } · 403 window-only / read-only / not-owner ·
13
13
  // 409 not-linked / not-held / changed / update / unreachable (#167 T5.3,
14
14
  // the hub decides; it adopts only the version `sha256` names)
@@ -340,7 +340,10 @@ export function createSyncRoutes(deps: SyncRouteDeps): RouteSpec[] {
340
340
  const answer = (body as { answer?: unknown } | null)?.answer;
341
341
  const folder = (body as { folder?: unknown } | null)?.folder ?? null;
342
342
  if (
343
- (answer !== 'delete' && answer !== 'keep') ||
343
+ (answer !== 'delete' &&
344
+ answer !== 'keep' &&
345
+ answer !== 'remove-here' &&
346
+ answer !== 'keep-here') ||
344
347
  (folder !== null && (typeof folder !== 'string' || folder.length > 1024))
345
348
  ) {
346
349
  return json(400, { ok: false, reason: 'bad-request', detail: 'Say delete or keep.' });
@@ -353,7 +356,22 @@ export function createSyncRoutes(deps: SyncRouteDeps): RouteSpec[] {
353
356
  detail: 'This project isn’t syncing with a hub right now.',
354
357
  });
355
358
  }
356
- const r = await control.answer(answer, folder as string | null);
359
+ // 2.1.1 T13 — the same card family for a batch the PROJECT deleted: `remove-here` files this
360
+ // Mac's copies into the trash in one pass, `keep-here` leaves them and never sends them back.
361
+ // 2.1.1 T8 / N4 — the set the person was shown, for every answer; a missing or stale one
362
+ // answers `changed` and nothing is applied
363
+ const digest =
364
+ typeof (body as { digest?: unknown } | null)?.digest === 'string'
365
+ ? String((body as { digest: string }).digest).slice(0, 128)
366
+ : '';
367
+ const r =
368
+ answer === 'remove-here' || answer === 'keep-here'
369
+ ? await control.answerIncoming(
370
+ answer === 'remove-here' ? 'remove' : 'keep',
371
+ folder as string | null,
372
+ digest
373
+ )
374
+ : await control.answer(answer, folder as string | null, digest);
357
375
  if (r.ok) return json(200, r);
358
376
  return json(r.reason === 'not-owner' ? 403 : 409, r);
359
377
  },
@@ -281,6 +281,10 @@ function isExempt(method: string, pathname: string): boolean {
281
281
  pathname === '/index.html' ||
282
282
  pathname === '/_canvas-shell' ||
283
283
  pathname === '/_canvas-shell.html' ||
284
+ // The team server's page sends the person's own browser back here; that browser never held
285
+ // the app's session. The route acts only on a `state` this process minted, once, and the code
286
+ // is worthless without the PKCE verifier that never left it (routes/hub-signin.ts).
287
+ pathname === '/_api/hub-signin/return' ||
284
288
  pathname.startsWith('/_client/') ||
285
289
  pathname.startsWith('/_canvas-runtime/')
286
290
  );
@@ -295,6 +299,13 @@ const PERSON_ONLY: readonly (readonly [string, RegExp])[] = [
295
299
  ['POST', /^\/_api\/git\/push$/],
296
300
  ['POST', /^\/_api\/share\/invites(\/[^/]+\/resend)?$/],
297
301
  ['POST', /^\/_api\/cloud\/(attach|attach\/code|move|signin\/start)$/],
302
+ // 2.1.1 — THIS folder joins the person's team server (routes/hub-link-folder.ts)
303
+ ['POST', /^\/_api\/hub\/link-folder$/],
304
+ // 2.1.1 T8 — a team-server sign-in, and saving a team-server credential, are the person's acts like
305
+ // the Maude Cloud sign-in above: the return hop needs no key, so starting it must need a person.
306
+ // The address check is the dialog's own step, so a key holder never uses it as a network probe.
307
+ ['POST', /^\/_api\/hub\/link$/],
308
+ ['POST', /^\/_api\/hub-signin\/(start|check)$/],
298
309
  ];
299
310
 
300
311
  export function isPersonOnlyRoute(method: string, pathname: string): boolean {
@@ -40,6 +40,9 @@
40
40
  import { existsSync, readFileSync } from 'node:fs';
41
41
  import type * as Y from 'yjs';
42
42
 
43
+ import { annotationsLaneValue } from '../annotations/board-text.ts';
44
+ import { parseBoard, serializeBoard } from '../annotations/schema.ts';
45
+ import type { AnnotationElement } from '../annotations/types.ts';
43
46
  import {
44
47
  cssFromDoc,
45
48
  htmlFromDoc,
@@ -51,6 +54,7 @@ import {
51
54
  import { commentKey } from './comment-identity.ts';
52
55
  import type { CommentLedger } from './comment-ledger.ts';
53
56
  import { hashBytes } from './echo-guard.ts';
57
+ import { cleanFolderName } from './held-deletes.ts';
54
58
  import type { SyncJournal } from './journal.ts';
55
59
  import type { DocProjection, ProjectionPaths, ProposalLane } from './projection.ts';
56
60
  import { readRecoveryBody, readRecoveryCandidate, saveRecoveryBody } from './source-recovery.ts';
@@ -179,6 +183,15 @@ export interface AcceptedColdStartInput {
179
183
  * cell wake), not an edit: it is materialized, never held.
180
184
  */
181
185
  wasAccepted?: (content: string) => Promise<boolean | null>;
186
+ /**
187
+ * 2.1.1 T11 — this disk is a hub's own checkout (the paired studio of a cell or a self-hosted
188
+ * workspace hub, `cellPairing`): the project's cache, not a person's work (DDR-243; the hub is
189
+ * the sole committer, DDR-209). A source lane that would be HELD is materialized instead — the
190
+ * project's version wins and the checkout's bytes go to the recovery slot. A held conflict there
191
+ * is a dead end: the hub's proxy refuses the conflict route in a cell (v2-S9.24b), so Compare
192
+ * and Keep mine answer 404, and the lane stays blocked behind it.
193
+ */
194
+ checkoutIsCache?: boolean;
182
195
  createDoc: (lanes: Partial<Record<ProposalLane, string>>) => Promise<{
183
196
  status: 'accepted' | 'rejected';
184
197
  code?: string;
@@ -216,7 +229,12 @@ export function localCreateLanes(
216
229
  export type AcceptedColdStartResult =
217
230
  | { kind: 'created' }
218
231
  | { kind: 'create-refused'; code?: string }
219
- | { kind: 'reconciled'; verdicts: LaneVerdict[] };
232
+ | {
233
+ kind: 'reconciled';
234
+ verdicts: LaneVerdict[];
235
+ /** S1 — lanes whose local value the project's replaced; each is in its recovery slot. */
236
+ setAside?: ProposalLane[];
237
+ };
220
238
 
221
239
  export async function acceptedColdStart(
222
240
  i: AcceptedColdStartInput
@@ -250,6 +268,21 @@ export async function acceptedColdStart(
250
268
  }
251
269
 
252
270
  const verdicts: LaneVerdict[] = [];
271
+ /** S1 — lanes whose local value the project's replaced, kept in their recovery slot. */
272
+ const setAside: ProposalLane[] = [];
273
+ const saveQuietly = (file: string, text: string): boolean => {
274
+ if (!i.historyDir) return false;
275
+ try {
276
+ saveRecoveryBody(i.historyDir, file, 'local', text);
277
+ return true;
278
+ } catch {
279
+ return false; /* recovery is best-effort for these lanes */
280
+ }
281
+ };
282
+ const keepAside = (lane: ProposalLane, file: string, text: string): void => {
283
+ saveQuietly(file, text);
284
+ if (!setAside.includes(lane)) setAside.push(lane);
285
+ };
253
286
 
254
287
  // ---- html — the canvas source
255
288
  const acceptedHtml = htmlFromDoc(i.doc);
@@ -327,7 +360,13 @@ export async function acceptedColdStart(
327
360
  verdicts.push({ lane: 'meta', decision: 'propose', base: '', local });
328
361
  } else {
329
362
  // No base is recorded for layout: the project's arrangement wins and the
330
- // projection merges it into the local file's private keys.
363
+ // projection merges it into the local file's private keys. S1 — unless the
364
+ // project once had exactly this layout (an older accepted state), it is this
365
+ // Mac's own (a first link to a server that already holds the canvas): kept
366
+ // in its own recovery slot and reported as set aside, never dropped.
367
+ if (metaText !== null && (await i.wasAccepted?.(local)) !== true) {
368
+ keepAside('meta', i.paths.meta, metaText);
369
+ }
331
370
  verdicts.push({ lane: 'meta', decision: 'materialize', local });
332
371
  }
333
372
  }
@@ -349,16 +388,48 @@ export async function acceptedColdStart(
349
388
  continue;
350
389
  }
351
390
  }
352
- if (i.historyDir && text) {
353
- try {
354
- saveRecoveryBody(i.historyDir, p, 'local', text);
355
- } catch {
356
- /* recovery is best-effort for these lanes */
391
+ // S1 (2.1.1) — "a difference on disk is an older accepted state" (the header)
392
+ // holds only for a value the project once accepted. One it never did is this
393
+ // Mac's own work: a first link to a server that already holds this canvas, or a
394
+ // raw edit made while the studio was down. Comments and board elements carry
395
+ // stable ids, so it joins the project as the accepted value plus what only this
396
+ // disk has; an id both sides changed keeps the project's, and this Mac's is set
397
+ // aside. A hub's checkout is the project's cache and owes it nothing (T11).
398
+ const onceAccepted = i.checkoutIsCache ? null : ((await i.wasAccepted?.(local)) ?? null);
399
+ if (onceAccepted === false) {
400
+ const joined = unionById(lane, local, accepted);
401
+ if (joined !== null) {
402
+ if (!joined.complete && text) keepAside(lane, p, text);
403
+ verdicts.push({ lane, decision: 'propose', base: accepted, local: joined.value });
404
+ continue;
357
405
  }
358
406
  }
407
+ if (text) {
408
+ // An older accepted state (or a hub checkout) is kept quietly, as before; anything
409
+ // else of this Mac's that the project's value replaces is reported.
410
+ if (onceAccepted === true || i.checkoutIsCache) saveQuietly(p, text);
411
+ else keepAside(lane, p, text);
412
+ }
359
413
  verdicts.push({ lane, decision: 'materialize', local: text ?? undefined });
360
414
  }
361
415
 
416
+ // ---- a hub checkout never holds (see `checkoutIsCache`)
417
+ if (i.checkoutIsCache) {
418
+ for (const v of verdicts) {
419
+ if (v.decision !== 'hold') continue;
420
+ const p = v.lane === 'html' ? i.paths.html : v.lane === 'css' ? i.paths.css : undefined;
421
+ if (i.historyDir && p && v.local !== undefined) {
422
+ try {
423
+ saveRecoveryBody(i.historyDir, p, 'local', v.local);
424
+ } catch {
425
+ /* best-effort, as for the other lanes the project's value wins on */
426
+ }
427
+ }
428
+ v.decision = 'materialize';
429
+ v.base = undefined;
430
+ }
431
+ }
432
+
362
433
  // ---- act
363
434
  for (const v of verdicts) {
364
435
  if (v.decision === 'propose' && v.local !== undefined) {
@@ -377,5 +448,70 @@ export async function acceptedColdStart(
377
448
  `[sync/${i.slug}] cold start: ${moved.map((v) => `${v.lane}=${v.decision}`).join(', ')}`
378
449
  );
379
450
  }
380
- return { kind: 'reconciled', verdicts };
451
+ if (setAside.length) {
452
+ log.warn(
453
+ `[sync/${i.slug}] cold start: the project's ${setAside.join(', ')} replaced this Mac's — kept in the recovery folder.`
454
+ );
455
+ }
456
+ return { kind: 'reconciled', verdicts, ...(setAside.length ? { setAside } : {}) };
457
+ }
458
+
459
+ const SET_ASIDE_WORDS: Partial<Record<ProposalLane, string>> = {
460
+ meta: 'layout',
461
+ annotations: 'sticky notes',
462
+ comments: 'comments',
463
+ };
464
+
465
+ /** S1 — the Sync notice for lanes set aside at cold start (CONTRACT §3–§4 voice). */
466
+ export function setAsideNotice(rel: string, slug: string, lanes: readonly ProposalLane[]): string {
467
+ // 2.1.1 N6 — the name can come from the server: no bidi/format/control characters in the sentence
468
+ const name =
469
+ cleanFolderName(
470
+ rel
471
+ .split('/')
472
+ .pop()
473
+ ?.replace(/\.tsx$/i, '') ?? ''
474
+ ) || cleanFolderName(rel);
475
+ slug = cleanFolderName(slug);
476
+ const words = lanes.map((l) => SET_ASIDE_WORDS[l] ?? l);
477
+ const list =
478
+ words.length > 1 ? `${words.slice(0, -1).join(', ')} and ${words[words.length - 1]}` : words[0];
479
+ return `${name}: the project’s ${list} replaced this Mac’s. This Mac’s copy is kept in _history/${slug}/sync-recovery/.`;
480
+ }
481
+
482
+ /**
483
+ * S1 — an id-keyed lane (comments, board elements) joined the way a first link
484
+ * needs: the accepted value, plus the entries only `local` has. `complete` is
485
+ * false when an id both sides hold differs (the project's entry is kept). Null
486
+ * when `local` adds nothing.
487
+ */
488
+ export function unionById(
489
+ lane: 'comments' | 'annotations',
490
+ local: string,
491
+ accepted: string
492
+ ): { value: string; complete: boolean } | null {
493
+ if (lane === 'comments') {
494
+ const there = parseList(accepted);
495
+ const byKey = new Map(there.map((c) => [commentKey(c), JSON.stringify(c)]));
496
+ let complete = true;
497
+ const extra: unknown[] = [];
498
+ for (const c of parseList(local)) {
499
+ const theirs = byKey.get(commentKey(c));
500
+ if (theirs === undefined) extra.push(c);
501
+ else if (theirs !== JSON.stringify(c)) complete = false;
502
+ }
503
+ return extra.length ? { value: JSON.stringify([...there, ...extra]), complete } : null;
504
+ }
505
+ const there = accepted ? parseBoard(accepted).elements : [];
506
+ const byId = new Map(there.map((e) => [e.id, JSON.stringify(e)]));
507
+ let complete = true;
508
+ const extra: AnnotationElement[] = [];
509
+ for (const e of parseBoard(local).elements) {
510
+ const theirs = byId.get(e.id);
511
+ if (theirs === undefined) extra.push(e);
512
+ else if (theirs !== JSON.stringify(e)) complete = false;
513
+ }
514
+ if (!extra.length) return null;
515
+ const value = annotationsLaneValue(serializeBoard([...there, ...extra]));
516
+ return value ? { value, complete } : null;
381
517
  }
@@ -1047,6 +1047,15 @@ export function createActionStage(opts: ActionStageOptions) {
1047
1047
  return ownerOf(slug, content, explicit) !== null || parks(slug);
1048
1048
  }
1049
1049
 
1050
+ /** Another run (open or held) whose staged lanes CREATE canvas `slug`, if any. */
1051
+ function creatorOf(slug: string, r: RunStage): RunStage | undefined {
1052
+ for (const other of runs.values()) {
1053
+ if (other === r) continue;
1054
+ for (const l of other.lanes.values()) if (l.slug === slug && l.create) return other;
1055
+ }
1056
+ return undefined;
1057
+ }
1058
+
1050
1059
  /** The accepted content of a lane: any staged run's base, else the write's own base. */
1051
1060
  function acceptedOf(k: string, fallback: string): string {
1052
1061
  for (const r of runs.values()) {
@@ -1131,8 +1140,16 @@ export function createActionStage(opts: ActionStageOptions) {
1131
1140
  slug: string,
1132
1141
  doc: string,
1133
1142
  p: LaneProposal,
1134
- joined: readonly Parked[] = []
1143
+ joined: readonly Parked[] = [],
1144
+ hopped = false
1135
1145
  ): Promise<ProposalOutcome> {
1146
+ // A canvas another run CREATED and has not published has no accepted content: this run's
1147
+ // change cannot be told apart from the creator's (a three-way merge against nothing always
1148
+ // conflicts), and it cannot be published without that create. The write joins the creator —
1149
+ // ONE hop (2.1.1 T8): two runs that both hold a create lane for the canvas (a stage restored
1150
+ // from an older build) would otherwise hand the write back and forth without end.
1151
+ const creator = hopped || r.lanes.has(`${slug}|${p.lane}`) ? undefined : creatorOf(slug, r);
1152
+ if (creator) return stageWrite(creator, slug, doc, p, joined, true);
1136
1153
  const k = `${slug}|${p.lane}`;
1137
1154
  const txs = [...joined.flatMap((e) => e.txs), p.transactionId];
1138
1155
  return new Promise<ProposalOutcome>((settle) => {
@@ -26,6 +26,12 @@ import { fetchJournal } from './journal-client.ts';
26
26
  /** Coalesce a burst of pokes into one journal read. */
27
27
  const READ_DEBOUNCE_MS = 150;
28
28
 
29
+ /** Paths whose last announced bytes are remembered (bounded, oldest out first). */
30
+ const ANNOUNCED_MEMO_CAP = 4096;
31
+
32
+ /** The "skipped a repeat" line is printed at most this often. */
33
+ const REPEAT_LOG_MS = 60_000;
34
+
29
35
  export interface CtlHealerOptions {
30
36
  hubUrl: string;
31
37
  token: string;
@@ -36,6 +42,8 @@ export interface CtlHealerOptions {
36
42
  debounceMs?: number;
37
43
  setTimeoutImpl?: typeof setTimeout;
38
44
  clearTimeoutImpl?: typeof clearTimeout;
45
+ /** Clock for the repeat-log throttle (tests). */
46
+ now?: () => number;
39
47
  }
40
48
 
41
49
  export interface CtlHealer {
@@ -60,6 +68,8 @@ export interface CtlHealer {
60
68
  healed(): number;
61
69
  /** Pokes whose head was at or below the cursor: pure noise, and expected. */
62
70
  ignored(): number;
71
+ /** Rows skipped because their path was already announced at those bytes. */
72
+ repeats(): number;
63
73
  }
64
74
 
65
75
  /**
@@ -85,6 +95,21 @@ export function createCtlHealer(opts: CtlHealerOptions): CtlHealer {
85
95
  let stopped = false;
86
96
  let healed = 0;
87
97
  let ignored = 0;
98
+ /**
99
+ * The bytes each path was last announced at — ONE ANNOUNCEMENT PER STATE.
100
+ *
101
+ * A heal tells the canvas layer "this file is different now". A row naming
102
+ * the bytes we already announced for that path says nothing new, and
103
+ * re-announcing it re-runs every `fs:any` consumer (index rebuilds, HMR,
104
+ * canvas rescans) for a file that did not change. A path stuck in a loop
105
+ * upstream then spins every open canvas with it; this caps the cost at one
106
+ * announcement per distinct version. A tombstone or a row with no hash
107
+ * forgets the path, so the next real arrival is always announced.
108
+ */
109
+ const announcedAt = new Map<string, string>();
110
+ let repeats = 0;
111
+ let repeatLoggedAt = Number.NEGATIVE_INFINITY;
112
+ const now = opts.now ?? Date.now;
88
113
  /**
89
114
  * Is there anything to read?
90
115
  *
@@ -134,19 +159,51 @@ export function createCtlHealer(opts: CtlHealerOptions): CtlHealer {
134
159
  // paths, capped — the receiving half of the "N poke(s) folded" line the
135
160
  // sender already prints.
136
161
  const announced: string[] = [];
162
+ // The LAST row per path is the path's state after this page; earlier rows
163
+ // for the same path are history the disk no longer shows.
164
+ const latest = new Map<string, (typeof page.entries)[number]>();
137
165
  for (const entry of page.entries) {
166
+ latest.delete(entry.path);
167
+ latest.set(entry.path, entry);
168
+ // A deletion inside the page still happened: what follows it is news.
169
+ if (entry.deleted || entry.sha256 === null) announcedAt.delete(entry.path);
170
+ }
171
+ let repeated = 0;
172
+ for (const entry of latest.values()) {
138
173
  // A tombstone is not a heal — Increment 6 owns deletion, and emitting
139
174
  // `fs:any` for a vanished path would make the canvas layer look for a
140
175
  // file that is deliberately gone.
141
176
  if (entry.deleted) continue;
177
+ if (entry.sha256 !== null && announcedAt.get(entry.path) === entry.sha256) {
178
+ repeated += 1;
179
+ continue;
180
+ }
142
181
  try {
143
182
  opts.emit(entry.path);
144
183
  healed += 1;
145
184
  announced.push(entry.path);
185
+ announcedAt.delete(entry.path);
186
+ if (entry.sha256 !== null) {
187
+ announcedAt.set(entry.path, entry.sha256);
188
+ if (announcedAt.size > ANNOUNCED_MEMO_CAP) {
189
+ const oldest = announcedAt.keys().next().value;
190
+ if (oldest !== undefined) announcedAt.delete(oldest);
191
+ }
192
+ }
146
193
  } catch (err) {
147
194
  log.warn?.(`[sync/ctl] heal emit failed for ${entry.path}: ${(err as Error).message}`);
148
195
  }
149
196
  }
197
+ if (repeated > 0) {
198
+ repeats += repeated;
199
+ const at = now();
200
+ if (at - repeatLoggedAt >= REPEAT_LOG_MS) {
201
+ repeatLoggedAt = at;
202
+ log.log?.(
203
+ `[sync/ctl] ${repeats} journal row(s) named a file at bytes already healed — not announced again.`
204
+ );
205
+ }
206
+ }
150
207
  if (announced.length > 0) {
151
208
  const shown = announced.slice(0, 5).join(', ');
152
209
  log.log?.(
@@ -249,5 +306,6 @@ export function createCtlHealer(opts: CtlHealerOptions): CtlHealer {
249
306
  },
250
307
  healed: () => healed,
251
308
  ignored: () => ignored,
309
+ repeats: () => repeats,
252
310
  };
253
311
  }
@@ -114,6 +114,19 @@ export type DeliveryState =
114
114
  * Mac last saw (`syncedHash ?? lastSeenHash`), so a teammate's new version is a new decision.
115
115
  */
116
116
  | 'hub-only'
117
+ /**
118
+ * 2.1.1 T13 — THE PROJECT DELETED THIS, AND THE BATCH IS HELD HERE: a hub tombstone this Mac still
119
+ * holds the unchanged file for, part of a batch larger than sync removes unasked (the inbound
120
+ * delete breaker). Waits for the person's answer in Sync details — Remove here too, or Keep them
121
+ * here. Nothing is removed or sent meanwhile.
122
+ */
123
+ | 'delete-in-held'
124
+ /**
125
+ * 2.1.1 T13 — KEPT HERE: the project deleted it, and the person chose to keep this Mac's copy. Not
126
+ * proposed for removal again and never pushed back; bound to the hash the project deleted (a local
127
+ * edit is a new decision, and a teammate recreating the file is a plain download).
128
+ */
129
+ | 'kept-here'
117
130
  /** Upload in flight. */
118
131
  | 'pushing'
119
132
  /** The hub answered 2xx and gave it a seq. */
@@ -146,6 +159,13 @@ export interface LedgerRow {
146
159
  * clear it.
147
160
  */
148
161
  remoteHash?: string | null;
162
+ /**
163
+ * The hub's null above is a TOMBSTONE, not "never had it" (2.1.1 T9). Without it a tombstone
164
+ * this machine did not act on (the inbound delete breaker held it) decayed on the next pass
165
+ * into `remote-regressed` — absence-as-authority — and the held files were pushed back over the
166
+ * delete. Meaningful only while `remoteHash` is null; any learned hash supersedes it.
167
+ */
168
+ remoteDeleted?: true;
149
169
  /**
150
170
  * STAT CACHE — the hash of what was last OBSERVED on disk, valid while
151
171
  * `(size, mtimeMs)` still match.
@@ -285,8 +305,11 @@ export interface FileLedger {
285
305
  ancestorOf(rel: string): string | null;
286
306
  /** The hub's hash for this path, as last learned. `undefined` = never learned. */
287
307
  remoteOf(rel: string): string | null | undefined;
288
- /** Record what the hub holds. A delta read UPDATES; only a full read clears. */
289
- noteRemote(rel: string, hash: string | null, seq?: number): void;
308
+ /** Record what the hub holds. A delta read UPDATES; only a full read clears.
309
+ * `deleted`: the null is the hub's tombstone (T9), remembered past this pass. */
310
+ noteRemote(rel: string, hash: string | null, seq?: number, deleted?: boolean): void;
311
+ /** The hub's latest word on this path, as last learned, is a tombstone (T9). */
312
+ remoteTombstoned(rel: string): boolean;
290
313
  /** After a FULL read: forget every remote we did not just see. */
291
314
  pruneRemotes(seen: Set<string>): void;
292
315
  /** All rows, for the doručenka. Defensive copy. */
@@ -447,6 +470,7 @@ export function createFileLedger(opts: FileLedgerOptions): FileLedger {
447
470
  ...(typeof r.remoteHash === 'string' || r.remoteHash === null
448
471
  ? { remoteHash: r.remoteHash }
449
472
  : {}),
473
+ ...(r.remoteHash === null && r.remoteDeleted === true ? { remoteDeleted: true } : {}),
450
474
  ...(Number.isFinite(r.size) ? { size: r.size } : {}),
451
475
  ...(Number.isFinite(r.mtimeMs) ? { mtimeMs: r.mtimeMs } : {}),
452
476
  ...(typeof r.state === 'string' ? { state: r.state as DeliveryState } : {}),
@@ -587,20 +611,30 @@ export function createFileLedger(opts: FileLedgerOptions): FileLedger {
587
611
  ancestorOf: (rel) => data.rows[rel]?.syncedHash ?? null,
588
612
  remoteOf: (rel) => data.rows[rel]?.remoteHash,
589
613
 
590
- noteRemote(rel, hash, seq) {
614
+ noteRemote(rel, hash, seq, deleted) {
591
615
  const r = rowFor(rel);
592
616
  r.remoteHash = hash;
617
+ if (hash === null && deleted === true) r.remoteDeleted = true;
618
+ else r.remoteDeleted = undefined;
593
619
  if (seq !== undefined) r.remoteSeq = seq;
594
620
  schedule();
595
621
  },
596
622
 
623
+ remoteTombstoned(rel) {
624
+ const r = data.rows[rel];
625
+ return r?.remoteHash === null && r.remoteDeleted === true;
626
+ },
627
+
597
628
  pruneRemotes(seen) {
598
629
  // ONLY a full compaction read may say "the hub does not have this".
599
630
  // Called with the set of paths that read carried; anything else loses
600
631
  // its remembered remote rather than keeping a value the hub has since
601
632
  // dropped.
602
633
  for (const [rel, r] of Object.entries(data.rows)) {
603
- if (!seen.has(rel) && r.remoteHash !== undefined) r.remoteHash = null;
634
+ if (!seen.has(rel) && r.remoteHash !== undefined) {
635
+ r.remoteHash = null;
636
+ r.remoteDeleted = undefined;
637
+ }
604
638
  }
605
639
  schedule();
606
640
  },