@inventarch/runtime 1.2.0 → 2.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 (55) hide show
  1. package/README.md +17 -1
  2. package/SPEC.md +25 -5
  3. package/dist/context.d.ts +10 -1
  4. package/dist/context.d.ts.map +1 -1
  5. package/dist/context.js +14 -5
  6. package/dist/context.js.map +1 -1
  7. package/dist/coordinate.d.ts +9 -2
  8. package/dist/coordinate.d.ts.map +1 -1
  9. package/dist/coordinate.js +14 -0
  10. package/dist/coordinate.js.map +1 -1
  11. package/dist/door.d.ts +17 -0
  12. package/dist/door.d.ts.map +1 -1
  13. package/dist/door.js +101 -3
  14. package/dist/door.js.map +1 -1
  15. package/dist/errors.d.ts +4 -2
  16. package/dist/errors.d.ts.map +1 -1
  17. package/dist/errors.js +7 -1
  18. package/dist/errors.js.map +1 -1
  19. package/dist/index.d.ts +10 -0
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +5 -0
  22. package/dist/index.js.map +1 -1
  23. package/dist/locator.d.ts +22 -2
  24. package/dist/locator.d.ts.map +1 -1
  25. package/dist/locator.js +290 -26
  26. package/dist/locator.js.map +1 -1
  27. package/dist/machine-protocol.d.ts +5 -0
  28. package/dist/machine-protocol.d.ts.map +1 -1
  29. package/dist/machine-protocol.js +141 -5
  30. package/dist/machine-protocol.js.map +1 -1
  31. package/dist/next.d.ts +151 -0
  32. package/dist/next.d.ts.map +1 -0
  33. package/dist/next.js +724 -0
  34. package/dist/next.js.map +1 -0
  35. package/dist/packet-host.d.ts +88 -0
  36. package/dist/packet-host.d.ts.map +1 -0
  37. package/dist/packet-host.js +239 -0
  38. package/dist/packet-host.js.map +1 -0
  39. package/dist/packet.d.ts +157 -0
  40. package/dist/packet.d.ts.map +1 -0
  41. package/dist/packet.js +207 -0
  42. package/dist/packet.js.map +1 -0
  43. package/dist/position.d.ts +275 -0
  44. package/dist/position.d.ts.map +1 -0
  45. package/dist/position.js +530 -0
  46. package/dist/position.js.map +1 -0
  47. package/dist/render.d.ts +6 -1
  48. package/dist/render.d.ts.map +1 -1
  49. package/dist/render.js +12 -0
  50. package/dist/render.js.map +1 -1
  51. package/dist/scope-key.d.ts +101 -0
  52. package/dist/scope-key.d.ts.map +1 -0
  53. package/dist/scope-key.js +175 -0
  54. package/dist/scope-key.js.map +1 -0
  55. package/package.json +24 -4
package/dist/next.js ADDED
@@ -0,0 +1,724 @@
1
+ import { valuesFor } from '@inventarch/language';
2
+ import { conditionHolds } from '@inventarch/graph';
3
+ import { RUNTIME_CODES } from './errors.js';
4
+ import { statedText } from './render.js';
5
+ import { freeze } from './types.js';
6
+ /** The refusal codes the delivery view can return; each is registered in RUNTIME_CODES. */
7
+ export const NEXT_CODES = Object.freeze(RUNTIME_CODES.filter((code) => code.startsWith('IA-RUNTIME-NEXT-')));
8
+ /** The command IA-RUNTIME-NEXT-NO-PLAN names: its help says which @plan, @milestone and @task records make a plan. */
9
+ const NO_PLAN_NEXT = 'ia next --help';
10
+ const SEATS = ['plan', 'milestone', 'task'];
11
+ const ATTRIBUTION_SUFFIX = { self: ', self-attributed', other: '', unknown: ', self-attribution unknown' };
12
+ const order = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
13
+ const refuse = (code, message, next, more = {}) => freeze({ ok: false, code, message, next, ...more });
14
+ const referenceText = (reference) => reference.kind === 'identity' ? reference.identity : `@${reference.discriminator} ${reference.name}`;
15
+ /**
16
+ * The most coordinates the intent line is read at to learn whether a conditional row can change it; past that many, a
17
+ * line that reads a conditional row stays unknown.
18
+ */
19
+ const COMPLETIONS = 256;
20
+ /** A condition as its terms read: `phase is act and severity is blocking`. */
21
+ const conditionText = (condition) => condition.map((term) => `${term.axis} is ${term.value}`).join(' and ');
22
+ /** The first of `items` per key, in their order. */
23
+ function firstPer(items, key) {
24
+ const kept = new Map();
25
+ for (const item of items)
26
+ if (!kept.has(key(item)))
27
+ kept.set(key(item), item);
28
+ return [...kept.values()];
29
+ }
30
+ /** Milestone vertices first, as they only release tasks; then tasks by (milestone identity, task identity). */
31
+ const releaseFirst = (a, b) => a.task === undefined
32
+ ? b.task === undefined
33
+ ? order(a.key, b.key)
34
+ : -1
35
+ : b.task === undefined
36
+ ? 1
37
+ : order(a.milestone, b.milestone) || order(a.task, b.task);
38
+ /** Tasks first, by (milestone identity, task identity); then milestone vertices by key. */
39
+ const tasksFirst = (a, b) => (a.task === undefined) === (b.task === undefined) ? releaseFirst(a, b) : a.task === undefined ? 1 : -1;
40
+ /**
41
+ * Kahn's algorithm over the vertices: repeatedly emit the ready vertex `releaseFirst` ranks first. Returns every vertex
42
+ * in that order, or, when a cycle leaves some waiting, the declared rows of one cycle among them, read from its first
43
+ * vertex by `tasksFirst`, and that vertex.
44
+ */
45
+ function sortVertices(vertices, arcs) {
46
+ const outgoing = new Map(), incoming = new Map(), waiting = new Map();
47
+ for (const key of vertices.keys()) {
48
+ outgoing.set(key, []);
49
+ incoming.set(key, []);
50
+ waiting.set(key, 0);
51
+ }
52
+ for (const arc of arcs) {
53
+ outgoing.get(arc.from).push(arc);
54
+ incoming.get(arc.to).push(arc);
55
+ waiting.set(arc.to, waiting.get(arc.to) + 1);
56
+ }
57
+ const ready = [...vertices.values()].filter((vertex) => waiting.get(vertex.key) === 0), emitted = [];
58
+ while (ready.length > 0) {
59
+ const vertex = ready.sort(releaseFirst).shift();
60
+ emitted.push(vertex);
61
+ for (const arc of outgoing.get(vertex.key)) {
62
+ waiting.set(arc.to, waiting.get(arc.to) - 1);
63
+ if (waiting.get(arc.to) === 0)
64
+ ready.push(vertices.get(arc.to));
65
+ }
66
+ }
67
+ if (emitted.length === vertices.size)
68
+ return { order: emitted };
69
+ // Each vertex left waits on another vertex left, so walking back along prerequisites closes a cycle. The walk
70
+ // stays on milestone vertices where it can, so a cycle of milestone rows is not reported through a milestone's tasks.
71
+ const left = new Set([...vertices.keys()].filter((key) => waiting.get(key) > 0));
72
+ const back = (key) => incoming
73
+ .get(key)
74
+ .filter((arc) => left.has(arc.from))
75
+ .sort((a, b) => releaseFirst(vertices.get(a.from), vertices.get(b.from)))[0];
76
+ const path = [], seen = new Map();
77
+ let key = [...left].map((k) => vertices.get(k)).sort(tasksFirst)[0].key;
78
+ while (!seen.has(key)) {
79
+ seen.set(key, path.length);
80
+ path.push(key);
81
+ key = back(key).from;
82
+ }
83
+ const loop = path.slice(seen.get(key)), first = loop.map((k) => vertices.get(k)).sort(tasksFirst)[0], at = loop.indexOf(first.key);
84
+ return {
85
+ cycle: [...loop.slice(at), ...loop.slice(0, at)].flatMap((k) => {
86
+ const row = back(k).row;
87
+ return row === undefined ? [] : [row];
88
+ }),
89
+ first,
90
+ };
91
+ }
92
+ /**
93
+ * The delivery view of one @plan in the scope `within`, or one refusal naming one next command. The seat is a @plan,
94
+ * @milestone or @task identity, read as its plan; without one, the plan is the only admitted @plan at band 100.
95
+ * IA-RUNTIME-NEXT-SEAT refuses a seat that is no admitted @plan, @milestone or @task; IA-RUNTIME-NEXT-NO-PLAN a seat
96
+ * that belongs to no admitted plan, or no seat and no authored plan; IA-RUNTIME-NEXT-AMBIGUOUS no seat and several
97
+ * authored plans; IA-RUNTIME-NEXT-CYCLE a plan whose `require` rows form a cycle, among tasks, milestones or both.
98
+ * Every read goes through `within`, but for the admission findings a whole-workspace `within` alone may disclose
99
+ * (db PT5), and nothing is written.
100
+ */
101
+ export function deliveryView(handle, within, seat) {
102
+ const read = { within }, snapshot = handle.snapshot(read), nodes = new Map(snapshot.records.map((node) => [node.identity, node]));
103
+ const viewed = new Map();
104
+ const rowsOf = (identity) => {
105
+ let rows = viewed.get(identity);
106
+ if (rows === undefined)
107
+ viewed.set(identity, (rows = handle.directedView(identity, read)));
108
+ return rows;
109
+ };
110
+ const word = (identity) => nodes.get(identity)?.discriminator;
111
+ const text = (identity, field) => {
112
+ const node = nodes.get(identity);
113
+ return node === undefined ? undefined : statedText(node, field);
114
+ };
115
+ /** The admitted records of `discriminator` among `identities`, once each, in identity order. */
116
+ const of = (identities, discriminator) => [...new Set(identities)].filter((identity) => word(identity) === discriminator).sort(order);
117
+ /** The counterparts of `identity`'s typed field references at `field`: its targets `out`, its holders `in`. */
118
+ const refs = (identity, field, direction) => rowsOf(identity)
119
+ .filter((row) => row.kind === 'field-ref' && row.field === field && row.direction === direction)
120
+ .map((row) => row.counterpart);
121
+ // Decision conditional-relations-in-delivery: the coordinate the scope binds, a phase or none (db resolveScope binds no
122
+ // other condition axis), which a row's condition is read against as graph traversal reads it.
123
+ const bound = snapshot.phase === undefined ? {} : { phase: snapshot.phase }, BOUND = { at: bound, closed: false };
124
+ /** The coordinates `at` may be completed to on `axis`: itself where it binds the axis, else with it absent or set. */
125
+ const completions = (at, axis) => at[axis] !== undefined ? [at] : [at, ...(valuesFor(axis) ?? []).map((value) => ({ ...at, [axis]: value }))];
126
+ /**
127
+ * The axes of `condition`, stated by `subject`, on which the bound coordinate leaves it undecided: graph
128
+ * `conditionHolds` reads the condition's terms on that axis differently at two of its completions. An axis the scope
129
+ * binds no value for is such an axis, but for provenance and artifact set, which `conditionHolds` reads from the
130
+ * subject alone, and for severity where the subject's own severity decides it (graph `effectiveSeverity` takes the
131
+ * stronger of the subject's and the coordinate's, so the coordinate can raise it but never lower it).
132
+ */
133
+ const openAxes = (condition, subject) => {
134
+ const node = nodes.get(subject), axes = [...new Set(condition.map((term) => term.axis))];
135
+ return node === undefined
136
+ ? axes
137
+ : axes.filter((axis) => {
138
+ const terms = condition.filter((term) => term.axis === axis);
139
+ return new Set(completions(bound, axis).map((at) => conditionHolds(terms, node.dimensions, at))).size > 1;
140
+ });
141
+ };
142
+ /**
143
+ * Whether `condition`, stated by `subject` (the author, graph G06's condition subject), holds where `reading` reads
144
+ * it, as graph `conditionHolds` decides it: at a closed reading's coordinate, true or false; at the bound coordinate,
145
+ * true or false where every completion of it agrees, else undefined, unless a term on another axis fails everywhere.
146
+ */
147
+ const holds = (condition, subject, reading = BOUND) => {
148
+ if (condition === undefined)
149
+ return true;
150
+ const node = nodes.get(subject);
151
+ if (node === undefined)
152
+ return undefined;
153
+ if (reading.closed)
154
+ return conditionHolds(condition, node.dimensions, reading.at);
155
+ let open = false;
156
+ for (const axis of new Set(condition.map((term) => term.axis))) {
157
+ const terms = condition.filter((term) => term.axis === axis), results = new Set(completions(bound, axis).map((at) => conditionHolds(terms, node.dimensions, at)));
158
+ if (results.size > 1)
159
+ open = true;
160
+ else if (!results.has(true))
161
+ return false;
162
+ }
163
+ return open ? undefined : true;
164
+ };
165
+ /** Why an undecided condition is unknown here: its terms, and the axes the scope binds no value to decide. */
166
+ const undecided = (condition, subject) => `conditional on ${conditionText(condition)}, which the scope binds no ${openAxes(condition, subject).join(' or ')} to decide (unknown)`;
167
+ /**
168
+ * The rows of `predicate` read from `identity`'s side, whichever end declared them, one per counterpart, the first
169
+ * whose condition holds, else the first undecided one (`holds` undefined); a row whose condition fails where it is
170
+ * read is no row.
171
+ */
172
+ const related = (identity, predicate, direction, reading = BOUND) => {
173
+ const kept = new Map();
174
+ for (const row of rowsOf(identity)) {
175
+ if (row.kind === 'field-ref' || row.predicate !== predicate || row.direction !== direction)
176
+ continue;
177
+ const at = holds(row.condition, row.declaredOn, reading);
178
+ if (at === false)
179
+ continue;
180
+ const prior = kept.get(row.counterpart);
181
+ if (prior === undefined || (prior.holds === undefined && at === true))
182
+ kept.set(row.counterpart, { row, holds: at });
183
+ }
184
+ return [...kept.values()];
185
+ };
186
+ /** The rows of `related` whose condition holds where they are read, or that have none. */
187
+ const holding = (identity, predicate, direction, reading = BOUND) => related(identity, predicate, direction, reading).flatMap((entry) => (entry.holds === true ? [entry.row] : []));
188
+ const status = (identity) => `status ${text(identity, 'work.status') ?? 'not stated'} (self-declared)`;
189
+ /** The record states `field`, a `section.key` path, whatever its value. */
190
+ const states = (identity, field) => {
191
+ const [section, key] = field.split('.');
192
+ return nodes
193
+ .get(identity)
194
+ .sections.some((s) => s.name === section && s.fields.some((f) => 'key' in f && f.key === key));
195
+ };
196
+ // db PT5: only a whole-workspace scope may disclose admission findings, so only it reads which work records admission
197
+ // refused (an identity another occurrence wins is admitted, not refused) and which files a language error refused
198
+ // whole (D03). A narrowed scope may leave tasks unread instead.
199
+ const complete = handle.isCompleteScope(within), here = complete ? '' : ' in this scope';
200
+ const refusedWork = complete
201
+ ? handle.refused.filter((record) => SEATS.includes(record.identity.split('/')[2]) && !nodes.has(record.identity))
202
+ : [], unparsed = complete
203
+ ? firstPer(handle.report.verdicts
204
+ .filter((verdict) => verdict.check === 'COMP-PARSE')
205
+ .flatMap((verdict) => verdict.findings)
206
+ .filter((finding) => finding.severity === 'error'), (finding) => finding.path)
207
+ : [];
208
+ const refusedAny = (discriminator) => refusedWork.some((record) => record.identity.split('/')[2] === discriminator);
209
+ /**
210
+ * Why a task of one milestone may go unread, or with `wholePlan` a task of the plan (a refused @milestone hides its
211
+ * tasks), when one may.
212
+ */
213
+ const unseen = (wholePlan) => !complete
214
+ ? 'records outside this scope are unknown'
215
+ : unparsed.length > 0 || refusedAny('task') || (wholePlan && refusedAny('milestone'))
216
+ ? 'records admission refused are unknown'
217
+ : undefined;
218
+ // The plan: the seat's, else the only authored one.
219
+ const authored = of(snapshot.records.filter((node) => node.band === 100).map((node) => node.identity), 'plan');
220
+ /** The view read without a seat, which runs: the only authored plan's, else the first's, else what makes a plan. */
221
+ const unseated = authored.length === 0 ? NO_PLAN_NEXT : authored.length === 1 ? 'ia next' : `ia next --seat ${authored[0]}`;
222
+ let plan;
223
+ if (seat !== undefined) {
224
+ const node = nodes.get(seat);
225
+ if (node === undefined)
226
+ return refuse('IA-RUNTIME-NEXT-SEAT', `${seat} is not an admitted record in this scope`, unseated);
227
+ if (!SEATS.includes(node.discriminator))
228
+ return refuse('IA-RUNTIME-NEXT-SEAT', `${seat} is a @${node.discriminator}; the delivery view is read from a @plan, @milestone or @task`, `ia position --seat ${seat}`);
229
+ const milestone = node.discriminator === 'task' ? of(refs(seat, 'work.milestone', 'out'), 'milestone')[0] : seat;
230
+ const found = node.discriminator === 'plan'
231
+ ? seat
232
+ : milestone === undefined
233
+ ? undefined
234
+ : of(refs(milestone, 'work.plan', 'out'), 'plan')[0];
235
+ if (found === undefined)
236
+ return refuse('IA-RUNTIME-NEXT-NO-PLAN', `${seat} belongs to no admitted @plan in this scope`, NO_PLAN_NEXT);
237
+ plan = found;
238
+ }
239
+ else {
240
+ const plans = authored;
241
+ if (plans.length === 0)
242
+ return refuse('IA-RUNTIME-NEXT-NO-PLAN', 'No admitted @plan at authored placement (band 100) in this scope', NO_PLAN_NEXT);
243
+ if (plans.length > 1)
244
+ return refuse('IA-RUNTIME-NEXT-AMBIGUOUS', `${plans.length} admitted @plan records at band 100 and no seat to choose one: ${plans.join(', ')}`, `ia next --seat ${plans[0]}`, { plans });
245
+ plan = plans[0];
246
+ }
247
+ const milestones = of(refs(plan, 'work.plan', 'in'), 'milestone');
248
+ const tasksOf = (milestone) => of(refs(milestone, 'work.milestone', 'in'), 'task');
249
+ const milestoneOf = new Map(milestones.flatMap((milestone) => tasksOf(milestone).map((task) => [task, milestone])));
250
+ const members = [...milestones, ...milestoneOf.keys()];
251
+ /** The records `identity` requires, each row whose condition holds here or that the scope does not decide. */
252
+ const requires = (identity) => related(identity, 'require', 'out');
253
+ // A requirement no admitted record answers is an admission finding with no row; the traversal still names it, with
254
+ // the lines that declare it and its condition, which is read here as a row's is.
255
+ const unanswered = new Map();
256
+ for (const edge of handle.traverse({ ...read, start: members, follow: ['require'], depth: 1 }).dangling)
257
+ if (edge.from !== null)
258
+ unanswered.set(edge.from, [
259
+ ...(unanswered.get(edge.from) ?? []),
260
+ {
261
+ reference: referenceText(edge.reference),
262
+ lines: edge.assertions.map((assertion) => assertion.source.line),
263
+ holds: holds(edge.condition, edge.conditionSubject),
264
+ ...(edge.condition === undefined ? {} : { condition: edge.condition }),
265
+ subject: edge.conditionSubject,
266
+ },
267
+ ]);
268
+ /**
269
+ * The references of `holder`'s own `require` declarations that give neither a row nor a dangling edge in this scope:
270
+ * their answer is outside it (db D09 prunes the row, and the traversal never reaches past the scope) or no row is
271
+ * read for it, so the requirement is unknown, never met. A declaration whose condition fails here is none; one the
272
+ * scope does not decide is unknown all the same. Every row and dangling edge answers its lines, conditional or not.
273
+ */
274
+ const unread = (holder) => {
275
+ const answered = new Set([
276
+ ...rowsOf(holder)
277
+ .filter((row) => row.kind === 'edge' && row.predicate === 'require' && row.direction === 'out')
278
+ .map((row) => row.source.line),
279
+ ...(unanswered.get(holder) ?? []).flatMap((entry) => entry.lines),
280
+ ]);
281
+ return nodes
282
+ .get(holder)
283
+ .edges.filter((edge) => edge.predicate === 'require' &&
284
+ edge.direction === 'out' &&
285
+ !answered.has(edge.span.line) &&
286
+ holds(edge.condition, holder) !== false)
287
+ .map((edge) => referenceText(edge.reference));
288
+ };
289
+ // One global order. A milestone is two vertices, its start (its own prerequisites met) and its end (satisfied):
290
+ // its tasks follow its start and precede its end, and a record requiring it follows its end. Requirements outside
291
+ // the plan are basis lines only, and so is a conditional requirement the scope does not decide.
292
+ const start = (milestone) => `start ${milestone}`, end = (milestone) => `end ${milestone}`;
293
+ const vertices = new Map(), arcs = [];
294
+ for (const milestone of milestones) {
295
+ vertices.set(start(milestone), { key: start(milestone), milestone });
296
+ vertices.set(end(milestone), { key: end(milestone), milestone });
297
+ arcs.push({ from: start(milestone), to: end(milestone) });
298
+ }
299
+ for (const [task, milestone] of milestoneOf) {
300
+ vertices.set(task, { key: task, milestone, task });
301
+ arcs.push({ from: start(milestone), to: task }, { from: task, to: end(milestone) });
302
+ }
303
+ for (const member of members)
304
+ for (const row of holding(member, 'require', 'out')) {
305
+ const target = row.counterpart, from = milestoneOf.has(target) ? target : milestones.includes(target) ? end(target) : undefined;
306
+ if (from !== undefined)
307
+ arcs.push({
308
+ from,
309
+ to: milestoneOf.has(member) ? member : start(member),
310
+ row: { from: member, to: target, declaredOn: row.declaredOn, path: row.source.path, line: row.source.line },
311
+ });
312
+ }
313
+ const sorted = sortVertices(vertices, arcs);
314
+ if ('cycle' in sorted)
315
+ return refuse('IA-RUNTIME-NEXT-CYCLE', `The require rows of ${plan} form a cycle, so no order exists: ${sorted.cycle
316
+ .map((row) => `${row.from} requires ${row.to}`)
317
+ .join(', ')}`, `ia position --seat ${sorted.first.task ?? sorted.first.milestone} --shape sequence`, { cycle: sorted.cycle });
318
+ // Exit evidence and the worked line read the same observations.
319
+ const observed = new Map();
320
+ const observationsOf = (identity) => {
321
+ let found = observed.get(identity);
322
+ if (found === undefined) {
323
+ const named = of([...refs(identity, 'evidence.subject', 'in'), ...refs(identity, 'work.exit-evidence', 'out')], 'observation');
324
+ found = named.map((observation) => {
325
+ const verdict = text(observation, 'evidence.verdict'), revision = text(observation, 'evidence.subject-revision'), evaluator = text(observation, 'evidence.evaluator');
326
+ return {
327
+ observation,
328
+ ...(verdict === undefined ? {} : { verdict }),
329
+ ...(revision === undefined ? {} : { readiness: handle.readiness(identity, revision, read) }),
330
+ ...(evaluator === undefined ? {} : { evaluator }),
331
+ };
332
+ });
333
+ observed.set(identity, found);
334
+ }
335
+ return found;
336
+ };
337
+ const evidenceOf = (identity) => observationsOf(identity).find((o) => o.verdict === 'success' && o.readiness === 'current');
338
+ const satisfaction = (milestone) => {
339
+ const own = evidenceOf(milestone);
340
+ if (own !== undefined)
341
+ return { satisfied: true, reason: `exit evidence ${own.observation}` };
342
+ const tasks = tasksOf(milestone), missing = tasks.filter((task) => evidenceOf(task) === undefined).length, why = unseen(false);
343
+ if (tasks.length === 0)
344
+ return { satisfied: false, reason: `no task${here} and no exit evidence` };
345
+ if (missing > 0)
346
+ return { satisfied: false, reason: `exit evidence missing for ${missing} of ${tasks.length} tasks` };
347
+ return why === undefined
348
+ ? { satisfied: true, reason: 'every task has exit evidence' }
349
+ : { satisfied: false, reason: `every task the view reads has exit evidence; ${why}` };
350
+ };
351
+ const prerequisite = (target, via) => {
352
+ const discriminator = word(target);
353
+ let satisfied, basis;
354
+ switch (discriminator) {
355
+ case 'task': {
356
+ const evidence = evidenceOf(target);
357
+ satisfied = evidence !== undefined;
358
+ basis = `task ${target}: ${evidence === undefined ? 'no exit evidence' : `exit evidence ${evidence.observation}`}`;
359
+ break;
360
+ }
361
+ case 'milestone': {
362
+ const reading = satisfaction(target);
363
+ satisfied = reading.satisfied;
364
+ basis = `milestone ${target}: ${reading.reason}`;
365
+ break;
366
+ }
367
+ case 'decision':
368
+ satisfied = text(target, 'decision.choice') !== undefined;
369
+ basis = `decision ${target}: ${satisfied ? 'choice made' : 'no choice'}`;
370
+ break;
371
+ default:
372
+ satisfied = false;
373
+ basis = `@${discriminator} ${target}: no delivery basis`;
374
+ }
375
+ return {
376
+ target,
377
+ word: discriminator,
378
+ ...(via === undefined ? {} : { via }),
379
+ satisfied,
380
+ basis: via === undefined ? basis : `${basis} (via ${via})`,
381
+ };
382
+ };
383
+ /**
384
+ * A requirement of `target` whose `condition`, stated by `subject`, the scope does not decide: never satisfied,
385
+ * whatever the target's state, its basis the condition and the axes the scope binds no value to decide.
386
+ */
387
+ const conditional = (target, via, condition, subject) => {
388
+ const discriminator = word(target), basis = `${['task', 'milestone', 'decision'].includes(discriminator) ? discriminator : `@${discriminator}`} ${target}: ${undecided(condition, subject)}`;
389
+ return {
390
+ target,
391
+ word: discriminator,
392
+ ...(via === undefined ? {} : { via }),
393
+ satisfied: false,
394
+ basis: via === undefined ? basis : `${basis} (via ${via})`,
395
+ };
396
+ };
397
+ /**
398
+ * The task's own requirements, then the ones it inherits from its milestone, each target once: the first line whose
399
+ * requirement holds here, else the first conditional one the scope does not decide.
400
+ */
401
+ const prerequisitesOf = (task) => {
402
+ const unmet = (reference, via, reason) => ({
403
+ target: reference,
404
+ ...(via === undefined ? {} : { via }),
405
+ satisfied: false,
406
+ basis: `${reference}: ${reason}${via === undefined ? '' : ` (via ${via})`}`,
407
+ });
408
+ const lines = (holder, via) => [
409
+ ...requires(holder).map(({ row, holds: at }) => ({
410
+ line: at === true
411
+ ? prerequisite(row.counterpart, via)
412
+ : conditional(row.counterpart, via, row.condition, row.declaredOn),
413
+ decided: at === true,
414
+ })),
415
+ ...(unanswered.get(holder) ?? []).flatMap(({ reference, holds: at, condition, subject }) => at === false
416
+ ? []
417
+ : [
418
+ {
419
+ line: unmet(reference, via, at === true
420
+ ? 'no admitted record answers it'
421
+ : `no admitted record answers it, ${undecided(condition, subject)}`),
422
+ decided: at === true,
423
+ },
424
+ ]),
425
+ ...unread(holder).map((reference) => ({
426
+ line: unmet(reference, via, 'no record in this scope answers it (unknown)'),
427
+ decided: true,
428
+ })),
429
+ ];
430
+ const milestone = milestoneOf.get(task), kept = new Map();
431
+ for (const entry of [...lines(task, undefined), ...lines(milestone, milestone)]) {
432
+ const prior = kept.get(entry.line.target);
433
+ if (prior === undefined || (!prior.decided && entry.decided))
434
+ kept.set(entry.line.target, entry);
435
+ }
436
+ return [...kept.values()].map((entry) => entry.line);
437
+ };
438
+ /**
439
+ * The @decision records grounding `record` through a row that holds where `reading` reads it, in identity order; the
440
+ * live ones, which no other of them supersedes unless the two supersede each other through a cycle among them, which
441
+ * removes neither; those in such a cycle; and the conditional rows the reading leaves undecided among those the
442
+ * grounding is read from (each grounding row, then each supersession between two decisions grounding it), `record`
443
+ * named as `label` in them.
444
+ */
445
+ const groundingOf = (record, reading = BOUND, label = record) => {
446
+ const grounds = related(record, 'ground', 'in', reading).filter((entry) => word(entry.row.counterpart) === 'decision'), decisions = of(grounds.flatMap((entry) => (entry.holds === true ? [entry.row.counterpart] : [])), 'decision'), candidates = of(grounds.map((entry) => entry.row.counterpart), 'decision');
447
+ const pending = [
448
+ ...grounds.flatMap(({ row, holds: at }) => at === true
449
+ ? []
450
+ : [{ text: `${row.counterpart} grounds ${label}`, condition: row.condition, subject: row.declaredOn }]),
451
+ ...candidates.flatMap((decision) => related(decision, 'supersede', 'out', reading).flatMap(({ row, holds: at }) => at === true || !candidates.includes(row.counterpart)
452
+ ? []
453
+ : [
454
+ {
455
+ text: `${decision} supersedes ${row.counterpart}`,
456
+ condition: row.condition,
457
+ subject: row.declaredOn,
458
+ },
459
+ ])),
460
+ ];
461
+ const supersedes = new Map(decisions.map((decision) => [
462
+ decision,
463
+ holding(decision, 'supersede', 'out', reading)
464
+ .map((row) => row.counterpart)
465
+ .filter((other) => decisions.includes(other)),
466
+ ]));
467
+ /** `to` is reached from `from` through one or more supersessions among the decisions. */
468
+ const reaches = (from, to) => {
469
+ const seen = new Set(), queue = [...supersedes.get(from)];
470
+ while (queue.length > 0) {
471
+ const next = queue.shift();
472
+ if (next === to)
473
+ return true;
474
+ if (!seen.has(next)) {
475
+ seen.add(next);
476
+ queue.push(...supersedes.get(next));
477
+ }
478
+ }
479
+ return false;
480
+ };
481
+ return {
482
+ live: decisions.filter((decision) => !decisions.some((other) => supersedes.get(other).includes(decision) && !reaches(decision, other))),
483
+ cyclic: decisions.filter((decision) => reaches(decision, decision)),
484
+ pending,
485
+ };
486
+ };
487
+ /** `records` with those `sure` holds before the rest, each part in its order. */
488
+ const sureFirst = (records, sure, key) => [...records].sort((a, b) => Number(!sure.has(key(a))) - Number(!sure.has(key(b))));
489
+ /**
490
+ * The first live @decision grounding `identity` where `reading` reads it that has a choice and an effective revision
491
+ * (design §10 line 1), each conditional row the reading leaves undecided read as no row, a decision a row that holds
492
+ * at the bound coordinate grounds read before one only a conditional row grounds; and those undecided rows.
493
+ */
494
+ const acceptedBy = (identity, reading, label = identity) => {
495
+ const grounding = groundingOf(identity, reading, label), sure = new Set(holding(identity, 'ground', 'in').map((row) => row.counterpart));
496
+ for (const decision of sureFirst(grounding.live, sure, (live) => live)) {
497
+ const revision = text(decision, 'decision.effective-revision');
498
+ if (text(decision, 'decision.choice') !== undefined && revision !== undefined)
499
+ return { accepted: { decision, revision }, pending: grounding.pending };
500
+ }
501
+ return { pending: grounding.pending };
502
+ };
503
+ /**
504
+ * The intent line where `reading` reads it, each conditional row the reading leaves undecided read as no row, and
505
+ * those of them that could change it. A supersession by an accepted record through a row that holds decides it, so no
506
+ * later supersession is read, a record a row that holds at the bound coordinate names read before one only a
507
+ * conditional row names; one the reading leaves undecided counts when its record is or may be accepted.
508
+ */
509
+ const intentAt = (task, reading) => {
510
+ const pending = [], sure = new Set(holding(task, 'supersede', 'in').map((row) => row.counterpart));
511
+ for (const { row, holds: at } of sureFirst(related(task, 'supersede', 'in', reading), sure, (entry) => entry.row.counterpart)) {
512
+ const by = acceptedBy(row.counterpart, reading);
513
+ if (at === undefined && (by.accepted !== undefined || by.pending.length > 0))
514
+ pending.push({ text: `${row.counterpart} supersedes it`, condition: row.condition, subject: row.declaredOn });
515
+ pending.push(...by.pending);
516
+ if (at === true && by.accepted !== undefined)
517
+ return {
518
+ line: {
519
+ dimension: 'intent',
520
+ value: 'superseded',
521
+ basis: `${row.counterpart} supersedes it, grounded by ${by.accepted.decision} @${by.accepted.revision}`,
522
+ },
523
+ pending,
524
+ };
525
+ }
526
+ const own = acceptedBy(task, reading, 'it');
527
+ pending.push(...own.pending);
528
+ if (own.accepted !== undefined)
529
+ return {
530
+ line: {
531
+ dimension: 'intent',
532
+ value: 'accepted',
533
+ basis: `${own.accepted.decision}: choice made, effective-revision ${own.accepted.revision}`,
534
+ },
535
+ pending,
536
+ };
537
+ const decision = groundingOf(task, reading).live[0];
538
+ return {
539
+ line: {
540
+ dimension: 'intent',
541
+ value: 'unknown',
542
+ basis: decision === undefined
543
+ ? `no @decision${here} grounds it`
544
+ : `${decision}: ${text(decision, 'decision.choice') === undefined ? 'no choice' : 'no effective-revision'}`,
545
+ },
546
+ pending,
547
+ };
548
+ };
549
+ /**
550
+ * The intent line (design §10 line 1). When the bound coordinate leaves a row it reads undecided, the line is read
551
+ * again at each completion of the bound coordinate on the axes those rows leave open (each absent, or set to each of
552
+ * its values), where every row is decided: a line that reads the same at every one is the line, since no binding the
553
+ * scope could take changes it and the conditional row is never read as satisfied, as when a decision that only may
554
+ * ground the task has no choice while another grounds it unconditionally and is accepted; else the intent is unknown,
555
+ * its basis the first such row. Past COMPLETIONS coordinates the line is not read again and stays unknown.
556
+ */
557
+ const intent = (task) => {
558
+ const { line, pending } = intentAt(task, BOUND);
559
+ if (pending.length === 0)
560
+ return line;
561
+ const axes = [...new Set(pending.flatMap((row) => openAxes(row.condition, row.subject)))], size = axes.reduce((product, axis) => product * ((valuesFor(axis)?.length ?? 0) + 1), 1);
562
+ if (size <= COMPLETIONS) {
563
+ const readings = axes
564
+ .reduce((all, axis) => all.flatMap((at) => completions(at, axis)), [bound])
565
+ .map((at) => intentAt(task, { at, closed: true }));
566
+ const [first] = readings;
567
+ if (first !== undefined &&
568
+ readings.every((reading) => reading.pending.length === 0 &&
569
+ reading.line.value === first.line.value &&
570
+ reading.line.basis === first.line.basis))
571
+ return first.line;
572
+ }
573
+ const [row] = pending;
574
+ return { dimension: 'intent', value: 'unknown', basis: `${row.text} ${undecided(row.condition, row.subject)}` };
575
+ };
576
+ const worked = (task) => {
577
+ const observations = observationsOf(task), current = (verdict) => observations.find((o) => o.readiness === 'current' && o.verdict === verdict);
578
+ const success = current('success'), refusal = current('refusal'), stale = observations.find((o) => o.readiness === 'previous');
579
+ if (success !== undefined)
580
+ return {
581
+ dimension: 'worked',
582
+ value: 'observed success',
583
+ basis: `${success.observation}: success at the current digest`,
584
+ };
585
+ if (refusal !== undefined)
586
+ return {
587
+ dimension: 'worked',
588
+ value: 'observed refusal',
589
+ basis: `${refusal.observation}: refusal at the current digest`,
590
+ };
591
+ if (stale !== undefined)
592
+ return {
593
+ dimension: 'worked',
594
+ value: 'stale',
595
+ basis: `${stale.observation}: its subject-revision is the digest in the previous snapshot`,
596
+ };
597
+ const other = observations[0];
598
+ // A narrowed scope may hold an observation it does not read, so absence there is unknown (IM-24).
599
+ if (other === undefined)
600
+ return {
601
+ dimension: 'worked',
602
+ value: complete ? 'unobserved' : 'unknown',
603
+ basis: `no @observation${here} names it`,
604
+ };
605
+ return {
606
+ dimension: 'worked',
607
+ value: 'unknown',
608
+ basis: `${other.observation}: ${other.readiness === undefined
609
+ ? 'no subject-revision'
610
+ : other.readiness === 'current'
611
+ ? `verdict ${other.verdict ?? 'not recorded'} at the current digest`
612
+ : 'its subject-revision matches neither retained snapshot'}`,
613
+ };
614
+ };
615
+ /** The steward the @system `system` names in `head.steward`, when the scope admits that @system. */
616
+ const stewardOf = (system) => {
617
+ const identity = `floor/definition/system/${system}`;
618
+ return nodes.has(identity) ? refs(identity, 'head.steward', 'out')[0] : undefined;
619
+ };
620
+ /** Whether the evaluator is the identity the task's `work.owner-agent` names, which only an answer in scope can say. */
621
+ const attributionOf = (task, evaluator) => {
622
+ const owner = refs(task, 'work.owner-agent', 'out')[0];
623
+ if (owner === undefined)
624
+ return states(task, 'work.owner-agent') ? 'unknown' : 'other';
625
+ return evaluator === undefined ? 'unknown' : evaluator === owner ? 'self' : 'other';
626
+ };
627
+ const ordered = sorted.order.flatMap((vertex) => (vertex.task === undefined ? [] : [vertex.task]));
628
+ const tasks = ordered.map((identity) => {
629
+ const prerequisites = prerequisitesOf(identity), found = evidenceOf(identity);
630
+ const evidence = found === undefined
631
+ ? undefined
632
+ : {
633
+ observation: found.observation,
634
+ ...(found.evaluator === undefined ? {} : { evaluator: found.evaluator }),
635
+ attribution: attributionOf(identity, found.evaluator),
636
+ };
637
+ const blockers = prerequisites.filter((p) => !p.satisfied);
638
+ const [verdict, line] = evidence !== undefined
639
+ ? [
640
+ 'evidenced',
641
+ `exit evidence recorded (${evidence.observation}, evaluator ${evidence.evaluator ?? 'not recorded'}${ATTRIBUTION_SUFFIX[evidence.attribution]})`,
642
+ ]
643
+ : blockers.length === 0
644
+ ? ['unblocked', 'no declared blocker']
645
+ : ['blocked', `blocked (${blockers.map((p) => p.basis).join('; ')})`];
646
+ return {
647
+ identity,
648
+ milestone: milestoneOf.get(identity),
649
+ status: status(identity),
650
+ prerequisites,
651
+ verdict,
652
+ line,
653
+ ...(evidence === undefined ? {} : { evidence }),
654
+ states: [
655
+ intent(identity),
656
+ { dimension: 'definition', value: 'admitted', basis: `db admission at digest ${nodes.get(identity).digest}` },
657
+ { dimension: 'realizable', value: 'not applicable', basis: 'a @task binds nothing' },
658
+ { dimension: 'realized', value: 'not applicable', basis: 'no effect owner realizes a @task' },
659
+ worked(identity),
660
+ ],
661
+ };
662
+ });
663
+ const plannedMilestones = sorted.order
664
+ .filter((vertex) => vertex.key === start(vertex.milestone))
665
+ .map(({ milestone }) => {
666
+ const reading = satisfaction(milestone);
667
+ return {
668
+ identity: milestone,
669
+ status: status(milestone),
670
+ tasks: ordered.filter((task) => milestoneOf.get(task) === milestone),
671
+ satisfied: reading.satisfied,
672
+ basis: reading.reason,
673
+ };
674
+ });
675
+ // Review items: live decisions grounding one record of the plan; accepted specs one of which supersedes the other
676
+ // with no replaced-scope, so the partial supersession that keeps both live is no item; and, on a whole-workspace
677
+ // scope, the work records and files admission refused, which no plan can place.
678
+ const review = [];
679
+ const item = (kind, records, system, message) => {
680
+ const owner = system === undefined ? undefined : stewardOf(system);
681
+ review.push({ kind, records, ...(owner === undefined ? {} : { owner }), message });
682
+ };
683
+ for (const record of [plan, ...plannedMilestones.map((m) => m.identity), ...ordered]) {
684
+ const { live, cyclic } = groundingOf(record);
685
+ if (live.length > 1)
686
+ item('grounding', [record, ...live], nodes.get(record).system, `${live.join(' and ')} each ground ${record}; ${cyclic.length === 0 ? 'none supersedes another' : `${cyclic.join(' and ')} supersede one another in a cycle`}`);
687
+ }
688
+ const accepted = (spec) => text(spec, 'work.status') === 'accepted';
689
+ for (const spec of of([...nodes.keys()], 'spec'))
690
+ for (const row of holding(spec, 'supersede', 'out')) {
691
+ const replaced = row.counterpart;
692
+ if (word(replaced) === 'spec' &&
693
+ text(spec, 'work.replaced-scope') === undefined &&
694
+ accepted(spec) &&
695
+ accepted(replaced))
696
+ item('currency', [spec, replaced], nodes.get(replaced).system, `${spec} supersedes ${replaced} with no replaced-scope, yet both declare status accepted`);
697
+ }
698
+ for (const refused of refusedWork)
699
+ item('admission', [refused.identity], refused.identity.split('/')[0], `admission refused ${refused.identity} at ${refused.path}:${refused.line} (${refused.reason}), so no plan can place it; ia validate reports why`);
700
+ for (const finding of unparsed)
701
+ item('admission', [], undefined, `${finding.code} at ${finding.path}:${finding.line} refuses every record in that file, so no plan can read them; ia validate reports why`);
702
+ const evidenced = tasks.filter((task) => task.verdict === 'evidenced').length, first = tasks.find((task) => task.verdict === 'unblocked'), why = unseen(true);
703
+ const summary = tasks.length === 0
704
+ ? `${plan} has no task${here}`
705
+ : evidenced === tasks.length
706
+ ? why === undefined
707
+ ? `every task has exit evidence (${evidenced} of ${tasks.length})`
708
+ : `every task the view reads has exit evidence (${evidenced} of ${tasks.length}); ${why}`
709
+ : `${evidenced} of ${tasks.length} tasks have exit evidence; ${first === undefined ? 'every other task is blocked' : `next: ${first.identity}, with no declared blocker`}`;
710
+ return freeze({
711
+ ok: true,
712
+ view: {
713
+ format: 'ia.delivery-view.v1',
714
+ revision: snapshot.revision,
715
+ plan,
716
+ milestones: plannedMilestones,
717
+ tasks,
718
+ review,
719
+ next: first === undefined ? null : `ia position --seat ${first.identity} --shape sequence`,
720
+ summary,
721
+ },
722
+ });
723
+ }
724
+ //# sourceMappingURL=next.js.map