@inventarch/cli 1.2.0 → 3.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.
- package/README.md +20 -5
- package/SPEC.md +86 -11
- package/assets/base/08eaab3e1a6215d78283b82a94a0228367ac7bd78d0a746c56db79c8d7546c3a.ia.tgz +0 -0
- package/assets/base.json +3 -3
- package/assets/host/d7722e32fd0511df2a6dfdf2353e621fdff1cf559d5c8b7ac256c7eceac0452f.tgz +0 -0
- package/assets/host.json +4 -4
- package/assets/vocabulary.json +11 -3
- package/dist/adopt.d.ts +8 -0
- package/dist/adopt.d.ts.map +1 -0
- package/dist/adopt.js +60 -0
- package/dist/adopt.js.map +1 -0
- package/dist/author.d.ts +32 -0
- package/dist/author.d.ts.map +1 -0
- package/dist/author.js +226 -0
- package/dist/author.js.map +1 -0
- package/dist/briefing.d.ts +2 -0
- package/dist/briefing.d.ts.map +1 -1
- package/dist/briefing.js +15 -3
- package/dist/briefing.js.map +1 -1
- package/dist/bundled-base.d.ts +18 -0
- package/dist/bundled-base.d.ts.map +1 -0
- package/dist/bundled-base.js +44 -0
- package/dist/bundled-base.js.map +1 -0
- package/dist/capture.d.ts +41 -6
- package/dist/capture.d.ts.map +1 -1
- package/dist/capture.js +132 -43
- package/dist/capture.js.map +1 -1
- package/dist/commands.d.ts +30 -8
- package/dist/commands.d.ts.map +1 -1
- package/dist/commands.js +287 -35
- package/dist/commands.js.map +1 -1
- package/dist/compile.d.ts +3 -4
- package/dist/compile.d.ts.map +1 -1
- package/dist/compile.js +28 -72
- package/dist/compile.js.map +1 -1
- package/dist/consumer.d.ts +11 -2
- package/dist/consumer.d.ts.map +1 -1
- package/dist/consumer.js +103 -20
- package/dist/consumer.js.map +1 -1
- package/dist/distribute.d.ts +30 -8
- package/dist/distribute.d.ts.map +1 -1
- package/dist/distribute.js +112 -60
- package/dist/distribute.js.map +1 -1
- package/dist/doctor-authority.d.ts +3 -0
- package/dist/doctor-authority.d.ts.map +1 -0
- package/dist/doctor-authority.js +65 -0
- package/dist/doctor-authority.js.map +1 -0
- package/dist/doctor-mounts.d.ts +4 -0
- package/dist/doctor-mounts.d.ts.map +1 -0
- package/dist/doctor-mounts.js +32 -0
- package/dist/doctor-mounts.js.map +1 -0
- package/dist/doctor.d.ts.map +1 -1
- package/dist/doctor.js +327 -79
- package/dist/doctor.js.map +1 -1
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +2 -1
- package/dist/format.js.map +1 -1
- package/dist/host-projection.d.ts +131 -6
- package/dist/host-projection.d.ts.map +1 -1
- package/dist/host-projection.js +663 -42
- package/dist/host-projection.js.map +1 -1
- package/dist/host.d.ts +154 -32
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +393 -142
- package/dist/host.js.map +1 -1
- package/dist/init.d.ts +296 -38
- package/dist/init.d.ts.map +1 -1
- package/dist/init.js +1303 -203
- package/dist/init.js.map +1 -1
- package/dist/main.d.ts +1 -6
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +4 -7
- package/dist/main.js.map +1 -1
- package/dist/migration-journal.d.ts +35 -0
- package/dist/migration-journal.d.ts.map +1 -0
- package/dist/migration-journal.js +205 -0
- package/dist/migration-journal.js.map +1 -0
- package/dist/next.d.ts +21 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +216 -0
- package/dist/next.js.map +1 -0
- package/dist/operation-help.d.ts.map +1 -1
- package/dist/operation-help.js +15 -4
- package/dist/operation-help.js.map +1 -1
- package/dist/pack.d.ts.map +1 -1
- package/dist/pack.js +24 -2
- package/dist/pack.js.map +1 -1
- package/dist/position.d.ts +22 -0
- package/dist/position.d.ts.map +1 -0
- package/dist/position.js +244 -0
- package/dist/position.js.map +1 -0
- package/dist/preview.d.ts +145 -0
- package/dist/preview.d.ts.map +1 -0
- package/dist/preview.js +962 -0
- package/dist/preview.js.map +1 -0
- package/dist/profile.d.ts +118 -0
- package/dist/profile.d.ts.map +1 -0
- package/dist/profile.js +362 -0
- package/dist/profile.js.map +1 -0
- package/dist/project.d.ts +45 -0
- package/dist/project.d.ts.map +1 -0
- package/dist/project.js +263 -0
- package/dist/project.js.map +1 -0
- package/dist/read.d.ts +12 -2
- package/dist/read.d.ts.map +1 -1
- package/dist/read.js +32 -18
- package/dist/read.js.map +1 -1
- package/dist/render.d.ts +24 -2
- package/dist/render.d.ts.map +1 -1
- package/dist/render.js +171 -4
- package/dist/render.js.map +1 -1
- package/dist/session.d.ts +39 -12
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +55 -11
- package/dist/session.js.map +1 -1
- package/dist/user-host.d.ts +3 -3
- package/dist/user-host.js +10 -10
- package/dist/user-host.js.map +1 -1
- package/dist/validate.d.ts +28 -16
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +245 -23
- package/dist/validate.js.map +1 -1
- package/package.json +6 -6
- package/assets/base/0305ca741b1dfec97ff35fbeb36d4a66a0c9c0614b730fe14fcdac0f1565e28a.ia.tgz +0 -0
- package/assets/host/c5fb2bfbba619cbd558ecc1e94dd2c16e37aa8599b4e423f1f59ed01f2074e03.tgz +0 -0
package/dist/preview.js
ADDED
|
@@ -0,0 +1,962 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `ia preview`: the read-only half of record authoring (milestone generation-binding plan amendments C18 and C19, lane C
|
|
3
|
+
* round 2), in the validate mode, whose move is Verification.
|
|
4
|
+
*
|
|
5
|
+
* - `ia preview <word> <name> [field=value ...] [--at <path>]` drafts a new record (language `draftSource`) and appends it
|
|
6
|
+
* to its file: `--at`, or `<first authored root>/<word>.ia`;
|
|
7
|
+
* - `ia preview --relate <owned> <spelling> <target>` adds one relationship row to an owned record;
|
|
8
|
+
* - `ia preview --set <owned> <section.key>=<value>` (or `+=` for one list item) sets one field of an owned record;
|
|
9
|
+
* - `ia preview <word>` prints the word's lowering, schema, default file and consent.
|
|
10
|
+
*
|
|
11
|
+
* Owned is a record at authored placement (band 100) whose file lies under an authored root the repository's
|
|
12
|
+
* `@workspace` declares in `composition.sources`, inside `.ia/src` and outside the floor, named by canonical identity or
|
|
13
|
+
* `@word name`. The edit is language's (`appendRecord`, `addRelationship`, `setField`): the whole file again, formatted,
|
|
14
|
+
* with one record changed. It is compiled through db's draft overlay (`reader.preview`) against one editor snapshot of the
|
|
15
|
+
* workspace, and printed with the record before and after, the findings it adds, the candidate revision and the target
|
|
16
|
+
* file's current sha256, which `ia author` will require. Every record of the file other than the target keeps its digest,
|
|
17
|
+
* or the preview refuses. The participant's mandate profile is judged first (`profile.ts`). Nothing is written: the
|
|
18
|
+
* snapshot publishes no cache, and every path is checked link by link and its file read through an opened handle.
|
|
19
|
+
*/
|
|
20
|
+
import { createHash } from 'node:crypto';
|
|
21
|
+
import { lstatSync, readdirSync, realpathSync } from 'node:fs';
|
|
22
|
+
import { basename, join, resolve } from 'node:path';
|
|
23
|
+
import { fieldTypeText } from '@inventarch/compliance';
|
|
24
|
+
import { linked, pathKey, readWorkspaceBytes } from '@inventarch/db';
|
|
25
|
+
import { mandateAuthorityOf, RuntimeError } from '@inventarch/runtime';
|
|
26
|
+
import { addRelationship, appendRecord, draftSource, encodeValue, relationshipConsent, setField, SourceEditError, VERB_PHRASES, } from '@inventarch/runtime/editor';
|
|
27
|
+
import { UsageError } from './args.js';
|
|
28
|
+
import { findCommand, nearestTokens } from './commands.js';
|
|
29
|
+
import { Refusal, requireRoot, respell } from './consumer.js';
|
|
30
|
+
import { ADMINISTRATIVE_WORDS, repositoryWorkspace, requireProfile } from './profile.js';
|
|
31
|
+
import { atom, document, entry, errorBlock, fieldRows, headerLine, quote, sectionLabel, terminalText, truncateDigest, words, } from './render.js';
|
|
32
|
+
import { isSystemName, starterSystem, systemPath } from './init.js';
|
|
33
|
+
import { identityNext, openEditor } from './session.js';
|
|
34
|
+
const WORD = /^[a-z][a-z0-9-]*$/;
|
|
35
|
+
const NAME = /^[A-Za-z][A-Za-z0-9-]*$/;
|
|
36
|
+
const FRAGMENT = '(?:#[A-Za-z0-9][A-Za-z0-9-]*(?:/[A-Za-z0-9][A-Za-z0-9-]*)*)?';
|
|
37
|
+
const IDENTITY = '[a-z][a-z0-9-]*/[a-z][a-z0-9-]*/[a-z][a-z0-9-]*/[A-Za-z0-9][A-Za-z0-9-]*';
|
|
38
|
+
const ASSIGNMENT = /^([A-Za-z][A-Za-z0-9-]*(?:\.[A-Za-z][A-Za-z0-9-]*)?)(\+?=)([\s\S]*)$/;
|
|
39
|
+
/** The bytes a source may hold for its opened-handle read; the db has already read it whole. */
|
|
40
|
+
const SOURCE_LIMIT = 16 * 1024 * 1024;
|
|
41
|
+
export const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
42
|
+
/**
|
|
43
|
+
* One record named across one positional or two: a canonical identity, `@word name` given as one argument, or `@word`
|
|
44
|
+
* then `name` as the shell splits them; `fragment` admits a trailing `#fragment`.
|
|
45
|
+
*/
|
|
46
|
+
function takeRecord(tokens, at, fragment) {
|
|
47
|
+
const tail = fragment ? FRAGMENT : '', first = tokens[at]?.trim().replace(/\s+/g, ' ');
|
|
48
|
+
if (first === undefined)
|
|
49
|
+
return undefined;
|
|
50
|
+
if (new RegExp(`^@[a-z][a-z0-9-]* [A-Za-z][A-Za-z0-9-]*${tail}$`).test(first))
|
|
51
|
+
return { spelled: first, next: at + 1 };
|
|
52
|
+
const name = tokens[at + 1];
|
|
53
|
+
if (WORD.test(first.slice(1)) &&
|
|
54
|
+
first.startsWith('@') &&
|
|
55
|
+
name !== undefined &&
|
|
56
|
+
new RegExp(`^[A-Za-z][A-Za-z0-9-]*${tail}$`).test(name))
|
|
57
|
+
return { spelled: `${first} ${name}`, next: at + 2 };
|
|
58
|
+
if (new RegExp(`^${IDENTITY}${tail}$`).test(first))
|
|
59
|
+
return { spelled: first, next: at + 1 };
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
const assignment = (text) => {
|
|
63
|
+
const match = ASSIGNMENT.exec(text);
|
|
64
|
+
return match === null ? undefined : { key: match[1], append: match[2] === '+=', value: match[3] };
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* §2.0: the positionals read into one of the four forms, before any workspace is read, so a malformed form is usage at
|
|
68
|
+
* exit 2. A field value split across arguments by the shell is joined again with single spaces: an argument that does
|
|
69
|
+
* not start `<key>=` continues the value before it.
|
|
70
|
+
*/
|
|
71
|
+
export function previewRequest(args) {
|
|
72
|
+
const tokens = args.positionals, at = args.value('at');
|
|
73
|
+
if (args.flag('relate')) {
|
|
74
|
+
const owned = takeRecord(tokens, 0, false);
|
|
75
|
+
if (owned === undefined)
|
|
76
|
+
throw new UsageError('Expected <owned> as a canonical identity or @<word> <name>');
|
|
77
|
+
let index = owned.next;
|
|
78
|
+
const verb = [];
|
|
79
|
+
while (index < tokens.length && !tokens[index].startsWith('@') && !tokens[index].includes('/'))
|
|
80
|
+
verb.push(tokens[index++]);
|
|
81
|
+
const spelling = verb.join(' ').trim().replace(/\s+/g, ' ');
|
|
82
|
+
if (!VERB_PHRASES.includes(spelling)) {
|
|
83
|
+
const [near] = nearestTokens(spelling, VERB_PHRASES, 1);
|
|
84
|
+
throw new UsageError(spelling === ''
|
|
85
|
+
? 'Expected <spelling> after <owned>, a relationship verb such as requires'
|
|
86
|
+
: `Unknown relationship verb "${spelling}"${near === undefined ? '' : `; did you mean "${near}"?`}`);
|
|
87
|
+
}
|
|
88
|
+
const target = takeRecord(tokens, index, true);
|
|
89
|
+
if (target === undefined)
|
|
90
|
+
throw new UsageError('Expected <target> as a canonical identity or @<word> <name>');
|
|
91
|
+
if (target.next < tokens.length)
|
|
92
|
+
throw new UsageError(`Unexpected argument ${tokens[target.next]}`);
|
|
93
|
+
return { mode: 'relate', owned: owned.spelled, spelling, target: target.spelled };
|
|
94
|
+
}
|
|
95
|
+
if (args.flag('set')) {
|
|
96
|
+
const owned = takeRecord(tokens, 0, false);
|
|
97
|
+
if (owned === undefined)
|
|
98
|
+
throw new UsageError('Expected <owned> as a canonical identity or @<word> <name>');
|
|
99
|
+
const set = assignment(tokens.slice(owned.next).join(' '));
|
|
100
|
+
if (set === undefined)
|
|
101
|
+
throw new UsageError('Expected <section.key>=<value> or <section.key>+=<value> after <owned>');
|
|
102
|
+
return { mode: 'set', owned: owned.spelled, assignment: set };
|
|
103
|
+
}
|
|
104
|
+
const [word, name, ...rest] = tokens;
|
|
105
|
+
if (word === undefined || !WORD.test(word))
|
|
106
|
+
throw new UsageError(`Expected <word> as a lowercase word; got ${word}`);
|
|
107
|
+
if (name === undefined)
|
|
108
|
+
return { mode: 'word', word, ...(at === undefined ? {} : { at }) };
|
|
109
|
+
if (!NAME.test(name))
|
|
110
|
+
throw new UsageError(`Expected <name> to begin with a letter, then letters, digits or hyphens; got ${name}`);
|
|
111
|
+
// Plan amendment C20: a system is init's starter system, at its own path, with no field to set.
|
|
112
|
+
if (word === 'system' && (rest.length > 0 || at !== undefined))
|
|
113
|
+
throw new UsageError(`A new @system is the starter system at ${systemPath('<name>')}; it takes no field and no --at`);
|
|
114
|
+
if (word === 'system' && !isSystemName(name))
|
|
115
|
+
throw new UsageError(`A system name is lowercase letters, digits and hyphens, at most 64; got ${name}`);
|
|
116
|
+
const fields = [];
|
|
117
|
+
for (const token of rest) {
|
|
118
|
+
const set = assignment(token);
|
|
119
|
+
if (set !== undefined) {
|
|
120
|
+
if (set.append)
|
|
121
|
+
throw new UsageError(`A new record sets each field with =; got ${token}`);
|
|
122
|
+
fields.push({ ...set });
|
|
123
|
+
}
|
|
124
|
+
else if (fields.length === 0)
|
|
125
|
+
throw new UsageError(`Expected <field>=<value>; got ${token}`);
|
|
126
|
+
else
|
|
127
|
+
fields.at(-1).value += ` ${token}`;
|
|
128
|
+
}
|
|
129
|
+
return { mode: 'record', word, name, fields, ...(at === undefined ? {} : { at }) };
|
|
130
|
+
}
|
|
131
|
+
const contains = (root, path) => root === '' || pathKey(path) === pathKey(root) || pathKey(path).startsWith(`${pathKey(root)}/`);
|
|
132
|
+
function rootsOf(snapshot, within, workspace) {
|
|
133
|
+
const declared = snapshot.roots({ within });
|
|
134
|
+
if (workspace === undefined)
|
|
135
|
+
return { workspace, authored: [], declared };
|
|
136
|
+
const node = snapshot.get(workspace, { within });
|
|
137
|
+
const spelled = (node?.sections ?? [])
|
|
138
|
+
.filter((section) => section.name === 'composition')
|
|
139
|
+
.flatMap((section) => section.fields)
|
|
140
|
+
.flatMap((field) => 'key' in field && field.key === 'sources' && field.value.kind === 'list' ? field.value.items : [])
|
|
141
|
+
.flatMap((item) => 'text' in item ? [item.text.trim().split(/\s+/)[0].replace(/^\.\//, '').replace(/\/+$/, '')] : []);
|
|
142
|
+
const order = (root) => {
|
|
143
|
+
const index = spelled.findIndex((text) => pathKey(text) === pathKey(root));
|
|
144
|
+
return index === -1 ? spelled.length : index;
|
|
145
|
+
};
|
|
146
|
+
const authored = declared
|
|
147
|
+
.filter((root) => root.workspace === workspace && root.placement === 'authored')
|
|
148
|
+
.map((root) => root.root)
|
|
149
|
+
.sort((a, b) => order(a) - order(b));
|
|
150
|
+
return { workspace, authored, declared };
|
|
151
|
+
}
|
|
152
|
+
/** Why `path` is not an owned authored path of the workspace, or undefined when it is. */
|
|
153
|
+
function unowned(roots, path) {
|
|
154
|
+
if (!pathKey(path).startsWith('.ia/src/') || !path.endsWith('.ia'))
|
|
155
|
+
return `${path} is no .ia file inside .ia/src`;
|
|
156
|
+
if (pathKey(path).startsWith('.ia/src/floor/'))
|
|
157
|
+
return `${path} is floor source`;
|
|
158
|
+
const holder = roots.declared.find((root) => contains(root.root, path));
|
|
159
|
+
if (holder === undefined || holder.workspace !== roots.workspace || holder.placement !== 'authored')
|
|
160
|
+
return roots.workspace === undefined
|
|
161
|
+
? `${path} lies under no authored root: this repository authors no @workspace`
|
|
162
|
+
: `${path} lies under no authored root ${roots.workspace} declares in composition.sources`;
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
/** The default file for a new `@<word>` record: `<first authored root inside .ia/src>/<word>.ia`. */
|
|
166
|
+
const defaultFile = (roots, word) => {
|
|
167
|
+
// A root of '' is the whole repository, which holds .ia/src (review C-N5).
|
|
168
|
+
const root = roots.authored.find((candidate) => candidate === '' || contains('.ia/src', candidate));
|
|
169
|
+
return root === undefined ? undefined : `${root === '' ? '.ia/src' : root}/${word}.ia`;
|
|
170
|
+
};
|
|
171
|
+
/**
|
|
172
|
+
* The target file as the snapshot admitted it, confirmed byte for byte through db's opened-handle reader; or, for a path
|
|
173
|
+
* no source holds, nothing there yet and no link on the way to it.
|
|
174
|
+
*/
|
|
175
|
+
function targetFile(root, snapshot, path, again, spelled = () => again) {
|
|
176
|
+
const source = snapshot.sources.find((candidate) => pathKey(candidate.path) === pathKey(path));
|
|
177
|
+
if (source !== undefined) {
|
|
178
|
+
if (source.path !== path)
|
|
179
|
+
throw new Refusal('IA-DB-PATH-UNSAFE', `${path} names the source ${source.path} in another spelling`, 3, { path }, `Run "${spelled(source.path)}" naming the source as ${source.path}.`);
|
|
180
|
+
let bytes;
|
|
181
|
+
try {
|
|
182
|
+
bytes = readWorkspaceBytes(root, path, SOURCE_LIMIT);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
const code = error.code;
|
|
186
|
+
throw new Refusal(typeof code === 'string' ? code : 'IA-DB-SOURCE-UNAVAILABLE', error instanceof Error ? error.message : String(error), 3, { path }, `Once ${path} is a regular file and nothing else is writing it, run "${again}" again.`);
|
|
187
|
+
}
|
|
188
|
+
if (Buffer.compare(Buffer.from(bytes), Buffer.from(source.text, 'utf8')) !== 0)
|
|
189
|
+
throw new Refusal('IA-DB-SOURCE-CHANGED', `File changed during read: ${path}`, 3, { path }, `Once nothing is writing ${path}, run "${again}" again.`);
|
|
190
|
+
return { path, text: source.text, exists: true, digest: sha256(bytes) };
|
|
191
|
+
}
|
|
192
|
+
const absolute = resolve(root, ...path.split('/'));
|
|
193
|
+
let present;
|
|
194
|
+
try {
|
|
195
|
+
present = lstatSync(absolute, { throwIfNoEntry: false }) !== undefined || linked(absolute);
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
present = true;
|
|
199
|
+
}
|
|
200
|
+
if (present)
|
|
201
|
+
throw new Refusal('IA-DB-PATH-UNSAFE', `${path} is not a workspace source, yet something is there or a link lies on the way to it`, 3, { path }, `Move what is at ${path} aside, then run "${again}".`);
|
|
202
|
+
return { path, text: '', exists: false, digest: sha256('') };
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Review C-R1: `path` as the volume spells it. Each component that exists is named by its directory entry, matched
|
|
206
|
+
* exactly; a component another spelling answers (a case variant on a case-insensitive volume, or an 8.3 short name) is
|
|
207
|
+
* replaced by the entry's own name, found by a case-insensitive match or the volume's real path. Components below the
|
|
208
|
+
* first one that does not exist are kept as typed. A mandate's covers and the authored roots are spelled as the volume
|
|
209
|
+
* spells them, so a path is judged only in that spelling.
|
|
210
|
+
*/
|
|
211
|
+
function onDisk(root, path) {
|
|
212
|
+
const parts = path.split('/'), spelled = [];
|
|
213
|
+
let directory = root;
|
|
214
|
+
for (const [index, part] of parts.entries()) {
|
|
215
|
+
let names;
|
|
216
|
+
try {
|
|
217
|
+
names = readdirSync(directory);
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
return [...spelled, ...parts.slice(index)].join('/');
|
|
221
|
+
}
|
|
222
|
+
if (!names.includes(part)) {
|
|
223
|
+
const candidate = join(directory, part);
|
|
224
|
+
let present;
|
|
225
|
+
try {
|
|
226
|
+
present = lstatSync(candidate, { throwIfNoEntry: false }) !== undefined;
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
present = true;
|
|
230
|
+
}
|
|
231
|
+
if (!present)
|
|
232
|
+
return [...spelled, ...parts.slice(index)].join('/');
|
|
233
|
+
const folded = names.filter((name) => name.toLowerCase() === part.toLowerCase());
|
|
234
|
+
let real = folded.length === 1 ? folded[0] : undefined;
|
|
235
|
+
if (real === undefined)
|
|
236
|
+
try {
|
|
237
|
+
real = basename(realpathSync.native(candidate));
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
real = part;
|
|
241
|
+
}
|
|
242
|
+
spelled.push(real);
|
|
243
|
+
directory = join(directory, real);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
spelled.push(part);
|
|
247
|
+
directory = join(directory, part);
|
|
248
|
+
}
|
|
249
|
+
return spelled.join('/');
|
|
250
|
+
}
|
|
251
|
+
/** The typed path, refused when the volume spells an existing part of it otherwise (C-R1), naming that spelling (C-R7). */
|
|
252
|
+
function spelledPath(run, path) {
|
|
253
|
+
const canonical = onDisk(run.root, path);
|
|
254
|
+
if (canonical === path)
|
|
255
|
+
return path;
|
|
256
|
+
throw new Refusal('IA-DB-PATH-UNSAFE', `${path} names ${canonical} in another spelling`, 3, { path }, `Run "${previewAgain(run, { options: { at: [canonical] } })}" naming the path as the volume spells it.`);
|
|
257
|
+
}
|
|
258
|
+
/** The source lines `node` spans in `text`. */
|
|
259
|
+
const linesOf = (text, node) => text
|
|
260
|
+
.split(/\r?\n/)
|
|
261
|
+
.slice(node.source.line - 1, node.source.endLine)
|
|
262
|
+
.join('\n');
|
|
263
|
+
/**
|
|
264
|
+
* The record's lines after an edit of it: formatting keeps every line where it is and the edit adds or replaces lines
|
|
265
|
+
* only inside the record, below its header, so the record starts where it did and grows by the lines the file grew by.
|
|
266
|
+
*/
|
|
267
|
+
const afterLines = (before, after, node) => {
|
|
268
|
+
const lines = (text) => text.replace(/\r?\n$/, '').split(/\r?\n/);
|
|
269
|
+
const grown = lines(after).length - lines(before).length;
|
|
270
|
+
return lines(after)
|
|
271
|
+
.slice(node.source.line - 1, node.source.endLine + grown)
|
|
272
|
+
.join('\n');
|
|
273
|
+
};
|
|
274
|
+
const findingKey = (finding) => JSON.stringify([finding.code, finding.path, finding.line, finding.message]);
|
|
275
|
+
/**
|
|
276
|
+
* The preview of this invocation's form, `changes` applied: what a refusal of either verb names to rerun, since an
|
|
277
|
+
* author form run again would need a digest the preview prints first.
|
|
278
|
+
*/
|
|
279
|
+
const previewAgain = (run, changes = {}) => respell({ command: findCommand('preview'), args: run.context.args }, changes);
|
|
280
|
+
const invalid = (message, next, where = null) => new Refusal('IA-CLI-EDIT-INVALID', message, 1, where, next);
|
|
281
|
+
const guidance = (run, word) => `Run "ia preview ${word}${run.rooted}" for the word's schema, fields and consent.`;
|
|
282
|
+
/** A language refusal of the edit, as IA-CLI-EDIT-INVALID naming the word's guidance. */
|
|
283
|
+
function edited(run, word, path, edit) {
|
|
284
|
+
try {
|
|
285
|
+
return edit();
|
|
286
|
+
}
|
|
287
|
+
catch (error) {
|
|
288
|
+
if (!(error instanceof SourceEditError))
|
|
289
|
+
throw error;
|
|
290
|
+
if (error.reason === 'parse' && !error.message.startsWith('The edit'))
|
|
291
|
+
throw invalid(error.message, `Run "ia validate${run.rooted}" for the located findings of ${path}.`, { path });
|
|
292
|
+
throw invalid(error.message, guidance(run, word), { path });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
/** The admitted record `spelled` names (canonical identity or `@word name`), or undefined. */
|
|
296
|
+
function recordNamed(run, spelled) {
|
|
297
|
+
const [identity, fragment] = spelled.split('#');
|
|
298
|
+
if (fragment !== undefined && fragment === '')
|
|
299
|
+
return undefined;
|
|
300
|
+
// `get` refuses an identity the scope does not hold, so an unknown one is looked up among the admitted records.
|
|
301
|
+
if (!identity.startsWith('@'))
|
|
302
|
+
return run.snapshot
|
|
303
|
+
.records({ within: run.within })
|
|
304
|
+
.find((node) => node.identity === identity || node.identity === identity.toLowerCase());
|
|
305
|
+
const [word, name] = identity.slice(1).split(' ');
|
|
306
|
+
const resolved = run.snapshot.resolve({ kind: 'ref', discriminator: word, name }, { within: run.within });
|
|
307
|
+
return resolved.ok ? run.snapshot.get(resolved.identity, { within: run.within }) : undefined;
|
|
308
|
+
}
|
|
309
|
+
const missing = (run, spelled) => new Refusal('IA-CLI-EDIT-MISSING', `No admitted record answers ${spelled}`, 1, null, spelled.startsWith('@')
|
|
310
|
+
? `Run "ia inspect${run.rooted}" for the overview of what the workspace admits.`
|
|
311
|
+
: identityNext(run.snapshot, spelled.split('#')[0], 'inspect', run.rooted));
|
|
312
|
+
/** The owned record a relate or set form edits, or the refusal that it is not one. */
|
|
313
|
+
function ownedRecord(run, node) {
|
|
314
|
+
const reason = node.band !== 100 || node.placement.kind !== 'authored'
|
|
315
|
+
? `${node.identity} is at ${node.placement.kind} placement (band ${node.band}), not authored by this workspace`
|
|
316
|
+
: unowned(run.roots, node.source.path);
|
|
317
|
+
if (reason !== undefined) {
|
|
318
|
+
const steward = run.snapshot
|
|
319
|
+
.records({ within: run.within })
|
|
320
|
+
.find((candidate) => candidate.discriminator === 'system' && candidate.name === node.system);
|
|
321
|
+
throw new Refusal('IA-CLI-EDIT-UNOWNED', reason, 1, { path: node.source.path, identity: node.identity }, `Run "ia position --seat ${steward?.identity ?? node.identity}${run.rooted}" for the system that owns ${node.identity}; author a record of your own instead.`);
|
|
322
|
+
}
|
|
323
|
+
if (node.parent !== undefined)
|
|
324
|
+
throw invalid(`${node.identity} is nested in ${node.parent}; edit it in its source`, guidance(run, node.discriminator), {
|
|
325
|
+
path: node.source.path,
|
|
326
|
+
identity: node.identity,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Review C2-R6 (a lead decision, flagged for the operator): whether a `@mandate` binds the acting participant, so that
|
|
331
|
+
* neither verb may create or change it, before or after the edit; moves pool across the mandates that bind an actor, so
|
|
332
|
+
* a participant that could write one could lift its own restrictions. It binds when its participant resolves to the
|
|
333
|
+
* actor, or when it names no participant and governs where the actor acts: its scope names the workspace, or it claims
|
|
334
|
+
* paths (`covers`). One whose authority the runtime cannot read binds too, since it would refuse every gated command
|
|
335
|
+
* here. Mandates are cooperative: a human, or another participant, still makes the change.
|
|
336
|
+
*/
|
|
337
|
+
function bindsActor(run, node, profile) {
|
|
338
|
+
if (node.discriminator !== 'mandate')
|
|
339
|
+
return false;
|
|
340
|
+
let authority;
|
|
341
|
+
try {
|
|
342
|
+
authority = mandateAuthorityOf(node);
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
if (error instanceof RuntimeError)
|
|
346
|
+
return true;
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
if (authority.participant !== undefined) {
|
|
350
|
+
if (profile.actor === undefined)
|
|
351
|
+
return false;
|
|
352
|
+
const resolved = run.snapshot.resolve({ kind: 'ref', discriminator: 'agent', name: authority.participant }, { within: run.within });
|
|
353
|
+
return resolved.ok && resolved.identity === profile.actor;
|
|
354
|
+
}
|
|
355
|
+
const workspace = profile.workspace === undefined ? undefined : run.snapshot.get(profile.workspace, { within: run.within })?.name;
|
|
356
|
+
return ((authority.covers?.length ?? 0) > 0 ||
|
|
357
|
+
(workspace !== undefined && (authority.scope ?? []).some((name) => name.toLowerCase() === workspace)));
|
|
358
|
+
}
|
|
359
|
+
/** IA-CLI-EDIT-MANDATE when `node`, before or after the edit, is a `@mandate` that binds the acting participant. */
|
|
360
|
+
function guardMandate(run, node, profile, path, created) {
|
|
361
|
+
if (node === undefined || !bindsActor(run, node, profile))
|
|
362
|
+
return;
|
|
363
|
+
const actor = profile.actor ?? 'whoever acts here', seat = created ? profile.workspace : node.identity;
|
|
364
|
+
throw new Refusal('IA-CLI-EDIT-MANDATE', `${node.identity} ${created ? 'would be a new' : 'is a'} @mandate that binds the acting participant, ${actor}; a participant may not create or change a mandate that binds it`, 1, { path, identity: node.identity }, seat === undefined
|
|
365
|
+
? `Run "ia position${run.rooted}" for the mandates that govern here; a human or another participant makes this change.`
|
|
366
|
+
: `Run "ia position --seat ${seat} --shape governance${run.rooted}" for the mandates that bind ${actor}; a human or another participant makes this change.`);
|
|
367
|
+
}
|
|
368
|
+
/** One schema field by `section.key`, or by a key no other field of the schema has. */
|
|
369
|
+
function schemaField(run, schema, word, key) {
|
|
370
|
+
const found = key.includes('.')
|
|
371
|
+
? schema.fields.filter((field) => `${field.section}.${field.key}` === key)
|
|
372
|
+
: schema.fields.filter((field) => field.key === key);
|
|
373
|
+
if (found.length === 1)
|
|
374
|
+
return found[0];
|
|
375
|
+
throw invalid(found.length === 0
|
|
376
|
+
? `@${word} declares no field ${key}`
|
|
377
|
+
: `${key} names ${found.map((field) => `${field.section}.${field.key}`).join(' and ')}; give it as <section>.<key>`, guidance(run, word));
|
|
378
|
+
}
|
|
379
|
+
function schemaOf(run, word, name) {
|
|
380
|
+
const schema = run.registry.schemas.get(name);
|
|
381
|
+
if (schema === undefined)
|
|
382
|
+
throw invalid(`@${word} has no admitted schema ${name}`, `Run "ia validate${run.rooted}" for why its schema is not admitted.`);
|
|
383
|
+
return schema;
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Compiles the candidate file through the snapshot's draft overlay and checks the edit stayed on its record: of the
|
|
387
|
+
* records the file holds before or after, only `identity` (or the new record) may change its digest. The findings
|
|
388
|
+
* reported are the target file's and any the candidate adds elsewhere.
|
|
389
|
+
*/
|
|
390
|
+
function compiled(run, target, text, expected) {
|
|
391
|
+
let candidate;
|
|
392
|
+
try {
|
|
393
|
+
candidate = run.snapshot.preview([{ path: target.path, text }]);
|
|
394
|
+
}
|
|
395
|
+
catch (error) {
|
|
396
|
+
const code = error.code;
|
|
397
|
+
throw new Refusal(typeof code === 'string' ? code : 'IA-DB-DRAFT-INVALID', error instanceof Error ? error.message : String(error), 3, { path: target.path }, `Run "${previewAgain(run, { options: { at: [] } })}" to preview the default file instead.`);
|
|
398
|
+
}
|
|
399
|
+
const key = pathKey(target.path), at = (node) => pathKey(node.source.path) === key;
|
|
400
|
+
const before = new Map(run.snapshot
|
|
401
|
+
.records({ within: run.within })
|
|
402
|
+
.filter(at)
|
|
403
|
+
.map((node) => [node.identity, node.digest]));
|
|
404
|
+
const nodes = candidate.records.filter(at), after = new Map(nodes.map((node) => [node.identity, node.digest]));
|
|
405
|
+
const record = nodes.find((node) => node.identity === expected.identity) ??
|
|
406
|
+
nodes.find((node) => node.discriminator === expected.word && node.name === expected.name.toLowerCase());
|
|
407
|
+
// A record admission refuses (a required field missing, say) is no node, but the refusal names its identity.
|
|
408
|
+
const refused = candidate.refused.find((entry) => pathKey(entry.path) === key && entry.identity === expected.identity);
|
|
409
|
+
const identity = record?.identity ?? refused?.identity ?? expected.identity;
|
|
410
|
+
const records = [...new Set([...before.keys(), ...after.keys()])]
|
|
411
|
+
.sort()
|
|
412
|
+
.map((id) => ({ identity: id, before: before.get(id) ?? null, after: after.get(id) ?? null }));
|
|
413
|
+
// A file absent before holds only what the edit writes (a starter system and its steward, say).
|
|
414
|
+
const beyond = [...new Set([...before.keys(), ...after.keys()])]
|
|
415
|
+
.filter((id) => target.exists && before.get(id) !== after.get(id) && id !== identity)
|
|
416
|
+
.sort();
|
|
417
|
+
if (beyond.length > 0)
|
|
418
|
+
throw invalid(`The edit would change records beyond its target in ${target.path}: ${beyond.join(', ')}`, `Run "ia validate${run.rooted}" for the located findings of ${target.path}.`, { path: target.path });
|
|
419
|
+
// Review C-R4: a finding counts when it is the edited (or new) record's, or one the base does not hold. In the target
|
|
420
|
+
// file lines move with the edit, so a finding there is matched by its code and record (its message, located finding
|
|
421
|
+
// prefix stripped, when it names none); elsewhere by its code, path, line and message.
|
|
422
|
+
const span = record === undefined ? undefined : record.source;
|
|
423
|
+
const own = (finding) => finding.identity === identity ||
|
|
424
|
+
(finding.identity === undefined && span !== undefined && finding.line >= span.line && finding.line <= span.endLine);
|
|
425
|
+
const keyOf = (finding) => pathKey(finding.path) === key
|
|
426
|
+
? JSON.stringify([
|
|
427
|
+
finding.code,
|
|
428
|
+
finding.identity ?? null,
|
|
429
|
+
finding.identity === undefined ? finding.message.replace(/^[^:]*:\d+: /, '') : null,
|
|
430
|
+
])
|
|
431
|
+
: findingKey(finding);
|
|
432
|
+
const base = new Map();
|
|
433
|
+
for (const finding of run.snapshot.report.findings)
|
|
434
|
+
base.set(keyOf(finding), (base.get(keyOf(finding)) ?? 0) + 1);
|
|
435
|
+
const findings = candidate.report.findings.filter((finding) => {
|
|
436
|
+
if (pathKey(finding.path) === key && own(finding))
|
|
437
|
+
return true;
|
|
438
|
+
const held = base.get(keyOf(finding)) ?? 0;
|
|
439
|
+
if (held === 0)
|
|
440
|
+
return true;
|
|
441
|
+
base.set(keyOf(finding), held - 1);
|
|
442
|
+
return false;
|
|
443
|
+
});
|
|
444
|
+
return {
|
|
445
|
+
identity,
|
|
446
|
+
node: record,
|
|
447
|
+
admitted: record !== undefined,
|
|
448
|
+
records,
|
|
449
|
+
revision: candidate.revision,
|
|
450
|
+
findings,
|
|
451
|
+
clean: !findings.some((finding) => finding.severity === 'error'),
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function previewRecord(run, request, mode) {
|
|
455
|
+
const { word, name } = request;
|
|
456
|
+
if (word === 'system')
|
|
457
|
+
return previewSystem(run, name, mode);
|
|
458
|
+
const typed = request.at ?? defaultFile(run.roots, word), path = typed === undefined || !portable(typed) ? typed : spelledPath(run, typed);
|
|
459
|
+
const profile = requireProfile({
|
|
460
|
+
reader: run.snapshot,
|
|
461
|
+
within: run.within,
|
|
462
|
+
context: run.context,
|
|
463
|
+
mode,
|
|
464
|
+
words: [word],
|
|
465
|
+
...(path === undefined || !portable(path) ? {} : { path }),
|
|
466
|
+
});
|
|
467
|
+
const registration = registrationOf(run, word);
|
|
468
|
+
const schema = schemaOf(run, word, registration.schema);
|
|
469
|
+
const target = ownedTarget(run, word, path);
|
|
470
|
+
const values = {};
|
|
471
|
+
for (const assigned of request.fields) {
|
|
472
|
+
const field = schemaField(run, schema, word, assigned.key);
|
|
473
|
+
// Each value is judged as its field's type first, so draftSource meets only values it spells.
|
|
474
|
+
edited(run, word, target.path, () => encodeValue(field, assigned.value));
|
|
475
|
+
// Review C-N10: one field given twice is refused alike whether spelled `key` or `section.key`.
|
|
476
|
+
if (values[`${field.section}/${field.key}`] !== undefined)
|
|
477
|
+
throw invalid(`@${word} field ${field.section}.${field.key} is given twice`, guidance(run, word));
|
|
478
|
+
values[`${field.section}/${field.key}`] = assigned.value;
|
|
479
|
+
}
|
|
480
|
+
const draft = edited(run, word, target.path, () => draftSource(word, name, schema, values));
|
|
481
|
+
const text = edited(run, word, target.path, () => appendRecord(target.text, draft));
|
|
482
|
+
// Spec 3.1: a new record's identity is its registration's system, kind and first facet, then its lowercased name.
|
|
483
|
+
const identity = `${registration.system}/${registration.kind}/${registration.facets[0]}/${name.toLowerCase()}`;
|
|
484
|
+
const result = compiled(run, target, text, { identity, word, name });
|
|
485
|
+
guardMandate(run, result.node, profile, target.path, true);
|
|
486
|
+
return {
|
|
487
|
+
view: {
|
|
488
|
+
mode: 'record',
|
|
489
|
+
root: run.root,
|
|
490
|
+
path: target.path,
|
|
491
|
+
digest: target.digest,
|
|
492
|
+
exists: target.exists,
|
|
493
|
+
identity: result.identity,
|
|
494
|
+
admitted: result.admitted,
|
|
495
|
+
records: result.records,
|
|
496
|
+
before: null,
|
|
497
|
+
after: draft.replace(/^#! ia [^\n]*\n/, '').trim(),
|
|
498
|
+
baseRevision: run.snapshot.revision,
|
|
499
|
+
revision: result.revision,
|
|
500
|
+
findings: result.findings,
|
|
501
|
+
clean: result.clean,
|
|
502
|
+
profile,
|
|
503
|
+
},
|
|
504
|
+
text,
|
|
505
|
+
target,
|
|
506
|
+
reference: `@${word} ${name}`,
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Plan amendment C20: a new local system is `ia init --system`'s starter system, `@system <name>` and its steward
|
|
511
|
+
* `@agent <name>-steward`, in `.ia/src/systems/<name>/system.ia`, a file no source may hold yet. Its words are the floor's
|
|
512
|
+
* `system` and `agent`, both judged for exclusion.
|
|
513
|
+
*/
|
|
514
|
+
function previewSystem(run, name, mode) {
|
|
515
|
+
const path = spelledPath(run, systemPath(name));
|
|
516
|
+
const profile = requireProfile({
|
|
517
|
+
reader: run.snapshot,
|
|
518
|
+
within: run.within,
|
|
519
|
+
context: run.context,
|
|
520
|
+
mode,
|
|
521
|
+
words: ['system', 'agent'],
|
|
522
|
+
path,
|
|
523
|
+
});
|
|
524
|
+
if (run.registry.systems.has(name))
|
|
525
|
+
throw invalid(`A system named ${name} is already in force here`, `Run "ia position --seat floor/definition/system/${name}${run.rooted}" for where that system sits.`);
|
|
526
|
+
const target = ownedTarget(run, 'system', path);
|
|
527
|
+
if (target.exists)
|
|
528
|
+
throw invalid(`${path} already holds a source`, `Run "ia validate${run.rooted}" for what that source admits.`, {
|
|
529
|
+
path,
|
|
530
|
+
});
|
|
531
|
+
const text = starterSystem(name), identity = `floor/definition/system/${name}`;
|
|
532
|
+
const result = compiled(run, target, text, { identity, word: 'system', name });
|
|
533
|
+
return {
|
|
534
|
+
view: {
|
|
535
|
+
mode: 'record',
|
|
536
|
+
root: run.root,
|
|
537
|
+
path,
|
|
538
|
+
digest: target.digest,
|
|
539
|
+
exists: false,
|
|
540
|
+
identity: result.identity,
|
|
541
|
+
admitted: result.admitted,
|
|
542
|
+
records: result.records,
|
|
543
|
+
before: null,
|
|
544
|
+
after: text.replace(/^#! ia [^\n]*\n/, '').trim(),
|
|
545
|
+
baseRevision: run.snapshot.revision,
|
|
546
|
+
revision: result.revision,
|
|
547
|
+
findings: result.findings,
|
|
548
|
+
clean: result.clean,
|
|
549
|
+
profile,
|
|
550
|
+
},
|
|
551
|
+
text,
|
|
552
|
+
target,
|
|
553
|
+
reference: `@system ${name}`,
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
function previewEdit(run, request, mode) {
|
|
557
|
+
const node = recordNamed(run, request.owned);
|
|
558
|
+
const profile = requireProfile({
|
|
559
|
+
reader: run.snapshot,
|
|
560
|
+
within: run.within,
|
|
561
|
+
context: run.context,
|
|
562
|
+
mode,
|
|
563
|
+
words: node === undefined ? [] : [node.discriminator],
|
|
564
|
+
...(node === undefined ? {} : { path: node.source.path }),
|
|
565
|
+
});
|
|
566
|
+
if (node === undefined)
|
|
567
|
+
throw missing(run, request.owned);
|
|
568
|
+
ownedRecord(run, node);
|
|
569
|
+
guardMandate(run, node, profile, node.source.path, false);
|
|
570
|
+
const word = node.discriminator, path = node.source.path, reference = `@${word} ${node.displayName}`;
|
|
571
|
+
let text;
|
|
572
|
+
if (request.mode === 'relate') {
|
|
573
|
+
const counterpart = recordNamed(run, request.target);
|
|
574
|
+
if (counterpart === undefined)
|
|
575
|
+
throw missing(run, request.target);
|
|
576
|
+
const fragment = request.target.split('#')[1];
|
|
577
|
+
const consent = relationshipConsent(run.registry, word, request.spelling, counterpart.discriminator, fragment);
|
|
578
|
+
if (consent.refused !== undefined)
|
|
579
|
+
throw new Refusal('IA-LANG-EDGE-UNCONSENTED', `The ${consent.refused.side} system ${consent.refused.system}, which registers @${consent.refused.side === 'source' ? consent.from : consent.to}, does not consent to ${consent.predicate} ${consent.from} -> ${consent.to}: no row of its consent ledger admits it`, 1, { path, identity: node.identity }, `Run "ia preview ${word}${run.rooted}" for the relationships @${word} may state and the consent each system gives them.`);
|
|
580
|
+
const target = targetFile(run.root, run.snapshot, path, previewAgain(run));
|
|
581
|
+
text = edited(run, word, path, () => addRelationship(target.text, reference, request.spelling, request.target));
|
|
582
|
+
return finish(run, request.mode, target, text, node, profile);
|
|
583
|
+
}
|
|
584
|
+
const schema = schemaOf(run, word, registrationOf(run, word).schema);
|
|
585
|
+
const field = schemaField(run, schema, word, request.assignment.key);
|
|
586
|
+
const target = targetFile(run.root, run.snapshot, path, previewAgain(run));
|
|
587
|
+
text = edited(run, word, path, () => setField(target.text, reference, `${field.section}.${field.key}`, request.assignment.value, schema, request.assignment.append));
|
|
588
|
+
return finish(run, request.mode, target, text, node, profile);
|
|
589
|
+
}
|
|
590
|
+
function finish(run, mode, target, text, node, profile) {
|
|
591
|
+
const result = compiled(run, target, text, { identity: node.identity, word: node.discriminator, name: node.name });
|
|
592
|
+
guardMandate(run, result.node, profile, target.path, false);
|
|
593
|
+
return {
|
|
594
|
+
view: {
|
|
595
|
+
mode,
|
|
596
|
+
root: run.root,
|
|
597
|
+
path: target.path,
|
|
598
|
+
digest: target.digest,
|
|
599
|
+
exists: target.exists,
|
|
600
|
+
identity: node.identity,
|
|
601
|
+
admitted: result.admitted,
|
|
602
|
+
records: result.records,
|
|
603
|
+
before: linesOf(target.text, node),
|
|
604
|
+
after: afterLines(target.text, text, node),
|
|
605
|
+
baseRevision: run.snapshot.revision,
|
|
606
|
+
revision: result.revision,
|
|
607
|
+
findings: result.findings,
|
|
608
|
+
clean: result.clean,
|
|
609
|
+
profile,
|
|
610
|
+
},
|
|
611
|
+
text,
|
|
612
|
+
target,
|
|
613
|
+
reference: `@${node.discriminator} ${node.displayName}`,
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
/** The candidate one record, relate or set form compiles to, judged for `mode`: preview's validate or author's. */
|
|
617
|
+
export function candidateOf(run, request, mode) {
|
|
618
|
+
const candidate = request.mode === 'record' ? previewRecord(run, request, mode) : previewEdit(run, request, mode);
|
|
619
|
+
if (mode === 'author') {
|
|
620
|
+
// Administrative records can change the actor, its governing closure, admission, or the edit guard itself.
|
|
621
|
+
// Freeze these words for every actor, including an ungoverned one: --actor is a declaration, not authentication.
|
|
622
|
+
// Comparing only the current actor's moves misses a newly created participant and future path selections.
|
|
623
|
+
const word = candidate.reference.slice(1).split(' ')[0];
|
|
624
|
+
if (ADMINISTRATIVE_WORDS.includes(word))
|
|
625
|
+
throw new Refusal('IA-CLI-EDIT-AUTHORITY', `ia author does not create or change @${word} records: this administrative word can change participant rights, admission or source protection; nothing was written`, 1, { path: candidate.target.path, identity: candidate.view.identity }, `Run "ia position${run.rooted}" to inspect the workspace's authority. An owner must make this administrative change in source and validate it; naming an actor does not authorize it.`);
|
|
626
|
+
}
|
|
627
|
+
return candidate;
|
|
628
|
+
}
|
|
629
|
+
/** The invocation a preview or an author form runs through: one editor snapshot of the workspace at `root`. */
|
|
630
|
+
export function invocationOf(context, root, editor) {
|
|
631
|
+
const snapshot = editor.snapshot, within = snapshot.resolveScope().token, supplied = context.args.value('root');
|
|
632
|
+
return {
|
|
633
|
+
context,
|
|
634
|
+
root,
|
|
635
|
+
rooted: supplied === undefined ? '' : ` --root ${quote(supplied)}`,
|
|
636
|
+
snapshot,
|
|
637
|
+
within,
|
|
638
|
+
registry: snapshot.inspect().graph.registry,
|
|
639
|
+
roots: rootsOf(snapshot, within, repositoryWorkspace(snapshot, within)),
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* A canonical workspace-relative path: what `reader.preview` and the opened-handle reader accept. db keeps its rule private,
|
|
644
|
+
* so this copy is held to it by a parity test (review C-N9, tests/preview.test.ts). The CLI also refuses DEL, the C1
|
|
645
|
+
* controls, the Unicode line and paragraph separators and the bidirectional controls, which db admits, so an `--at` path
|
|
646
|
+
* a terminal or a line scanner could misread is never written (review C-RC4); the parity test states that difference.
|
|
647
|
+
*/
|
|
648
|
+
export function portable(path) {
|
|
649
|
+
return (path !== '' &&
|
|
650
|
+
path === path.normalize('NFC') &&
|
|
651
|
+
path.length <= 1024 &&
|
|
652
|
+
!/[\\\u0000-\u001f<>:"|?*]/.test(path) &&
|
|
653
|
+
!/[\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/.test(path) &&
|
|
654
|
+
path
|
|
655
|
+
.split('/')
|
|
656
|
+
.every((part) => part !== '' &&
|
|
657
|
+
part !== '.' &&
|
|
658
|
+
part !== '..' &&
|
|
659
|
+
!/[. ]$/.test(part) &&
|
|
660
|
+
!/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(?:\.|$)/i.test(part)));
|
|
661
|
+
}
|
|
662
|
+
function registrationOf(run, word) {
|
|
663
|
+
const registration = run.registry.registrations.get(word);
|
|
664
|
+
if (registration !== undefined && !run.registry.blocked.has(word))
|
|
665
|
+
return registration;
|
|
666
|
+
const [near] = nearestTokens(word, [...run.registry.registrations.keys()].filter((key) => !run.registry.blocked.has(key)), 1);
|
|
667
|
+
throw invalid(run.registry.blocked.has(word)
|
|
668
|
+
? `@${word} is registered by two systems at one band, so no record of it can be admitted here`
|
|
669
|
+
: `No admitted system registers the word ${word}`, near === undefined
|
|
670
|
+
? `Run "ia inspect${run.rooted}" for the overview of what the workspace admits.`
|
|
671
|
+
: `Run "ia preview ${near}${run.rooted}" for the nearest word this workspace registers.`);
|
|
672
|
+
}
|
|
673
|
+
/** The file a new record goes to, checked as an owned authored path, then read as `targetFile` reads it. */
|
|
674
|
+
function ownedTarget(run, word, path) {
|
|
675
|
+
const fallback = defaultFile(run.roots, word);
|
|
676
|
+
if (path === undefined)
|
|
677
|
+
throw new Refusal('IA-CLI-EDIT-UNOWNED', run.roots.workspace === undefined
|
|
678
|
+
? 'This repository authors no @workspace, so it declares no authored root to hold a new record'
|
|
679
|
+
: `${run.roots.workspace} declares no authored root inside .ia/src in composition.sources`, 1, run.roots.workspace === undefined ? null : { identity: run.roots.workspace }, run.roots.workspace === undefined
|
|
680
|
+
? `Run "ia position${run.rooted}" for the repository's position.`
|
|
681
|
+
: `Run "ia position --seat ${run.roots.workspace}${run.rooted}" for the roots the workspace declares.`);
|
|
682
|
+
const elsewhere = fallback !== undefined && fallback !== path
|
|
683
|
+
? `Run "${previewAgain(run, { options: { at: [] } })}" to preview the default file ${fallback} instead.`
|
|
684
|
+
: run.roots.workspace === undefined
|
|
685
|
+
? `Run "ia position${run.rooted}" for the repository's position; it authors no @workspace to declare roots.`
|
|
686
|
+
: `Run "ia position --seat ${run.roots.workspace}${run.rooted}" for the roots the workspace declares.`;
|
|
687
|
+
if (!portable(path))
|
|
688
|
+
throw new Refusal('IA-DB-PATH-UNSAFE', `Unsafe workspace path: ${path}`, 3, { path }, elsewhere);
|
|
689
|
+
const reason = unowned(run.roots, path);
|
|
690
|
+
if (reason !== undefined)
|
|
691
|
+
throw new Refusal('IA-CLI-EDIT-UNOWNED', reason, 1, { path }, elsewhere);
|
|
692
|
+
return targetFile(run.root, run.snapshot, path, previewAgain(run), (spelled) => previewAgain(run, { options: { at: [spelled] } }));
|
|
693
|
+
}
|
|
694
|
+
/** A placeholder for one field's value in the guidance's example command. */
|
|
695
|
+
const placeholder = (field) => {
|
|
696
|
+
const item = field.type.replace(/^list of /, ''), one = item === 'ref'
|
|
697
|
+
? `@${field.target ?? '<word>'} <name>`
|
|
698
|
+
: field.values !== undefined
|
|
699
|
+
? field.values.join('|')
|
|
700
|
+
: `<${field.form ?? item}>`;
|
|
701
|
+
return field.type.startsWith('list of ') ? `[${one}, ...]` : one;
|
|
702
|
+
};
|
|
703
|
+
function previewWord(run, request) {
|
|
704
|
+
const word = request.word, typed = request.at ?? defaultFile(run.roots, word), path = typed === undefined || !portable(typed) ? typed : spelledPath(run, typed);
|
|
705
|
+
const profile = requireProfile({
|
|
706
|
+
reader: run.snapshot,
|
|
707
|
+
within: run.within,
|
|
708
|
+
context: run.context,
|
|
709
|
+
mode: 'validate',
|
|
710
|
+
words: [word],
|
|
711
|
+
...(path === undefined || !portable(path) ? {} : { path }),
|
|
712
|
+
});
|
|
713
|
+
const registration = registrationOf(run, word);
|
|
714
|
+
const schema = run.registry.schemas.get(registration.schema) ?? null;
|
|
715
|
+
// The rows that name the word, in any system's ledger, and every row of its own system's ledger that can admit it:
|
|
716
|
+
// the relationships a record of the word may state or receive, each needing its other end's system to consent too.
|
|
717
|
+
const names = (side) => side !== '*' && side.includes(word);
|
|
718
|
+
const admits = (side) => side === '*' || side.includes(word) || side.includes('any-adopter');
|
|
719
|
+
const consent = [...run.registry.consent.entries()]
|
|
720
|
+
.flatMap(([system, rows]) => rows
|
|
721
|
+
.filter((row) => system === registration.system
|
|
722
|
+
? admits(row.sources) || admits(row.targets)
|
|
723
|
+
: names(row.sources) || names(row.targets))
|
|
724
|
+
.map((row) => ({ system, predicate: row.predicate, targets: row.targets, sources: row.sources })))
|
|
725
|
+
.sort((a, b) => Number(b.system === registration.system) - Number(a.system === registration.system));
|
|
726
|
+
// Plan amendment C20: a system has a file of its own, `ia author system <name>` writes it, and it takes no field.
|
|
727
|
+
if (word === 'system')
|
|
728
|
+
return {
|
|
729
|
+
root: run.root,
|
|
730
|
+
word,
|
|
731
|
+
registration,
|
|
732
|
+
schema,
|
|
733
|
+
consent,
|
|
734
|
+
file: null,
|
|
735
|
+
template: systemPath('<name>'),
|
|
736
|
+
example: 'ia preview system <name>',
|
|
737
|
+
profile,
|
|
738
|
+
};
|
|
739
|
+
const file = path === undefined ? null : ownedTarget(run, word, path);
|
|
740
|
+
const required = (schema?.fields ?? []).filter((field) => field.must);
|
|
741
|
+
return {
|
|
742
|
+
root: run.root,
|
|
743
|
+
word,
|
|
744
|
+
registration,
|
|
745
|
+
schema,
|
|
746
|
+
consent,
|
|
747
|
+
file: file === null ? null : { path: file.path, exists: file.exists, digest: file.digest },
|
|
748
|
+
example: schema === null
|
|
749
|
+
? null
|
|
750
|
+
: [
|
|
751
|
+
'ia',
|
|
752
|
+
'preview',
|
|
753
|
+
word,
|
|
754
|
+
'<name>',
|
|
755
|
+
...required.map((field) => `${field.section}.${field.key}=${quote(placeholder(field))}`),
|
|
756
|
+
].join(' '),
|
|
757
|
+
profile,
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
const profileEnvelope = (profile) => ({
|
|
761
|
+
actor: profile.actor ?? null,
|
|
762
|
+
by: profile.by ?? null,
|
|
763
|
+
mandates: profile.mandates,
|
|
764
|
+
...(profile.notice === undefined ? {} : { notice: profile.notice }),
|
|
765
|
+
});
|
|
766
|
+
export function previewEnvelope(view) {
|
|
767
|
+
const count = (severity) => view.findings.filter((finding) => finding.severity === severity).length;
|
|
768
|
+
return {
|
|
769
|
+
version: 1,
|
|
770
|
+
mode: view.mode,
|
|
771
|
+
root: view.root,
|
|
772
|
+
path: view.path,
|
|
773
|
+
digest: view.digest,
|
|
774
|
+
exists: view.exists,
|
|
775
|
+
identity: view.identity,
|
|
776
|
+
admitted: view.admitted,
|
|
777
|
+
records: view.records,
|
|
778
|
+
before: view.before,
|
|
779
|
+
after: view.after,
|
|
780
|
+
baseRevision: view.baseRevision,
|
|
781
|
+
revision: view.revision,
|
|
782
|
+
clean: view.clean,
|
|
783
|
+
counts: { errors: count('error'), warnings: count('warning') },
|
|
784
|
+
findings: view.findings,
|
|
785
|
+
profile: profileEnvelope(view.profile),
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
export function wordEnvelope(view) {
|
|
789
|
+
const { registration, schema } = view;
|
|
790
|
+
return {
|
|
791
|
+
version: 1,
|
|
792
|
+
mode: 'word',
|
|
793
|
+
root: view.root,
|
|
794
|
+
word: view.word,
|
|
795
|
+
system: registration.system,
|
|
796
|
+
lowering: {
|
|
797
|
+
kind: registration.kind,
|
|
798
|
+
category: registration.category,
|
|
799
|
+
facets: registration.facets,
|
|
800
|
+
...(registration.primitive === undefined ? {} : { primitive: registration.primitive }),
|
|
801
|
+
...(registration.move === undefined ? {} : { move: registration.move }),
|
|
802
|
+
...(registration.artifactSet === undefined ? {} : { artifactSet: registration.artifactSet }),
|
|
803
|
+
},
|
|
804
|
+
schema: schema === null
|
|
805
|
+
? null
|
|
806
|
+
: {
|
|
807
|
+
name: schema.name,
|
|
808
|
+
closed: schema.closed,
|
|
809
|
+
sections: schema.sections.map((section) => ({ name: section.name, must: section.must })),
|
|
810
|
+
fields: schema.fields.map((field) => ({
|
|
811
|
+
path: `${field.section}.${field.key}`,
|
|
812
|
+
type: fieldTypeText(field),
|
|
813
|
+
must: field.must,
|
|
814
|
+
...(field.description === undefined ? {} : { description: field.description }),
|
|
815
|
+
})),
|
|
816
|
+
edges: schema.edges.map((edge) => ({
|
|
817
|
+
spelling: edge.spelling,
|
|
818
|
+
target: edge.target,
|
|
819
|
+
must: edge.must,
|
|
820
|
+
cardinality: edge.cardinality,
|
|
821
|
+
})),
|
|
822
|
+
},
|
|
823
|
+
consent: view.consent,
|
|
824
|
+
file: view.file,
|
|
825
|
+
...(view.template === undefined ? {} : { template: view.template }),
|
|
826
|
+
example: view.example,
|
|
827
|
+
profile: profileEnvelope(view.profile),
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
const sourceBlock = (label, text, caps) => [
|
|
831
|
+
sectionLabel(label, caps),
|
|
832
|
+
...text.split('\n').map((line) => (line === '' ? '' : ` ${terminalText(line)}`)),
|
|
833
|
+
];
|
|
834
|
+
const actorRow = (profile) => words(profile.actor === undefined
|
|
835
|
+
? `none named${profile.notice === undefined ? '' : `; ${profile.notice}`}`
|
|
836
|
+
: `${profile.actor} (${profile.by === 'actor' ? '--actor' : profile.by === 'steward' ? 'the workspace steward' : 'the one participant'})${profile.mandates.length === 0
|
|
837
|
+
? `; ${profile.notice ?? 'no mandate governs here'}`
|
|
838
|
+
: `, under ${profile.mandates.join(', ')}`}`);
|
|
839
|
+
export function renderPreview(view, caps) {
|
|
840
|
+
const errors = view.findings.filter((finding) => finding.severity === 'error').length, warnings = view.findings.length - errors;
|
|
841
|
+
const blocks = [
|
|
842
|
+
headerLine('Preview', terminalText(view.path), [{ text: view.exists ? 'existing file' : 'new file', column: 50 }], caps),
|
|
843
|
+
entry([
|
|
844
|
+
words(`${view.clean ? 'Clean candidate' : 'Candidate with errors'}: ${errors} ${errors === 1 ? 'error' : 'errors'}, ${warnings} ${warnings === 1 ? 'warning' : 'warnings'} in what it changes.`),
|
|
845
|
+
], { depth: 1, symbol: view.clean ? 'success' : 'error' }, caps),
|
|
846
|
+
fieldRows([
|
|
847
|
+
{
|
|
848
|
+
label: 'record',
|
|
849
|
+
value: [
|
|
850
|
+
atom(view.identity, 'cyan', 0),
|
|
851
|
+
...(view.admitted ? [] : words('refused by admission; the findings say why', 'dim', 2)),
|
|
852
|
+
],
|
|
853
|
+
},
|
|
854
|
+
{
|
|
855
|
+
label: 'sha256',
|
|
856
|
+
value: [atom(view.digest, null, 0)],
|
|
857
|
+
note: words('the file as it is now; an absent file reads as empty', 'dim'),
|
|
858
|
+
},
|
|
859
|
+
{
|
|
860
|
+
label: 'revision',
|
|
861
|
+
value: words(`${truncateDigest(view.baseRevision, caps.ascii)} -> ${truncateDigest(view.revision, caps.ascii)}`),
|
|
862
|
+
},
|
|
863
|
+
{ label: 'actor', value: actorRow(view.profile) },
|
|
864
|
+
], { depth: 1 }, caps),
|
|
865
|
+
...(view.before === null ? [] : [sourceBlock('Before', view.before, caps)]),
|
|
866
|
+
sourceBlock(view.before === null ? 'Record' : 'After', view.after, caps),
|
|
867
|
+
];
|
|
868
|
+
const located = view.findings.map((finding) => errorBlock({
|
|
869
|
+
location: finding.path === '' ? null : terminalText(`${finding.path}:${finding.line}`),
|
|
870
|
+
...(finding.identity === undefined ? {} : { identity: terminalText(finding.identity) }),
|
|
871
|
+
code: finding.code,
|
|
872
|
+
message: terminalText(finding.message),
|
|
873
|
+
severity: finding.severity,
|
|
874
|
+
}, { depth: 1 }, caps));
|
|
875
|
+
if (located.length > 0)
|
|
876
|
+
blocks.push([sectionLabel('Findings', caps), ...located.flat()]);
|
|
877
|
+
blocks.push(entry([words('Preview writes nothing.')], { depth: 0, symbol: 'step' }, caps));
|
|
878
|
+
return document(blocks, { leadingBlank: true });
|
|
879
|
+
}
|
|
880
|
+
export function renderWord(view, caps) {
|
|
881
|
+
const { registration, schema } = view;
|
|
882
|
+
const lowering = [
|
|
883
|
+
`category ${registration.category}`,
|
|
884
|
+
`facets ${registration.facets.join(', ')}`,
|
|
885
|
+
...(registration.primitive === undefined ? [] : [`primitive ${registration.primitive}`]),
|
|
886
|
+
...(registration.move === undefined ? [] : [`move ${registration.move}`]),
|
|
887
|
+
...(registration.artifactSet === undefined ? [] : [`artifact set ${registration.artifactSet}`]),
|
|
888
|
+
].join('; ');
|
|
889
|
+
const side = (value) => (value === '*' ? '*' : value.join(', '));
|
|
890
|
+
const blocks = [
|
|
891
|
+
headerLine('Word', view.word, [{ text: registration.system, column: 30 }], caps),
|
|
892
|
+
fieldRows([
|
|
893
|
+
{ label: 'lowers to', value: words(`${registration.kind} (${lowering})`) },
|
|
894
|
+
{
|
|
895
|
+
label: 'schema',
|
|
896
|
+
value: words(schema === null ? 'none admitted' : `${schema.name}, ${schema.closed ? 'closed' : 'open'}`),
|
|
897
|
+
},
|
|
898
|
+
{
|
|
899
|
+
label: 'file',
|
|
900
|
+
value: words(view.template !== undefined
|
|
901
|
+
? `${view.template}, a new file for each system`
|
|
902
|
+
: view.file === null
|
|
903
|
+
? 'none: the workspace declares no authored root inside .ia/src'
|
|
904
|
+
: `${view.file.path} (${view.file.exists ? 'existing' : 'new'}), sha256 ${view.file.digest}`),
|
|
905
|
+
},
|
|
906
|
+
{ label: 'actor', value: actorRow(view.profile) },
|
|
907
|
+
], { depth: 1 }, caps),
|
|
908
|
+
];
|
|
909
|
+
if (schema !== null) {
|
|
910
|
+
blocks.push([
|
|
911
|
+
sectionLabel('Sections', caps),
|
|
912
|
+
...schema.sections.map((section) => ` ${section.must ? 'must' : 'may'} have ${section.name}`),
|
|
913
|
+
]);
|
|
914
|
+
blocks.push([
|
|
915
|
+
sectionLabel('Fields', caps),
|
|
916
|
+
...fieldRows(schema.fields.map((field) => ({
|
|
917
|
+
label: `${field.must ? 'must' : 'may'} ${field.section}.${field.key}`,
|
|
918
|
+
value: words(`${fieldTypeText(field)}${field.description === undefined ? '' : ` - ${field.description}`}`),
|
|
919
|
+
})), { depth: 1 }, caps),
|
|
920
|
+
]);
|
|
921
|
+
if (schema.edges.length > 0)
|
|
922
|
+
blocks.push([
|
|
923
|
+
sectionLabel('Edges', caps),
|
|
924
|
+
...schema.edges.map((edge) => ` ${edge.must ? 'must' : 'may'} ${edge.spelling} ${edge.target} ${edge.cardinality}`),
|
|
925
|
+
]);
|
|
926
|
+
}
|
|
927
|
+
if (view.consent.length > 0)
|
|
928
|
+
blocks.push([
|
|
929
|
+
sectionLabel('Consent', caps),
|
|
930
|
+
...view.consent.map((row) => ` ${row.system}: ${row.predicate} ${side(row.targets)} using ${side(row.sources)}`),
|
|
931
|
+
]);
|
|
932
|
+
if (view.example !== null)
|
|
933
|
+
blocks.push([
|
|
934
|
+
sectionLabel('Preview a new record', caps),
|
|
935
|
+
...entry([[atom(view.example, null, 0)]], { depth: 1 }, caps),
|
|
936
|
+
]);
|
|
937
|
+
return document(blocks, { leadingBlank: true });
|
|
938
|
+
}
|
|
939
|
+
export function runPreview(context) {
|
|
940
|
+
const { args, caps, json } = context;
|
|
941
|
+
const request = previewRequest(args);
|
|
942
|
+
const root = requireRoot(context);
|
|
943
|
+
const editor = openEditor(root);
|
|
944
|
+
try {
|
|
945
|
+
const run = invocationOf(context, root, editor);
|
|
946
|
+
if (request.mode === 'word') {
|
|
947
|
+
const view = previewWord(run, request);
|
|
948
|
+
return json
|
|
949
|
+
? { exitCode: 0, stdout: JSON.stringify(wordEnvelope(view)) + '\n', stderr: '' }
|
|
950
|
+
: { exitCode: 0, stdout: renderWord(view, caps), stderr: '' };
|
|
951
|
+
}
|
|
952
|
+
const { view } = candidateOf(run, request, 'validate');
|
|
953
|
+
const exitCode = view.clean ? 0 : 1;
|
|
954
|
+
return json
|
|
955
|
+
? { exitCode, stdout: JSON.stringify(previewEnvelope(view)) + '\n', stderr: '' }
|
|
956
|
+
: { exitCode, stdout: renderPreview(view, caps), stderr: '' };
|
|
957
|
+
}
|
|
958
|
+
finally {
|
|
959
|
+
editor.close();
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
//# sourceMappingURL=preview.js.map
|