@inventarch/runtime 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +11 -2
  4. package/SPEC.md +77 -0
  5. package/dist/authoring/index.d.ts +159 -0
  6. package/dist/authoring/index.d.ts.map +1 -0
  7. package/dist/authoring/index.js +416 -0
  8. package/dist/authoring/index.js.map +1 -0
  9. package/dist/authoring-execution/execution.d.ts +12 -0
  10. package/dist/authoring-execution/execution.d.ts.map +1 -0
  11. package/dist/authoring-execution/execution.js +73 -0
  12. package/dist/authoring-execution/execution.js.map +1 -0
  13. package/dist/authoring-execution/index.d.ts +6 -0
  14. package/dist/authoring-execution/index.d.ts.map +1 -0
  15. package/dist/authoring-execution/index.js +6 -0
  16. package/dist/authoring-execution/index.js.map +1 -0
  17. package/dist/authoring-execution/inventory.d.ts +5 -0
  18. package/dist/authoring-execution/inventory.d.ts.map +1 -0
  19. package/dist/authoring-execution/inventory.js +41 -0
  20. package/dist/authoring-execution/inventory.js.map +1 -0
  21. package/dist/authoring-execution/shared.d.ts +22 -0
  22. package/dist/authoring-execution/shared.d.ts.map +1 -0
  23. package/dist/authoring-execution/shared.js +101 -0
  24. package/dist/authoring-execution/shared.js.map +1 -0
  25. package/dist/authoring-execution/types.d.ts +43 -0
  26. package/dist/authoring-execution/types.d.ts.map +1 -0
  27. package/dist/authoring-execution/types.js +21 -0
  28. package/dist/authoring-execution/types.js.map +1 -0
  29. package/dist/candidate.d.ts +49 -0
  30. package/dist/candidate.d.ts.map +1 -0
  31. package/dist/candidate.js +158 -0
  32. package/dist/candidate.js.map +1 -0
  33. package/dist/classify.d.ts +12 -0
  34. package/dist/classify.d.ts.map +1 -0
  35. package/dist/classify.js +21 -0
  36. package/dist/classify.js.map +1 -0
  37. package/dist/collect.d.ts +16 -0
  38. package/dist/collect.d.ts.map +1 -0
  39. package/dist/collect.js +133 -0
  40. package/dist/collect.js.map +1 -0
  41. package/dist/context.d.ts +5 -0
  42. package/dist/context.d.ts.map +1 -0
  43. package/dist/context.js +124 -0
  44. package/dist/context.js.map +1 -0
  45. package/dist/coordinate.d.ts +21 -0
  46. package/dist/coordinate.d.ts.map +1 -0
  47. package/dist/coordinate.js +40 -0
  48. package/dist/coordinate.js.map +1 -0
  49. package/dist/door.d.ts +17 -0
  50. package/dist/door.d.ts.map +1 -0
  51. package/dist/door.js +217 -0
  52. package/dist/door.js.map +1 -0
  53. package/dist/editor/index.d.ts +5 -0
  54. package/dist/editor/index.d.ts.map +1 -0
  55. package/dist/editor/index.js +4 -0
  56. package/dist/editor/index.js.map +1 -0
  57. package/dist/editor/types.d.ts +226 -0
  58. package/dist/editor/types.d.ts.map +1 -0
  59. package/dist/editor/types.js +2 -0
  60. package/dist/editor/types.js.map +1 -0
  61. package/dist/editor/workspace.d.ts +46 -0
  62. package/dist/editor/workspace.d.ts.map +1 -0
  63. package/dist/editor/workspace.js +903 -0
  64. package/dist/editor/workspace.js.map +1 -0
  65. package/dist/entry.d.ts +9 -0
  66. package/dist/entry.d.ts.map +1 -0
  67. package/dist/entry.js +26 -0
  68. package/dist/entry.js.map +1 -0
  69. package/dist/errors.d.ts +8 -0
  70. package/dist/errors.d.ts.map +1 -0
  71. package/dist/errors.js +15 -0
  72. package/dist/errors.js.map +1 -0
  73. package/dist/index.d.ts +25 -0
  74. package/dist/index.d.ts.map +1 -0
  75. package/dist/index.js +14 -0
  76. package/dist/index.js.map +1 -0
  77. package/dist/machine-protocol.d.ts +33 -0
  78. package/dist/machine-protocol.d.ts.map +1 -0
  79. package/dist/machine-protocol.js +339 -0
  80. package/dist/machine-protocol.js.map +1 -0
  81. package/dist/mentions.d.ts +20 -0
  82. package/dist/mentions.d.ts.map +1 -0
  83. package/dist/mentions.js +79 -0
  84. package/dist/mentions.js.map +1 -0
  85. package/dist/publication.d.ts +22 -0
  86. package/dist/publication.d.ts.map +1 -0
  87. package/dist/publication.js +275 -0
  88. package/dist/publication.js.map +1 -0
  89. package/dist/render.d.ts +9 -0
  90. package/dist/render.d.ts.map +1 -0
  91. package/dist/render.js +78 -0
  92. package/dist/render.js.map +1 -0
  93. package/dist/select.d.ts +16 -0
  94. package/dist/select.d.ts.map +1 -0
  95. package/dist/select.js +55 -0
  96. package/dist/select.js.map +1 -0
  97. package/dist/steward.d.ts +22 -0
  98. package/dist/steward.d.ts.map +1 -0
  99. package/dist/steward.js +45 -0
  100. package/dist/steward.js.map +1 -0
  101. package/dist/types.d.ts +97 -0
  102. package/dist/types.d.ts.map +1 -0
  103. package/dist/types.js +10 -0
  104. package/dist/types.js.map +1 -0
  105. package/package.json +161 -3
@@ -0,0 +1,903 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { existsSync, lstatSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { INSTALL_PATHS } from '@inventarch/db/distribution';
5
+ import { EditorDatabase } from '@inventarch/db/editor';
6
+ import { AXES, CONDITION_AXES, PHASES, PRIMITIVES, VERB_PHRASES, consentFor, parse, valuesFor, verbOf, } from '@inventarch/language';
7
+ import { contains, cursorContext, draftSource, format, lineRange, projectSource, recordsIn, } from '@inventarch/language/editor';
8
+ import { cell, conditionHolds, reaches, stableSerialize, validateCoordinate } from '@inventarch/graph';
9
+ import { evaluateSteward } from '../steward.js';
10
+ const hash = (text) => createHash('sha256').update(text).digest('hex');
11
+ const occurrence = (path, line, discriminator, name) => JSON.stringify([path, line, discriminator, name]);
12
+ const locationOf = (path) => path.slice(0, Math.max(0, path.lastIndexOf('/')));
13
+ const escaped = (text) => text.replace(/[\\`*_{}\[\]()<>#+.!|]/g, '\\$&');
14
+ const same = (a, b) => stableSerialize(a) === stableSerialize(b);
15
+ export class EditorError extends Error {
16
+ code;
17
+ constructor(code, message) {
18
+ super(message);
19
+ this.code = code;
20
+ this.name = 'EditorError';
21
+ }
22
+ }
23
+ export class EditorWorkspace {
24
+ ownerSession = randomUUID();
25
+ root;
26
+ #db;
27
+ #projections = new Map();
28
+ #lines = new Map();
29
+ #sources;
30
+ #actions = new Map();
31
+ #actionKeys = new Map();
32
+ #nodeIndexes = new Map();
33
+ #views = new Map();
34
+ #closed = false;
35
+ #writableSystems;
36
+ constructor(root, options = {}) {
37
+ this.#db = new EditorDatabase(root, options);
38
+ this.root = this.#db.root;
39
+ this.#writableSystems = new Set(options.writableSystems ?? []);
40
+ }
41
+ #instanceTarget(system) {
42
+ const view = this.#db.current.inspect(), declaration = view.graph.registry.systems.get(system);
43
+ if (!declaration || !view.admittedSystems.includes(system))
44
+ return false;
45
+ const source = this.sources.find((s) => s.path === declaration.path);
46
+ return (this.#writableSystems.has(system) || (source?.writable === true && source.location.placement.kind === 'authored'));
47
+ }
48
+ get sources() {
49
+ this.#assertOpen();
50
+ return this.#db.current.sources;
51
+ }
52
+ #assertOpen() {
53
+ if (this.#closed)
54
+ throw new EditorError('unavailable', 'Workspace owner has been removed');
55
+ }
56
+ #location(path) {
57
+ const directory = locationOf(path);
58
+ return this.sources.some((s) => s.location.placement.reach !== '' && reaches(s.location.placement.reach, directory))
59
+ ? directory
60
+ : '';
61
+ }
62
+ #sourceIndex() {
63
+ this.#assertOpen();
64
+ return (this.#sources ??= new Map(this.sources.map((s) => [s.path, s])));
65
+ }
66
+ sourceText(path) {
67
+ return this.#sourceIndex().get(path)?.text;
68
+ }
69
+ #source(path) {
70
+ const source = this.#sourceIndex().get(path);
71
+ if (source === undefined)
72
+ throw new EditorError('unavailable', 'Source is no longer in this workspace');
73
+ return source;
74
+ }
75
+ #project(path) {
76
+ let projected = this.#projections.get(path);
77
+ if (projected === undefined) {
78
+ projected = projectSource(this.#source(path).text, path);
79
+ this.#projections.set(path, projected);
80
+ }
81
+ return projected;
82
+ }
83
+ #sourceLines(path) {
84
+ let lines = this.#lines.get(path);
85
+ if (!lines) {
86
+ lines = this.#source(path).text.split(/\r?\n/);
87
+ this.#lines.set(path, lines);
88
+ }
89
+ return lines;
90
+ }
91
+ update(overlays, refresh = false) {
92
+ this.#assertOpen();
93
+ this.#db.update(overlays, refresh);
94
+ this.#sources = undefined;
95
+ this.#projections.clear();
96
+ this.#lines.clear();
97
+ this.#actions.clear();
98
+ this.#actionKeys.clear();
99
+ this.#nodeIndexes.clear();
100
+ this.#views.clear();
101
+ return this.stamp();
102
+ }
103
+ stamp(location = '', phase = null) {
104
+ this.#assertOpen();
105
+ return {
106
+ protocol: 1,
107
+ ownerSession: this.ownerSession,
108
+ generation: this.#db.generation,
109
+ savedRevision: this.#db.savedRevision,
110
+ viewRevision: this.#db.current.snapshot({ root: location, phase }).revision,
111
+ location,
112
+ phase,
113
+ };
114
+ }
115
+ assertStamp(stamp) {
116
+ if (stamp === null ||
117
+ typeof stamp !== 'object' ||
118
+ stamp.protocol !== 1 ||
119
+ stamp.ownerSession !== this.ownerSession ||
120
+ !same(this.stamp(stamp.location, stamp.phase), stamp))
121
+ throw new EditorError('stale', 'The view changed. Refresh and review the current source before continuing.');
122
+ }
123
+ #link(path, span) {
124
+ const source = this.#source(path), range = 'start' in span ? span : lineRange(this.#sourceLines(path), span);
125
+ const key = JSON.stringify([path, range]);
126
+ let action = this.#actionKeys.get(key);
127
+ if (action === undefined) {
128
+ action = randomUUID();
129
+ this.#actions.set(action, { path, range });
130
+ this.#actionKeys.set(key, action);
131
+ }
132
+ return { action, path, range, readOnly: !source.writable };
133
+ }
134
+ source(action, stamp) {
135
+ this.assertStamp(stamp);
136
+ const found = this.#actions.get(action);
137
+ if (found === undefined)
138
+ throw new EditorError('stale', 'This source action is no longer available');
139
+ const source = this.#source(found.path);
140
+ return { ...this.#link(found.path, found.range), text: source.text, virtual: source.origin !== 'local' };
141
+ }
142
+ #node(path, record, location = this.#location(path), phase = null) {
143
+ const graph = this.#db.current.inspect({ root: location, phase }).graph;
144
+ let index = this.#nodeIndexes.get(graph.revision);
145
+ if (index === undefined) {
146
+ index = new Map([...graph.nodes.values()].map((n) => [JSON.stringify([n.source.path, n.source.line]), n]));
147
+ this.#nodeIndexes.set(graph.revision, index);
148
+ }
149
+ return index.get(JSON.stringify([path, record.span.line]));
150
+ }
151
+ #summary(path, record, location, phase) {
152
+ const view = this.#db.current.inspect({ root: location, phase });
153
+ const node = this.#node(path, record, location, phase);
154
+ const candidate = node === undefined
155
+ ? view.graph.occurrences.find((o) => o.node.source.path === path && o.node.source.line === record.span.line)
156
+ : undefined;
157
+ const refused = view.refused.find((r) => r.path === path && r.line === record.span.line);
158
+ const error = view.report.findings.some((f) => f.path === path && f.severity === 'error');
159
+ const says = record.sections
160
+ .find((s) => s.name === 'meaning')
161
+ ?.children.find((c) => c.kind === 'field' && c.key === 'says');
162
+ return {
163
+ occurrence: occurrence(path, record.span.line, record.discriminator, record.name),
164
+ identity: node?.identity ?? candidate?.node.identity ?? refused?.identity ?? null,
165
+ name: record.name,
166
+ discriminator: record.discriminator,
167
+ system: node?.system ?? candidate?.node.system ?? null,
168
+ kind: node?.kind ?? null,
169
+ description: says !== undefined && says.kind !== 'record' && 'text' in says.value ? says.value.text : '',
170
+ status: node !== undefined
171
+ ? 'admitted'
172
+ : refused !== undefined || error
173
+ ? 'refused'
174
+ : candidate?.status === 'winner'
175
+ ? 'syntax-only'
176
+ : (candidate?.status ?? 'syntax-only'),
177
+ source: this.#link(path, { line: record.span.line, endLine: record.span.line }),
178
+ };
179
+ }
180
+ #findOccurrence(key) {
181
+ for (const source of this.sources)
182
+ for (const record of recordsIn(this.#project(source.path).ast))
183
+ if (occurrence(source.path, record.span.line, record.discriminator, record.name) === key)
184
+ return { path: source.path, record };
185
+ throw new EditorError('unavailable', 'The selected record occurrence is no longer available');
186
+ }
187
+ diagnostics(location = '', phase = null) {
188
+ return this.#db.current
189
+ .inspect({ root: location, phase })
190
+ .report.findings.filter((f) => this.sourceText(f.path) !== undefined)
191
+ .map((f) => ({
192
+ code: f.code,
193
+ message: f.message,
194
+ severity: f.severity,
195
+ path: f.path,
196
+ range: lineRange(this.#sourceLines(f.path), { line: f.line, endLine: f.endLine ?? f.line }),
197
+ }));
198
+ }
199
+ view(location = '', phase = null) {
200
+ const key = JSON.stringify([location, phase]), cached = this.#views.get(key);
201
+ if (cached !== undefined)
202
+ return cached;
203
+ const inspected = this.#db.current.inspect({ root: location, phase });
204
+ const records = this.sources
205
+ .filter((s) => reaches(s.location.placement.reach, location))
206
+ .flatMap((s) => recordsIn(this.#project(s.path).ast).map((r) => this.#summary(s.path, r, location, phase)));
207
+ const result = {
208
+ stamp: this.stamp(location, phase),
209
+ records,
210
+ systems: inspected.admittedSystems,
211
+ diagnostics: this.diagnostics(location, phase),
212
+ outcome: inspected.report.outcome,
213
+ health: inspected.report.verdicts
214
+ .filter((v) => v.outcome !== 'pass')
215
+ .map((v) => ({ check: v.check, outcome: v.outcome })),
216
+ };
217
+ this.#views.set(key, result);
218
+ return result;
219
+ }
220
+ #target(reference, location) {
221
+ const resolved = this.#db.current.resolve(reference, { root: location });
222
+ if (!resolved.ok)
223
+ return undefined;
224
+ const node = this.#db.current.get(resolved.identity, { root: location });
225
+ if (node === undefined)
226
+ return undefined;
227
+ const span = resolved.fragment === undefined
228
+ ? { line: node.source.line, endLine: node.source.line }
229
+ : (node.requirements.find((r) => r.id === resolved.fragment)?.span ??
230
+ node.cells.find((c) => `${c.phase}/${c.primitive}` === resolved.fragment)?.span);
231
+ return span === undefined ? undefined : this.#link(node.source.path, span);
232
+ }
233
+ composition(stamp = this.stamp()) {
234
+ this.assertStamp(stamp);
235
+ const view = this.view(stamp.location, stamp.phase), groups = new Map();
236
+ for (const source of this.sources) {
237
+ if (source.origin !== 'adopted')
238
+ continue;
239
+ const match = /^(\.ia\/adopted\/([^/]+)\/([a-f0-9]{64})\/)/.exec(source.path);
240
+ if (!match)
241
+ continue;
242
+ const group = groups.get(match[1]) ?? { id: match[2], revision: match[3], files: 0 };
243
+ group.files++;
244
+ groups.set(match[1], group);
245
+ }
246
+ const contents = (prefix, files = this.sources.filter((s) => s.path.startsWith(prefix)).length) => {
247
+ const records = view.records.filter((r) => r.source.path.startsWith(prefix));
248
+ return {
249
+ prefix,
250
+ files,
251
+ records: records.length,
252
+ systems: [...new Set(records.flatMap((r) => (r.system === null ? [] : [r.system])))].sort(),
253
+ };
254
+ };
255
+ const dependencies = [
256
+ ...[...groups].map(([prefix, { id, revision, files }]) => ({
257
+ kind: 'adopted',
258
+ id,
259
+ revision,
260
+ access: 'captured-source',
261
+ ...contents(prefix, files),
262
+ })),
263
+ ...this.#db.current.installed.map(({ id, version, archive }) => ({
264
+ kind: 'installed',
265
+ id,
266
+ version,
267
+ archive,
268
+ access: 'installed-package',
269
+ ...contents(`${INSTALL_PATHS.store}/${archive}/`),
270
+ })),
271
+ ];
272
+ const local = this.sources.filter((s) => s.origin === 'local' && s.path.startsWith('.ia/src/') && !s.path.startsWith('.ia/src/floor/'));
273
+ const localRevision = hash(stableSerialize(local
274
+ .map(({ path, text }) => ({ path, text }))
275
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))));
276
+ const uses = [], seen = new Set();
277
+ const add = (occurrence, reason, target) => {
278
+ if (!target)
279
+ return;
280
+ const dependency = dependencies.find((d) => target.path.startsWith(d.prefix));
281
+ if (!dependency)
282
+ return;
283
+ const key = JSON.stringify([occurrence, reason, target.path, target.range]);
284
+ if (seen.has(key))
285
+ return;
286
+ seen.add(key);
287
+ uses.push({ occurrence, dependency: dependency.id, reason, target });
288
+ };
289
+ if (dependencies.length)
290
+ for (const summary of view.records.filter((r) => r.status === 'admitted' && local.some((s) => s.path === r.source.path))) {
291
+ const { path, record } = this.#findOccurrence(summary.occurrence), at = summary.source.range.start;
292
+ add(summary.occurrence, 'schema', this.definition(path, at, true)[0]);
293
+ add(summary.occurrence, 'registration', this.definition(path, at)[0]);
294
+ const projection = this.#project(path), records = recordsIn(projection.ast);
295
+ for (const ref of projection.references) {
296
+ // Attribute a typed use to its innermost record, not every enclosing record.
297
+ const containing = records
298
+ .filter((r) => r.span.line <= ref.range.start.line + 1 && r.span.endLine >= ref.range.end.line + 1)
299
+ .at(-1);
300
+ if (containing === record)
301
+ add(summary.occurrence, 'reference', this.#target(ref.reference, this.#location(path)));
302
+ }
303
+ }
304
+ return { stamp, localRevision, dependencies, uses };
305
+ }
306
+ definition(path, at, type = false) {
307
+ const projection = this.#project(path), registry = this.#db.current.inspect({ root: this.#location(path) }).graph.registry;
308
+ const record = recordsIn(projection.ast)
309
+ .filter((r) => r.span.line <= at.line + 1 && r.span.endLine >= at.line + 1)
310
+ .at(-1);
311
+ if (type && record !== undefined) {
312
+ const registration = registry.registrations.get(record.discriminator), schema = registration === undefined ? undefined : registry.schemas.get(registration.schema);
313
+ return schema === undefined ? [] : [this.#link(schema.path, schema.span)];
314
+ }
315
+ const reference = projection.references.find((r) => contains(r.range, at));
316
+ if (reference !== undefined) {
317
+ const target = this.#target(reference.reference, this.#location(path));
318
+ return target === undefined ? [] : [target];
319
+ }
320
+ if (record?.span.line === at.line + 1) {
321
+ const registration = registry.registrations.get(record.discriminator), system = registration === undefined ? undefined : registry.systems.get(registration.system);
322
+ const entry = system?.entries.find((e) => e.keyword === record.discriminator);
323
+ return system === undefined ? [] : [this.#link(system.path, entry?.span ?? system.span)];
324
+ }
325
+ return [];
326
+ }
327
+ references(path, at, includeDeclaration = false) {
328
+ const projection = this.#project(path), use = projection.references.find((r) => contains(r.range, at));
329
+ const record = recordsIn(projection.ast)
330
+ .filter((r) => r.span.line <= at.line + 1 && r.span.endLine >= at.line + 1)
331
+ .at(-1);
332
+ const node = record === undefined ? undefined : this.#node(path, record);
333
+ const reference = use?.reference ?? (node === undefined ? undefined : { kind: 'identity', identity: node.identity });
334
+ if (reference === undefined)
335
+ return [];
336
+ const target = this.#target(reference, this.#location(path));
337
+ if (target === undefined)
338
+ return [];
339
+ const found = includeDeclaration ? [target] : [];
340
+ for (const source of this.sources)
341
+ for (const candidate of this.#project(source.path).references) {
342
+ const destination = this.#target(candidate.reference, this.#location(source.path));
343
+ if (destination?.path === target.path &&
344
+ (reference.fragment === undefined || same(destination.range, target.range))) {
345
+ const resolved = this.#db.current.resolve(candidate.reference, { root: this.#location(source.path) });
346
+ const requested = this.#db.current.resolve(reference, { root: this.#location(path) });
347
+ if (resolved.ok && requested.ok && resolved.identity === requested.identity)
348
+ found.push(this.#link(source.path, candidate.range));
349
+ }
350
+ }
351
+ return found;
352
+ }
353
+ hover(path, at) {
354
+ const projected = this.#project(path), ref = projected.references.find((r) => contains(r.range, at));
355
+ if (ref !== undefined) {
356
+ const resolved = this.#db.current.resolve(ref.reference, { root: this.#location(path) });
357
+ const node = resolved.ok ? this.#db.current.get(resolved.identity, { root: this.#location(path) }) : undefined;
358
+ return {
359
+ range: ref.range,
360
+ markdown: node === undefined
361
+ ? `**Unresolved reference**\n\n${escaped(resolved.ok ? 'Target unavailable' : resolved.code)}`
362
+ : `**${escaped(node.displayName)}** · ${escaped(node.discriminator)}\n\n\`${node.identity}\`\n\n${escaped(node.source.path)}:${node.source.line}${resolved.ok && resolved.fragment !== undefined && this.#target(ref.reference, this.#location(path)) === undefined ? '\n\nFragment is missing.' : ''}\n\n${ref.use === 'value' ? 'Typed reference; this use does not create a graph relationship.' : 'Relationship target resolved in this source context.'}`,
363
+ };
364
+ }
365
+ const record = recordsIn(projected.ast)
366
+ .filter((r) => r.span.line <= at.line + 1 && r.span.endLine >= at.line + 1)
367
+ .at(-1);
368
+ if (record === undefined)
369
+ return undefined;
370
+ const summary = this.#summary(path, record, this.#location(path), null), findings = this.diagnostics(locationOf(path)).filter((f) => contains(f.range, at));
371
+ const registry = this.#db.current.inspect({ root: this.#location(path) }).graph.registry, registration = registry.registrations.get(record.discriminator);
372
+ return {
373
+ range: lineRange(this.#source(path).text, { line: at.line + 1, endLine: at.line + 1 }),
374
+ markdown: `**${escaped(record.name)}** · ${summary.status}\n\n${escaped(summary.description)}\n\n${registration === undefined ? 'Discriminator is not registered.' : `Schema: ${escaped(registration.schema)} · Kind: ${registration.kind}`}${findings.map((f) => `\n\n**${f.code}** ${escaped(f.message)}`).join('')}`,
375
+ };
376
+ }
377
+ symbols(path, query = '') {
378
+ return (path === undefined ? this.sources : [this.#source(path)]).flatMap((s) => recordsIn(this.#project(s.path).ast)
379
+ .filter((r) => `${r.discriminator} ${r.name}`.toLowerCase().includes(query.toLowerCase()))
380
+ .map((r) => ({
381
+ name: r.name,
382
+ detail: `@${r.discriminator}`,
383
+ path: s.path,
384
+ range: lineRange(s.text, r.span),
385
+ selectionRange: lineRange(s.text, { line: r.span.line, endLine: r.span.line }),
386
+ })));
387
+ }
388
+ folding(path) {
389
+ const source = this.#source(path), ast = this.#project(path).ast;
390
+ return recordsIn(ast)
391
+ .flatMap((r) => [r.span, ...r.sections.map((s) => s.span)])
392
+ .filter((s) => s.endLine > s.line)
393
+ .map((s) => lineRange(source.text, s));
394
+ }
395
+ formatting(path) {
396
+ const source = this.#source(path);
397
+ if (!source.writable)
398
+ return null;
399
+ const result = format(source.text, path).text;
400
+ return result === null
401
+ ? null
402
+ : (source.text.startsWith('\uFEFF') && !result.startsWith('\uFEFF') ? '\uFEFF' : '') +
403
+ (source.text.includes('\r\n') ? result.replace(/\r?\n/g, '\r\n') : result);
404
+ }
405
+ completions(path, at, limit = 100) {
406
+ const source = this.#source(path), cursor = cursorContext(source.text, path, at, this.#project(path)), location = this.#location(path);
407
+ if (cursor.slot === 'none')
408
+ return [];
409
+ const { registry } = this.#db.current.inspect({ root: location }).graph;
410
+ const registration = cursor.record === undefined ? undefined : registry.registrations.get(cursor.record.discriminator);
411
+ const schema = registration === undefined ? undefined : registry.schemas.get(registration.schema);
412
+ const result = [];
413
+ const add = (label, detail, kind = 'keyword', insertText = label, citation) => {
414
+ result.push({
415
+ label,
416
+ detail,
417
+ kind,
418
+ insertText,
419
+ range: cursor.range,
420
+ ...(citation === undefined ? {} : { citation }),
421
+ });
422
+ };
423
+ if (cursor.slot === 'header')
424
+ for (const entry of registry.registrations.values())
425
+ add(`@${entry.keyword}`, `${entry.system} · ${entry.kind} · schema ${entry.schema}`, 'keyword', `@${entry.keyword}`, { kind: 'word', keyword: entry.keyword });
426
+ else if (cursor.slot === 'reference' || cursor.slot === 'fragment') {
427
+ const relationVerb = cursor.section === 'relationships'
428
+ ? VERB_PHRASES.map((phrase) => ({ phrase, verb: verbOf(phrase) }))
429
+ .filter(({ phrase }) => cursor.words.join(' ').startsWith(phrase + ' '))
430
+ .sort((a, b) => b.phrase.length - a.phrase.length)[0]?.verb
431
+ : undefined;
432
+ for (const node of this.#db.current.records({ root: location })) {
433
+ if (cursor.discriminator !== undefined && !node.discriminator.startsWith(cursor.discriminator))
434
+ continue;
435
+ const targetRegistration = registry.registrations.get(node.discriminator);
436
+ const short = targetRegistration?.facets[0] === node.facet;
437
+ // Qualified identities are valid relationship targets; ordinary ref fields have short-reference grammar.
438
+ if (!short && relationVerb === undefined)
439
+ continue;
440
+ const reference = short ? `@${node.discriminator} ${node.displayName}` : node.identity;
441
+ if (relationVerb !== undefined && cursor.record !== undefined) {
442
+ const from = relationVerb.direction === 'out' ? cursor.record.discriminator : node.discriminator;
443
+ const to = relationVerb.direction === 'out' ? node.discriminator : cursor.record.discriminator;
444
+ if (consentFor(registry, relationVerb.predicate, from, to) !== undefined)
445
+ continue;
446
+ const constraint = schema?.edges.find((e) => e.predicate === relationVerb.predicate);
447
+ if (relationVerb.direction === 'out' &&
448
+ constraint !== undefined &&
449
+ constraint.target !== node.kind &&
450
+ constraint.target !== node.discriminator)
451
+ continue;
452
+ }
453
+ if (cursor.slot === 'fragment') {
454
+ if (node.name !== cursor.targetName?.toLowerCase())
455
+ continue;
456
+ for (const fragment of [
457
+ ...node.requirements.map((r) => r.id),
458
+ ...node.cells.map((c) => `${c.phase}/${c.primitive}`),
459
+ ]) {
460
+ const text = `${reference}#${fragment}`;
461
+ if (text
462
+ .toLowerCase()
463
+ .startsWith(source.text.split(/\r?\n/)[at.line].slice(cursor.range.start.character, at.character).toLowerCase()))
464
+ add(text, node.identity, 'reference', text, { kind: 'record', identity: node.identity });
465
+ }
466
+ }
467
+ else {
468
+ if (cursor.targetName !== undefined && !node.name.startsWith(cursor.targetName.toLowerCase()))
469
+ continue;
470
+ add(reference, node.identity, 'reference', reference, { kind: 'record', identity: node.identity });
471
+ }
472
+ }
473
+ return result.sort((a, b) => a.label.localeCompare(b.label)).slice(0, Math.min(100, Math.max(1, limit)));
474
+ }
475
+ else if (cursor.slot === 'section' || cursor.slot === 'field') {
476
+ if (cursor.slot === 'section') {
477
+ for (const section of schema?.sections ?? [])
478
+ add(section.name, section.must ? 'Required section' : 'Schema section', 'field');
479
+ add('relationships', 'Typed relationships; consent checked at both endpoints', 'field');
480
+ }
481
+ for (const field of schema?.fields ?? [])
482
+ if (field.section === (cursor.section ?? ''))
483
+ add(field.key, `${field.must ? 'Required · ' : ''}${this.#fieldType(field.type)}`, 'field', field.key, {
484
+ kind: 'field',
485
+ schema: schema.name,
486
+ section: field.section,
487
+ key: field.key,
488
+ });
489
+ if (cursor.section === 'relationships')
490
+ for (const phrase of VERB_PHRASES)
491
+ add(phrase, `${verbOf(phrase).direction} · ${verbOf(phrase).predicate}`);
492
+ if (cursor.section === 'cognition')
493
+ for (const value of [...PHASES, ...PRIMITIVES, 'primary'])
494
+ add(value, 'Cognition address');
495
+ if (cursor.section === 'activation')
496
+ add('activate when', 'Coordinate selector');
497
+ }
498
+ else {
499
+ const words = cursor.words, previous = words[words.length - (cursor.prefix === '' ? 1 : 2)] ?? '';
500
+ const axis = previous === 'is' ? words[words.length - (cursor.prefix === '' ? 2 : 3)] : previous;
501
+ for (const value of valuesFor(axis ?? '') ?? [])
502
+ add(value, `Admitted ${axis} value`, 'value');
503
+ if (previous === 'when' || previous === 'and')
504
+ for (const value of CONDITION_AXES)
505
+ add(value, 'Condition axis');
506
+ if (previous === 'primary')
507
+ for (const value of PRIMITIVES)
508
+ add(value, 'Primary cognition primitive', 'value');
509
+ if (AXES.some((a) => a === previous))
510
+ add('is', 'Axis comparison');
511
+ const field = schema?.fields.find((f) => f.section === (cursor.section ?? '') && words.join(' ').startsWith(f.key + ' '));
512
+ if (field?.type === 'ref' || field?.type === 'list of ref')
513
+ for (const entry of registry.registrations.values())
514
+ add(`@${entry.keyword} `, 'Typed reference', 'reference', `@${entry.keyword} `, {
515
+ kind: 'word',
516
+ keyword: entry.keyword,
517
+ });
518
+ if (field?.type === 'flag')
519
+ for (const value of ['true', 'false'])
520
+ add(value, 'Flag', 'value');
521
+ }
522
+ return [
523
+ ...new Map(result.filter((r) => r.label.toLowerCase().startsWith(cursor.prefix.toLowerCase())).map((r) => [r.label, r])).values(),
524
+ ]
525
+ .sort((a, b) => a.label.localeCompare(b.label))
526
+ .slice(0, Math.min(100, Math.max(1, limit)));
527
+ }
528
+ /** Design C04: the longer documentation of one selected item, loaded lazily under the stamp its list was computed with. A changed view refuses as stale. */
529
+ completionDocumentation(path, citation, stamp) {
530
+ this.assertStamp(stamp);
531
+ const location = this.#location(path), { registry } = this.#db.current.inspect({ root: location }).graph;
532
+ if (citation.kind === 'record') {
533
+ const node = this.#db.current.get(citation.identity, { root: location });
534
+ if (node === undefined)
535
+ return undefined;
536
+ const says = node.sections.find((s) => s.name === 'meaning')?.fields.find((f) => 'key' in f && f.key === 'says');
537
+ const text = says !== undefined && 'key' in says && 'text' in says.value ? says.value.text : '';
538
+ return `**${escaped(node.displayName)}** · @${escaped(node.discriminator)}\n\n\`${node.identity}\`\n\n${escaped(node.system)} · ${node.kind}${text === '' ? '' : `\n\n${escaped(text)}`}\n\n\`${node.source.path}:${node.source.line}\``;
539
+ }
540
+ if (citation.kind === 'word') {
541
+ const registration = registry.registrations.get(citation.keyword);
542
+ if (registration === undefined)
543
+ return undefined;
544
+ const schema = registry.schemas.get(registration.schema), required = schema?.sections.filter((s) => s.must).map((s) => s.name) ?? [];
545
+ return `**@${escaped(registration.keyword)}** · ${escaped(registration.system)} · ${registration.kind}\n\nSchema \`${registration.schema}\`${schema === undefined ? ' is unavailable.' : `${schema.closed ? ' (closed)' : ''}${required.length === 0 ? '' : ` · required sections: ${required.map(escaped).join(', ')}`}\n\n\`${schema.path}:${schema.span.line}\``}`;
546
+ }
547
+ const schema = registry.schemas.get(citation.schema), field = schema?.fields.find((f) => f.section === citation.section && f.key === citation.key);
548
+ if (schema === undefined || field === undefined)
549
+ return undefined;
550
+ return `**${escaped(field.key)}** · ${this.#fieldType(field.type)}${field.must ? ' · required' : ''}${field.description === undefined ? '' : `\n\n${escaped(field.description)}`}\n\nSchema \`${schema.name}\` · section ${escaped(field.section === '' ? '(head)' : field.section)}\n\n\`${schema.path}:${field.span.line}\``;
551
+ }
552
+ #fieldType(type) {
553
+ return type;
554
+ }
555
+ semanticTokens(path) {
556
+ const projected = this.#project(path);
557
+ if (!projected.supported)
558
+ return [];
559
+ const records = [...recordsIn(projected.ast)].sort((a, b) => a.span.line - b.span.line), registry = this.#db.current.inspect({ root: this.#location(path) }).graph.registry;
560
+ const stack = [], refs = new Map();
561
+ let nextRecord = 0;
562
+ for (const reference of projected.references)
563
+ for (let line = reference.range.start.line; line <= reference.range.end.line; line++) {
564
+ const ranges = refs.get(line) ?? [];
565
+ ranges.push(reference.range);
566
+ refs.set(line, ranges);
567
+ }
568
+ return projected.tokens.flatMap(({ token, range }) => {
569
+ if (range.start.line !== range.end.line)
570
+ return [];
571
+ while (nextRecord < records.length && records[nextRecord].span.line <= range.start.line + 1) {
572
+ const upcoming = records[nextRecord++];
573
+ while (stack.length && stack.at(-1).span.endLine < upcoming.span.line)
574
+ stack.pop();
575
+ stack.push(upcoming);
576
+ }
577
+ while (stack.length && stack.at(-1).span.endLine < range.start.line + 1)
578
+ stack.pop();
579
+ const record = stack.at(-1);
580
+ const section = record?.sections.find((s) => s.span.line <= range.start.line + 1 && s.span.endLine >= range.start.line + 1);
581
+ const registration = record === undefined ? undefined : registry.registrations.get(record.discriminator);
582
+ const schema = registration === undefined ? undefined : registry.schemas.get(registration.schema);
583
+ let type;
584
+ const modifiers = [];
585
+ if (token.kind === 'sigil') {
586
+ type = 'type';
587
+ if (record?.span.line === token.line)
588
+ modifiers.push('declaration');
589
+ }
590
+ else if (token.kind === 'string' || token.kind === 'prose')
591
+ type = 'string';
592
+ else if (token.kind === 'word') {
593
+ if (record?.span.line === token.line) {
594
+ type = 'class';
595
+ modifiers.push('declaration');
596
+ }
597
+ else if (section?.span.line === token.line)
598
+ type = 'namespace';
599
+ else if (refs.get(range.start.line)?.some((r) => contains(r, range.start)))
600
+ type = 'variable';
601
+ else if (schema?.fields.some((f) => {
602
+ if (f.section !== (section?.name ?? ''))
603
+ return false;
604
+ const row = this.#sourceLines(path)[range.start.line] ?? '', start = row.length - row.trimStart().length;
605
+ return (row.slice(start).startsWith(f.key + ' ') &&
606
+ range.start.character >= start &&
607
+ range.end.character <= start + f.key.length);
608
+ }))
609
+ type = 'property';
610
+ else if (verbOf(token.value) !== undefined || ['when', 'is', 'and', 'primary', 'means'].includes(token.value))
611
+ type = 'keyword';
612
+ else if ([...PHASES, ...PRIMITIVES, ...CONDITION_AXES].some((v) => v === token.value))
613
+ type = 'enumMember';
614
+ }
615
+ return type === undefined
616
+ ? []
617
+ : [
618
+ {
619
+ line: range.start.line,
620
+ character: range.start.character,
621
+ length: range.end.character - range.start.character,
622
+ type,
623
+ modifiers,
624
+ },
625
+ ];
626
+ });
627
+ }
628
+ #relationship(edge, coordinate, nodes) {
629
+ const node = nodes.get(edge.conditionSubject), from = edge.from === null ? undefined : nodes.get(edge.from), to = edge.to === null ? undefined : nodes.get(edge.to);
630
+ const gated = coordinate !== undefined && node !== undefined && !conditionHolds(edge.condition, node.dimensions, coordinate);
631
+ return {
632
+ from: edge.from,
633
+ to: edge.to,
634
+ predicate: edge.predicate,
635
+ state: gated
636
+ ? 'gated'
637
+ : edge.from === null || edge.to === null
638
+ ? 'dangling'
639
+ : edge.condition === undefined
640
+ ? 'active'
641
+ : 'conditional',
642
+ source: this.#link(edge.source.path, edge.source),
643
+ fromSource: from === undefined ? null : this.#link(from.source.path, { line: from.source.line, endLine: from.source.line }),
644
+ toSource: to === undefined ? null : this.#link(to.source.path, { line: to.source.line, endLine: to.source.line }),
645
+ condition: edge.condition?.map((t) => `${t.axis} is ${t.value}`).join(' and ') ?? '',
646
+ };
647
+ }
648
+ inspect(key, stamp, coordinate = {}) {
649
+ this.assertStamp(stamp);
650
+ const selected = this.#findOccurrence(key), options = { root: stamp.location, phase: stamp.phase };
651
+ const view = this.#db.current.inspect(options), node = this.#node(selected.path, selected.record, stamp.location, stamp.phase);
652
+ const record = this.#summary(selected.path, selected.record, stamp.location, stamp.phase), schema = node === undefined ? undefined : view.graph.registry.schemas.get(node.schema);
653
+ const selectedCell = node === undefined ? undefined : cell(node, coordinate);
654
+ const references = this.references(selected.path, { line: selected.record.span.line - 1, character: 1 });
655
+ return {
656
+ stamp,
657
+ record,
658
+ relationships: node === undefined
659
+ ? []
660
+ : view.graph.edges
661
+ .filter((e) => e.from === node.identity || e.to === node.identity)
662
+ .map((e) => this.#relationship(e, coordinate, view.graph.nodes)),
663
+ schema: schema === undefined
664
+ ? null
665
+ : {
666
+ name: schema.name,
667
+ closed: schema.closed,
668
+ fields: schema.fields.map((f) => ({ ...f, type: this.#fieldType(f.type) })),
669
+ source: this.#link(schema.path, schema.span),
670
+ },
671
+ cells: node?.cells.map((c) => ({
672
+ phase: c.phase,
673
+ primitive: c.primitive,
674
+ text: c.text,
675
+ primary: c.primary,
676
+ source: this.#link(node.source.path, c.span),
677
+ })) ?? [],
678
+ selectedCell: selectedCell === undefined ? null : { kind: selectedCell.kind, text: selectedCell.cell.text },
679
+ checks: view.report.verdicts
680
+ .filter((v) => v.scope === node?.identity || v.findings.some((f) => f.path === selected.path))
681
+ .map((v) => ({ check: v.check, outcome: v.outcome, messages: v.findings.map((f) => f.message) })),
682
+ typedReferences: references.length,
683
+ incomingRelationships: node === undefined ? 0 : view.graph.edges.filter((e) => e.to === node.identity).length,
684
+ };
685
+ }
686
+ graph(key, stamp = this.stamp(), coordinate, depth = 1) {
687
+ this.assertStamp(stamp);
688
+ if (coordinate !== undefined)
689
+ validateCoordinate(coordinate);
690
+ const view = this.view(stamp.location, stamp.phase), graph = this.#db.current.inspect({ root: stamp.location, phase: stamp.phase }).graph;
691
+ const selected = key === undefined ? undefined : view.records.find((r) => r.occurrence === key);
692
+ if (key !== undefined && selected === undefined)
693
+ throw new EditorError('unavailable', 'Graph focus is absent');
694
+ const traversal = selected?.identity == null
695
+ ? undefined
696
+ : this.#db.current.traverse({
697
+ root: stamp.location,
698
+ phase: stamp.phase,
699
+ start: [selected.identity],
700
+ depth: Math.min(3, Math.max(0, depth)),
701
+ maxNodes: 250,
702
+ maxEdges: 500,
703
+ ...(coordinate === undefined ? {} : { coordinate }),
704
+ });
705
+ const ids = traversal === undefined
706
+ ? new Set(graph.nodes.keys())
707
+ : new Set([
708
+ ...traversal.nodes.map((n) => n.identity),
709
+ ...traversal.gated.flatMap((e) => [e.from, e.to].filter((id) => id !== null)),
710
+ ]);
711
+ const candidates = view.records.filter((r) => r.status === 'admitted' && r.identity !== null && ids.has(r.identity));
712
+ const nodes = candidates.slice(0, 250), visible = new Set(nodes.map((r) => r.identity));
713
+ const allEdges = traversal === undefined ? graph.edges : [...traversal.edges, ...traversal.gated, ...traversal.dangling];
714
+ const edges = allEdges
715
+ .filter((e) => (e.from === null || visible.has(e.from)) && (e.to === null || visible.has(e.to)))
716
+ .slice(0, 500)
717
+ .map((e) => this.#relationship(e, coordinate, graph.nodes));
718
+ const groups = new Map();
719
+ for (const node of graph.nodes.values())
720
+ groups.set(node.system, (groups.get(node.system) ?? 0) + 1);
721
+ return {
722
+ stamp,
723
+ nodes,
724
+ edges,
725
+ containment: this.#containment(view, visible, stamp.location, stamp.phase),
726
+ truncated: traversal?.truncated === true || candidates.length > nodes.length || allEdges.length > edges.length,
727
+ totals: { nodes: candidates.length, edges: allEdges.length },
728
+ groups: [...groups].map(([system, count]) => ({ system, count })),
729
+ };
730
+ }
731
+ /** N04: nested admitted winners with at least one visible endpoint; never added to edges, traversal, nodes or totals. */
732
+ #containment(view, visible, location, phase) {
733
+ const admitted = new Map(view.records.flatMap((r) => (r.status === 'admitted' && r.identity !== null ? [[r.identity, r]] : [])));
734
+ const links = [], nodes = new Map();
735
+ let truncated = false;
736
+ for (const source of this.sources)
737
+ if (reaches(source.location.placement.reach, location))
738
+ for (const record of recordsIn(this.#project(source.path).ast)) {
739
+ const parent = record.nested.length === 0 ? undefined : this.#node(source.path, record, location, phase)?.identity;
740
+ if (parent === undefined || !admitted.has(parent))
741
+ continue;
742
+ for (const nested of record.nested) {
743
+ const child = this.#node(source.path, nested, location, phase)?.identity;
744
+ if (child === undefined || !admitted.has(child) || (!visible.has(parent) && !visible.has(child)))
745
+ continue;
746
+ const extra = [parent, child].filter((id) => !visible.has(id) && !nodes.has(id));
747
+ if (links.length >= 500 || nodes.size + extra.length > 250) {
748
+ truncated = true;
749
+ continue;
750
+ }
751
+ for (const id of extra)
752
+ nodes.set(id, admitted.get(id));
753
+ links.push({
754
+ parent,
755
+ child,
756
+ source: this.#link(source.path, { line: nested.span.line, endLine: nested.span.line }),
757
+ });
758
+ }
759
+ }
760
+ return { links, nodes: [...nodes.values()], truncated };
761
+ }
762
+ steward(system, identity) {
763
+ return evaluateSteward(this.#db.current.records(), system, identity === undefined ? { kind: 'operator' } : { kind: 'agent', identity });
764
+ }
765
+ draftShapes() {
766
+ const view = this.#db.current.inspect();
767
+ return [...view.graph.registry.registrations.values()]
768
+ .filter((r) => !['system', 'schema'].includes(r.keyword) && view.admittedSystems.includes(r.system))
769
+ .flatMap((registration) => {
770
+ const schema = view.graph.registry.schemas.get(registration.schema);
771
+ return schema === undefined || !this.#instanceTarget(registration.system)
772
+ ? []
773
+ : [
774
+ {
775
+ discriminator: registration.keyword,
776
+ system: registration.system,
777
+ schema: schema.name,
778
+ sections: schema.sections,
779
+ fields: schema.fields.map((f) => ({
780
+ section: f.section,
781
+ key: f.key,
782
+ must: f.must,
783
+ type: this.#fieldType(f.type),
784
+ ...(f.description === undefined ? {} : { description: f.description }),
785
+ })),
786
+ },
787
+ ];
788
+ });
789
+ }
790
+ draft(discriminator, name, fields = {}) {
791
+ if (!/^[A-Za-z][A-Za-z0-9-]*$/.test(name))
792
+ throw new EditorError('invalid', 'Use a record name beginning with a letter, followed by letters, numbers or hyphens');
793
+ const shape = this.draftShapes().find((s) => s.discriminator === discriminator);
794
+ if (shape === undefined)
795
+ throw new EditorError('unavailable', 'No writable admitted system provides this discriminator');
796
+ const schema = this.#db.current.inspect().graph.registry.schemas.get(shape.schema);
797
+ if (schema === undefined)
798
+ throw new EditorError('unavailable', 'The draft schema is no longer admitted');
799
+ const text = draftSource(discriminator, name, schema, fields);
800
+ return { path: `.ia/src/systems/${shape.system}/records/${name.toLowerCase()}.ia`, text };
801
+ }
802
+ validateProposal(files, stamp, target) {
803
+ this.assertStamp(stamp);
804
+ const messages = [], paths = new Set();
805
+ if (!Array.isArray(files) ||
806
+ files.some((f) => f === null || typeof f !== 'object' || typeof f.path !== 'string' || typeof f.text !== 'string'))
807
+ throw new EditorError('invalid', 'Expected source paths and text');
808
+ if (new Set(files.map((f) => f.path.split('/')[3])).size > 1)
809
+ messages.push('A proposal must create files in one admitted system.');
810
+ if (files.length === 0 ||
811
+ files.length > 10 ||
812
+ files.reduce((n, f) => n + Buffer.byteLength(f.text), 0) > 1024 * 1024)
813
+ messages.push('Propose 1–10 files, at most 1 MiB total.');
814
+ for (const file of files) {
815
+ if (typeof file.path !== 'string' || typeof file.text !== 'string' || Buffer.byteLength(file.text) > 256 * 1024) {
816
+ messages.push('Each file needs a path and at most 256 KiB of source.');
817
+ continue;
818
+ }
819
+ const parts = file.path.split('/'), system = parts[3] ?? '', pathKey = file.path.toLowerCase();
820
+ if (parts.slice(0, 3).join('/') !== '.ia/src/systems' ||
821
+ parts.length < 5 ||
822
+ !file.path.endsWith('.ia') ||
823
+ parts.some((p) => !p ||
824
+ p === '.' ||
825
+ p === '..' ||
826
+ /[\\\u0000-\u001f<>:"|?*]|[. ]$/.test(p) ||
827
+ /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(p))) {
828
+ messages.push(`Unsafe target path: ${file.path}`);
829
+ continue;
830
+ }
831
+ if (paths.has(pathKey) ||
832
+ this.sources.some((s) => s.path.toLowerCase() === pathKey) ||
833
+ existsSync(resolve(this.root, file.path)))
834
+ messages.push(`Target already exists or aliases another proposal: ${file.path}`);
835
+ paths.add(pathKey);
836
+ let parent = this.root;
837
+ for (const part of parts.slice(0, -1)) {
838
+ parent = resolve(parent, part);
839
+ if (existsSync(parent) && lstatSync(parent).isSymbolicLink())
840
+ messages.push(`Source aliases are refused: ${file.path}`);
841
+ }
842
+ if (!this.#instanceTarget(system))
843
+ messages.push(`Target system is not an admitted writable authored system: ${system}`);
844
+ const decision = evaluateSteward(this.#db.current.records(), system, { kind: 'operator' });
845
+ if (!decision.allowed)
846
+ messages.push(decision.message);
847
+ const ast = parse(file.text, file.path).ast;
848
+ if (target !== undefined &&
849
+ (system !== target.system || recordsIn(ast).some((r) => r.discriminator !== target.discriminator)))
850
+ messages.push('Proposed instances do not match the requested system and discriminator.');
851
+ if (recordsIn(ast).some((r) => r.discriminator === 'system' || r.discriminator === 'schema' || r.name.endsWith('-steward')))
852
+ messages.push('Create Files cannot change system, schema or steward authority.');
853
+ const foreign = recordsIn(ast).find((r) => this.#db.current.inspect().graph.registry.registrations.get(r.discriminator)?.system !== system);
854
+ if (foreign !== undefined)
855
+ messages.push(`@${foreign.discriminator} is not owned by ${system}.`);
856
+ }
857
+ let diagnostics = [];
858
+ if (messages.length === 0) {
859
+ const candidate = this.#db.current.candidate(files.map((f) => ({ ...f, version: 0 })));
860
+ try {
861
+ const before = this.#db.current.inspect(), after = candidate.inspect();
862
+ const key = (f) => stableSerialize([f.code, f.path, f.line, f.message]);
863
+ const existing = new Set(before.report.findings.filter((f) => f.severity === 'error').map(key));
864
+ const newErrors = after.report.findings.filter((f) => f.severity === 'error' && !existing.has(key(f)));
865
+ diagnostics = newErrors.map((f) => ({
866
+ code: f.code,
867
+ severity: f.severity,
868
+ message: f.message,
869
+ path: f.path,
870
+ range: lineRange(candidate.sources.find((s) => s.path === f.path)?.text ?? '', {
871
+ line: f.line,
872
+ endLine: f.endLine ?? f.line,
873
+ }),
874
+ }));
875
+ if (newErrors.length > 0)
876
+ messages.push(`${newErrors.length} new admission error(s).`);
877
+ const admitted = new Set([...after.graph.nodes.values()].map((n) => stableSerialize([n.identity, n.source.path])));
878
+ if ([...before.graph.nodes.values()].some((n) => !admitted.has(stableSerialize([n.identity, n.source.path]))))
879
+ messages.push('The proposal removes or shadows an existing admitted record.');
880
+ for (const file of files)
881
+ if (![...after.graph.nodes.values()].some((n) => n.source.path === file.path))
882
+ messages.push(`No record from ${file.path} was admitted.`);
883
+ }
884
+ finally {
885
+ candidate.close();
886
+ }
887
+ }
888
+ return {
889
+ stamp,
890
+ allowed: messages.length === 0,
891
+ messages,
892
+ diagnostics,
893
+ files: files.map((f) => ({ ...f, hash: hash(f.text) })),
894
+ };
895
+ }
896
+ close() {
897
+ this.#db.close();
898
+ this.#closed = true;
899
+ this.#actions.clear();
900
+ this.#projections.clear();
901
+ }
902
+ }
903
+ //# sourceMappingURL=workspace.js.map