@1agh/maude 2.1.0 → 2.1.2

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 (153) hide show
  1. package/apps/studio/access/request.ts +1 -0
  2. package/apps/studio/actions/agents.ts +45 -42
  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/verbs.ts +49 -0
  6. package/apps/studio/actions.manifest.json +162 -20
  7. package/apps/studio/actions.parity.json +13 -1
  8. package/apps/studio/ai/create-claim.ts +1 -1
  9. package/apps/studio/bin/_asset-file.mjs +117 -0
  10. package/apps/studio/bin/_canvas-file.mjs +146 -0
  11. package/apps/studio/bin/_curl-local.mjs +7 -4
  12. package/apps/studio/bin/_footage.mjs +123 -0
  13. package/apps/studio/bin/_pdf-playwright.mjs +14 -0
  14. package/apps/studio/bin/_png-playwright.mjs +15 -1
  15. package/apps/studio/bin/_pw-launch.mjs +98 -0
  16. package/apps/studio/bin/_retry-save.mjs +49 -0
  17. package/apps/studio/bin/_sync.mjs +145 -2
  18. package/apps/studio/bin/asset-rename.sh +12 -0
  19. package/apps/studio/bin/asset-trash.sh +12 -0
  20. package/apps/studio/bin/canvas-move.sh +12 -0
  21. package/apps/studio/bin/canvas-new.sh +12 -0
  22. package/apps/studio/bin/footage.sh +12 -0
  23. package/apps/studio/bin/generate.sh +7 -0
  24. package/apps/studio/bin/retry-save.sh +13 -0
  25. package/apps/studio/bridge/canvas-mode-store.ts +11 -2
  26. package/apps/studio/bridge/dgn-protocol.ts +8 -3
  27. package/apps/studio/bridge/occlusion.ts +45 -0
  28. package/apps/studio/canvas-theme-pill.tsx +169 -26
  29. package/apps/studio/client/app.jsx +16 -4
  30. package/apps/studio/client/export-center.jsx +32 -3
  31. package/apps/studio/client/home/HomeAccountBanner.jsx +61 -0
  32. package/apps/studio/client/home/HomeAccountsChip.jsx +404 -0
  33. package/apps/studio/client/home/HomeConnection.jsx +112 -0
  34. package/apps/studio/client/home/ProjectRows.jsx +514 -0
  35. package/apps/studio/client/home/home-accounts-model.js +234 -76
  36. package/apps/studio/client/home/home-api.js +10 -2
  37. package/apps/studio/client/home/home-app.jsx +151 -394
  38. package/apps/studio/client/home/home-icons.jsx +8 -0
  39. package/apps/studio/client/home/home-model.js +149 -1
  40. package/apps/studio/client/home/home-where-model.js +105 -0
  41. package/apps/studio/client/home/home.css +621 -53
  42. package/apps/studio/client/home/use-account-fix.js +123 -0
  43. package/apps/studio/client/hooks/use-palette-and-panels.jsx +3 -1
  44. package/apps/studio/client/hooks/use-tabs.jsx +11 -4
  45. package/apps/studio/client/panels/TeamProjects.jsx +137 -134
  46. package/apps/studio/client/share-link.js +12 -0
  47. package/apps/studio/client/styles/_index.css +4 -0
  48. package/apps/studio/client/v2/assets/generate-ask.jsx +3 -1
  49. package/apps/studio/client/v2/diagnostics/diagnostics-host.jsx +1 -0
  50. package/apps/studio/client/v2/diagnostics/diagnostics-model.js +32 -2
  51. package/apps/studio/client/v2/diagnostics/diagnostics-sheet.jsx +35 -8
  52. package/apps/studio/client/v2/diagnostics/diagnostics.css +34 -0
  53. package/apps/studio/client/v2/diagnostics/sync-details/sync-details-model.js +94 -3
  54. package/apps/studio/client/v2/diagnostics/sync-details/sync-details.jsx +187 -4
  55. package/apps/studio/client/v2/export/done-toast.jsx +2 -5
  56. package/apps/studio/client/v2/export/export-sheet.jsx +9 -2
  57. package/apps/studio/client/v2/export/export.css +9 -0
  58. package/apps/studio/client/v2/export/exports-model.js +16 -3
  59. package/apps/studio/client/v2/export/file-rows.jsx +81 -5
  60. package/apps/studio/client/v2/export/native-save.js +33 -0
  61. package/apps/studio/client/v2/export/sections/print-copy.js +3 -0
  62. package/apps/studio/client/v2/export/sections/print.jsx +37 -20
  63. package/apps/studio/client/v2/link-server/LinkServerDialog.jsx +492 -0
  64. package/apps/studio/client/v2/link-server/LinkServerHost.jsx +42 -0
  65. package/apps/studio/client/v2/link-server/link-server-api.js +142 -0
  66. package/apps/studio/client/v2/link-server/link-server-model.js +438 -0
  67. package/apps/studio/client/v2/link-server/link-server.css +109 -0
  68. package/apps/studio/client/v2/onboarding/AdvancedSheets.jsx +31 -86
  69. package/apps/studio/client/v2/onboarding/onboarding-model.js +1 -18
  70. package/apps/studio/client/v2/search/search-keywords.js +3 -2
  71. package/apps/studio/client/v2/settings/account.jsx +4 -2
  72. package/apps/studio/client/v2/settings/advanced-section.jsx +245 -148
  73. package/apps/studio/client/v2/settings/connection-row.jsx +3 -59
  74. package/apps/studio/client/v2/settings/connections-section.jsx +118 -425
  75. package/apps/studio/client/v2/settings/general-section.jsx +138 -43
  76. package/apps/studio/client/v2/settings/project-sync-settings.jsx +4 -3
  77. package/apps/studio/client/v2/settings/reset-section.jsx +14 -3
  78. package/apps/studio/client/v2/settings/settings-card.jsx +142 -0
  79. package/apps/studio/client/v2/settings/settings-cards.js +220 -0
  80. package/apps/studio/client/v2/settings/settings-handlers.js +7 -6
  81. package/apps/studio/client/v2/settings/settings-model.js +91 -31
  82. package/apps/studio/client/v2/settings/settings-sheet.jsx +25 -6
  83. package/apps/studio/client/v2/settings/settings.css +374 -64
  84. package/apps/studio/client/v2/settings/this-project-card.jsx +730 -0
  85. package/apps/studio/client/v2/settings/this-project-model.js +172 -0
  86. package/apps/studio/client/v2/settings/use-connections.js +3 -2
  87. package/apps/studio/client/v2/settings/use-open-card.js +37 -0
  88. package/apps/studio/client/v2/shell/connection-state.js +197 -0
  89. package/apps/studio/client/v2/shell/menu-runner.js +7 -2
  90. package/apps/studio/client/v2/shell/occlusion-insets.js +37 -9
  91. package/apps/studio/client/v2/shell/project-account-bus.js +36 -0
  92. package/apps/studio/client/v2/shell/project-account-card.jsx +357 -148
  93. package/apps/studio/client/v2/shell/project-account-model.js +272 -149
  94. package/apps/studio/client/v2/shell/project-account-toast.js +66 -0
  95. package/apps/studio/client/v2/shell/project-account.css +237 -0
  96. package/apps/studio/client/v2/shell/share-cluster-host.jsx +166 -83
  97. package/apps/studio/client/v2/shell/shell-parity.js +3 -2
  98. package/apps/studio/client/v2/shell/shell-parity.json +40 -26
  99. package/apps/studio/client/v2/shell/use-account.js +2 -0
  100. package/apps/studio/client/v2/shell/use-occluded-insets.js +13 -3
  101. package/apps/studio/client/v2/signin/use-signin.js +1 -1
  102. package/apps/studio/cloud/endpoints.ts +29 -4
  103. package/apps/studio/collab/room.ts +21 -7
  104. package/apps/studio/dist/client.bundle.js +886 -886
  105. package/apps/studio/dist/comment-mount.js +2 -2
  106. package/apps/studio/dist/styles.css +1 -1
  107. package/apps/studio/exporters/ghostscript.ts +78 -1
  108. package/apps/studio/exporters/pdf-fonts.ts +31 -4
  109. package/apps/studio/generation/jobs.ts +6 -0
  110. package/apps/studio/home/accounts.ts +30 -11
  111. package/apps/studio/home/cloud.ts +6 -1
  112. package/apps/studio/home/hub-health.ts +76 -0
  113. package/apps/studio/home/routes.ts +9 -3
  114. package/apps/studio/http.ts +14 -2
  115. package/apps/studio/migrate/hub.ts +8 -1
  116. package/apps/studio/routes/agent.ts +6 -2
  117. package/apps/studio/routes/hub-link-folder.ts +334 -0
  118. package/apps/studio/routes/hub-signin.ts +78 -1
  119. package/apps/studio/routes/index.ts +4 -0
  120. package/apps/studio/routes/project-undo.ts +10 -0
  121. package/apps/studio/routes/sync.ts +22 -4
  122. package/apps/studio/server.ts +25 -0
  123. package/apps/studio/shell/api-key.ts +11 -0
  124. package/apps/studio/shell/cli-yield.ts +48 -11
  125. package/apps/studio/sync/accepted-cold-start.ts +144 -8
  126. package/apps/studio/sync/action-stage.ts +18 -1
  127. package/apps/studio/sync/ctl-heal.ts +58 -0
  128. package/apps/studio/sync/file-ledger.ts +38 -4
  129. package/apps/studio/sync/file-plane.ts +226 -19
  130. package/apps/studio/sync/held-deletes.ts +86 -5
  131. package/apps/studio/sync/hub-link.ts +8 -0
  132. package/apps/studio/sync/index.ts +68 -4
  133. package/apps/studio/sync/link-consent.ts +22 -75
  134. package/apps/studio/sync/link-survey.ts +252 -0
  135. package/apps/studio/sync/local-kernel.ts +16 -1
  136. package/apps/studio/sync/seed-progress.ts +12 -0
  137. package/apps/studio/sync/source-recovery.ts +18 -2
  138. package/apps/studio/sync/status.ts +11 -1
  139. package/apps/studio/sync/writer-registry.ts +5 -0
  140. package/apps/studio/whats-new.json +36 -0
  141. package/cli/commands/design.mjs +74 -16
  142. package/cli/lib/bash-guard.mjs +23 -4
  143. package/cli/lib/confine-read.mjs +2 -0
  144. package/cli/lib/design-help.gen.mjs +15 -2
  145. package/cli/lib/design-hook.mjs +1 -1
  146. package/cli/lib/desktop-locate.mjs +36 -8
  147. package/cli/lib/studio-locate.mjs +8 -2
  148. package/cli/lib/sub-verbs.mjs +13 -1
  149. package/package.json +9 -8
  150. package/apps/studio/client/home/HomeAccounts.jsx +0 -262
  151. package/apps/studio/client/v2/onboarding/HubSheet.jsx +0 -212
  152. package/apps/studio/client/v2/shell/account-card-model.js +0 -114
  153. package/apps/studio/client/v2/shell/account-card.jsx +0 -189
@@ -48,7 +48,7 @@ import type { TrashListing, TrashOutcome } from '../history/trash.ts';
48
48
  import { createHistory } from '../history.ts';
49
49
  import { SYNTHETIC_FS_DELAY_MS } from '../hmr-broadcast.ts';
50
50
  import { rekeyUserState } from '../home/user-state.ts';
51
- import { acceptedColdStart, localCreateLanes } from './accepted-cold-start.ts';
51
+ import { acceptedColdStart, localCreateLanes, setAsideNotice } from './accepted-cold-start.ts';
52
52
  import { type AcceptedLink, createAcceptedLink, type StructuralOutcome } from './accepted-link.ts';
53
53
  import { createAccessRelay } from './access-notices.ts';
54
54
  import { type RunFence, shellClaimLane } from './action-stage.ts';
@@ -113,7 +113,12 @@ import {
113
113
  withFormatParam,
114
114
  } from './format-sync.ts';
115
115
  import { createFsReader, type FsReader } from './fs-mirror.ts';
116
- import { createHeldDeletes, type HeldDeletesControl, heldDeleteDetail } from './held-deletes.ts';
116
+ import {
117
+ createHeldDeletes,
118
+ type HeldDeletesControl,
119
+ heldDeleteDetail,
120
+ heldIncomingDetail,
121
+ } from './held-deletes.ts';
117
122
  import { canvasLanes, namedField, type RowNamed } from './history-fields.ts';
118
123
  import { type HubDocRow, hubHolds, indexHubDocs } from './hub-listing.ts';
119
124
  import { HUB_UNDO_READ_MAX_BYTES, hubTextUndoConflict } from './hub-text-undo.ts';
@@ -2302,6 +2307,30 @@ export function createSyncRuntime(
2302
2307
  */
2303
2308
  const retiredDocs = new Set<string>();
2304
2309
 
2310
+ /**
2311
+ * The stale local copies a retirement left in place, keyed slug → the body's
2312
+ * size and mtime when it was let go.
2313
+ *
2314
+ * When a retired document's new path never appears, the old file stays on
2315
+ * disk (a recoverable ghost beats a lost canvas). The discovery rescan then
2316
+ * found a canvas on disk with no provider and adopted it again — whose
2317
+ * handshake read the same retirement, released it, and waited out the same
2318
+ * missing path, on every rescan for as long as the process ran: a full
2319
+ * document transfer each time, for a file nobody touched. The rescan skips a
2320
+ * copy whose body is unchanged since it was let go; an edit to it, or a new
2321
+ * file at the path, changes the stamp and is adopted as usual.
2322
+ */
2323
+ const retiredCopies = new Map<string, string>();
2324
+ const bodyStamp = (abs: string | undefined): string | null => {
2325
+ if (!abs) return null;
2326
+ try {
2327
+ const st = statSync(abs);
2328
+ return `${st.size}:${st.mtimeMs}`;
2329
+ } catch {
2330
+ return null;
2331
+ }
2332
+ };
2333
+
2305
2334
  /**
2306
2335
  * What the hub's last listing said each document HOLDS, in bytes.
2307
2336
  *
@@ -2421,6 +2450,12 @@ export function createSyncRuntime(
2421
2450
  const newAbs = path.resolve(ctx.paths.designRoot, norm);
2422
2451
  const contained =
2423
2452
  newAbs === ctx.paths.designRoot || newAbs.startsWith(ctx.paths.designRoot + path.sep);
2453
+ // The old body stays on disk from here on unless it is parked below:
2454
+ // remember it, so the next rescan does not adopt it straight back.
2455
+ if (!(desc.html && path.resolve(desc.html) === newAbs)) {
2456
+ const stamp = bodyStamp(desc.html);
2457
+ if (stamp !== null && retiredCopies.size < NUDGE_MEMO_CAP) retiredCopies.set(slug, stamp);
2458
+ }
2424
2459
  if (!contained) return; // hostile path — never act on it
2425
2460
  // A DOCUMENT THAT MOVED TO WHERE IT ALREADY IS DID NOT MOVE.
2426
2461
  //
@@ -4086,6 +4121,8 @@ export function createSyncRuntime(
4086
4121
  ownAccepted,
4087
4122
  ownAcceptedCss,
4088
4123
  wasAccepted: (content) => acceptedLink.client.holdsValue(content),
4124
+ // T11 — a hub's own checkout is the project's cache: never a held conflict there.
4125
+ checkoutIsCache: cellPairing !== null,
4089
4126
  createDoc:
4090
4127
  createdHere !== null
4091
4128
  ? async () => ({ status: 'accepted' as const, html: createdHere })
@@ -4103,6 +4140,16 @@ export function createSyncRuntime(
4103
4140
  // (the same file, or a module that keeps its name), so it joins it.
4104
4141
  joined = await acceptedColdStart({ ...coldStart, inProject: true });
4105
4142
  }
4143
+ // S1 (2.1.1) — what the project's version replaced of this Mac's (a first link) is in
4144
+ // its recovery slot; say so instead of only logging it.
4145
+ if (joined.kind === 'reconciled' && joined.setAside?.length) {
4146
+ store.notice({
4147
+ id: `set-aside-${canvas.slug}`,
4148
+ severity: 'warn',
4149
+ text: setAsideNotice(rel, canvas.slug, joined.setAside),
4150
+ lanes: [...joined.setAside],
4151
+ });
4152
+ }
4106
4153
  renamedAway.delete(docName);
4107
4154
  projection.reconcile();
4108
4155
  } else if (projection) {
@@ -5062,7 +5109,18 @@ export function createSyncRuntime(
5062
5109
  // agent reads.
5063
5110
  markUntrusted();
5064
5111
  }
5065
- const incoming = added.map((slug) => bySlug.get(slug)).filter((c) => !!c);
5112
+ const incoming = added
5113
+ .map((slug) => bySlug.get(slug))
5114
+ .filter((c): c is CanvasDescriptor => {
5115
+ if (!c) return false;
5116
+ const was = retiredCopies.get(c.slug);
5117
+ if (was === undefined) return true;
5118
+ // Unchanged since its retirement released it: adopting it again
5119
+ // can only end in the same release.
5120
+ if (bodyStamp(c.html) === was) return false;
5121
+ retiredCopies.delete(c.slug);
5122
+ return true;
5123
+ });
5066
5124
  // S6.13 — only a project that does not answer gets its creates now;
5067
5125
  // one that answers creates them on the handshake, as it always has.
5068
5126
  const offline =
@@ -5547,6 +5605,7 @@ export function createSyncRuntime(
5547
5605
  // Read once: calling it inside the spread evaluated it twice and made
5548
5606
  // its `null` case the object's type.
5549
5607
  const blockedMedia = filePlane?.blocked() ?? null;
5608
+ const conflictCopiesNow = filePlane?.conflictCopies() ?? {};
5550
5609
  const ignoreFoldersNow = planeIgnoreFolders();
5551
5610
  const purgeNow = heldDeletesControl?.view().purge ?? null;
5552
5611
  statusStore?.updateFiles?.({
@@ -5556,6 +5615,9 @@ export function createSyncRuntime(
5556
5615
  ...(filePlane
5557
5616
  ? {
5558
5617
  delivery: filePlane.doruceka(),
5618
+ ...(Object.keys(conflictCopiesNow).length > 0
5619
+ ? { conflictCopies: conflictCopiesNow }
5620
+ : {}),
5559
5621
  ...(filePlane.dorucekaTotal() > MAX_DORUCEKA_ROWS
5560
5622
  ? { deliveryTruncated: filePlane.dorucekaTotal() - MAX_DORUCEKA_ROWS }
5561
5623
  : {}),
@@ -7103,11 +7165,13 @@ export function filePlaneHeld(
7103
7165
  count: result.deleteHeld.count,
7104
7166
  paths: result.deleteHeld.paths,
7105
7167
  ...(result.deleteHeld.folders ? { folders: result.deleteHeld.folders } : {}),
7168
+ ...(result.deleteHeld.digest ? { digest: result.deleteHeld.digest } : {}),
7106
7169
  detail:
7107
7170
  result.deleteHeld.direction === 'out'
7108
7171
  ? // Issue #207 (7b) — the row's two buttons are the answer (Delete on the hub too · Keep on the hub).
7109
7172
  heldDeleteDetail(result.deleteHeld.count, result.deleteHeld.folders ?? [])
7110
- : `The project wants to remove ${result.deleteHeld.count} files here — more than sync will delete without you saying so. Nothing was removed. They stay until you accept or the project puts them back.`,
7173
+ : // 2.1.1 T13 — the row's two buttons are the answer (Remove here too · Keep them here).
7174
+ heldIncomingDetail(result.deleteHeld.count, result.deleteHeld.folders ?? []),
7111
7175
  });
7112
7176
  }
7113
7177
  if (result.firstAnchorHeld) {
@@ -20,22 +20,16 @@
20
20
  // and the app's own managed copies (the desktop passes its registry binding as
21
21
  // `MAUDE_APP_BOUND_HUB`, which a repo cannot set).
22
22
  //
23
- // MIGRATION (a project already syncing on this Mac before this shipped keeps syncing, no prompt).
24
- // The record is derived ONCE from this Mac's own evidence of the link — `_sync.json` (its `url`) or
25
- // `_state/sync-journal.json` (its `hubUrl`) naming the same hub. Why that is safe:
26
- // - both are runtime state, gitignored in every DDR-115 list, so a clone does not carry them;
27
- // - a repo that force-adds one anyway is refused: the file must not be tracked by git;
28
- // - and it must be OLDER than this store (`since` — stamped the first time this build looked), so
29
- // evidence written after the fix (a clone, an unzip with fresh times) never counts. Only a
30
- // consented runtime writes either file from now on, and that one already has a record;
31
- // - it must be a plain file in a plain `_state/` (no symlink to another project's genuine file).
32
- // What is NOT closed: an archive that restores backdated mtimes AND carries a forged `_sync.json`,
33
- // with no `.git`, extracted before this build first ran. Narrow, and the old build trusted it anyway.
23
+ // NO MIGRATION FROM FOLDER CONTENT (2.1.1, N1). Builds before 2.1.1 derived a `migrated` record at
24
+ // boot from the folder's own runtime sync files when their mtime predated this store. Retired:
25
+ // whoever made the folder controls both the files and their timestamps (archives restore stored
26
+ // mtimes), so that lane let folder content say "confirmed". Nothing inside the folder writes a
27
+ // record now. A `migrated` record an earlier build already wrote stays valid (`LinkHow` keeps the
28
+ // value, `matches` honours it like any other); a folder with no record gets the neutral Review…
29
+ // state and one Connect.
34
30
 
35
31
  import {
36
32
  chmodSync,
37
- existsSync,
38
- lstatSync,
39
33
  mkdirSync,
40
34
  readdirSync,
41
35
  readFileSync,
@@ -69,13 +63,12 @@ export interface LinkClaim {
69
63
  export interface ConsentOptions {
70
64
  /** the folder holding `.design/` — the record's key (by realpath) */
71
65
  repoRoot: string;
66
+ /** kept for callers; nothing under it is read as evidence of a link (N1) */
72
67
  designRoot: string;
73
68
  /** the store file (default `linksPath()`) */
74
69
  file?: string;
75
70
  env?: Record<string, string | undefined>;
76
71
  now?: () => number;
77
- /** is `abs` tracked by git in `repoRoot`? (injected in tests; default runs git) */
78
- tracked?: (repoRoot: string, abs: string) => boolean;
79
72
  }
80
73
 
81
74
  export type ConsentVerdict =
@@ -161,7 +154,7 @@ function loadOrInit(file: string, now: number): LinksFile {
161
154
  try {
162
155
  writeStore(file, fresh);
163
156
  } catch {
164
- /* unwritable: `since` stays now for this boot, which only narrows migration */
157
+ /* unwritable: the store is created on the next write */
165
158
  }
166
159
  return fresh;
167
160
  }
@@ -177,6 +170,15 @@ export function projectLinkOf(repoRoot: string, file: string = linksPath()): Pro
177
170
  return readStore(file)?.links[folderKey(repoRoot)] ?? null;
178
171
  }
179
172
 
173
+ /** 2.1.1 T8 — has ANY folder on this Mac been linked to `url`? (Link your server asks before the
174
+ * first link to a server this Mac never linked, whatever that server says it holds.) */
175
+ export function hubEverLinked(url: string, file: string = linksPath()): boolean {
176
+ const hub = normHub(url);
177
+ if (!hub) return false;
178
+ const links = readStore(file)?.links ?? {};
179
+ return Object.values(links).some((r) => !!r && typeof r === 'object' && r.hub === hub);
180
+ }
181
+
180
182
  /** Write (or replace) this folder's record — a person linked or confirmed it on this Mac. */
181
183
  export function recordProjectLink(
182
184
  repoRoot: string,
@@ -243,63 +245,10 @@ export function forgetFolderEverywhere(
243
245
  return n;
244
246
  }
245
247
 
246
- function gitTracked(repoRoot: string, abs: string): boolean {
247
- try {
248
- const r = Bun.spawnSync(['git', 'ls-files', '--error-unmatch', '--', abs], {
249
- cwd: repoRoot,
250
- stdout: 'ignore',
251
- stderr: 'ignore',
252
- env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' },
253
- });
254
- return r.exitCode === 0;
255
- } catch {
256
- return false;
257
- }
258
- }
259
-
260
- /** A plain file (not a symlink) inside a plain directory chain under `designRoot`. */
261
- function plainFile(designRoot: string, rel: string): boolean {
262
- let cur = designRoot;
263
- for (const part of rel.split('/')) {
264
- cur = path.join(cur, part);
265
- try {
266
- if (lstatSync(cur).isSymbolicLink()) return false;
267
- } catch {
268
- return false;
269
- }
270
- }
271
- return true;
272
- }
273
-
274
- /** This Mac's own pre-fix evidence of syncing `hub` here — see the header for why it is safe. */
275
- function migrationEvidence(o: ConsentOptions, hub: string, since: number): boolean {
276
- const tracked = o.tracked ?? gitTracked;
277
- const lanes: Array<[string, string]> = [
278
- ['_sync.json', 'url'],
279
- ['_state/sync-journal.json', 'hubUrl'],
280
- ];
281
- for (const [rel, key] of lanes) {
282
- const abs = path.join(o.designRoot, rel);
283
- if (!existsSync(abs) || !plainFile(o.designRoot, rel)) continue;
284
- let named: string | null = null;
285
- let mtime = Number.POSITIVE_INFINITY;
286
- try {
287
- mtime = lstatSync(abs).mtimeMs;
288
- named = normHub((JSON.parse(readFileSync(abs, 'utf8')) as Record<string, unknown>)?.[key]);
289
- } catch {
290
- continue;
291
- }
292
- if (named !== hub || !(mtime < since)) continue;
293
- if (tracked(o.repoRoot, abs)) continue;
294
- return true;
295
- }
296
- return false;
297
- }
298
-
299
248
  /**
300
249
  * May this Mac honour `claim` for this folder? A matching record → yes. Else the app's own binding
301
- * (`MAUDE_APP_BOUND_HUB`, the desktop registry's managed copy) or this Mac's pre-fix evidence →
302
- * yes, and the record is written so the question is never asked again. Else no: park the claim.
250
+ * (`MAUDE_APP_BOUND_HUB`, the desktop registry's managed copy) → yes, and the record is written so
251
+ * the question is never asked again. Else no: park the claim. Nothing in the folder counts (N1).
303
252
  */
304
253
  export function linkConsent(claim: LinkClaim, o: ConsentOptions): ConsentVerdict {
305
254
  const hub = normHub(claim.url);
@@ -313,10 +262,8 @@ export function linkConsent(claim: LinkClaim, o: ConsentOptions): ConsentVerdict
313
262
  // A record for ANOTHER hub is a person's choice on this Mac; a claim that differs from it is not
314
263
  // migrated past — it waits for Connect like any other.
315
264
  if (rec) return { ok: false, reason: 'other-hub' };
316
- let how: LinkHow | null = null;
317
- if (normHub(env.MAUDE_APP_BOUND_HUB) === hub) how = 'app';
318
- else if (migrationEvidence(o, hub, store.since)) how = 'migrated';
319
- if (!how) return { ok: false, reason: 'no-record' };
265
+ if (normHub(env.MAUDE_APP_BOUND_HUB) !== hub) return { ok: false, reason: 'no-record' };
266
+ const how: LinkHow = 'app';
320
267
  try {
321
268
  recordProjectLink(o.repoRoot, claim, how, { file, now: () => now });
322
269
  } catch {
@@ -0,0 +1,252 @@
1
+ // 2.1.1 — what linking THIS folder to a team server would do, counted before anything moves
2
+ // (routes/hub-link-folder.ts, decision maude/v2-2.1.1-b5-link-folder-confirm-before-merge).
3
+ //
4
+ // A self-hosted server holds ONE project. When it is empty, linking seeds it from this folder (the
5
+ // sync runtime's ordinary seed-up). When it already holds work, the two sides would be merged, so the
6
+ // person is told first, in counts:
7
+ //
8
+ // onlyHere canvases + files on this Mac the server does not have (they go up)
9
+ // onlyThere canvases + files on the server this Mac does not have (they come down)
10
+ // differ on both sides with different content (they are merged)
11
+ // same on both sides, identical
12
+ //
13
+ // Both sides are read the way the sync runtime reads them: the server through its own manifests
14
+ // (`GET /api/projects/current/v1/bootstrap` — canvas paths + the `html` lane's sha256 — and
15
+ // `GET /api/files`, the file plane's sha256 manifest), this Mac through the file plane's walk and
16
+ // classifier (`walkClassifiedAll`). Nothing here writes, and the credential only rides requests to
17
+ // the server it belongs to: a redirect is refused, never followed.
18
+ //
19
+ // An older server without the accepted-revisions bootstrap answers its document listing instead
20
+ // (`GET /api/documents`: names and byte counts). Content cannot be compared from that, so a canvas
21
+ // on both sides counts as `differ` — the safe direction: it can only ask for a confirm, never skip one.
22
+
23
+ import { createHash } from 'node:crypto';
24
+ import { readFileSync } from 'node:fs';
25
+ import path from 'node:path';
26
+ import type { CanvasGroupLike } from './file-membership.ts';
27
+ import { walkClassifiedAll } from './file-plane.ts';
28
+ import { slugFromDocName } from './remote-docs.ts';
29
+
30
+ export interface SideSurvey {
31
+ /** design-root-relative canvas body path (`ui/home.tsx`) → sha256 of its source, null = unknown */
32
+ canvases: Map<string, string | null>;
33
+ /** design-root-relative file path → sha256 */
34
+ files: Map<string, string>;
35
+ /** canvases are compared by slug only (an older server's listing) */
36
+ bySlug?: boolean;
37
+ /** This Mac's side only: the files that are pictures, video and the like (the inert-media class). */
38
+ media?: Set<string>;
39
+ /**
40
+ * The server's side only (2.1.1 T14): whether it has a place to store media. `false` only when it
41
+ * said so (no file journal and no checkout); a server that did not answer is assumed to store it.
42
+ */
43
+ storesMedia?: boolean;
44
+ }
45
+
46
+ export interface LinkCounts {
47
+ onlyHere: number;
48
+ onlyThere: number;
49
+ differ: number;
50
+ same: number;
51
+ }
52
+
53
+ export type HubSurvey =
54
+ | { ok: true; survey: SideSurvey }
55
+ | { ok: false; reason: 'signed-out' | 'offline' };
56
+
57
+ const TIMEOUT_MS = 15_000;
58
+ const sha256 = (b: Uint8Array | string) => createHash('sha256').update(b).digest('hex');
59
+ const HEX64 = /^[0-9a-f]{64}$/;
60
+
61
+ /** A canvas body path's slug, the way a flat document name spells it. */
62
+ export function slugOfRel(rel: string): string {
63
+ return path.posix
64
+ .basename(rel)
65
+ .replace(/\.tsx$/i, '')
66
+ .toLowerCase();
67
+ }
68
+
69
+ /** This Mac's side: canvas bodies + file-plane files, through the plane's own walk. */
70
+ export function surveyLocal(
71
+ designRoot: string,
72
+ canvasGroups?: readonly CanvasGroupLike[]
73
+ ): SideSurvey {
74
+ const canvases = new Map<string, string | null>();
75
+ const files = new Map<string, string>();
76
+ const media = new Set<string>();
77
+ for (const f of walkClassifiedAll(designRoot, canvasGroups)) {
78
+ if (f.cls === 'never') continue;
79
+ let hash: string | null = null;
80
+ try {
81
+ hash = sha256(readFileSync(f.abs));
82
+ } catch {
83
+ hash = null;
84
+ }
85
+ if (f.cls === 'canvas-owned') {
86
+ if (/\.tsx$/i.test(f.rel)) canvases.set(f.rel, hash);
87
+ continue;
88
+ }
89
+ if (hash) {
90
+ files.set(f.rel, hash);
91
+ if (f.cls === 'inert-media') media.add(f.rel);
92
+ }
93
+ }
94
+ return { canvases, files, media };
95
+ }
96
+
97
+ type Got = { status: number; body: Record<string, unknown> | null };
98
+
99
+ async function getJson(url: string, token: string, doFetch: typeof fetch): Promise<Got> {
100
+ try {
101
+ const res = await doFetch(url, {
102
+ headers: { authorization: `Bearer ${token}` },
103
+ // the credential belongs to this server: a redirect would carry it elsewhere
104
+ redirect: 'manual',
105
+ signal: AbortSignal.timeout(TIMEOUT_MS),
106
+ });
107
+ if (res.status !== 200) return { status: res.status, body: null };
108
+ const body = (await res.json().catch(() => null)) as Record<string, unknown> | null;
109
+ return { status: 200, body: body && typeof body === 'object' ? body : null };
110
+ } catch {
111
+ return { status: 0, body: null };
112
+ }
113
+ }
114
+
115
+ const refused = (s: number) => s === 401 || s === 403;
116
+
117
+ /**
118
+ * Does the server have a place for pictures and videos? A server that carries the file journal
119
+ * (`ledger`) stores them in it; an older one stores them in its project checkout. With neither, its
120
+ * media door answers 405 and they stay on this Mac (sync/media-gate.ts). Unknown is "yes": the line
121
+ * this feeds is only said when the server told us it can't.
122
+ */
123
+ export function serverStoresMedia(health: Record<string, unknown> | null): boolean {
124
+ if (!health) return true;
125
+ const caps = health.capabilities;
126
+ if (!Array.isArray(caps)) return true; // a server that predates capabilities: say nothing
127
+ if (caps.includes('ledger')) return true;
128
+ const checkout = (health.workspace as { checkout?: unknown } | undefined)?.checkout;
129
+ return checkout === 'present';
130
+ }
131
+
132
+ /** The server's side, with the credential this Mac holds for it. */
133
+ export async function surveyHub(
134
+ hubUrl: string,
135
+ token: string,
136
+ doFetch: typeof fetch = fetch
137
+ ): Promise<HubSurvey> {
138
+ const base = hubUrl.replace(/\/+$/, '');
139
+ const canvases = new Map<string, string | null>();
140
+ const files = new Map<string, string>();
141
+ let bySlug = false;
142
+
143
+ const boot = await getJson(`${base}/api/projects/current/v1/bootstrap`, token, doFetch);
144
+ if (refused(boot.status)) return { ok: false, reason: 'signed-out' };
145
+ if (boot.status === 200 && Array.isArray(boot.body?.docs)) {
146
+ for (const d of boot.body.docs as unknown[]) {
147
+ const row = d as { path?: unknown; retired?: unknown; lanes?: unknown };
148
+ if (!row || row.retired || typeof row.path !== 'string' || !row.path) continue;
149
+ const html = (row.lanes as { html?: { hash?: unknown } } | undefined)?.html?.hash;
150
+ canvases.set(row.path, typeof html === 'string' && HEX64.test(html) ? html : null);
151
+ }
152
+ } else {
153
+ // an older server: its listing (names + byte counts) — a name that holds nothing is not work
154
+ const list = await getJson(`${base}/api/documents`, token, doFetch);
155
+ if (refused(list.status)) return { ok: false, reason: 'signed-out' };
156
+ if (list.status !== 200 || !Array.isArray(list.body?.documents))
157
+ return { ok: false, reason: 'offline' };
158
+ bySlug = true;
159
+ for (const d of list.body.documents as unknown[]) {
160
+ const row = d as { name?: unknown; bytes?: unknown };
161
+ const slug = typeof row?.name === 'string' ? slugFromDocName(row.name) : null;
162
+ if (slug && Number(row.bytes) > 0) canvases.set(slug, null);
163
+ }
164
+ }
165
+
166
+ const manifest = await getJson(`${base}/api/files`, token, doFetch);
167
+ if (refused(manifest.status)) return { ok: false, reason: 'signed-out' };
168
+ if (manifest.status === 200 && Array.isArray(manifest.body?.files)) {
169
+ for (const f of manifest.body.files as unknown[]) {
170
+ const row = f as { path?: unknown; sha256?: unknown };
171
+ if (typeof row?.path === 'string' && typeof row.sha256 === 'string' && HEX64.test(row.sha256))
172
+ files.set(row.path, row.sha256);
173
+ }
174
+ } else if (manifest.status === 0) {
175
+ return { ok: false, reason: 'offline' };
176
+ }
177
+ // any other answer (an older server without the file plane) = no files there
178
+
179
+ // 2.1.1 T14 — can this server store media at all? (`/health` needs no credential)
180
+ const health = await getJson(`${base}/health`, token, doFetch);
181
+ const storesMedia = serverStoresMedia(health.status === 200 ? health.body : null);
182
+
183
+ return {
184
+ ok: true,
185
+ survey: {
186
+ canvases,
187
+ files,
188
+ ...(bySlug ? { bySlug } : {}),
189
+ ...(storesMedia ? {} : { storesMedia }),
190
+ },
191
+ };
192
+ }
193
+
194
+ /** Does the server hold any work at all? */
195
+ export function holdsWork(s: SideSurvey): boolean {
196
+ return s.canvases.size > 0 || s.files.size > 0;
197
+ }
198
+
199
+ function countMaps(
200
+ here: ReadonlyMap<string, string | null>,
201
+ there: ReadonlyMap<string, string | null>,
202
+ out: LinkCounts
203
+ ): void {
204
+ for (const [k, h] of here) {
205
+ if (!there.has(k)) out.onlyHere++;
206
+ else {
207
+ const t = there.get(k) ?? null;
208
+ if (h && t && h === t) out.same++;
209
+ else out.differ++;
210
+ }
211
+ }
212
+ for (const k of there.keys()) if (!here.has(k)) out.onlyThere++;
213
+ }
214
+
215
+ export interface LinkComparison extends LinkCounts {
216
+ /** the same four counts, canvases only and files only (the dialog names each) */
217
+ canvases: LinkCounts;
218
+ files: LinkCounts;
219
+ /**
220
+ * 2.1.1 T14 — pictures and videos only this Mac has that the server has no place for: they stay
221
+ * here, so they are NOT in `onlyHere` ("sent up"). Absent when there are none.
222
+ */
223
+ stayHere?: number;
224
+ }
225
+
226
+ const zero = (): LinkCounts => ({ onlyHere: 0, onlyThere: 0, differ: 0, same: 0 });
227
+
228
+ /** Here vs there: the four counts the dialog words, in total and per kind. */
229
+ export function compareSurveys(here: SideSurvey, there: SideSurvey): LinkComparison {
230
+ const canvases = zero();
231
+ const files = zero();
232
+ const localCanvases = there.bySlug
233
+ ? new Map([...here.canvases.keys()].map((rel) => [slugOfRel(rel), null as string | null]))
234
+ : here.canvases;
235
+ countMaps(localCanvases, there.canvases, canvases);
236
+ countMaps(here.files, there.files, files);
237
+ // media only this Mac has, on a server that can't store it: counted apart, never "sent up"
238
+ let stay = 0;
239
+ if (there.storesMedia === false && here.media) {
240
+ for (const rel of here.media) if (here.files.has(rel) && !there.files.has(rel)) stay++;
241
+ files.onlyHere -= stay;
242
+ }
243
+ return {
244
+ ...(stay ? { stayHere: stay } : {}),
245
+ onlyHere: canvases.onlyHere + files.onlyHere,
246
+ onlyThere: canvases.onlyThere + files.onlyThere,
247
+ differ: canvases.differ + files.differ,
248
+ same: canvases.same + files.same,
249
+ canvases,
250
+ files,
251
+ };
252
+ }
@@ -82,6 +82,7 @@ import { hashBytes } from './echo-guard.ts';
82
82
  import { canvasLanes, namedField, type RowNamed } from './history-fields.ts';
83
83
  import { type HubEffect, hubTextUndoConflict } from './hub-text-undo.ts';
84
84
  import { mergeSource } from './source-merge.ts';
85
+ import { saveRecoveryBody } from './source-recovery.ts';
85
86
  import { type ParkedCanvas, removeClearedCopies } from './trash-clear-copies.ts';
86
87
  import {
87
88
  asTarget,
@@ -902,7 +903,21 @@ export function openLocalHome(opts: LocalHomeOptions): LocalHome {
902
903
  onRefused: (w) => {
903
904
  if (!(LOCAL_LANES as readonly string[]).includes(w.lane)) return;
904
905
  const lane = w.lane as LocalLane;
905
- if (diskLane(w.slug, lane) === w.content) writeLane(w.slug, lane, w.base);
906
+ if (diskLane(w.slug, lane) !== w.content) return;
907
+ // the refused bytes leave the disk, never the project: they are kept in the canvas's
908
+ // recovery folder first, and a write that cannot keep them is not rolled back
909
+ try {
910
+ saveRecoveryBody(
911
+ path.join(opts.designRoot, '_history', canvasSlugFromRel(w.slug, designRel)),
912
+ lane === 'html' ? w.slug : `${w.slug}.${lane}`,
913
+ 'local',
914
+ w.content
915
+ );
916
+ } catch (err) {
917
+ log.warn(`[local-kernel] ${w.slug}: refused write kept on disk (${String(err)})`);
918
+ return;
919
+ }
920
+ writeLane(w.slug, lane, w.base);
906
921
  },
907
922
  // #164 — writes a call's window parked and nobody claimed: recorded as outside, as the watcher
908
923
  // would have recorded them (one action per canvas; the disk already holds the bytes)
@@ -225,6 +225,12 @@ export function computeSeedProgress(input: SeedProgressInput): SeedProgress {
225
225
  delivered += 1;
226
226
  continue;
227
227
  }
228
+ // 2.1.1 T14 — a conflict that already parked this Mac's version beside the file has nothing left to
229
+ // move (the hub holds both): delivered, though it stays listed for a person to look at.
230
+ if (state === 'conflict' && row.conflictCopy) {
231
+ delivered += 1;
232
+ continue;
233
+ }
228
234
  if (state === 'ignored') {
229
235
  ignored += 1;
230
236
  continue;
@@ -241,6 +247,12 @@ export function computeSeedProgress(input: SeedProgressInput): SeedProgress {
241
247
  heldDeletedHere += 1;
242
248
  continue;
243
249
  }
250
+ // 2.1.1 T13 — the project deleted it and this Mac is waiting for the person's answer, or kept the
251
+ // copy by choice: held here, never "waiting" to move.
252
+ if (state === 'delete-in-held' || state === 'kept-here') {
253
+ held += 1;
254
+ continue;
255
+ }
244
256
  if (isHeldByConsent(row)) {
245
257
  held += 1;
246
258
  if (row.reason === CODE_MODULE_HELD_REASON) heldCode += 1;
@@ -20,6 +20,22 @@ export interface RecoveryCandidate {
20
20
  resolved: boolean;
21
21
  }
22
22
 
23
+ /**
24
+ * S1 (2.1.1) — the suffix of a file's recovery slots. A canvas's side files are all `.json`
25
+ * (`<slug>.annotations.json`, `<name>.meta.json`, `_comments/<slug>.json`), so naming a slot by the
26
+ * extension alone put the board, the layout and the comments in ONE `local.json`: the last lane a
27
+ * cold start set aside overwrote the copy of the one before (a first link lost the person's
28
+ * comments that way). Each lane keeps its own slot; `.tsx`/`.css` keep theirs.
29
+ */
30
+ export function recoverySuffix(file: string): string {
31
+ const base = path.basename(file).toLowerCase();
32
+ if (base.endsWith('.annotations.json')) return '.annotations.json';
33
+ if (base.endsWith('.meta.json')) return '.meta.json';
34
+ if (path.basename(path.dirname(file)) === '_comments' && base.endsWith('.json'))
35
+ return '.comments.json';
36
+ return path.extname(file);
37
+ }
38
+
23
39
  function candidatePath(historyDir: string, file: string): string {
24
40
  return path.join(historyDir, 'sync-recovery', `candidate${path.extname(file)}.json`);
25
41
  }
@@ -126,7 +142,7 @@ export function saveRecoveryBody(
126
142
  ): string {
127
143
  if (Buffer.byteLength(body, 'utf8') > MAX_HTML_BYTES)
128
144
  throw new Error('Recovery source exceeds size limit');
129
- const target = path.join(historyDir, 'sync-recovery', `${slot}${path.extname(file)}`);
145
+ const target = path.join(historyDir, 'sync-recovery', `${slot}${recoverySuffix(file)}`);
130
146
  writableRecoveryDir(historyDir);
131
147
  if (!existsSync(target) || readFileSync(target, 'utf8') !== body) atomicWrite(target, body);
132
148
  return target;
@@ -138,7 +154,7 @@ export function readRecoveryBody(
138
154
  file: string,
139
155
  slot: RecoverySlot
140
156
  ): string | null {
141
- const target = path.join(historyDir, 'sync-recovery', `${slot}${path.extname(file)}`);
157
+ const target = path.join(historyDir, 'sync-recovery', `${slot}${recoverySuffix(file)}`);
142
158
  try {
143
159
  if (statSync(target).size > MAX_HTML_BYTES) return null;
144
160
  return readFileSync(target, 'utf8');