@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
@@ -0,0 +1,334 @@
1
+ // 2.1.1 — "Link your server" in a project tab connects THIS folder to the person's own team server
2
+ // (decision maude/v2-2.1.1-b5-link-folder-confirm-before-merge).
3
+ //
4
+ // POST /_api/hub/link-folder { url } → { ok, state: 'linked', url, sync }
5
+ // | { ok, state: 'needs-confirm', confirm, counts, host }
6
+ // POST /_api/hub/link-folder { url, confirm } → { ok, state: 'linked', … } (the person said yes)
7
+ //
8
+ // The sign-in already happened on the server's own page (`/_api/hub-signin/*`), which stored this Mac's
9
+ // credential for it; this route only uses that credential. A self-hosted server holds ONE project:
10
+ //
11
+ // • (2.1.1 T8) a server this Mac never linked any folder to → ALWAYS the confirm below first, with
12
+ // what goes up (`empty: true` when the server holds nothing) — the server's survey is its word;
13
+ // • it holds nothing yet → link now: the folder's format marker goes up first (raise-only, V2-1.12
14
+ // §5.2, as Move to cloud), then the attach lane (`cloud/endpoints.ts` `attachStored` → `linkFolder`:
15
+ // linkedHub in config.json, the link recorded on this Mac, the live sync runtime cycled — whose
16
+ // seed-up uploads the folder);
17
+ // • it already holds work → NOTHING is written: the answer counts what only this Mac has, what only
18
+ // the server has and what differs (sync/link-survey.ts), with a one-time confirm code bound to that
19
+ // server. A second POST with the code links, exactly as above. Never a silent two-way merge.
20
+ //
21
+ // linkedHub is written only by the attach lane, only on success. A folder already linked to another
22
+ // server, a worktree tab, a server this Mac holds no sign-in for and a server on a newer format than
23
+ // this build are refused before anything moves.
24
+ //
25
+ // MAIN ORIGIN, WINDOW ONLY: it spends the team-server credential and uploads the project, so it is the
26
+ // person's act in the Maude window — the same gate as Move to cloud (`Sec-Fetch-Site: same-origin`,
27
+ // which a page cannot forge and the loopback helper refuses to send), plus PERSON_ONLY (shell/api-key.ts)
28
+ // and `guardTableRoute`'s CSRF + DNS-rebind gates. Never canvas-safe; a cell never serves it
29
+ // (apps/hub/src/studio-manifest.mjs: REFUSED — a cell holds no team-server credential of its own).
30
+ // No answer ever carries a credential.
31
+
32
+ import { randomBytes } from 'node:crypto';
33
+ import { readFileSync } from 'node:fs';
34
+ import { join } from 'node:path';
35
+
36
+ import type { CloudEndpointResult } from '../cloud/endpoints.ts';
37
+ import { SUPPORTED_FORMAT } from '../format.ts';
38
+ import { hubAddress } from '../home/hub.ts';
39
+ import { createHubFormatClient } from '../migrate/hub.ts';
40
+ import { worktreeOf } from '../shell/worktree.ts';
41
+ import type { CanvasGroupLike } from '../sync/file-membership.ts';
42
+ import { getHubRecord, normalizeUrl } from '../sync/hubs-config.ts';
43
+ import { hubEverLinked, linksPath, normHub, projectLinkOf } from '../sync/link-consent.ts';
44
+ import {
45
+ compareSurveys,
46
+ holdsWork,
47
+ type LinkComparison,
48
+ surveyHub,
49
+ surveyLocal,
50
+ } from '../sync/link-survey.ts';
51
+ import type { RouteSpec } from './table.ts';
52
+
53
+ export const HUB_LINK_FOLDER_PATH = '/_api/hub/link-folder';
54
+
55
+ export interface HubLinkFolderDeps {
56
+ designRoot: string;
57
+ /** config.json `canvasGroups` — the plane's walk classifies against them */
58
+ canvasGroups?: () => readonly CanvasGroupLike[] | undefined;
59
+ /** the folder's own format marker (config.json `formatVersion ?? 1`) */
60
+ localFormat: () => number;
61
+ /** the attach lane (cloud/endpoints.ts) — the one place linkedHub is written */
62
+ attachStored(hubUrl: string): Promise<CloudEndpointResult>;
63
+ /** this profile's hubs.json; absent = `hubsConfigPath()` */
64
+ hubsConfigPath?: string;
65
+ /** #206 §5 — the main project's name when this server serves a worktree tab */
66
+ worktreeOf?: () => string | null;
67
+ /** 2.1.1 T8 — the folder holding `.design/`: "already linked" is decided by THIS Mac's link record
68
+ * for it (sync/link-consent.ts), never by the committed config.json alone. Absent = the record is
69
+ * not consulted (the claim alone decides, as before). */
70
+ repoRoot?: string;
71
+ /** this Mac's link records (`project-links.json`); absent = `linksPath()` */
72
+ linksFile?: string;
73
+ /** seams for tests */
74
+ fetchImpl?: typeof fetch;
75
+ now?: () => number;
76
+ }
77
+
78
+ /** CONTRACT §3–§4 voice. Every refusal says nothing was linked. */
79
+ export const LINK_FOLDER_WORDS = {
80
+ windowOnly: 'Link your server from the Maude window.',
81
+ badAddress: 'That doesn’t look like a server address. Nothing was linked.',
82
+ signedOut: (host: string) => `Sign in to ${host} first. Nothing was linked.`,
83
+ offline: (host: string) =>
84
+ `${host} didn’t answer. Nothing was linked — try again when this Mac is online.`,
85
+ linkedElsewhere: (host: string) =>
86
+ `This project already syncs with ${host}. Unlink it there first. Nothing was linked.`,
87
+ worktree: (main: string) => `This folder syncs from ${main}. Link ${main} instead.`,
88
+ newer: (host: string) =>
89
+ `${host} runs a newer Maude than this one. Update Maude, then link again. Nothing was linked.`,
90
+ format: (host: string) =>
91
+ `${host} needs an update before this project can sync with it. Nothing was linked.`,
92
+ // 2.1.1 T14 — the server's software is current, but its project is still on the old format and only
93
+ // the project's OWNER can raise it: a member can do nothing about "needs an update"
94
+ formatOwner: (host: string) =>
95
+ `${host} is on an older format. Its owner needs to open it in Maude 2.1 once before this folder can sync. Nothing was linked.`,
96
+ expired: 'That confirmation expired. Press Link again to see what syncing would do.',
97
+ failed: 'Linking didn’t finish. Your work is still on this Mac.',
98
+ };
99
+
100
+ const CONFIRM_TTL_MS = 10 * 60_000;
101
+ const MAX_PENDING = 16;
102
+
103
+ const json = (status: number, body: unknown) =>
104
+ Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
105
+
106
+ const hostOf = (url: string) => {
107
+ try {
108
+ return new URL(url).host;
109
+ } catch {
110
+ return url;
111
+ }
112
+ };
113
+
114
+ class LinkRefusal extends Error {
115
+ constructor(
116
+ readonly status: number,
117
+ readonly reason: string,
118
+ message: string
119
+ ) {
120
+ super(message);
121
+ }
122
+ }
123
+
124
+ export function createHubLinkFolderRoutes(deps: HubLinkFolderDeps): RouteSpec[] {
125
+ const doFetch = deps.fetchImpl ?? fetch;
126
+ const now = deps.now ?? Date.now;
127
+ /** confirm code → the server it was shown for. One use; a restart forgets them (the safe way). */
128
+ const pending = new Map<string, { url: string; expires: number }>();
129
+ /** Serialises POSTs: two presses must not link twice or race the config write. */
130
+ let gate: Promise<unknown> = Promise.resolve();
131
+
132
+ const linksFile = () => deps.linksFile ?? linksPath();
133
+
134
+ /** The server this folder is linked to ON THIS MAC, or null. The committed `linkedHub` is a claim
135
+ * (a clone, a peer's edit): it counts only when this Mac's link record for the folder names the
136
+ * same server (gate-b-sec4). An unconfirmed claim is "not linked" — never "already linked", never
137
+ * "unlink it there first" pointing at a host the repo names. */
138
+ function linkedHub(): string | null {
139
+ let url: string;
140
+ try {
141
+ const cfg = JSON.parse(readFileSync(join(deps.designRoot, 'config.json'), 'utf8'));
142
+ const raw = cfg?.linkedHub?.url;
143
+ if (typeof raw !== 'string' || !raw) return null;
144
+ try {
145
+ url = normalizeUrl(raw);
146
+ } catch {
147
+ url = raw;
148
+ }
149
+ } catch {
150
+ return null;
151
+ }
152
+ if (deps.repoRoot === undefined) return url;
153
+ const rec = projectLinkOf(deps.repoRoot, linksFile());
154
+ return rec && rec.hub === normHub(url) ? url : null;
155
+ }
156
+
157
+ function mint(url: string): string {
158
+ const t = now();
159
+ for (const [k, v] of pending) if (v.expires <= t) pending.delete(k);
160
+ while (pending.size >= MAX_PENDING) {
161
+ const oldest = pending.keys().next().value;
162
+ if (oldest === undefined) break;
163
+ pending.delete(oldest);
164
+ }
165
+ const code = randomBytes(18).toString('base64url');
166
+ pending.set(code, { url, expires: t + CONFIRM_TTL_MS });
167
+ return code;
168
+ }
169
+
170
+ function redeem(code: string, url: string): boolean {
171
+ const row = pending.get(code);
172
+ if (!row) return false;
173
+ pending.delete(code); // one use, whatever the outcome
174
+ return row.url === url && row.expires > now();
175
+ }
176
+
177
+ /** V2-1.12 §5.2 — raise-only, before the first seed-up; a newer server is refused. */
178
+ async function checkFormat(url: string, token: string): Promise<void> {
179
+ const host = hostOf(url);
180
+ const client = createHubFormatClient({ url, token }, doFetch);
181
+ const health = await client.health();
182
+ if (!health.ok) throw new LinkRefusal(503, 'offline', LINK_FOLDER_WORDS.offline(host));
183
+ const hub = health.formatVersion ?? 1;
184
+ if (hub > SUPPORTED_FORMAT)
185
+ throw new LinkRefusal(409, 'format-newer', LINK_FOLDER_WORDS.newer(host));
186
+ const local = deps.localFormat();
187
+ if (!(local > 1) || hub >= local) return;
188
+ if (!health.capabilities.includes('format-v2'))
189
+ throw new LinkRefusal(409, 'format', LINK_FOLDER_WORDS.format(host));
190
+ const set = await client.setFormat(local === 2 ? 2 : 1);
191
+ if (!set.ok) {
192
+ if (set.status === 0) throw new LinkRefusal(503, 'offline', LINK_FOLDER_WORDS.offline(host));
193
+ // the owner's door: a member's bearer is refused there
194
+ if (set.status === 401 || set.status === 403)
195
+ throw new LinkRefusal(409, 'format-owner', LINK_FOLDER_WORDS.formatOwner(host));
196
+ throw new LinkRefusal(409, 'format', LINK_FOLDER_WORDS.format(host));
197
+ }
198
+ }
199
+
200
+ async function link(url: string, token: string): Promise<Response> {
201
+ await checkFormat(url, token);
202
+ const attached = await deps.attachStored(url);
203
+ const j = (attached.json ?? {}) as {
204
+ ok?: unknown;
205
+ url?: unknown;
206
+ sync?: unknown;
207
+ note?: unknown;
208
+ };
209
+ if (attached.status === 401)
210
+ throw new LinkRefusal(401, 'signed-out', LINK_FOLDER_WORDS.signedOut(hostOf(url)));
211
+ if (attached.status !== 200 || j.ok !== true || typeof j.url !== 'string')
212
+ throw new LinkRefusal(502, 'failed', LINK_FOLDER_WORDS.failed);
213
+ // the attach answer, minus anything but what the dialog reads (it carries no credential today;
214
+ // naming the fields keeps it that way if the lane's answer ever grows)
215
+ return json(200, {
216
+ ok: true,
217
+ state: 'linked',
218
+ url: j.url,
219
+ sync: j.sync ?? null,
220
+ ...(typeof j.note === 'string' ? { note: j.note } : {}),
221
+ });
222
+ }
223
+
224
+ async function handle(req: Request): Promise<Response> {
225
+ let body: { url?: unknown; confirm?: unknown } = {};
226
+ try {
227
+ const text = await req.text();
228
+ if (text.length > 4096) throw new Error('too long');
229
+ body = text.trim() ? JSON.parse(text) : {};
230
+ if (!body || typeof body !== 'object' || Array.isArray(body))
231
+ throw new Error('not an object');
232
+ } catch {
233
+ return json(400, { ok: false, reason: 'bad-request', error: LINK_FOLDER_WORDS.badAddress });
234
+ }
235
+ // 2.1.1 T8 — the one address grammar every other door uses: https, or http only on loopback (the
236
+ // credential and the whole folder never travel in clear to a remote host)
237
+ const addr = hubAddress(body.url);
238
+ if (!addr.ok)
239
+ return json(400, { ok: false, reason: 'bad-address', error: LINK_FOLDER_WORDS.badAddress });
240
+ const url = addr.url;
241
+ const host = hostOf(url);
242
+
243
+ const linked = linkedHub();
244
+ if (linked && linked === url)
245
+ return json(200, { ok: true, state: 'linked', url, already: true });
246
+ if (linked)
247
+ return json(409, {
248
+ ok: false,
249
+ reason: 'linked-elsewhere',
250
+ error: LINK_FOLDER_WORDS.linkedElsewhere(hostOf(linked)),
251
+ });
252
+
253
+ const rec = getHubRecord(url, deps.hubsConfigPath);
254
+ if (!rec?.token)
255
+ return json(401, {
256
+ ok: false,
257
+ reason: 'signed-out',
258
+ error: LINK_FOLDER_WORDS.signedOut(host),
259
+ });
260
+
261
+ try {
262
+ if (body.confirm !== undefined) {
263
+ if (typeof body.confirm !== 'string' || !redeem(body.confirm, url))
264
+ return json(409, {
265
+ ok: false,
266
+ reason: 'confirm-expired',
267
+ error: LINK_FOLDER_WORDS.expired,
268
+ });
269
+ return await link(url, rec.token);
270
+ }
271
+
272
+ const there = await surveyHub(url, rec.token, doFetch);
273
+ if (!there.ok) {
274
+ return there.reason === 'signed-out'
275
+ ? json(401, { ok: false, reason: 'signed-out', error: LINK_FOLDER_WORDS.signedOut(host) })
276
+ : json(503, { ok: false, reason: 'offline', error: LINK_FOLDER_WORDS.offline(host) });
277
+ }
278
+ // 2.1.1 T8 — the FIRST link to a server this Mac never linked always asks, with what goes up,
279
+ // whatever the server says it holds (its survey is the server's word, not the person's).
280
+ const first = !hubEverLinked(url, linksFile());
281
+ if (!holdsWork(there.survey) && !first) return await link(url, rec.token);
282
+
283
+ const counts: LinkComparison = compareSurveys(
284
+ surveyLocal(deps.designRoot, deps.canvasGroups?.()),
285
+ there.survey
286
+ );
287
+ return json(200, {
288
+ ok: true,
289
+ state: 'needs-confirm',
290
+ host,
291
+ counts,
292
+ confirm: mint(url),
293
+ // the server holds nothing: the dialog says what goes up, not what merges
294
+ ...(holdsWork(there.survey) ? {} : { empty: true }),
295
+ });
296
+ } catch (err) {
297
+ if (err instanceof LinkRefusal)
298
+ return json(err.status, { ok: false, reason: err.reason, error: err.message });
299
+ console.error(`[hub-link-folder] ${(err as Error)?.message}`);
300
+ return json(500, { ok: false, reason: 'failed', error: LINK_FOLDER_WORDS.failed });
301
+ }
302
+ }
303
+
304
+ return [
305
+ {
306
+ method: 'POST',
307
+ path: '/_api/hub/link-folder',
308
+ origin: 'main',
309
+ // the `session` class, like Move to cloud: linking your own folder is the owner's act on their own
310
+ // place; a folder already linked (the only one a hub role applies to) answers 409 first
311
+ readOnly: 'allowed',
312
+ handle(req) {
313
+ // the person's act in the Maude window: only a browser's own same-origin fetch carries this
314
+ if (req.headers.get('sec-fetch-site') !== 'same-origin')
315
+ return json(403, {
316
+ ok: false,
317
+ reason: 'window-only',
318
+ error: LINK_FOLDER_WORDS.windowOnly,
319
+ });
320
+ // #206 §5: a worktree tab syncs from its main project — linking it would make a second copy
321
+ const main = (deps.worktreeOf ?? worktreeOf)();
322
+ if (main)
323
+ return json(409, {
324
+ ok: false,
325
+ reason: 'worktree',
326
+ error: LINK_FOLDER_WORDS.worktree(main),
327
+ });
328
+ const next = gate.then(() => handle(req));
329
+ gate = next.catch(() => null);
330
+ return next;
331
+ },
332
+ },
333
+ ];
334
+ }
@@ -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
@@ -179,6 +179,14 @@ export interface ProjectUndoDeps {
179
179
  * sticky while keeping the thread (contract S4-S9-votes-comments §3.2).
180
180
  */
181
181
  guard?: (target: UndoTarget, req: Request) => Promise<Response | null>;
182
+ /**
183
+ * #216 — bring the canvas's pending writes onto the op log before the stack is read. An annotation
184
+ * gesture made with the canvas open lands in its live collab room, which reaches the op log only at
185
+ * the room's debounced flush (800 ms, re-armed by every update): ⌘Z read before it found nothing, or
186
+ * took back the step BEFORE the gesture (the stickies made inside a section the person just moved).
187
+ * http.ts wires it to that room's `flush()`. A failure never blocks the read.
188
+ */
189
+ settle?: (repoRel: string) => Promise<void>;
182
190
  }
183
191
 
184
192
  /** V2-1.5 §5.3 bus payload, from a history row (+ the attribution when known). */
@@ -356,6 +364,8 @@ export function createProjectUndoRoutes(deps: ProjectUndoDeps): RouteSpec[] {
356
364
  const since = Number(url.searchParams.get('since') ?? 0);
357
365
  const runtime = deps.control();
358
366
  if (!runtime?.acceptedHistory) return json(200, { ok: false, reason: 'legacy' });
367
+ // #216 — the canvas's live room flushed first: the gesture ⌘Z means is on the stack
368
+ await deps.settle?.(repoRel).catch(() => {});
359
369
  // P8 (board 01 cf-undo-ai) — a run whose turn just ended is on the stack before ⌘Z reads it.
360
370
  await runsLanded(runtime);
361
371
  const rows = await runtime
@@ -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
  },
@@ -78,6 +78,7 @@ import {
78
78
  terminalKeyMode,
79
79
  } from './shell/api-key.ts';
80
80
  import {
81
+ appAlreadyServes,
81
82
  isCliRole,
82
83
  registryPath,
83
84
  SERVER_ROLE_ENV,
@@ -125,6 +126,26 @@ if (process.argv.includes('--home')) {
125
126
  const ctx = createContext();
126
127
  bootStep('context');
127
128
 
129
+ // fix-bulk B2 (#206 DDR-250 decision 1, boot half) — a terminal-started server decides whether the
130
+ // app already serves this root BEFORE it writes anything (key file, `_server.json`, the store lock) or
131
+ // joins sync. It used to boot fully, overwrite the app's `_server.json`, step down 2 s later and remove
132
+ // the file it had written: the app's server was left with none. The running watcher below still
133
+ // covers an app that opens the project later.
134
+ if (!isWorkspaceMode() && isCliRole(process.env)) {
135
+ const appPort = await appAlreadyServes({
136
+ root: ctx.paths.repoRoot,
137
+ rootId: rootIdentity(ctx.paths.repoRoot),
138
+ file: registryPath(),
139
+ });
140
+ if (appPort !== null) {
141
+ console.log(
142
+ ` Maude is serving this project now (port ${appPort}) — this server is not starting.\n` +
143
+ ' `maude design open <canvas>` shows a canvas there.'
144
+ );
145
+ process.exit(0);
146
+ }
147
+ }
148
+
128
149
  // V2-2.9 (T23) — persist the per-source diagnostics (server · sync · ai · export) under
129
150
  // ~/.maude/logs (or $MAUDE_LOG_DIR), scrubbed, 7 days. Local only: nothing is sent anywhere.
130
151
  await initDiagnostics({ repoRoot: ctx.paths.repoRoot });
@@ -425,6 +446,10 @@ const http = createHttp(ctx, api, inspects, aiActivity, exportJobs, generateJobs
425
446
  runs: runRegistry,
426
447
  // V2-1.15 §4 #13 — a person's live hold (awareness `holding`) denies the AI's write
427
448
  personHolds: collab ? personHoldsOf(collab.registry, (rel) => api.fileSlug(rel)) : undefined,
449
+ // #216 — ⌘Z reads the stack after the canvas's live room has flushed its pending gesture
450
+ settleCanvasRoom: async (repoRel) => {
451
+ await collab?.registry.peek(api.fileSlug(repoRel))?.flush();
452
+ },
428
453
  });
429
454
  askQueue = http.askQueue;
430
455
  // S9.9 — `currentAccess()` outside a request (timers, boot): this process's own answer.
@@ -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 {