@sdd-method/maintain-cli 0.11.0 → 0.13.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 (38) hide show
  1. package/dist/lib/behaviour-store/archive.js +13 -0
  2. package/dist/lib/catalogue/aggregate.js +64 -0
  3. package/dist/lib/catalogue/build.js +45 -2
  4. package/dist/lib/catalogue/builders/adr-governs.js +39 -0
  5. package/dist/lib/catalogue/builders/adrs.js +11 -0
  6. package/dist/lib/catalogue/builders/capability-spec.js +1 -0
  7. package/dist/lib/catalogue/builders/contract-revisions.js +126 -0
  8. package/dist/lib/catalogue/builders/data-model.js +316 -0
  9. package/dist/lib/catalogue/builders/entities-mermaid.js +18 -85
  10. package/dist/lib/catalogue/builders/feature-grounding.js +1 -0
  11. package/dist/lib/catalogue/builders/features.js +23 -2
  12. package/dist/lib/catalogue/builders/integration-components.js +49 -5
  13. package/dist/lib/catalogue/builders/journey-requirement.js +144 -0
  14. package/dist/lib/catalogue/builders/quality-scores.js +17 -0
  15. package/dist/lib/catalogue/builders/requirements.js +168 -32
  16. package/dist/lib/catalogue/canonical-schema.yaml +845 -28
  17. package/dist/lib/catalogue/manifest-loader.js +13 -0
  18. package/dist/lib/catalogue/retired-catalogues.js +25 -0
  19. package/dist/lib/catalogue/rubric-coverage-map.yaml +108 -2
  20. package/dist/lib/catalogue/schema-compat.js +1 -1
  21. package/dist/lib/catalogue/schema-loader.js +3 -0
  22. package/dist/lib/catalogue/staleness-verdicts.js +75 -6
  23. package/dist/lib/metamodel/tql-subset-parser.js +35 -2
  24. package/dist/lib/structure/catalogue.js +183 -0
  25. package/dist/lib/structure/compose.js +174 -0
  26. package/dist/lib/structure/effects.js +36 -0
  27. package/dist/lib/structure/model.js +212 -0
  28. package/dist/lib/structure/render.js +242 -0
  29. package/dist/lib/structure/view.js +301 -0
  30. package/dist/lib/validate/agreement-evidence.js +216 -0
  31. package/dist/lib/validate/behaviour-store.js +516 -28
  32. package/dist/lib/validate/dispatch.js +21 -0
  33. package/dist/lib/validate/feature-spec-pointers.js +175 -0
  34. package/dist/lib/validate/journey-impact.js +193 -0
  35. package/dist/lib/validate/structural-model.js +265 -0
  36. package/dist/maintain-version.json +2 -2
  37. package/dist/verify-version.json +2 -2
  38. package/package.json +2 -2
@@ -0,0 +1,301 @@
1
+ import { elementKey, revision } from "./model.js";
2
+ export const STRUCTURE = "structure";
3
+ export function catalogueOf(schema, name) {
4
+ return schema.catalogues.find((c) => c.name === name);
5
+ }
6
+ /** The model's elements as one view, reporting an id held twice. */
7
+ export function viewOf(files, problems) {
8
+ const view = new Map();
9
+ for (const f of files) {
10
+ for (const e of f.elements) {
11
+ const byId = view.get(e.catalogue) ?? new Map();
12
+ const prior = byId.get(e.id);
13
+ if (prior) {
14
+ problems.push(`${e.file}: ${elementKey(e.catalogue, e.id)} is also in ${prior.file}; an element is owned by one partition, and an id is held once`);
15
+ continue;
16
+ }
17
+ byId.set(e.id, e);
18
+ view.set(e.catalogue, byId);
19
+ }
20
+ }
21
+ return view;
22
+ }
23
+ export function revisionOf(e) {
24
+ return revision(e.catalogue, e.id, e.columns);
25
+ }
26
+ function typeOk(type, v) {
27
+ switch (type) {
28
+ case "int":
29
+ case "integer":
30
+ return typeof v === "number" && Number.isInteger(v);
31
+ case "number":
32
+ return typeof v === "number";
33
+ case "boolean":
34
+ return typeof v === "boolean";
35
+ case "date":
36
+ return typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v);
37
+ default:
38
+ return typeof v === "string";
39
+ }
40
+ }
41
+ /** The element's own shape against its catalogue: class, columns, required columns, types, vocabularies. */
42
+ export function checkElementShape(schema, e, where, problems) {
43
+ const key = elementKey(e.catalogue, e.id);
44
+ const cat = catalogueOf(schema, e.catalogue);
45
+ if (!cat) {
46
+ problems.push(`${where}: ${key}: the metamodel declares no catalogue ${e.catalogue}`);
47
+ return;
48
+ }
49
+ if (cat.sourceOfTruth !== STRUCTURE) {
50
+ problems.push(`${where}: ${key}: ${e.catalogue} is of class ${cat.sourceOfTruth ?? "(none)"}, not structure; it is authored elsewhere`);
51
+ return;
52
+ }
53
+ for (const [col, v] of Object.entries(e.columns)) {
54
+ const def = cat.columns.find((c) => c.name === col);
55
+ if (!def) {
56
+ problems.push(`${where}: ${key}: ${e.catalogue} has no column ${col}`);
57
+ continue;
58
+ }
59
+ if (def.sourceOfTruth !== STRUCTURE) {
60
+ problems.push(`${where}: ${key}: ${e.catalogue}.${col} is of class ${def.sourceOfTruth ?? "(none)"}, not structure; it is never written in the model`);
61
+ continue;
62
+ }
63
+ if (v === "")
64
+ problems.push(`${where}: ${key}: ${col} is empty; omit an empty value`);
65
+ else if (!typeOk(def.type, v))
66
+ problems.push(`${where}: ${key}: ${col} must be of type ${def.type}`);
67
+ const en = cat.columnEnums[col];
68
+ if (en !== undefined && typeof v === "string" && v !== "") {
69
+ const values = schema.enums[en.replace(/^enums\./, "")]?.values.map((x) => x.value) ?? [];
70
+ if (!values.includes(v))
71
+ problems.push(`${where}: ${key}: ${col} ${JSON.stringify(v)} is not a value of ${en}`);
72
+ }
73
+ }
74
+ for (const def of cat.columns) {
75
+ if (def.name === cat.primaryKey || def.nullable || def.sourceOfTruth !== STRUCTURE)
76
+ continue;
77
+ if (e.columns[def.name] === undefined)
78
+ problems.push(`${where}: ${key}: required column ${def.name} is missing`);
79
+ }
80
+ }
81
+ function find(view, catalogue, column, value) {
82
+ const byId = view.get(catalogue);
83
+ if (!byId)
84
+ return undefined;
85
+ if (column === "id")
86
+ return byId.get(value);
87
+ for (const e of byId.values())
88
+ if (String(e.columns[column] ?? "") === value)
89
+ return e;
90
+ return undefined;
91
+ }
92
+ /** The element's references: each non-external foreign key with a value. */
93
+ export function referencesOf(schema, e) {
94
+ const cat = catalogueOf(schema, e.catalogue);
95
+ if (!cat)
96
+ return [];
97
+ const out = [];
98
+ for (const fk of cat.foreignKeys) {
99
+ if (fk.external)
100
+ continue;
101
+ const v = e.columns[fk.column];
102
+ if (v === undefined || v === "")
103
+ continue;
104
+ const [target, targetColumn] = fk.references.split(".");
105
+ out.push({ column: fk.column, catalogue: target, targetColumn: targetColumn ?? "id", value: String(v), structural: catalogueOf(schema, target)?.sourceOfTruth === STRUCTURE });
106
+ }
107
+ return out;
108
+ }
109
+ /** The natural key's value for an element, or null when the catalogue declares none or the element lacks a part. */
110
+ function naturalKey(cat, e) {
111
+ const nk = cat.naturalKey;
112
+ if (!nk || nk.length === 0)
113
+ return null;
114
+ const parts = nk.map((c) => (c === "id" ? e.id : e.columns[c]));
115
+ if (parts.some((p) => p === undefined || p === ""))
116
+ return null;
117
+ return parts.map(String).join("\u0000");
118
+ }
119
+ /**
120
+ * The checks a view must satisfy on its own: every element's shape, references resolved within the view (or, into a
121
+ * catalogue of another class, against its built rows), no cycle through a self-reference, natural keys unique, and
122
+ * domain invariants naming their entity's own attributes and relationships.
123
+ */
124
+ export function validateView(schema, view, built, problems, unresolved) {
125
+ for (const [catalogue, byId] of view) {
126
+ const cat = catalogueOf(schema, catalogue);
127
+ for (const e of byId.values()) {
128
+ const shape = [];
129
+ checkElementShape(schema, e, e.file, shape);
130
+ problems.push(...shape);
131
+ if (!cat || cat.sourceOfTruth !== STRUCTURE)
132
+ continue;
133
+ for (const r of referencesOf(schema, e)) {
134
+ if (r.structural) {
135
+ if (!find(view, r.catalogue, r.targetColumn, r.value))
136
+ problems.push(`${e.file}: ${elementKey(catalogue, e.id)}: ${r.column} ${JSON.stringify(r.value)} names no ${r.catalogue} element in this view (${elementKey(r.catalogue, r.value)})`);
137
+ }
138
+ else {
139
+ const rows = built(r.catalogue, r.targetColumn);
140
+ if (rows === null)
141
+ unresolved.add(r.catalogue);
142
+ else if (!rows.has(r.value))
143
+ problems.push(`${e.file}: ${elementKey(catalogue, e.id)}: ${r.column} ${JSON.stringify(r.value)} names no row of ${r.catalogue} as built`);
144
+ }
145
+ }
146
+ }
147
+ if (!cat || cat.sourceOfTruth !== STRUCTURE)
148
+ continue;
149
+ // Hierarchies through a self-reference stay acyclic.
150
+ for (const fk of cat.foreignKeys.filter((f) => f.references.split(".")[0] === catalogue && !f.external)) {
151
+ const reported = new Set();
152
+ for (const start of byId.values()) {
153
+ const path = [];
154
+ const onPath = new Set();
155
+ let cur = start;
156
+ while (cur && !onPath.has(cur.id)) {
157
+ onPath.add(cur.id);
158
+ path.push(cur.id);
159
+ const next = cur.columns[fk.column];
160
+ cur = next === undefined || next === "" ? undefined : byId.get(String(next));
161
+ }
162
+ if (cur && onPath.has(cur.id)) {
163
+ const cycle = path.slice(path.indexOf(cur.id));
164
+ const sig = [...cycle].sort().join(",");
165
+ if (!reported.has(sig)) {
166
+ reported.add(sig);
167
+ problems.push(`${start.file}: ${catalogue}.${fk.column} forms a cycle: ${[...cycle, cur.id].map((id) => elementKey(catalogue, id)).join(" -> ")}`);
168
+ }
169
+ }
170
+ }
171
+ }
172
+ // Natural keys are unique.
173
+ const seen = new Map();
174
+ for (const e of byId.values()) {
175
+ const k = naturalKey(cat, e);
176
+ if (k === null)
177
+ continue;
178
+ const prior = seen.get(k);
179
+ if (prior)
180
+ problems.push(`${e.file}: ${elementKey(catalogue, e.id)} and ${elementKey(catalogue, prior.id)} share the natural key (${cat.naturalKey.join(", ")}) ${JSON.stringify(k.split("\u0000").join(", "))}`);
181
+ else
182
+ seen.set(k, e);
183
+ }
184
+ }
185
+ // Domain invariants name their own entity's attributes and relationships.
186
+ for (const inv of view.get("domain_invariants")?.values() ?? []) {
187
+ const key = elementKey("domain_invariants", inv.id);
188
+ const entity = String(inv.columns["entity_id"] ?? "");
189
+ const kind = String(inv.columns["kind"] ?? "");
190
+ const attrs = String(inv.columns["attribute_ids"] ?? "").split(";").map((s) => s.trim()).filter(Boolean);
191
+ const rel = String(inv.columns["relationship_id"] ?? "");
192
+ if ((kind === "unique" || kind === "required") && attrs.length === 0)
193
+ problems.push(`${inv.file}: ${key}: a ${kind} invariant names its attributes (attribute_ids)`);
194
+ if (kind === "cardinality" && rel === "")
195
+ problems.push(`${inv.file}: ${key}: a cardinality invariant names its relationship (relationship_id)`);
196
+ for (const a of attrs) {
197
+ const at = view.get("entity_attributes")?.get(a);
198
+ if (!at)
199
+ problems.push(`${inv.file}: ${key}: attribute ${elementKey("entity_attributes", a)} is not in this view`);
200
+ else if (String(at.columns["entity_id"] ?? "") !== entity)
201
+ problems.push(`${inv.file}: ${key}: attribute ${elementKey("entity_attributes", a)} belongs to ${String(at.columns["entity_id"] ?? "")}, not ${entity}`);
202
+ }
203
+ if (rel !== "") {
204
+ const r = view.get("entity_relationships")?.get(rel);
205
+ if (r && String(r.columns["from_entity_id"] ?? "") !== entity)
206
+ problems.push(`${inv.file}: ${key}: relationship ${elementKey("entity_relationships", rel)} is ${String(r.columns["from_entity_id"] ?? "")}'s, not ${entity}'s`);
207
+ }
208
+ }
209
+ }
210
+ /**
211
+ * One change's deltas against the current view (M-ADR 0230 §4.4): each element's shape, ADDED ids new, MODIFIED and
212
+ * REMOVED ids held by the delta's partition, and a base revision for every element it modifies, removes or reads.
213
+ * A base revision that no longer matches the current element is reported as moved: the change is revalidated.
214
+ * `addedElsewhere` holds the elements other open changes add, for a reference into one of them.
215
+ */
216
+ export function validateDeltas(schema, current, deltas, addedElsewhere, problems) {
217
+ const ownAdded = new Set();
218
+ const dependsOn = new Set();
219
+ for (const d of deltas) {
220
+ for (const e of d.added)
221
+ ownAdded.add(elementKey(e.catalogue, e.id));
222
+ for (const c of d.dependsOn)
223
+ dependsOn.add(c);
224
+ }
225
+ const seenWrite = new Map();
226
+ for (const d of deltas) {
227
+ const write = (key, op) => {
228
+ const prior = seenWrite.get(key);
229
+ if (prior)
230
+ problems.push(`${d.file}: ${op} ${key}, which this change also writes in ${prior}`);
231
+ else
232
+ seenWrite.set(key, `${d.file} (${op})`);
233
+ };
234
+ const needBase = (key, why) => {
235
+ const b = d.base.get(key);
236
+ if (b === undefined) {
237
+ problems.push(`${d.file}: no base revision for ${key}, which it ${why}`);
238
+ return;
239
+ }
240
+ const [catalogue, ...rest] = key.split("/");
241
+ const cur = current.get(catalogue)?.get(rest.join("/"));
242
+ if (cur && revisionOf(cur) !== b)
243
+ problems.push(`${d.file}: base revision of ${key} has moved since the change was written (${b.slice(0, 19)}… now ${revisionOf(cur).slice(0, 19)}…): revalidate the change`);
244
+ };
245
+ for (const e of d.added) {
246
+ const key = elementKey(e.catalogue, e.id);
247
+ checkElementShape(schema, e, `${d.file}: ADDED`, problems);
248
+ if (current.get(e.catalogue)?.has(e.id))
249
+ problems.push(`${d.file}: ADDED ${key}, which the model already holds; an added id is new`);
250
+ write(key, "ADDED");
251
+ }
252
+ for (const e of d.modified) {
253
+ const key = elementKey(e.catalogue, e.id);
254
+ checkElementShape(schema, e, `${d.file}: MODIFIED`, problems);
255
+ const cur = current.get(e.catalogue)?.get(e.id);
256
+ if (!cur)
257
+ problems.push(`${d.file}: MODIFIED ${key}, which the model does not hold`);
258
+ else {
259
+ if (cur.partition !== d.partition)
260
+ problems.push(`${d.file}: MODIFIED ${key}, which partition ${cur.partition} owns, not ${d.partition}`);
261
+ needBase(key, "modifies");
262
+ }
263
+ write(key, "MODIFIED");
264
+ }
265
+ for (const r of d.removed) {
266
+ const key = elementKey(r.catalogue, r.id);
267
+ const cur = current.get(r.catalogue)?.get(r.id);
268
+ if (!cur)
269
+ problems.push(`${d.file}: REMOVED ${key}, which the model does not hold`);
270
+ else {
271
+ if (cur.partition !== d.partition)
272
+ problems.push(`${d.file}: REMOVED ${key}, which partition ${cur.partition} owns, not ${d.partition}`);
273
+ needBase(key, "removes");
274
+ }
275
+ write(key, "REMOVED");
276
+ }
277
+ // Reads: every element an added or modified element references.
278
+ for (const e of [...d.added, ...d.modified]) {
279
+ for (const r of referencesOf(schema, e)) {
280
+ if (!r.structural)
281
+ continue;
282
+ const target = r.targetColumn === "id" ? r.value : find(current, r.catalogue, r.targetColumn, r.value)?.id;
283
+ const key = elementKey(r.catalogue, target ?? r.value);
284
+ if (target !== undefined && current.get(r.catalogue)?.has(target)) {
285
+ needBase(key, `reads (${elementKey(e.catalogue, e.id)}.${r.column})`);
286
+ continue;
287
+ }
288
+ if (ownAdded.has(key))
289
+ continue;
290
+ const by = addedElsewhere.get(key);
291
+ if (by !== undefined && dependsOn.has(by))
292
+ continue;
293
+ if (by !== undefined)
294
+ problems.push(`${d.file}: ${elementKey(e.catalogue, e.id)}.${r.column} names ${key}, which open change ${by} adds; declare it in depends_on`);
295
+ else
296
+ problems.push(`${d.file}: ${elementKey(e.catalogue, e.id)}.${r.column} names ${key}, which is in neither the model nor an open change`);
297
+ }
298
+ }
299
+ }
300
+ }
301
+ //# sourceMappingURL=view.js.map
@@ -0,0 +1,216 @@
1
+ // What an agreement binds and what a verdict must show (M-ADR 0222 §4.6, M-ADR 0223 §4.4-§4.6).
2
+ // Pure text helpers; behaviour-store.ts runs them against git.
3
+ //
4
+ // agreed content the change's proposal, deltas, Gate 0, design, tasks (checkboxes ignored), the test plan's
5
+ // scenario-to-test rows (its Before and After cells ignored) and its structural deltas with their
6
+ // base revisions (M-ADR 0230 §4.4, Proposed; report only until it is accepted) are what was approved. Each is compared
7
+ // with its state at the record's pinned commit: the latest amendment's commit, else sdd.commit.
8
+ // requirement a requirement's block in a spec: its heading to the next requirement or section heading. The
9
+ // stale check compares the blocks a change targets, not the whole file.
10
+ // scenario kind changed (a scenario of an ADDED requirement, or one of a MODIFIED requirement that is new or
11
+ // differs from the living spec's scenario of the same title) goes red then green; carried (identical
12
+ // to the living spec's) is regression and stays green.
13
+ // verdict line verdict.md's own verdict: `Verdict: PASS|FAIL` or a leading `**PASS**`/`**FAIL**`.
14
+ /** The files under a change directory that agreement binds, relative to the change directory. */
15
+ export function boundFile(rel) {
16
+ return /^(proposal|design|gate-0|tasks|test-plan)\.md$/.test(rel) || /^specs\/.+\/spec\.md$/.test(rel) || structuralFile(rel);
17
+ }
18
+ /**
19
+ * A change's structural artifact (M-ADR 0230 §4.4, Proposed): a partition delta or the no-op claim, both agreed
20
+ * content, so a delta's base revisions are pinned with it. The effect record (structure/applied.yaml) is written by
21
+ * the archive, after agreement, and is not.
22
+ */
23
+ export function structuralFile(rel) {
24
+ return /^structure\/[^/]+\.yaml$/.test(rel) && rel !== "structure/applied.yaml";
25
+ }
26
+ /** A bound file's content as agreement compares it: all of it, with only the fields execution fills in masked. */
27
+ export function normaliseBound(rel, text) {
28
+ if (rel === "tasks.md")
29
+ return text.replace(/^(\s*-\s*\[)\s*[xX~]?\s*(\])/gm, "$1 $2").trimEnd();
30
+ if (rel === "test-plan.md")
31
+ return normaliseTestPlan(text);
32
+ return text.trimEnd();
33
+ }
34
+ /**
35
+ * The test plan as agreed. Masked, because execution fills them in: the last two cells (Before and After) of each
36
+ * row of the scenario table, and the whole Ledger and Mutants sections. Everything else, the stand-ins and any
37
+ * strategy or limitation stated, stays bound.
38
+ */
39
+ export function normaliseTestPlan(text) {
40
+ const out = [];
41
+ let section = "";
42
+ for (const line of text.split("\n")) {
43
+ const h = /^##\s+(.+?)\s*$/.exec(line);
44
+ if (h) {
45
+ section = h[1].toLowerCase();
46
+ if (section !== "mutants")
47
+ out.push(line);
48
+ continue;
49
+ }
50
+ // The ledger and the mutants are what apply records: the mutants are written against guards that exist only once
51
+ // the change is applied, and the judge writes its own for any guard they miss (M-ADR 0228 §4.1, Proposed).
52
+ if (section === "ledger" || section === "mutants")
53
+ continue;
54
+ if (section === "" && /^\s*\|/.test(line)) {
55
+ const cells = line.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim());
56
+ out.push(cells.slice(0, Math.max(0, cells.length - 2)).join(" | "));
57
+ continue;
58
+ }
59
+ out.push(line);
60
+ }
61
+ return out.join("\n").trimEnd();
62
+ }
63
+ /** A tasks file's repository groups (`## <n>. <repository>`) and the requirements each says it implements. */
64
+ export function taskGroups(tasks) {
65
+ const out = [];
66
+ let current = null;
67
+ for (const line of tasks.split("\n")) {
68
+ const g = /^##\s+\d+\.\s+`?([A-Za-z0-9][A-Za-z0-9._-]*)`?\s*$/.exec(line);
69
+ if (g) {
70
+ current = { repo: g[1], implements: [] };
71
+ out.push(current);
72
+ continue;
73
+ }
74
+ if (/^##\s/.test(line)) {
75
+ current = null;
76
+ continue;
77
+ }
78
+ const m = /^\s*(?:[-*]\s+)?\**Implements:?\**:?\s*(.+)$/i.exec(line);
79
+ if (current && m)
80
+ current.implements.push(...m[1].split(",").map((x) => x.trim().replace(/^`|`$/g, "")).filter((x) => x && !/^none$/i.test(x)));
81
+ }
82
+ return out;
83
+ }
84
+ /** A pinned commit: 7 to 40 hex characters. */
85
+ export function isCommit(v) {
86
+ return typeof v === "string" && /^[0-9a-f]{7,40}$/i.test(v);
87
+ }
88
+ /** a >= b, for x.y.z versions; a missing or malformed version is lowest. */
89
+ export function versionAtLeast(a, b) {
90
+ const p = (v) => (v && /^\d+\.\d+\.\d+$/.test(v) ? v.split(".").map(Number) : [-1, -1, -1]);
91
+ const [x, y] = [p(a), p(b)];
92
+ for (let i = 0; i < 3; i++)
93
+ if (x[i] !== y[i])
94
+ return x[i] > y[i];
95
+ return true;
96
+ }
97
+ /** The test plan's scenario-to-test rows: every table row before `## Ledger`, as trimmed cells, with the first row (the header) and separator rows dropped. The template holds one table there; a second would be read as more rows. */
98
+ export function testPlanMapping(text) {
99
+ const head = text.split(/^##\s+Ledger\b/m)[0] ?? "";
100
+ const rows = head.split("\n").filter((l) => /^\s*\|/.test(l)).map((l) => l.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim()));
101
+ return rows.filter((r, i) => i > 0 && !r.every((c) => /^:?-{3,}:?$/.test(c) || c === ""));
102
+ }
103
+ /** The test plan table's header cells, lower-cased. */
104
+ export function testPlanHeader(text) {
105
+ const head = text.split(/^##\s+Ledger\b/m)[0] ?? "";
106
+ const first = head.split("\n").find((l) => /^\s*\|/.test(l));
107
+ return first ? first.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim().toLowerCase()) : [];
108
+ }
109
+ /** A requirement's block: `### Requirement: <name>` to the next requirement or `##` heading. Null when absent. */
110
+ export function requirementBlock(spec, name) {
111
+ const lines = spec.split("\n");
112
+ const start = lines.findIndex((l) => new RegExp(`^###\\s+Requirement:\\s*${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*$`).test(l));
113
+ if (start < 0)
114
+ return null;
115
+ let end = lines.length;
116
+ for (let i = start + 1; i < lines.length; i++) {
117
+ if (/^###\s+Requirement:/.test(lines[i]) || /^##\s/.test(lines[i])) {
118
+ end = i;
119
+ break;
120
+ }
121
+ }
122
+ return lines.slice(start, end).join("\n").trimEnd();
123
+ }
124
+ /** Scenario title -> its block text, within one requirement block. */
125
+ export function scenarios(block) {
126
+ const out = new Map();
127
+ let title = null;
128
+ let buf = [];
129
+ const flush = () => {
130
+ if (title !== null)
131
+ out.set(title, buf.join("\n").trim());
132
+ };
133
+ for (const line of block.split("\n")) {
134
+ const m = /^####\s+Scenario:\s*(.+?)\s*$/.exec(line);
135
+ if (m) {
136
+ flush();
137
+ title = m[1];
138
+ buf = [];
139
+ continue;
140
+ }
141
+ if (title !== null)
142
+ buf.push(line);
143
+ }
144
+ flush();
145
+ return out;
146
+ }
147
+ /** The section a requirement sits under in a delta: ADDED, MODIFIED, REMOVED or RENAMED. */
148
+ export function deltaOperation(delta, name) {
149
+ let op = null;
150
+ for (const line of delta.split("\n")) {
151
+ const s = /^##\s+(ADDED|MODIFIED|REMOVED|RENAMED)\s+Requirements\b/.exec(line);
152
+ if (s)
153
+ op = s[1];
154
+ else if (/^##\s/.test(line))
155
+ op = null;
156
+ if (new RegExp(`^###\\s+Requirement:\\s*${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*$`).test(line))
157
+ return op;
158
+ }
159
+ return null;
160
+ }
161
+ /** changed or carried, for one scenario of a requirement in a delta, against the living spec (null when the delta has no such scenario). */
162
+ export function scenarioKind(delta, living, requirement, scenario) {
163
+ const op = deltaOperation(delta, requirement);
164
+ const block = requirementBlock(delta, requirement);
165
+ if (!op || !block)
166
+ return null;
167
+ const mine = scenarios(block).get(scenario);
168
+ if (mine === undefined)
169
+ return null;
170
+ if (op !== "MODIFIED")
171
+ return "changed";
172
+ const theirs = living === null ? null : requirementBlock(living, requirement);
173
+ const before = theirs === null ? undefined : scenarios(theirs).get(scenario);
174
+ return before !== undefined && before === mine ? "carried" : "changed";
175
+ }
176
+ /** verdict.md's own verdict, or null when it states none in a form this reads. */
177
+ export function verdictLine(text) {
178
+ const m = /^\s*(?:#+\s*)?Verdict:\s*\**\s*(PASS|FAIL)\b/im.exec(text) ?? /^\s*\*\*(PASS|FAIL)\*\*/m.exec(text);
179
+ return m?.[1] ?? null;
180
+ }
181
+ /** Two pins name one commit when one abbreviates the other. */
182
+ export function sameCommit(a, b) {
183
+ const [x, y] = [a.toLowerCase(), b.toLowerCase()];
184
+ return x.length >= 7 && y.length >= 7 && (x.startsWith(y) || y.startsWith(x));
185
+ }
186
+ function isoDate(v) {
187
+ if (v instanceof Date && !Number.isNaN(v.getTime()))
188
+ return v.toISOString().slice(0, 10);
189
+ if (typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v))
190
+ return v;
191
+ return null;
192
+ }
193
+ /**
194
+ * Problems with one agreement condition (M-ADR 0222 §4.6 as amended); `today` is YYYY-MM-DD. A withdrawn or
195
+ * superseded change has closed its obligations: its conditions are not overdue.
196
+ */
197
+ export function conditionProblems(c, today, recordStatus = "agreed") {
198
+ const out = [];
199
+ for (const k of ["assumption", "owner", "how", "release_limit"]) {
200
+ if (typeof c[k] !== "string" || c[k].trim() === "")
201
+ out.push(`no ${k}`);
202
+ }
203
+ const by = isoDate(c.validate_by);
204
+ if (by === null)
205
+ out.push("validate_by is not a YYYY-MM-DD date");
206
+ const status = typeof c.status === "string" ? c.status : "";
207
+ if (!["open", "validated", "failed"].includes(status))
208
+ out.push(`status ${JSON.stringify(c.status)} is not open | validated | failed`);
209
+ if ((status === "validated" || status === "failed") && (typeof c.evidence !== "string" || c.evidence.trim() === ""))
210
+ out.push(`${status} without evidence`);
211
+ if (status === "open" && by !== null && by < today && recordStatus !== "withdrawn" && recordStatus !== "superseded")
212
+ out.push(`OVERDUE: open past its validate_by ${by}; validate it, extend it by a ruling, or withdraw the change`);
213
+ return out;
214
+ }
215
+ export { isoDate };
216
+ //# sourceMappingURL=agreement-evidence.js.map