@north-light/api 0.3.755 → 0.3.757

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 (75) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +0 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/health.d.ts +0 -54
  6. package/dist/api/routes.d.ts +0 -1
  7. package/dist/api/routes.js +0 -1
  8. package/dist/build-root.d.ts +0 -3
  9. package/dist/build-root.js +0 -9
  10. package/dist/commands/profile/new.js +2 -2
  11. package/dist/commands/profile/project.js +2 -1
  12. package/dist/commands/sys/branch.js +1 -1
  13. package/dist/commands/sys/daemon.js +1 -1
  14. package/dist/commands/sys.js +1 -2
  15. package/dist/core/canvas/executions.d.ts +0 -3
  16. package/dist/core/canvas/executions.js +1 -17
  17. package/dist/core/canvas/pid.d.ts +0 -10
  18. package/dist/core/canvas/pid.js +0 -16
  19. package/dist/core/directory/join.js +18 -1
  20. package/dist/core/grants/mirror.d.ts +0 -5
  21. package/dist/core/grants/mirror.js +0 -7
  22. package/dist/core/grants/sync.js +2 -2
  23. package/dist/core/human/page-schema.d.ts +1 -1
  24. package/dist/core/io.js +0 -5
  25. package/dist/core/layout.d.ts +0 -2
  26. package/dist/core/layout.js +2 -19
  27. package/dist/core/profiles/manifest.js +12 -18
  28. package/dist/core/profiles/project-dir.d.ts +3 -0
  29. package/dist/core/profiles/project-dir.js +20 -0
  30. package/dist/daemon/api/map.d.ts +1 -6
  31. package/dist/daemon/api/map.js +0 -16
  32. package/dist/daemon/api/operations.js +0 -1
  33. package/dist/daemon/control.d.ts +0 -8
  34. package/dist/daemon/manage.js +1 -1
  35. package/package.json +1 -1
  36. package/dist/commands/sys/migrate.d.ts +0 -1
  37. package/dist/commands/sys/migrate.js +0 -79
  38. package/dist/core/layout-migrate/index.d.ts +0 -38
  39. package/dist/core/layout-migrate/index.js +0 -523
  40. package/dist/core/layout-migrate/paths.d.ts +0 -30
  41. package/dist/core/layout-migrate/paths.js +0 -118
  42. package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
  43. package/dist/core/layout-migrate/stored-paths.js +0 -424
  44. package/dist/core/layout-migrate/stores.d.ts +0 -30
  45. package/dist/core/layout-migrate/stores.js +0 -543
  46. package/dist/core/locked-file.d.ts +0 -27
  47. package/dist/core/locked-file.js +0 -121
  48. package/dist/core/scoped-state/db.d.ts +0 -17
  49. package/dist/core/scoped-state/db.js +0 -271
  50. package/dist/core/scoped-state/legacy-profiles.d.ts +0 -11
  51. package/dist/core/scoped-state/legacy-profiles.js +0 -65
  52. package/dist/core/scoped-state/migrate.d.ts +0 -15
  53. package/dist/core/scoped-state/migrate.js +0 -332
  54. package/dist/core/scoped-state/schema.d.ts +0 -14
  55. package/dist/core/scoped-state/schema.js +0 -52
  56. package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
  57. package/dist/migrations/004-canvas-documents/apply.js +0 -113
  58. package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
  59. package/dist/migrations/004-canvas-documents/index.js +0 -89
  60. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
  61. package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
  62. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
  63. package/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
  64. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
  65. package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
  66. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
  67. package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
  68. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
  69. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
  70. package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
  71. package/dist/migrations/004-canvas-documents/plan.js +0 -410
  72. package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
  73. package/dist/migrations/004-canvas-documents/pointers.js +0 -95
  74. package/dist/migrations/activation.d.ts +0 -17
  75. package/dist/migrations/activation.js +0 -46
@@ -1,410 +0,0 @@
1
- // The import plan: turns the frozen legacy corpus into owners, documents with
2
- // revisions and rules, and profile manifest changes, plus the blockers and the
3
- // report the dry run shows. Pure over its inputs: no db, no bodies written.
4
- // A plan with blockers is still complete, so the dry run shows everything.
5
- import { realpathSync } from 'node:fs';
6
- import { homedir } from 'node:os';
7
- import { isAbsolute, join, relative } from 'node:path';
8
- import { parseFrontmatterGeneric } from '../../core/frontmatter.js';
9
- import { handleHint } from '../../core/graph/repo-sync/identity.js';
10
- import { andIntoRules, documentFields } from './fields.js';
11
- import { rewritePointers } from './pointers.js';
12
- /** The store migrations every plan assumes already ran (the previous release's lanes). */
13
- export const CONVERGED_MARKER_IDS = ['001-surfaces-frontmatter', '002-profile-project-memory', '003-repository-root-memory-identity'];
14
- /** Delivery caps, smallest first; a disagreement keeps the larger. */
15
- const CAP_ORDER = ['none', 'name', 'preview', 'content'];
16
- function real(p) {
17
- try {
18
- return realpathSync(p);
19
- }
20
- catch {
21
- return p;
22
- }
23
- }
24
- const appHandle = (grantee) => grantee.replace(/^app:/, '');
25
- export function planImport(corpus, ctx) {
26
- const blockers = [];
27
- const counts = {};
28
- const count = (k, n = 1) => {
29
- counts[k] = (counts[k] ?? 0) + n;
30
- };
31
- const droppedFields = [];
32
- const rewrites = [];
33
- const resolutions = [];
34
- const resolve = (r) => {
35
- resolutions.push(r);
36
- count(`resolutions.${r.kind}`);
37
- };
38
- // ── preconditions and unreadable sources ─────────────────────────────────
39
- const hasContent = corpus.docs.length > 0;
40
- if (hasContent) {
41
- const ids = [...(ctx.markerIds ?? [])].sort();
42
- if (ids.join('\n') !== [...CONVERGED_MARKER_IDS].sort().join('\n')) {
43
- blockers.push({ kind: 'marker', paths: [], message: `this runtime skipped the store migrations of the previous release (on-disk-migrations.json lists ${ctx.markerIds === null ? 'nothing' : JSON.stringify(ctx.markerIds)}); start the previous crtr release once, then upgrade` });
44
- }
45
- }
46
- for (const d of corpus.docs) {
47
- if (d.invalid !== undefined) {
48
- resolve({ kind: d.invalid.kind, paths: [d.path], message: d.invalid.kind === 'invalid-source'
49
- ? `${d.path}: ${d.invalid.reason} — imported the whole file as the body, with no rules`
50
- : `${d.path}: ${d.invalid.reason} — imported the current file without its history` });
51
- }
52
- }
53
- // ── owners ────────────────────────────────────────────────────────────────
54
- // Handles are unique per owner type, so only same-type clashes need resolving.
55
- const owners = new Map();
56
- const handleOwner = new Map(); // `<type>\0<handle>` → owner key
57
- const held = (type, handle) => handleOwner.get(`${type}\0${handle}`);
58
- const hold = (type, handle, key) => { handleOwner.set(`${type}\0${handle}`, key); };
59
- const keyOfExisting = (e) => e.type === 'repo' && e.externalId !== null ? `repo:${e.externalId}`
60
- : e.type === 'person' ? 'person'
61
- : e.type === 'profile' && e.externalId !== null ? `profile:${e.externalId}`
62
- : `${e.type}:${e.handle}`;
63
- for (const e of ctx.existingOwners)
64
- hold(e.type, e.handle, keyOfExisting(e));
65
- const freeHandle = (type, wanted) => {
66
- let n = 2;
67
- while (held(type, `${wanted}-${n}`) !== undefined)
68
- n += 1;
69
- return `${wanted}-${n}`;
70
- };
71
- const claim = (owner) => {
72
- const prior = owners.get(owner.key);
73
- if (prior !== undefined)
74
- return prior;
75
- const holder = held(owner.type, owner.handle);
76
- const handle = holder !== undefined && holder !== owner.key ? freeHandle(owner.type, owner.handle) : owner.handle;
77
- const planned = { ...owner, handle };
78
- hold(planned.type, handle, planned.key);
79
- owners.set(planned.key, planned);
80
- return planned;
81
- };
82
- for (const e of ctx.existingOwners) {
83
- if (e.type === 'person')
84
- owners.set('person', { key: 'person', type: 'person', handle: e.handle });
85
- }
86
- const person = claim({ key: 'person', type: 'person', handle: 'user' });
87
- const profileById = new Map(ctx.roots.profiles.map((p) => [p.id, p]));
88
- const nodeIds = new Set(ctx.roots.nodes.map((n) => n.id));
89
- const nodeDir = new Map(ctx.roots.nodes.map((n) => [n.id, n.dir]));
90
- // Profiles sharing a display name: an existing owner keeps its handle, then the
91
- // earliest id; each later one takes its profile id as its handle.
92
- const profileHandle = new Map();
93
- for (const p of [...ctx.roots.profiles].sort((a, b) => a.id.localeCompare(b.id))) {
94
- const holder = held('profile', p.name);
95
- if (holder === undefined || holder === `profile:${p.id}`) {
96
- profileHandle.set(p.id, p.name);
97
- hold('profile', p.name, `profile:${p.id}`);
98
- continue;
99
- }
100
- const handle = held('profile', p.id) === undefined ? p.id : freeHandle('profile', p.id);
101
- profileHandle.set(p.id, handle);
102
- hold('profile', handle, `profile:${p.id}`);
103
- resolve({ kind: 'profile-handle', paths: p.manifestPath === undefined ? [] : [p.manifestPath], message: `profile ${p.id} shares the name \`${p.name}\` with ${holder}; it takes the handle \`${handle}\`` });
104
- }
105
- const repoClaims = new Map(); // owner key → claim
106
- const rootKey = new Map(); // checkout root → owner key
107
- const identify = (ref, paths) => {
108
- if (rootKey.has(ref.root))
109
- return;
110
- // A folder git does not recognize as a checkout (no `.git`, or a linked
111
- // worktree whose git dir was pruned) is a local-path repo, like a folder with no remote.
112
- const id = ref.commonDir === null
113
- ? { ok: false, code: 'not-a-repo', dir: ref.root, reason: 'no .git' }
114
- : ctx.repoIdentity(ref.root);
115
- let scheme = 'local-path';
116
- let externalId = real(ref.root);
117
- let hint = handleHint(externalId);
118
- if (id.ok) {
119
- scheme = id.scheme;
120
- externalId = id.externalId;
121
- hint = id.handleHint;
122
- }
123
- else if (id.code !== 'not-a-repo') {
124
- resolve({ kind: 'repo-identity', paths, message: `${ref.root}: repo identity lookup failed (${id.code}: ${id.reason}); imported as the local-path repo ${externalId}` });
125
- }
126
- const key = `repo:${externalId}`;
127
- rootKey.set(ref.root, key);
128
- const existing = ctx.existingOwners.find((e) => e.type === 'repo' && e.externalId === externalId);
129
- const prior = repoClaims.get(key);
130
- if (prior !== undefined)
131
- prior.roots.push(ref.root);
132
- else
133
- repoClaims.set(key, { key, scheme, externalId, wanted: existing?.handle ?? ref.namespace ?? hint, roots: [ref.root] });
134
- };
135
- for (const s of corpus.storeRoots)
136
- if (s.owner.type === 'repo' && s.skipped === undefined)
137
- identify(s.owner, [s.root]);
138
- for (const d of corpus.docs)
139
- if (d.owner.type === 'repo')
140
- identify(d.owner, [d.path]);
141
- const renamedRepos = new Map(); // owner key → handle change
142
- const byWanted = new Map();
143
- for (const c of repoClaims.values())
144
- byWanted.set(c.wanted, [...(byWanted.get(c.wanted) ?? []), c]);
145
- for (const [wanted, claims] of [...byWanted].sort(([a], [b]) => a.localeCompare(b))) {
146
- // Existing owner first, then git identity over local-path, then external id.
147
- const rank = (c) => (held('repo', wanted) === c.key ? 0 : c.scheme === 'git' ? 1 : 2);
148
- claims.sort((a, b) => rank(a) - rank(b) || a.externalId.localeCompare(b.externalId));
149
- for (const c of claims) {
150
- const planned = claim({ key: c.key, type: 'repo', handle: wanted, scheme: c.scheme, externalId: c.externalId });
151
- if (planned.handle === wanted)
152
- continue;
153
- renamedRepos.set(c.key, { from: wanted, to: planned.handle });
154
- resolve({ kind: 'repo-handle', paths: c.roots, message: `repo ${c.externalId} (${c.roots.join(', ')}) wanted the handle \`${wanted}\`, held by ${held('repo', wanted)}; it takes \`${planned.handle}\` and its documents' \`[[${wanted}/…]]\` links are rewritten to match` });
155
- }
156
- }
157
- const repoOwners = new Map(); // checkout root → owner
158
- for (const [root, key] of rootKey)
159
- repoOwners.set(root, owners.get(key));
160
- const repoOwner = (ref) => repoOwners.get(ref.root);
161
- const profileOwner = (id) => {
162
- const p = profileById.get(id);
163
- const app = claim({ key: `app:${appHandle(p?.app ?? 'app:terminal')}`, type: 'app', handle: appHandle(p?.app ?? 'app:terminal') });
164
- return claim({ key: `profile:${id}`, type: 'profile', handle: profileHandle.get(id) ?? p?.name ?? id, ownerKey: app.key });
165
- };
166
- const ownerFor = (doc) => {
167
- switch (doc.owner.type) {
168
- case 'person': return person;
169
- case 'profile': return profileOwner(doc.owner.id);
170
- case 'repo': return repoOwner(doc.owner);
171
- case 'node': return claim({ key: `node:${doc.owner.id}`, type: 'node', handle: doc.owner.id });
172
- }
173
- };
174
- // Separate clones of one repo (same identity, different git dirs) import once,
175
- // from the clone whose store was changed most recently; the rest are reported.
176
- const newest = new Map(); // checkout root → newest doc mtime
177
- for (const d of corpus.docs) {
178
- if (d.owner.type === 'repo' && d.mtime > (newest.get(d.owner.root) ?? ''))
179
- newest.set(d.owner.root, d.mtime);
180
- }
181
- const chosenClone = new Map(); // owner key → checkout root
182
- for (const [root, owner] of repoOwners) {
183
- const prior = chosenClone.get(owner.key);
184
- if (prior === undefined || (newest.get(root) ?? '') > (newest.get(prior) ?? ''))
185
- chosenClone.set(owner.key, root);
186
- }
187
- const skipped = [...corpus.skipped];
188
- const cloneSkipped = new Set();
189
- const drafts = [];
190
- const byName = new Map(); // `<ownerKey>\0<name>` → draft holding that name
191
- for (const doc of corpus.docs) {
192
- const owner = ownerFor(doc);
193
- if (doc.owner.type === 'repo' && chosenClone.get(owner.key) !== doc.owner.root) {
194
- if (!cloneSkipped.has(doc.owner.root)) {
195
- cloneSkipped.add(doc.owner.root);
196
- skipped.push({ path: doc.owner.root, reason: `duplicate-clone: ${owner.handle} imports from ${chosenClone.get(owner.key)}` });
197
- }
198
- count('documents.duplicate-clone');
199
- continue;
200
- }
201
- let ownerKey = owner.key;
202
- let name = doc.name;
203
- const isReport = doc.source === 'report';
204
- // An unreadable source keeps its whole file as the body and gets no rules.
205
- const fields = documentFields(doc.invalid?.kind === 'invalid-source' ? null : doc.frontmatter, doc.body, {
206
- ...(isReport ? { kind: 'report' } : {}),
207
- missingPrivacy: owner.type === 'repo' ? 'public' : 'private',
208
- });
209
- for (const field of fields.dropped)
210
- droppedFields.push({ path: doc.path, field });
211
- let rules = fields.rules;
212
- let preview = fields.preview;
213
- if (doc.source === 'context' && name === 'roadmap') {
214
- rules = [...rules, { on: 'boot', deliver: 'content' }];
215
- preview = preview || `The roadmap of node ${owner.handle}`;
216
- }
217
- // A document needs a preview; an empty source (no text and no
218
- // when-and-why-to-read) previews as its name.
219
- if (preview.trim() === '') {
220
- preview = doc.name;
221
- resolve({ kind: 'empty-preview', paths: [doc.path], message: `${doc.path} has no text to preview; its preview is its name, ${doc.name}` });
222
- }
223
- // A repo owns only public documents: a non-public one stays the person's
224
- // and loads in the repo through its rules.
225
- if (owner.type === 'repo' && fields.privacy !== 'public') {
226
- rules = andIntoRules(rules, { repo: owner.handle });
227
- ownerKey = person.key;
228
- name = `${owner.handle}/${name}`;
229
- count('documents.private-repo-to-person');
230
- }
231
- const revisions = revisionsOf(doc, nodeIds, resolve);
232
- const ownerHandle = owners.get(ownerKey).handle;
233
- const draft = {
234
- doc,
235
- qualified: `${ownerHandle}/${name}`,
236
- contextDir: doc.owner.type === 'node' ? join(nodeDir.get(doc.owner.id) ?? '', 'context') : null,
237
- repoKey: doc.owner.type === 'repo' ? owner.key : null,
238
- planned: {
239
- ownerKey, name, kind: fields.kind, privacy: fields.privacy, preview, summary: fields.summary, whyItExists: fields.whyItExists,
240
- unlisted: fields.unlisted, lintIgnore: fields.lintIgnore, extensions: fields.extensions, rules, revisions, sourcePath: doc.path,
241
- },
242
- };
243
- // Two sources importing as one name: the newer by mtime keeps it, the older
244
- // imports as `<name>.conflict-<n>`.
245
- const key = `${ownerKey}\0${name}`;
246
- const prior = byName.get(key);
247
- if (prior !== undefined) {
248
- const older = prior.doc.mtime <= doc.mtime ? prior : draft;
249
- let n = 1;
250
- while (byName.has(`${ownerKey}\0${name}.conflict-${n}`))
251
- n += 1;
252
- older.planned.name = `${name}.conflict-${n}`;
253
- older.qualified = `${ownerHandle}/${older.planned.name}`;
254
- byName.set(`${ownerKey}\0${older.planned.name}`, older);
255
- byName.set(key, older === prior ? draft : prior);
256
- resolve({ kind: 'name-clash', paths: [prior.doc.path, doc.path], message: `${prior.doc.path} and ${doc.path} both import as \`${ownerHandle}/${name}\`; the newer keeps the name and ${older.doc.path} imports as \`${older.planned.name}\`` });
257
- }
258
- else {
259
- byName.set(key, draft);
260
- }
261
- drafts.push(draft);
262
- count(`documents.${fields.kind}`);
263
- count(`documents.owner.${owners.get(ownerKey).type}`);
264
- count('revisions', revisions.length);
265
- }
266
- // ── pointer rewrite of head bodies ────────────────────────────────────────
267
- const byPath = new Map();
268
- const reports = new Set();
269
- const indexHandles = new Set();
270
- for (const d of drafts) {
271
- byPath.set(d.doc.path, d.qualified);
272
- byPath.set(real(d.doc.path), d.qualified);
273
- if (d.doc.source === 'report')
274
- reports.add(d.qualified);
275
- const owner = owners.get(d.planned.ownerKey);
276
- if (d.planned.name === 'index' && owner.type !== 'node')
277
- indexHandles.add(owner.handle);
278
- }
279
- const targets = { byPath, reports, indexHandles, home: ctx.home ?? homedir(), real };
280
- for (const d of drafts) {
281
- const head = d.planned.revisions[d.planned.revisions.length - 1];
282
- const r = rewritePointers(head.body, targets, { contextDir: d.contextDir });
283
- // A repo that yielded its wanted handle: its own documents' links to that handle follow it.
284
- const renamed = d.repoKey === null ? undefined : renamedRepos.get(d.repoKey);
285
- if (renamed !== undefined) {
286
- const from = `[[${renamed.from}/`;
287
- const to = `[[${renamed.to}/`;
288
- if (r.body.includes(from)) {
289
- r.body = r.body.split(from).join(to);
290
- r.rewrites.push({ from, to });
291
- }
292
- }
293
- if (r.rewrites.length === 0)
294
- continue;
295
- head.body = r.body;
296
- for (const w of r.rewrites)
297
- rewrites.push({ path: d.doc.path, ...w });
298
- count('documents.rewritten');
299
- }
300
- // ── profile.json projects[].memory → stored delivery_limits[<repo handle>] ─
301
- const profileLimits = [];
302
- const stored = new Map(ctx.storedProfiles.map((p) => [p.id, p.deliveryLimits]));
303
- for (const p of ctx.roots.profiles) {
304
- if (p.raw === undefined || p.manifestPath === undefined)
305
- continue;
306
- const projects = Array.isArray(p.raw['projects']) ? p.raw['projects'] : [];
307
- if (!projects.some((e) => e !== null && typeof e === 'object' && 'memory' in e))
308
- continue;
309
- const current = stored.get(p.id);
310
- if (current === undefined) {
311
- skipped.push({ path: p.manifestPath, reason: `profile-not-stored: profile ${p.id} has a manifest but no stored profile row; its memory caps are not carried over` });
312
- continue;
313
- }
314
- const limits = { ...current };
315
- const limitFrom = new Map();
316
- projects.forEach((e) => {
317
- if (e === null || typeof e !== 'object' || !('memory' in e))
318
- return e;
319
- const { memory, ...rest } = e;
320
- if (memory === 'content' || typeof rest.path !== 'string')
321
- return rest;
322
- const handle = projectHandle(rest.path, ctx, repoOwners);
323
- if (handle === null) {
324
- // The cap governed that folder's project store, and it has none: nothing to carry over.
325
- skipped.push({ path: p.manifestPath, reason: `delivery-limit-dropped: project ${rest.path} (memory ${String(memory)}) is in no repo and has no project store` });
326
- return rest;
327
- }
328
- const prior = limits[handle];
329
- if (prior !== undefined && prior !== memory) {
330
- const larger = CAP_ORDER.indexOf(String(memory)) > CAP_ORDER.indexOf(prior) ? String(memory) : prior;
331
- resolve({ kind: 'delivery-limit', paths: [p.manifestPath], message: `profile ${p.name}: ${limitFrom.get(handle) ?? 'delivery_limits'} and ${rest.path} both map to repo \`${handle}\` with different memory caps (${prior}, ${String(memory)}); kept the larger, ${larger}` });
332
- if (larger === prior)
333
- return rest;
334
- }
335
- limits[handle] = String(memory);
336
- limitFrom.set(handle, rest.path);
337
- return rest;
338
- });
339
- if (Object.keys(limits).some((h) => limits[h] !== current[h]))
340
- profileLimits.push({ profileId: p.id, deliveryLimits: limits });
341
- }
342
- count('profile-limits', profileLimits.length);
343
- counts['stores'] = corpus.storeRoots.filter((s) => s.skipped === undefined).length;
344
- counts['stores.duplicate-worktree'] = corpus.storeRoots.filter((s) => s.skipped !== undefined).length;
345
- counts['owners'] = owners.size;
346
- counts['orphan-history'] = corpus.orphanHistory;
347
- counts['orphan-node-dirs'] = corpus.orphanNodeDirs;
348
- counts['non-markdown'] = corpus.nonMarkdown;
349
- counts['exposure-ledgers-not-imported'] = corpus.injectedDocs;
350
- return {
351
- owners: [...owners.values()],
352
- documents: drafts.map((d) => d.planned),
353
- profileLimits,
354
- blockers,
355
- report: { stores: corpus.storeRoots, counts, rewrites, droppedFields, skipped, resolutions },
356
- };
357
- }
358
- /** Repo handle a profile project path's memory cap moves to. */
359
- function projectHandle(path, ctx, repoOwners) {
360
- // A planned repo whose checkout encloses the path (nearest first).
361
- const p = real(path);
362
- let best = null;
363
- for (const [root, owner] of repoOwners) {
364
- const rel = relative(real(root), p);
365
- if ((rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) && (best === null || root.length > best.root.length))
366
- best = { root, owner };
367
- }
368
- const id = ctx.repoIdentity(p);
369
- if (id.ok) {
370
- const planned = [...repoOwners.values()].find((o) => o.externalId === id.externalId);
371
- if (planned)
372
- return planned.handle;
373
- const existing = ctx.existingOwners.find((e) => e.type === 'repo' && e.externalId === id.externalId);
374
- return existing?.handle ?? id.handleHint;
375
- }
376
- return best?.owner.handle ?? null;
377
- }
378
- /** Revisions of one legacy document, oldest first (§2 "Revisions"). */
379
- function revisionsOf(doc, nodeIds, resolve) {
380
- const author = (id) => (typeof id === 'string' && nodeIds.has(id) ? id : null);
381
- if (doc.source !== 'store') {
382
- return [{ body: doc.body, authorNodeId: doc.owner.type === 'node' && nodeIds.has(doc.owner.id) ? doc.owner.id : null, rationale: null, createdAt: doc.mtime }];
383
- }
384
- const revs = [];
385
- for (const r of doc.history) {
386
- if (r.op !== 'create' && r.op !== 'edit' && r.op !== 'move')
387
- continue;
388
- let body;
389
- try {
390
- body = parseFrontmatterGeneric(r.after).body;
391
- }
392
- catch (e) {
393
- resolve({ kind: 'invalid-history', paths: [doc.path], message: `${doc.path}: history record at ${r.at} has invalid frontmatter (${e.message}); imported the current file without its history` });
394
- return [{ body: doc.body, authorNodeId: null, rationale: null, createdAt: doc.mtime }];
395
- }
396
- if (revs.length > 0 && revs[revs.length - 1].body === body)
397
- continue;
398
- revs.push({ body, authorNodeId: author(r.node), rationale: r.rationale ?? null, createdAt: r.at });
399
- }
400
- if (revs.length === 0) {
401
- const origin = (doc.frontmatter?.['origin'] ?? {});
402
- const stamp = (v) => (typeof v === 'string' ? v : v instanceof Date ? v.toISOString() : null);
403
- const at = stamp(origin['created']) ?? stamp(doc.frontmatter?.['last-updated']) ?? doc.mtime;
404
- return [{ body: doc.body, authorNodeId: author(origin['node']), rationale: null, createdAt: at }];
405
- }
406
- if (revs[revs.length - 1].body !== doc.body) {
407
- revs.push({ body: doc.body, authorNodeId: null, rationale: 'changed outside crtr before import', createdAt: doc.mtime });
408
- }
409
- return revs;
410
- }
@@ -1,23 +0,0 @@
1
- export interface PointerTargets {
2
- /** Absolute file path (as read and realpath) → qualified document name. */
3
- byPath: ReadonlyMap<string, string>;
4
- /** `<node-id>/reports/<stem>` of every imported report. */
5
- reports: ReadonlySet<string>;
6
- /** Owner handles that have an imported `index` document. */
7
- indexHandles: ReadonlySet<string>;
8
- home: string;
9
- /** Resolve symlinks of a path that is not in `byPath` as written; returns the input when it does not exist. */
10
- real: (path: string) => string;
11
- }
12
- export interface PointerContext {
13
- /** The node folder's `context/` dir when the document is owned by a node (for `$CRTR_CONTEXT_DIR/…`). */
14
- contextDir: string | null;
15
- }
16
- /** Rewrite one head body; `rewrites` receives every replacement made. */
17
- export declare function rewritePointers(body: string, t: PointerTargets, ctx: PointerContext): {
18
- body: string;
19
- rewrites: Array<{
20
- from: string;
21
- to: string;
22
- }>;
23
- };
@@ -1,95 +0,0 @@
1
- // Head-body pointer rewrite: a path or report ref naming a file this import
2
- // brings in becomes `[[<qualified name>]]`; `[[<handle>]]` naming an owner
3
- // with an imported front-door document becomes `[[<handle>/index]]`. Fenced
4
- // code blocks are left as they are; an inline code span whose whole content
5
- // is such a pointer is replaced span and all. Paths to files the import does
6
- // not bring in stay text.
7
- import { join } from 'node:path';
8
- // A pointer may end a sentence: a trailing `.` counts as its end unless a name character follows it.
9
- const PATH_RE = /(?<![\w./$-])((?:~|\$CRTR_CONTEXT_DIR|\$\{CRTR_CONTEXT_DIR\})?\/[^\s()[\]<>`'"]*?\.md)(?![\w-]|\.[\w-])/g;
10
- const REPORT_RE = /(?<![\w/-])([a-z0-9]+(?:-[a-z0-9]+)+):reports\/([A-Za-z0-9._-]+?)(?:\.md)?(?![\w-]|\.[\w-])/g;
11
- const HANDLE_LINK_RE = /\[\[([^\]|#/\s]+)((?:[|#][^\]]*)?)\]\]/g;
12
- function resolvePointer(raw, t, ctx) {
13
- let abs;
14
- if (raw.startsWith('~/'))
15
- abs = join(t.home, raw.slice(2));
16
- else if (raw.startsWith('$')) {
17
- if (ctx.contextDir === null)
18
- return null;
19
- abs = join(ctx.contextDir, raw.slice(raw.indexOf('/') + 1));
20
- }
21
- else
22
- abs = raw;
23
- return t.byPath.get(abs) ?? t.byPath.get(t.real(abs)) ?? null;
24
- }
25
- function resolveReport(node, base, t) {
26
- const name = `${node}/reports/${base}`;
27
- return t.reports.has(name) ? name : null;
28
- }
29
- function rewriteText(text, t, ctx, rewrites) {
30
- const sub = (from, to) => {
31
- if (to === null)
32
- return from;
33
- rewrites.push({ from, to: `[[${to}]]` });
34
- return `[[${to}]]`;
35
- };
36
- return text
37
- .replace(PATH_RE, (m, raw) => sub(m, resolvePointer(raw, t, ctx)))
38
- .replace(REPORT_RE, (m, node, base) => sub(m, resolveReport(node, base, t)))
39
- .replace(HANDLE_LINK_RE, (m, handle, rest) => {
40
- if (!t.indexHandles.has(handle))
41
- return m;
42
- const to = `[[${handle}/index${rest}]]`;
43
- rewrites.push({ from: m, to });
44
- return to;
45
- });
46
- }
47
- function rewriteCodeSpan(span, inner, t, ctx, rewrites) {
48
- const v = inner.trim();
49
- const report = /^([a-z0-9]+(?:-[a-z0-9]+)+):reports\/([A-Za-z0-9._-]+?)(?:\.md)?$/.exec(v);
50
- const target = report !== null ? resolveReport(report[1], report[2], t)
51
- : /^(?:~|\$CRTR_CONTEXT_DIR|\$\{CRTR_CONTEXT_DIR\})?\/\S*\.md$/.test(v) ? resolvePointer(v, t, ctx) : null;
52
- if (target === null)
53
- return span;
54
- rewrites.push({ from: span, to: `[[${target}]]` });
55
- return `[[${target}]]`;
56
- }
57
- /** Rewrite one head body; `rewrites` receives every replacement made. */
58
- export function rewritePointers(body, t, ctx) {
59
- const rewrites = [];
60
- const out = [];
61
- let fence = null;
62
- let prose = [];
63
- const flush = () => {
64
- if (prose.length === 0)
65
- return;
66
- const text = prose.join('\n');
67
- const parts = [];
68
- let last = 0;
69
- for (const m of text.matchAll(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g)) {
70
- parts.push(rewriteText(text.slice(last, m.index), t, ctx, rewrites));
71
- parts.push(rewriteCodeSpan(m[0], m[2], t, ctx, rewrites));
72
- last = m.index + m[0].length;
73
- }
74
- parts.push(rewriteText(text.slice(last), t, ctx, rewrites));
75
- out.push(parts.join(''));
76
- prose = [];
77
- };
78
- for (const line of body.split('\n')) {
79
- const marker = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
80
- if (fence === null && marker !== undefined) {
81
- flush();
82
- fence = marker;
83
- out.push(line);
84
- }
85
- else if (fence !== null) {
86
- out.push(line);
87
- if (marker !== undefined && marker[0] === fence[0] && marker.length >= fence.length && line.trim() === marker)
88
- fence = null;
89
- }
90
- else
91
- prose.push(line);
92
- }
93
- flush();
94
- return { body: out.join('\n'), rewrites };
95
- }
@@ -1,17 +0,0 @@
1
- import { type CanvasImportResult } from './004-canvas-documents/index.js';
2
- export type { CanvasImportResult } from './004-canvas-documents/index.js';
3
- /** A migration blocker is a STANDING condition, not a transient fault: the same
4
- * stores produce the same blockers on every boot, so a caller that retries a
5
- * daemon start against one retries forever. Typing it lets the startup path
6
- * tell "try again" apart from "this needs a human", and carry the repair line
7
- * to whoever can act on it. */
8
- export declare class MigrationBlockedError extends Error {
9
- readonly blockerPaths: readonly string[];
10
- constructor(message: string, blockerPaths: readonly string[]);
11
- }
12
- /** Startup: import the legacy stores unless already recorded. Throws `MigrationBlockedError` when the plan has blockers. */
13
- export declare function activateCanvasImport(): Promise<CanvasImportResult | null>;
14
- /** `crtr sys migrate`: plan (and unless `dryRun`, apply) regardless of startup state. */
15
- export declare function runForcedCanvasImport(opts: {
16
- dryRun: boolean;
17
- }): Promise<CanvasImportResult>;
@@ -1,46 +0,0 @@
1
- import { mkdirSync } from 'node:fs';
2
- import { dirname } from 'node:path';
3
- import { onDiskMigrationLockPath } from '../core/canvas/paths.js';
4
- import { withExclusiveDirectoryLockAsync } from '../core/exclusive-lock.js';
5
- import { DAEMON_STARTUP_WINDOW_MS } from '../daemon/startup-policy.js';
6
- import { canvasImportDone, runCanvasImport } from './004-canvas-documents/index.js';
7
- /** A migration blocker is a STANDING condition, not a transient fault: the same
8
- * stores produce the same blockers on every boot, so a caller that retries a
9
- * daemon start against one retries forever. Typing it lets the startup path
10
- * tell "try again" apart from "this needs a human", and carry the repair line
11
- * to whoever can act on it. */
12
- export class MigrationBlockedError extends Error {
13
- blockerPaths;
14
- constructor(message, blockerPaths) {
15
- super(message);
16
- this.name = 'MigrationBlockedError';
17
- this.blockerPaths = blockerPaths;
18
- }
19
- }
20
- function coordinate(body) {
21
- const lockPath = onDiskMigrationLockPath();
22
- mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
23
- return withExclusiveDirectoryLockAsync(lockPath, async () => body(), {
24
- timeoutMs: DAEMON_STARTUP_WINDOW_MS,
25
- timeoutError: () => new Error(`timed out waiting for the canvas import lock: ${lockPath}`),
26
- });
27
- }
28
- /** Startup: import the legacy stores unless already recorded. Throws `MigrationBlockedError` when the plan has blockers. */
29
- export async function activateCanvasImport() {
30
- return await coordinate(async () => {
31
- if (await canvasImportDone())
32
- return null;
33
- const result = await runCanvasImport({ dryRun: false });
34
- if (result.blockers.length > 0) {
35
- const paths = [...new Set(result.blockers.flatMap((b) => b.paths))];
36
- const lines = [`canvas import (004-canvas-documents) blocked by ${result.blockers.length} finding(s)`, ...result.blockers.map((b) => `${b.kind}: ${b.message}`)];
37
- lines.push('Repair each finding, then: crtr sys migrate --dry-run, then crtr sys migrate');
38
- throw new MigrationBlockedError(lines.join('\n'), paths);
39
- }
40
- return result;
41
- });
42
- }
43
- /** `crtr sys migrate`: plan (and unless `dryRun`, apply) regardless of startup state. */
44
- export async function runForcedCanvasImport(opts) {
45
- return await coordinate(async () => await runCanvasImport(opts));
46
- }