yarramate 0.20.0 → 0.21.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.
@@ -11,7 +11,7 @@
11
11
  import type { CanvasGraph } from "../../graph-projection.js";
12
12
  import type { YarramateApplyResult, YarramateOperation } from "../../operations.js";
13
13
  import type { ProjectionDefinition, ProjectionQuery } from "../../projection.js";
14
- export declare const VISUAL_PROTOCOL_VERSION: "yarramate/visual-protocol/v2";
14
+ export declare const VISUAL_PROTOCOL_VERSION: "yarramate/visual-protocol/v3";
15
15
  export declare const VISUAL_LIMITS: {
16
16
  readonly messageBytes: number;
17
17
  readonly modelBytes: number;
@@ -124,6 +124,18 @@ export interface VisualLayoutPositions {
124
124
  }
125
125
  export interface VisualChangesetCommitPayload {
126
126
  readonly operations: readonly YarramateOperation[];
127
+ /**
128
+ * What the browser believed each targeted document held when the rows were
129
+ * staged — sha256 keyed by manifest-relative path, pinned at staging time and
130
+ * never refreshed while rows remain staged. The runtime refuses the batch when
131
+ * a pin no longer matches the file, so a same-field overwrite of a write the
132
+ * reviewer never saw cannot land silently (ADR 0093).
133
+ *
134
+ * Required, not optional: a browser that omits it is exactly the browser that
135
+ * cannot detect the conflict, which is why this field is what makes the
136
+ * protocol `v3`.
137
+ */
138
+ readonly sourceDigests: Readonly<Record<string, string>>;
127
139
  }
128
140
  export interface VisualLayoutSavePayload {
129
141
  readonly projectionId: string;
@@ -1,4 +1,4 @@
1
- export const VISUAL_PROTOCOL_VERSION = "yarramate/visual-protocol/v2";
1
+ export const VISUAL_PROTOCOL_VERSION = "yarramate/visual-protocol/v3";
2
2
  export const VISUAL_LIMITS = {
3
3
  messageBytes: 64 * 1024,
4
4
  modelBytes: 5 * 1024 * 1024,
@@ -1,5 +1,16 @@
1
1
  import { type ParseResult, type VisualBrowserInput, type VisualDiagnosticResult, type VisualEvent, type VisualHandoff, type VisualModel, type VisualResponse, type VisualSessionDescriptor, type VisualSessionRequest, type VisualSessionStarted, type VisualStatus } from './protocol-contract.js';
2
2
  export * from './protocol-contract.js';
3
+ /**
4
+ * The one way this adapter mints a source digest.
5
+ *
6
+ * `visual-model/v1` requires a canonical model to record the digests it was
7
+ * derived from (`YMVS112`) and pins their shape to 64 lowercase hex characters,
8
+ * so the value lives beside the validator that enforces it: the request builder
9
+ * mints them for the initial model, the session server re-mints them on every
10
+ * recompile and checks a commit's pins against the files on disk, and all three
11
+ * are the same hash by construction rather than by three matching literals.
12
+ */
13
+ export declare const digestOf: (source: string) => string;
3
14
  export declare const parseVisualModel: (input: unknown) => ParseResult<VisualModel>;
4
15
  export declare const parseVisualSessionRequest: (input: unknown) => ParseResult<VisualSessionRequest>;
5
16
  export declare const parseVisualSessionStarted: (input: unknown) => ParseResult<VisualSessionStarted>;
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { posix } from 'node:path';
2
3
  import Ajv2020Module from 'ajv/dist/2020.js';
3
4
  import { describeSchemaViolation, readableSchemaErrors, } from '../../source-document.js';
@@ -57,6 +58,17 @@ ajv.addSchema([
57
58
  operationsSchema,
58
59
  applyResultSchema,
59
60
  ]);
61
+ /**
62
+ * The one way this adapter mints a source digest.
63
+ *
64
+ * `visual-model/v1` requires a canonical model to record the digests it was
65
+ * derived from (`YMVS112`) and pins their shape to 64 lowercase hex characters,
66
+ * so the value lives beside the validator that enforces it: the request builder
67
+ * mints them for the initial model, the session server re-mints them on every
68
+ * recompile and checks a commit's pins against the files on disk, and all three
69
+ * are the same hash by construction rather than by three matching literals.
70
+ */
71
+ export const digestOf = (source) => createHash('sha256').update(source).digest('hex');
60
72
  // Diagnostics report the document they came from rather than a source file,
61
73
  // because visual protocol documents arrive as parsed JSON over the wire.
62
74
  const documentPaths = new WeakMap();
@@ -1,9 +1,8 @@
1
- import { createHash } from 'node:crypto';
2
1
  import { readFileSync } from 'node:fs';
3
2
  import { resolve } from 'node:path';
4
3
  import { loadProjection } from '../../projection.js';
5
4
  import { loadWorkspaceManifest } from '../../workspace.js';
6
- import { parseVisualSessionRequest } from './protocol.js';
5
+ import { digestOf, parseVisualSessionRequest } from './protocol.js';
7
6
  import { buildVisualModelGraph } from './session-store.js';
8
7
  /**
9
8
  * The one manifest a session can serve. `startVisualServer` resolves exactly
@@ -21,7 +20,6 @@ const requestDiagnostic = (code, message, path = MANIFEST_PATH) => ({
21
20
  line: 1,
22
21
  column: 1,
23
22
  });
24
- const digestOf = (source) => createHash('sha256').update(source).digest('hex');
25
23
  /**
26
24
  * Builds the `yarramate/visual-session-request/v1` document that `start`
27
25
  * consumes, from the workspace on disk.
@@ -7,7 +7,7 @@ import { fileURLToPath } from "node:url";
7
7
  import Ajv2020Module from "ajv/dist/2020.js";
8
8
  import { WebSocketServer } from "ws";
9
9
  import { parse, stringify } from "yaml";
10
- import { VISUAL_LIMITS, VISUAL_PROTOCOL_VERSION, parseVisualBrowserInput, parseVisualResponse, parseVisualSessionStarted, parseVisualStatus, visualBrowserInputType, } from "./protocol.js";
10
+ import { VISUAL_LIMITS, VISUAL_PROTOCOL_VERSION, digestOf, parseVisualBrowserInput, parseVisualResponse, parseVisualSessionStarted, parseVisualStatus, visualBrowserInputType, } from "./protocol.js";
11
11
  import { appendTerminalEvent, appendVisualEvent, appendVisualResponse, createVisualSession, isActionableVisualEvent, recoverVisualSession, removeVisualSession, writeVisualSessionDescriptor, } from "./session-store.js";
12
12
  import { loadProjection, evaluateProjection, } from "../../projection.js";
13
13
  import { compileWorkspaceWithProfileContext, } from "../../compiler.js";
@@ -415,6 +415,7 @@ export const startVisualServer = async (options) => {
415
415
  documents: [],
416
416
  vocabulary: { conceptKinds: [], relationshipKinds: [] },
417
417
  layouts,
418
+ sourceDigests: request.initialModel.sourceDigests,
418
419
  };
419
420
  const capabilities = {
420
421
  chat: request.chatEnabled,
@@ -470,6 +471,9 @@ export const startVisualServer = async (options) => {
470
471
  documents: resolvedWorkspace.documents,
471
472
  vocabulary: { conceptKinds, relationshipKinds },
472
473
  layouts: rendered.layouts,
474
+ // Minted from the bytes this compile just read, so what the browser
475
+ // renders and what it can later claim it rendered are the same read.
476
+ sourceDigests: Object.fromEntries(sources.map(({ path, source }) => [path, digestOf(source)])),
473
477
  };
474
478
  return true;
475
479
  }
@@ -1055,6 +1059,56 @@ export const startVisualServer = async (options) => {
1055
1059
  // the agent anything, so it is answered here directly rather than
1056
1060
  // through the pending queue a poll would drain. This never runs
1057
1061
  // `git commit` - the user reverts a landed batch with `git revert`.
1062
+ // A batch states what it expected each document it touches to hold, and
1063
+ // that expectation is checked against the files before anything is
1064
+ // written. Without it `applyOperations` below would read the workspace
1065
+ // at commit time and do exactly as told, so a row staged against a
1066
+ // value some other writer has since replaced overwrites that writer
1067
+ // silently - the one path left where this adapter loses a write it
1068
+ // reports as landed (ADR 0093).
1069
+ //
1070
+ // Every targeted document that exists is checked, not just every pin
1071
+ // sent: a batch that vouches for nothing would otherwise buy back the
1072
+ // unconditional write by omission, and a precondition nobody has to
1073
+ // state is decoration.
1074
+ const pins = event.payload.sourceDigests;
1075
+ const refused = [];
1076
+ for (const path of new Set(event.payload.operations.map((operation) => operation.document))) {
1077
+ let held;
1078
+ try {
1079
+ held = digestOf(readFileSync(resolve(options.cwd, path), "utf8"));
1080
+ }
1081
+ catch {
1082
+ // Not there to read: `apply` creates it, or something removed it.
1083
+ held = undefined;
1084
+ }
1085
+ const pinned = pins[path];
1086
+ if (held === undefined) {
1087
+ if (pinned !== undefined) {
1088
+ refused.push(serverDiagnostic("YMVS312", `Document "${path}" no longer exists; these edits were staged against it`));
1089
+ }
1090
+ continue;
1091
+ }
1092
+ if (pinned === undefined) {
1093
+ refused.push(serverDiagnostic("YMVS313", `Document "${path}" is edited without stating what it held when the edit was staged`));
1094
+ continue;
1095
+ }
1096
+ if (pinned !== held) {
1097
+ refused.push(serverDiagnostic("YMVS312", `Document "${path}" changed after these edits were staged`));
1098
+ }
1099
+ }
1100
+ if (refused.length > 0) {
1101
+ // Preserve-and-refresh: the rows stay staged in the browser exactly as
1102
+ // a refused apply already leaves them, and the fresh model follows so
1103
+ // the reviewer re-reads the value before deciding what to do with it.
1104
+ sendFrame(socket, {
1105
+ kind: "apply-result",
1106
+ result: { ok: false, diagnostics: refused },
1107
+ });
1108
+ if (recompileWorkspace())
1109
+ broadcast({ kind: "model", model: rendered });
1110
+ return;
1111
+ }
1058
1112
  const operationsSource = stringify({
1059
1113
  format: "yarramate/operations/v1",
1060
1114
  operations: event.payload.operations,
@@ -25,6 +25,13 @@ export interface VisualRenderedModel {
25
25
  readonly layouts: {
26
26
  readonly [projectionId: string]: VisualLayoutPositions;
27
27
  };
28
+ /**
29
+ * The sha256 of every workspace source this graph was compiled from, keyed by
30
+ * manifest-relative path — the same map `visual-model/v1` already requires of
31
+ * a canonical model (`YMVS112`), forwarded rather than dropped so the browser
32
+ * can state what it rendered when it asks for a commit.
33
+ */
34
+ readonly sourceDigests: Readonly<Record<string, string>>;
28
35
  }
29
36
  /**
30
37
  * One line of the conversation, as plain text.
@@ -2,16 +2,19 @@ import { readFileSync, writeFileSync } from 'node:fs';
2
2
  import { resolve } from 'node:path';
3
3
  import { isMap, isScalar, isSeq, parseDocument, stringify, } from 'yaml';
4
4
  import Ajv2020Module from 'ajv/dist/2020.js';
5
+ import { loadAdapterMapping } from './adapter-mapping.js';
5
6
  import { diagnosticJson, humanDiagnostics, usage, } from './cli-support.js';
6
7
  import { compileWorkspace } from './compiler.js';
7
8
  import { evaluateEvidence, loadEvidence } from './evidence.js';
9
+ import { loadProjection } from './projection.js';
8
10
  import { loadSourceDocument, locateSourcePath, } from './source-document.js';
11
+ import { declaredStateIds, rewriteSubjectReferences, scanSubjectReferences, } from './subject-references.js';
9
12
  import { loadWorkspaceManifest } from './workspace.js';
10
13
  import operationsSchema from '../schema/yarramate-operations.schema.json' with { type: 'json'
11
14
  };
12
15
  const Ajv2020 = Ajv2020Module.default;
13
16
  // `discriminator` routes a batch entry to the single branch its `op` names, so
14
- // one malformed operation reports one fault instead of nine near-misses.
17
+ // one malformed operation reports one fault instead of ten near-misses.
15
18
  const validateOperations = new Ajv2020({
16
19
  allErrors: true,
17
20
  discriminator: true,
@@ -302,6 +305,18 @@ export const applyOperations = (operations, workspace, cwd) => {
302
305
  // overlay — or an observation aimed at a compiler document — is rejected
303
306
  // before anything is touched.
304
307
  const workspaceEvidence = new Map(resolvedWorkspace.evidence.map((path) => [resolve(cwd, path), path]));
308
+ // A rename re-points references, and references live in four kinds of file,
309
+ // so the write set is wider than the two above. Projections and adapter
310
+ // mappings are never an operation's own target — they are only ever carried
311
+ // along by a rename — but they are written, so they carry their manifest
312
+ // path for the touched-document list and their group for the walker.
313
+ const referenceFiles = [
314
+ ['document', resolvedWorkspace.documents],
315
+ ['projection', resolvedWorkspace.projections],
316
+ ['evidence', resolvedWorkspace.evidence],
317
+ ['adapter-mapping', resolvedWorkspace.adapterMappings],
318
+ ].flatMap(([group, paths]) => paths.map((path) => ({ absolute: resolve(cwd, path), path, group })));
319
+ const referenceFileOf = new Map(referenceFiles.map((file) => [file.absolute, file]));
305
320
  const candidates = new Map();
306
321
  const counts = {
307
322
  addedConcepts: 0,
@@ -310,14 +325,19 @@ export const applyOperations = (operations, workspace, cwd) => {
310
325
  updatedRelationships: 0,
311
326
  deletedConcepts: 0,
312
327
  deletedRelationships: 0,
328
+ renamedConcepts: 0,
329
+ renamedRelationships: 0,
313
330
  addedObservations: 0,
314
331
  updatedObservations: 0,
315
332
  deletedObservations: 0,
316
333
  };
317
334
  const deletions = [];
318
- const locateOperation = (index, message) => ({
335
+ // Addresses this batch moved off, so the residue walk below can prove none of
336
+ // them survived anywhere.
337
+ const renames = [];
338
+ const locateOperation = (index, message, code = 'YM912') => ({
319
339
  severity: 'error',
320
- code: 'YM912',
340
+ code,
321
341
  message,
322
342
  ...locateSourcePath(operationsPath, yaml, lineCounter, ['operations', index, 'document'], `/operations/${index}/document`),
323
343
  });
@@ -365,6 +385,72 @@ export const applyOperations = (operations, workspace, cwd) => {
365
385
  counts.deletedRelationships += 1;
366
386
  }
367
387
  }
388
+ else if (operation.op === 'rename-concept' ||
389
+ operation.op === 'rename-relationship') {
390
+ const collection = operation.op === 'rename-concept' ? 'concepts' : 'relationships';
391
+ const id = operation.op === 'rename-concept'
392
+ ? operation.concept.id
393
+ : operation.relationship.id;
394
+ if (itemMap(source, collection, id) === undefined) {
395
+ return failed([
396
+ locate(`Operation ${index} renames "${id}", which does not exist in ${operation.document}`),
397
+ ]);
398
+ }
399
+ // A rename that does not move the address would report every reference to
400
+ // it as residue below, which reads as a rewrite fault rather than what it
401
+ // is. Nothing would be written either, so `renamedConcepts: 1` over an
402
+ // empty document list would be a false receipt.
403
+ if (operation.to === id) {
404
+ return failed([
405
+ locate(`Operation ${index} renames "${id}" to itself, so no address moves`),
406
+ ]);
407
+ }
408
+ // A state shares the `document#local` spelling with a subject but not the
409
+ // id space. A collision on either end would make one address name two
410
+ // things, so it is refused rather than re-pointed by guess.
411
+ const states = declaredStateIds(source);
412
+ const collision = states.includes(id)
413
+ ? id
414
+ : states.includes(operation.to)
415
+ ? operation.to
416
+ : undefined;
417
+ if (collision !== undefined) {
418
+ return failed([
419
+ locate(`Operation ${index} renames "${id}" to "${operation.to}", but ${operation.document} declares a state "${collision}" — one address would name two things`),
420
+ ]);
421
+ }
422
+ const { documentId } = scanSubjectReferences(source, 'document');
423
+ const rename = {
424
+ from: `${documentId}#${id}`,
425
+ to: `${documentId}#${operation.to}`,
426
+ };
427
+ // Total within the workspace: the declaration and every declarative
428
+ // reference to it move in this one batch, so nothing is left addressing an
429
+ // id that stopped existing. Staged text is the input, so a second rename
430
+ // in the same batch reads the first one's result.
431
+ for (const file of referenceFiles) {
432
+ const before = candidates.get(file.absolute) ?? readFileSync(file.absolute, 'utf8');
433
+ const rewrite = rewriteSubjectReferences(before, file.group, rename);
434
+ if (!rewrite.ok) {
435
+ return failed([
436
+ locate(`Operation ${index} cannot move "${rename.from}": ${file.path} holds ${rewrite.aliases.length === 1 ? 'an alias' : 'aliases'} at ${rewrite.aliases.join(', ')}, which the rewrite cannot re-point`),
437
+ ]);
438
+ }
439
+ if (rewrite.source !== before) {
440
+ candidates.set(file.absolute, rewrite.source);
441
+ }
442
+ }
443
+ // The target document's own declaration moved in that same walk, so the
444
+ // staged text is the authority from here on.
445
+ source = candidates.get(absolute) ?? source;
446
+ renames.push({ index, from: rename.from });
447
+ if (operation.op === 'rename-concept') {
448
+ counts.renamedConcepts += 1;
449
+ }
450
+ else {
451
+ counts.renamedRelationships += 1;
452
+ }
453
+ }
368
454
  else if (operation.op === 'add-observation') {
369
455
  const address = observationAddress(operation.observation);
370
456
  const matches = byObservation(operation.observation);
@@ -604,11 +690,50 @@ export const applyOperations = (operations, workspace, cwd) => {
604
690
  if (!evaluation.ok)
605
691
  return failed(evaluation.diagnostics);
606
692
  }
693
+ // Totality is checked, not trusted: no file this batch touched may still name
694
+ // an address a rename moved off. A splice that landed text re-parsing to the
695
+ // old value refuses here rather than shipping a reference to an id that
696
+ // stopped existing. A position the enumeration omits is invisible to this
697
+ // walk - the schema-derived completeness test is what covers that.
698
+ if (renames.length > 0) {
699
+ const movedFrom = new Map(renames.map(({ from, index }) => [from, index]));
700
+ const residue = referenceFiles.flatMap((file) => {
701
+ const source = candidates.get(file.absolute);
702
+ if (source === undefined)
703
+ return [];
704
+ return scanSubjectReferences(source, file.group)
705
+ .hits.filter((hit) => movedFrom.has(hit.address))
706
+ .map((hit) => {
707
+ const index = movedFrom.get(hit.address);
708
+ return locateOperation(index, `Operation ${index} moved "${hit.address}", but ${file.path} still names it at ${hit.pointer}`, 'YM913');
709
+ });
710
+ });
711
+ if (residue.length > 0)
712
+ return failed(residue);
713
+ }
714
+ // Projections and adapter mappings are not `compileWorkspace` input, so a
715
+ // rewrite that produced an unreadable address is caught here rather than by
716
+ // the next command to read the file.
717
+ for (const file of referenceFiles) {
718
+ const source = candidates.get(file.absolute);
719
+ if (source === undefined)
720
+ continue;
721
+ if (file.group === 'projection') {
722
+ const loaded = loadProjection({ path: file.path, source });
723
+ if (!loaded.ok)
724
+ return failed(loaded.diagnostics);
725
+ }
726
+ else if (file.group === 'adapter-mapping') {
727
+ const loaded = loadAdapterMapping({ path: file.path, source });
728
+ if (!loaded.ok)
729
+ return failed(loaded.diagnostics);
730
+ }
731
+ }
607
732
  for (const [absolute, source] of candidates) {
608
733
  writeFileSync(absolute, source, 'utf8');
609
734
  }
610
735
  const touched = [...candidates.keys()]
611
- .map((absolute) => workspaceDocuments.get(absolute) ?? workspaceEvidence.get(absolute))
736
+ .map((absolute) => referenceFileOf.get(absolute).path)
612
737
  .sort();
613
738
  return {
614
739
  ok: true,
@@ -658,15 +783,9 @@ export function runApplyCommand(options, cwd) {
658
783
  stderr: '',
659
784
  };
660
785
  }
661
- const applied = result.applied.addedConcepts +
662
- result.applied.addedRelationships +
663
- result.applied.updatedConcepts +
664
- result.applied.updatedRelationships +
665
- result.applied.deletedConcepts +
666
- result.applied.deletedRelationships +
667
- result.applied.addedObservations +
668
- result.applied.updatedObservations +
669
- result.applied.deletedObservations;
786
+ // Every counter, summed by iteration rather than by hand, so a new
787
+ // operation kind cannot silently report zero work.
788
+ const applied = Object.values(result.applied).reduce((total, count) => total + count, 0);
670
789
  return {
671
790
  exitCode: 0,
672
791
  stdout: `Applied ${applied} operation${applied === 1 ? '' : 's'} to ${result.documents.join(', ')}\n`,
@@ -103,6 +103,22 @@ export type YarramateOperation = {
103
103
  readonly relationship: {
104
104
  readonly id: string;
105
105
  };
106
+ } | {
107
+ readonly op: 'rename-concept';
108
+ readonly document: string;
109
+ readonly concept: {
110
+ readonly id: string;
111
+ };
112
+ /** The local id this subject should have had. Every declarative
113
+ * reference to the old address moves with it; prose does not. */
114
+ readonly to: string;
115
+ } | {
116
+ readonly op: 'rename-relationship';
117
+ readonly document: string;
118
+ readonly relationship: {
119
+ readonly id: string;
120
+ };
121
+ readonly to: string;
106
122
  } | {
107
123
  readonly op: 'add-observation';
108
124
  readonly document: string;
@@ -131,6 +147,8 @@ export interface YarramateApplyResult {
131
147
  readonly updatedRelationships: number;
132
148
  readonly deletedConcepts: number;
133
149
  readonly deletedRelationships: number;
150
+ readonly renamedConcepts: number;
151
+ readonly renamedRelationships: number;
134
152
  readonly addedObservations: number;
135
153
  readonly updatedObservations: number;
136
154
  readonly deletedObservations: number;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Every place a subject address can appear on disk, and the surgery that moves
3
+ * one. A rename is only honest if it is total: an address left behind is a
4
+ * dangling reference or, worse, a selector that silently stops matching. The
5
+ * enumeration below is the single statement of where those addresses live, and
6
+ * `test/subject-references.test.ts` derives the same set from the JSON Schemas
7
+ * so a new reference field cannot be added without landing here too.
8
+ */
9
+ /** The four on-disk document kinds that can name a subject. */
10
+ export type SubjectReferenceGroup = 'document' | 'projection' | 'evidence' | 'adapter-mapping';
11
+ /**
12
+ * How the address is spelled at a position.
13
+ * - `declaration`: the subject's own local id, always bare, in its own document.
14
+ * - `reference`: bare local id (meaning "this document") or fully qualified.
15
+ * - `qualified`: always `document#local`, optionally with a `~aspect` suffix
16
+ * (claim addresses are minted that way - see `compiler.ts`).
17
+ */
18
+ export type SubjectReferenceForm = 'declaration' | 'reference' | 'qualified';
19
+ export interface SubjectReferencePosition {
20
+ readonly group: SubjectReferenceGroup;
21
+ /** Key path from the document root; `*` matches every sequence index. */
22
+ readonly path: readonly string[];
23
+ readonly form: SubjectReferenceForm;
24
+ }
25
+ export declare const SUBJECT_REFERENCE_POSITIONS: readonly SubjectReferencePosition[];
26
+ /**
27
+ * Positions that carry reference *syntax* but are not subject addresses, with
28
+ * the reason. Kept as data because the schema-derived completeness test asserts
29
+ * that the two lists together account for every reference-typed position: an
30
+ * omission has to be argued for here rather than forgotten.
31
+ */
32
+ export declare const EXCLUDED_REFERENCE_POSITIONS: readonly {
33
+ readonly group: SubjectReferenceGroup;
34
+ readonly path: readonly string[];
35
+ readonly reason: string;
36
+ }[];
37
+ export interface SubjectReferenceHit {
38
+ /** JSON pointer into the document, for diagnostics. */
39
+ readonly pointer: string;
40
+ /** Qualified address with any `~aspect` suffix removed. */
41
+ readonly address: string;
42
+ readonly form: SubjectReferenceForm;
43
+ /** Source offsets of the scalar's own bytes, quotes included. */
44
+ readonly start: number;
45
+ readonly end: number;
46
+ /** The scalar exactly as written, quotes included. */
47
+ readonly raw: string;
48
+ }
49
+ export interface SubjectReferenceScan {
50
+ /** The document's own id, `''` when it declares none. */
51
+ readonly documentId: string;
52
+ readonly hits: readonly SubjectReferenceHit[];
53
+ /**
54
+ * Pointers at reference positions that hold an alias node. The walker cannot
55
+ * re-point one, so a rename refuses rather than silently leaving it behind.
56
+ */
57
+ readonly aliases: readonly string[];
58
+ }
59
+ /**
60
+ * Every subject address a file of this group holds. Pure read: the parse is
61
+ * thrown away, so callers stay free to splice the original bytes.
62
+ */
63
+ export declare const scanSubjectReferences: (source: string, group: SubjectReferenceGroup) => SubjectReferenceScan;
64
+ export interface SubjectRename {
65
+ /** Qualified address as declared today. */
66
+ readonly from: string;
67
+ /** Qualified address it should have had; the document part never moves. */
68
+ readonly to: string;
69
+ }
70
+ export type SubjectRewriteResult = {
71
+ readonly ok: true;
72
+ readonly source: string;
73
+ /** Pointers this rewrite moved, in document order. */
74
+ readonly moved: readonly string[];
75
+ } | {
76
+ readonly ok: false;
77
+ readonly aliases: readonly string[];
78
+ };
79
+ /**
80
+ * Re-points every reference to `rename.from` in one file. Only the matched
81
+ * scalars' own bytes change - nothing is re-rendered, so byte identity holds
82
+ * everywhere else, a bare reference stays bare, a qualified one stays
83
+ * qualified, a `~aspect` suffix survives, and the original quoting is kept.
84
+ */
85
+ export declare const rewriteSubjectReferences: (source: string, group: SubjectReferenceGroup, rename: SubjectRename) => SubjectRewriteResult;
86
+ /**
87
+ * Local ids of the architecture states a document declares. States share the
88
+ * `document#local` spelling with subjects but not the id space, so a rename
89
+ * whose old or new id collides with one cannot be re-pointed unambiguously and
90
+ * is refused instead.
91
+ */
92
+ export declare const declaredStateIds: (source: string) => readonly string[];