@sdd-method/verify-cli 2.2.0 → 2.4.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.
@@ -0,0 +1,136 @@
1
+ import { readFile, readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { parse as parseYaml } from "yaml";
4
+ import { BUNDLE_CACHE_REL, REGISTRY_FILE } from "../sync/bundle-cache.js";
5
+ /**
6
+ * Scan the bundle cache for registries and return every archetype found.
7
+ * Bundles without any registry.yaml are skipped silently (vendor packs
8
+ * etc.). A registry may sit at the bundle's payload root or nested
9
+ * (multi-bundle producer repos keep one registry per bundle subtree,
10
+ * e.g. a vertical overlay's `verticals/fleet/registry.yaml`) — all are
11
+ * read; seed paths stay payload-root-relative regardless of where the
12
+ * declaring registry sits.
13
+ */
14
+ export async function discoverArchetypes(targetRepo) {
15
+ const cacheRoot = join(targetRepo, BUNDLE_CACHE_REL);
16
+ let entries;
17
+ try {
18
+ entries = await readdir(cacheRoot, { withFileTypes: true });
19
+ }
20
+ catch {
21
+ return [];
22
+ }
23
+ const out = [];
24
+ for (const e of entries) {
25
+ if (!e.isDirectory())
26
+ continue;
27
+ const bundleCacheDir = join(cacheRoot, e.name);
28
+ const at = e.name.lastIndexOf("@");
29
+ const bundleName = at > 0 ? e.name.slice(0, at) : e.name;
30
+ for (const registryPath of await findRegistryFiles(bundleCacheDir)) {
31
+ let raw;
32
+ try {
33
+ raw = await readFile(registryPath, "utf8");
34
+ }
35
+ catch {
36
+ continue;
37
+ }
38
+ let parsed;
39
+ try {
40
+ parsed = parseYaml(raw);
41
+ }
42
+ catch {
43
+ continue; // malformed registry — skip rather than break scaffold
44
+ }
45
+ if (parsed === null || typeof parsed !== "object")
46
+ continue;
47
+ if (!Array.isArray(parsed.archetypes))
48
+ continue;
49
+ const tier = typeof parsed.tier === "string" ? parsed.tier : "unknown";
50
+ for (const a of parsed.archetypes) {
51
+ if (a === null || typeof a !== "object")
52
+ continue;
53
+ const rec = a;
54
+ const id = typeof rec.id === "string" ? rec.id : undefined;
55
+ const seeds = Array.isArray(rec.seeds)
56
+ ? rec.seeds.filter((s) => typeof s === "string")
57
+ : [];
58
+ if (!id || seeds.length === 0)
59
+ continue;
60
+ out.push({
61
+ id,
62
+ tier,
63
+ seeds,
64
+ bundleName,
65
+ bundleCacheDir,
66
+ ...(typeof rec.layer === "string" && { layer: rec.layer }),
67
+ ...(typeof rec.domain_name === "string" && { domainName: rec.domain_name }),
68
+ ...(typeof rec.status === "string" && { status: rec.status }),
69
+ ...(typeof rec.notes === "string" && { notes: rec.notes }),
70
+ });
71
+ }
72
+ }
73
+ }
74
+ return out;
75
+ }
76
+ /** Depth cap for nested-registry discovery — bundle payloads are shallow. */
77
+ const REGISTRY_SCAN_MAX_DEPTH = 4;
78
+ /**
79
+ * Find every registry.yaml within a cached bundle (root + nested),
80
+ * depth-capped. Returns absolute paths in a stable (sorted) order.
81
+ */
82
+ async function findRegistryFiles(dir, depth = 0) {
83
+ let entries;
84
+ try {
85
+ entries = await readdir(dir, { withFileTypes: true });
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ const found = [];
91
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
92
+ if (e.isFile() && e.name === REGISTRY_FILE) {
93
+ found.push(join(dir, e.name));
94
+ }
95
+ else if (e.isDirectory() && depth < REGISTRY_SCAN_MAX_DEPTH) {
96
+ found.push(...(await findRegistryFiles(join(dir, e.name), depth + 1)));
97
+ }
98
+ }
99
+ return found;
100
+ }
101
+ /**
102
+ * Resolve an archetype reference against the cache. Accepts bare ids
103
+ * (`core/identity`) and bundle-qualified ids
104
+ * (`ref-arch-core-b2b-saas:core/identity`).
105
+ */
106
+ export async function resolveArchetype(targetRepo, reference) {
107
+ const available = await discoverArchetypes(targetRepo);
108
+ let bundleFilter;
109
+ let id = reference;
110
+ const colon = reference.indexOf(":");
111
+ if (colon > 0) {
112
+ bundleFilter = reference.slice(0, colon);
113
+ id = reference.slice(colon + 1);
114
+ }
115
+ const matches = available.filter((a) => a.id === id && (bundleFilter === undefined || a.bundleName === bundleFilter));
116
+ if (matches.length === 1) {
117
+ return { ok: true, archetype: matches[0], available };
118
+ }
119
+ if (matches.length === 0) {
120
+ const known = available.map((a) => `${a.bundleName}:${a.id}`).join(", ");
121
+ return {
122
+ ok: false,
123
+ available,
124
+ error: available.length === 0
125
+ ? `No archetype registries found in ${BUNDLE_CACHE_REL}/ — sync an archetype-bearing bundle first (M-ADR 0176).`
126
+ : `Archetype '${reference}' not found in cached registries. Available: ${known}`,
127
+ };
128
+ }
129
+ const collisions = matches.map((a) => `${a.bundleName}:${a.id}`).join(", ");
130
+ return {
131
+ ok: false,
132
+ available,
133
+ error: `Archetype id '${id}' is declared by multiple bundles (${collisions}). Use the qualified form '<bundle>:<id>'.`,
134
+ };
135
+ }
136
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1,109 @@
1
+ import { appendFile, copyFile, mkdir, readFile, readdir, rm } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ /**
4
+ * Consumer-side bundle cache (M-ADR 0176 §4.2).
5
+ *
6
+ * Every consumed non-forward-base bundle is extracted to
7
+ * `<targetRepo>/.sdd/bundle-cache/<bundleName>@<version>/` — the
8
+ * resolution substrate for `sdd-cli scaffold domain --archetype` and
9
+ * the staging source for materialise-mode paths. The cache directory
10
+ * is gitignored (ensured at sync time).
11
+ *
12
+ * Cache layout per bundle: the bundle's payload tree, verbatim (so
13
+ * registry.yaml and scaffold-source files sit at their shipped paths).
14
+ * Stale versions of the same bundle name are pruned on refresh.
15
+ */
16
+ export const BUNDLE_CACHE_REL = ".sdd/bundle-cache";
17
+ /**
18
+ * The registry file name (M-ADR 0176 §4.1) — always cache-only. A bundle may
19
+ * ship its registry at the payload root or nested (a multi-bundle producer
20
+ * repo keeps one registry per bundle subtree, e.g. a vertical overlay's
21
+ * `verticals/fleet/registry.yaml`, because the producer-layout rule forbids
22
+ * path mapping and the root name can only be claimed once).
23
+ */
24
+ export const REGISTRY_FILE = "registry.yaml";
25
+ /**
26
+ * The application-archetype vocabulary file name (M-ADR 0191 §4.2) — always
27
+ * cache-only, like the registry. Carries the seedless classification
28
+ * vocabulary a bundle contributes (resolution data, not adopter-editable
29
+ * content). May sit at the payload root (core layer) or nested (a vertical
30
+ * overlay's `verticals/<v>/application-archetypes.yaml`), same as the
31
+ * registry.
32
+ */
33
+ export const VOCAB_FILE = "application-archetypes.yaml";
34
+ /**
35
+ * Split a bundle's managed paths into the set to materialise into the
36
+ * repo tree vs the set that stays cache-only (M-ADR 0176 §4.3):
37
+ * scaffold-source-prefixed paths, registry files, and the archetype
38
+ * vocabulary file are cache-only.
39
+ */
40
+ export function splitConsumptionModes(managedPaths, scaffoldSourcePaths) {
41
+ const prefixes = scaffoldSourcePaths ?? [];
42
+ const materialise = [];
43
+ const cacheOnly = [];
44
+ for (const p of managedPaths) {
45
+ const isScaffoldSource = prefixes.some((prefix) => p.startsWith(prefix));
46
+ const isRegistry = p === REGISTRY_FILE || p.endsWith(`/${REGISTRY_FILE}`);
47
+ const isVocab = p === VOCAB_FILE || p.endsWith(`/${VOCAB_FILE}`);
48
+ if (isScaffoldSource || isRegistry || isVocab) {
49
+ cacheOnly.push(p);
50
+ }
51
+ else {
52
+ materialise.push(p);
53
+ }
54
+ }
55
+ return { materialise, cacheOnly };
56
+ }
57
+ /**
58
+ * Extract a bundle's payload into the cache, replacing any previously
59
+ * cached version of the same bundle name (one cached version per
60
+ * bundle — the lock pins exactly one).
61
+ */
62
+ export async function cacheBundle(input) {
63
+ const cacheRoot = join(input.targetRepo, BUNDLE_CACHE_REL);
64
+ await prunePreviousVersions(cacheRoot, input.bundleName);
65
+ const dest = join(cacheRoot, `${input.bundleName}@${input.bundleVersion}`);
66
+ for (const p of input.managedPaths) {
67
+ const src = join(input.payloadDir, p);
68
+ const dst = join(dest, p);
69
+ await mkdir(dirname(dst), { recursive: true });
70
+ await copyFile(src, dst);
71
+ }
72
+ return dest;
73
+ }
74
+ async function prunePreviousVersions(cacheRoot, bundleName) {
75
+ let entries;
76
+ try {
77
+ entries = await readdir(cacheRoot, { withFileTypes: true });
78
+ }
79
+ catch {
80
+ return; // no cache yet
81
+ }
82
+ for (const e of entries) {
83
+ if (e.isDirectory() && e.name.startsWith(`${bundleName}@`)) {
84
+ await rm(join(cacheRoot, e.name), { recursive: true, force: true });
85
+ }
86
+ }
87
+ }
88
+ /**
89
+ * Ensure the consumer's .gitignore excludes the bundle cache. Appends
90
+ * a marked line when absent; leaves adopter content untouched otherwise.
91
+ */
92
+ export async function ensureCacheGitignored(targetRepo) {
93
+ const giPath = join(targetRepo, ".gitignore");
94
+ const line = `${BUNDLE_CACHE_REL}/`;
95
+ let existing = "";
96
+ try {
97
+ existing = await readFile(giPath, "utf8");
98
+ }
99
+ catch {
100
+ // no .gitignore yet — create one below
101
+ }
102
+ if (existing.split("\n").some((l) => l.trim() === line || l.trim() === BUNDLE_CACHE_REL)) {
103
+ return false;
104
+ }
105
+ const prefixNewline = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
106
+ await appendFile(giPath, `${prefixNewline}# sdd-cli bundle cache (M-ADR 0176) — extracted bundle payloads, not source\n${line}\n`);
107
+ return true;
108
+ }
109
+ //# sourceMappingURL=bundle-cache.js.map
@@ -0,0 +1,169 @@
1
+ // archetype-citations: an estate's citations of reference-architecture archetype behaviour still say what is true
2
+ // (seed once, then cite; scaffold/archetype-behaviour.ts writes them).
3
+ //
4
+ // For each docs/domains/<domain>/archetype-citations.yaml, each citation is resolved against the archetype's
5
+ // behaviour rows in the bundle the estate has cached (its locked version):
6
+ // unresolved the citations name no cached bundle or archetype, the cited requirement is gone from the
7
+ // archetype, the relation is not one of the four, a departure has no reason or decision, or the
8
+ // estate requirement it names exists in neither the living specs nor an open change;
9
+ // stale a derived, extended or narrowed citation whose archetype requirement no longer has the digest
10
+ // recorded: the archetype changed since the estate took or re-aligned it. Review it and re-pin
11
+ // (move `digest` and `version`), or record that the estate departs.
12
+ // A departed citation is never stale: departing is a decision, recorded with its reason, not drift. With no
13
+ // citations anywhere the check reports [N/A], an empty population, not a pass.
14
+ //
15
+ // A digest must be a quoted string: YAML reads an unquoted all-digit value, or digits around one `e`, as a
16
+ // number, which would compare as a false stale. A narrowed or extended citation may say why in `reason`
17
+ // (`note` is read as the same). `not_adopted` records archetype requirements the estate has decided not to
18
+ // take, each with its reason and decision; every id must resolve, and none may be both cited and not adopted.
19
+ // A coverage line names the archetype requirements neither cited nor recorded as not adopted: the gaps, which
20
+ // are reported, not failed, since an estate may be part-way through adopting.
21
+ import { readdir, readFile } from "node:fs/promises";
22
+ import { join } from "node:path";
23
+ import { parse as parseYaml } from "yaml";
24
+ import { cachedVersion, CITATIONS_FILE, loadArchetypeBehaviour, RELATIONS } from "../scaffold/archetype-behaviour.js";
25
+ import { discoverArchetypes } from "../scaffold/registry.js";
26
+ const REQ_RE = /^###\s+Requirement:\s*(.+?)\s*$/gm;
27
+ async function list(dir) {
28
+ try {
29
+ return (await readdir(dir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
30
+ }
31
+ catch {
32
+ return [];
33
+ }
34
+ }
35
+ /** Every requirement title in the living specs and in open changes (a seeded change not yet archived counts). */
36
+ async function estateRequirements(repo) {
37
+ const titles = new Set();
38
+ const specFiles = [];
39
+ for (const d of await list(join(repo, "openspec", "specs")))
40
+ specFiles.push(join(repo, "openspec", "specs", d, "spec.md"));
41
+ for (const c of await list(join(repo, "openspec", "changes"))) {
42
+ if (c === "archive")
43
+ continue;
44
+ for (const d of await list(join(repo, "openspec", "changes", c, "specs"))) {
45
+ specFiles.push(join(repo, "openspec", "changes", c, "specs", d, "spec.md"));
46
+ }
47
+ }
48
+ for (const f of specFiles) {
49
+ let text;
50
+ try {
51
+ text = await readFile(f, "utf8");
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ for (const m of text.matchAll(REQ_RE))
57
+ titles.add(m[1]);
58
+ }
59
+ return titles;
60
+ }
61
+ export async function checkArchetypeCitations(repo) {
62
+ const domains = await list(join(repo, "docs", "domains"));
63
+ const files = [];
64
+ for (const d of domains) {
65
+ const p = join(repo, "docs", "domains", d, CITATIONS_FILE);
66
+ try {
67
+ files.push([`docs/domains/${d}/${CITATIONS_FILE}`, await readFile(p, "utf8")]);
68
+ }
69
+ catch {
70
+ // no citations for this domain
71
+ }
72
+ }
73
+ if (files.length === 0)
74
+ return { exitCode: 0, stdout: "[N/A] no archetype citations (docs/domains/*/archetype-citations.yaml) in this repository\n" };
75
+ const archetypes = await discoverArchetypes(repo);
76
+ const titles = await estateRequirements(repo);
77
+ const lines = [];
78
+ let problems = 0;
79
+ let total = 0;
80
+ const bad = (tag, msg) => {
81
+ lines.push(`[${tag}] ${msg}`);
82
+ problems++;
83
+ };
84
+ for (const [rel, text] of files) {
85
+ let doc;
86
+ try {
87
+ doc = (parseYaml(text) ?? {});
88
+ }
89
+ catch (e) {
90
+ bad("unresolved", `${rel}: does not parse: ${e.message.split("\n")[0]}`);
91
+ continue;
92
+ }
93
+ const archetype = archetypes.find((a) => a.id === doc.archetype && a.bundleName === doc.bundle);
94
+ if (!archetype) {
95
+ bad("unresolved", `${rel}: archetype ${String(doc.archetype)} of bundle ${String(doc.bundle)} is not in the bundle cache (sync the bundle)`);
96
+ continue;
97
+ }
98
+ const reqs = await loadArchetypeBehaviour(archetype.bundleCacheDir, archetype.seeds);
99
+ const byId = new Map((reqs ?? []).map((r) => [r.id, r]));
100
+ const at = cachedVersion(archetype.bundleCacheDir) ?? "the cached bundle";
101
+ const cites = Array.isArray(doc.citations) ? doc.citations : [];
102
+ const notAdopted = Array.isArray(doc.not_adopted) ? doc.not_adopted : [];
103
+ if (cites.length === 0 && notAdopted.length === 0)
104
+ bad("unresolved", `${rel}: lists no citations`);
105
+ const citedIds = new Set(cites.map((c) => String(c.cites)));
106
+ for (const n of notAdopted) {
107
+ total++;
108
+ const tag = `${rel}: not adopted ${String(n.cites)}`;
109
+ if (!byId.has(String(n.cites))) {
110
+ bad("unresolved", `${tag}: ${archetype.bundleName} ${at} has no archetype requirement ${String(n.cites)}`);
111
+ }
112
+ else if (!n.reason || !n.decision) {
113
+ bad("unresolved", `${tag}: a non-adoption needs its reason and the decision that took it`);
114
+ }
115
+ else if (citedIds.has(String(n.cites))) {
116
+ bad("unresolved", `${tag}: it is also cited; an archetype requirement is either answered or not adopted`);
117
+ }
118
+ else {
119
+ lines.push(`[ok] ${tag} (${String(n.reason)})`);
120
+ }
121
+ }
122
+ for (const c of cites) {
123
+ total++;
124
+ const tag = `${rel}: '${String(c.requirement)}' -> ${String(c.cites)}`;
125
+ const relation = String(c.relation);
126
+ if (typeof c.digest !== "string") {
127
+ bad("unresolved", `${tag}: digest must be a quoted string (YAML read ${String(c.digest)} as a ${typeof c.digest}); quote it`);
128
+ continue;
129
+ }
130
+ if (!RELATIONS.includes(relation)) {
131
+ bad("unresolved", `${tag}: relation must be one of ${RELATIONS.join(", ")} (got ${relation})`);
132
+ continue;
133
+ }
134
+ if (relation === "departed" && (!c.reason || !c.decision)) {
135
+ bad("unresolved", `${tag}: a departure needs its reason and the decision that took it`);
136
+ continue;
137
+ }
138
+ if (relation !== "departed" && !titles.has(String(c.requirement))) {
139
+ bad("unresolved", `${tag}: this estate has no requirement titled so (living specs or open changes)`);
140
+ continue;
141
+ }
142
+ const src = byId.get(String(c.cites));
143
+ if (!src) {
144
+ bad("unresolved", `${tag}: ${archetype.bundleName} ${at} has no archetype requirement ${String(c.cites)}`);
145
+ continue;
146
+ }
147
+ if (relation === "departed") {
148
+ lines.push(`[ok] ${tag} (departed: ${String(c.reason)})`);
149
+ }
150
+ else if (src.digest !== String(c.digest)) {
151
+ bad("stale", `${tag}: the archetype requirement changed (${String(c.digest)} at ${String(doc.version)} -> ${src.digest} at ${at}); review it and re-pin, or record a departure`);
152
+ }
153
+ else {
154
+ const why = c.reason ?? c.note;
155
+ lines.push(`[ok] ${tag} (${relation}${why && relation !== "derived" ? `: ${String(why)}` : ""})`);
156
+ }
157
+ }
158
+ const answered = new Set([...citedIds, ...notAdopted.map((n) => String(n.cites))]);
159
+ const gaps = [...byId.keys()].filter((id) => !answered.has(id));
160
+ lines.push(`[coverage] ${rel}: ${byId.size - gaps.length} of ${byId.size} ${archetype.id} requirements answered ` +
161
+ `(${[...citedIds].filter((id) => byId.has(id)).length} cited, ${notAdopted.length} not adopted)` +
162
+ (gaps.length ? `; not yet answered: ${gaps.join(", ")}` : ""));
163
+ }
164
+ const verdict = problems
165
+ ? `[FAIL] archetype citations: ${problems} of ${total} unresolved or stale`
166
+ : `[PASS] archetype citations: ${total} resolve, none stale`;
167
+ return { exitCode: problems ? 1 : 0, stdout: lines.join("\n") + "\n" + verdict + "\n" };
168
+ }
169
+ //# sourceMappingURL=archetype-citations.js.map
@@ -20,6 +20,16 @@
20
20
  // never against itself (M-ADR 0222 §4.3, §4.4). A list the catalogue gives nothing to
21
21
  // check against (no Observed in line, or a repository with no catalogue contracts) fails:
22
22
  // a cross-check of zero contracts is unresolved, not a pass.
23
+ // 7. features: every living spec is keyed by a catalogue feature (M-ADR 0221 §4.7). A spec keyed by no
24
+ // feature is dropped from the catalogue by the requirements builder, which reports it only as a
25
+ // build finding; this check makes it a failure, so a shipped requirement cannot vanish from the
26
+ // catalogue with every check green. Without catalogues/features.csv the check is unresolved, not
27
+ // passed.
28
+ // 8. overlap: no requirement of a living spec is named by two open, agreed changes, whether added,
29
+ // modified, removed or renamed (M-ADR 0223 §4.10). Proposals may overlap.
30
+ // 9. schema: the store's config.yaml selects the method's sdd-change schema, and the store's copy of it
31
+ // (openspec/schemas/sdd-change/) is identical to the one the SDD's bundle shipped
32
+ // (docs/method/foundations/openspec/sdd-change/). Sync refreshes the copy (M-ADR 0223 §4.2).
23
33
  // 6. scope: a baseline ADDS requirements; it REMOVES, MODIFIES or RENAMES only a requirement whose
24
34
  // latest archived change was a baseline, which is how a corrective baseline withdraws
25
35
  // what a baseline admitted wrongly. A requirement a judged change shipped is changed only
@@ -29,14 +39,18 @@
29
39
  //
30
40
  // OPENSPEC'S OWN VALIDATION is the separate validator `behaviour-store-openspec`, because it needs
31
41
  // the OpenSpec CLI at OPENSPEC_VERSION (the Method Validation module installs it). Without a store
32
- // both report [N/A], an empty population, never a pass.
42
+ // both report [N/A], an empty population, never a pass. It also archives each open, agreed change in a
43
+ // scratch copy of the store and validates the specs it would leave (M-ADR 0223 §4.5): a change's own
44
+ // --strict run exempts its MODIFIED requirements from the 500-character limit the specs are held to.
33
45
  import { execFile } from "node:child_process";
34
- import { access, readdir, readFile } from "node:fs/promises";
46
+ import { access, cp, mkdtemp, readdir, readFile, rm } from "node:fs/promises";
47
+ import { tmpdir } from "node:os";
35
48
  import { basename, join } from "node:path";
36
49
  import { promisify } from "node:util";
37
50
  import { parseDocument } from "yaml";
38
51
  import { observedIn, orderArchives, parseRequirements, parseSurfaces, renamedFrom, surfaceMatches } from "../behaviour-store/archive.js";
39
52
  import { parseCatalogueCsv } from "../catalogue/csv-reader.js";
53
+ import { compareStoreSchema, SCHEMA_NAME, SHIPPED_SCHEMA_DIR, STORE_CONFIG, STORE_SCHEMA_DIR, storeSchemaName } from "../behaviour-store/schema.js";
40
54
  const execFileAsync = promisify(execFile);
41
55
  /** The OpenSpec release the method depends on (M-ADR 0223 ruling 2). The module installs exactly this. */
42
56
  export const OPENSPEC_VERSION = "1.14.3";
@@ -236,7 +250,9 @@ export async function checkBehaviourStore(repo) {
236
250
  const record = records.get(change);
237
251
  if (tasks !== null && TASK_DONE_RE.test(tasks)) {
238
252
  started++;
239
- if (!record)
253
+ if (!record && recordFiles.some((f) => f.replace(/\.ya?ml$/, "") === change))
254
+ failures.push(`${dir}: has completed tasks but its agreement record (${AGREEMENTS_DIR}/${change}.yaml) is malformed; see its record failures`);
255
+ else if (!record)
240
256
  failures.push(`${dir}: has completed tasks but no agreement record (${AGREEMENTS_DIR}/${change}.yaml)`);
241
257
  else if (record.status !== "agreed")
242
258
  failures.push(`${dir}: has completed tasks but its agreement record is ${record.status}, not agreed`);
@@ -259,6 +275,29 @@ export async function checkBehaviourStore(repo) {
259
275
  }
260
276
  lines.push(`agreement: ${open.length} open change(s), ${started} with completed tasks`);
261
277
  lines.push(staleChecked === 0 ? "stale: vacuous (no open agreed change modifies, removes or renames a requirement)" : `stale: ${staleChecked} targeted living spec(s) checked against their agreed commits`);
278
+ // 8. overlap: two open, agreed changes never name the same requirement of one living spec (M-ADR 0223 §4.10).
279
+ // A name counts whether the delta adds, modifies, removes or renames it (both FROM and TO). Proposals may overlap.
280
+ const claimed = new Map();
281
+ let agreedOpen = 0;
282
+ for (const change of open) {
283
+ if (records.get(change)?.status !== "agreed")
284
+ continue;
285
+ agreedOpen++;
286
+ const specsDir = join(repo, STORE_DIR, "changes", change, "specs");
287
+ for (const spec of await dirs(specsDir)) {
288
+ const text = (await readText(join(specsDir, spec, "spec.md"))) ?? "";
289
+ const names = new Set([...parseRequirements(text).filter((r) => r.operation).map((r) => r.name), ...renamedFrom(text)]);
290
+ for (const name of names) {
291
+ const key = `${spec}::${name}`;
292
+ const other = claimed.get(key);
293
+ if (other)
294
+ failures.push(`${STORE_DIR}/changes/${change}: OVERLAP: requirement "${name}" of ${spec} is also named by agreed change ${other}; one waits for the other to archive, or the two become one change (M-ADR 0223 §4.10)`);
295
+ else
296
+ claimed.set(key, change);
297
+ }
298
+ }
299
+ }
300
+ lines.push(agreedOpen < 2 ? `overlap: vacuous (${agreedOpen} open agreed change)` : `overlap: ${claimed.size} requirement name(s) across ${agreedOpen} open agreed changes`);
262
301
  // 4. archived changes
263
302
  const archived = await dirs(join(repo, STORE_DIR, "changes", "archive"));
264
303
  let baselines = 0;
@@ -285,7 +324,31 @@ export async function checkBehaviourStore(repo) {
285
324
  lines.push(`verdicts: ${archived.length} archived change(s), ${baselines} baseline(s), ${archived.length - baselines} needing a PASS verdict`);
286
325
  // 5. surfaces, and 6. what each baseline may change, in archive order
287
326
  const archiveRel = `${STORE_DIR}/changes/archive`;
288
- const { order, ties } = await orderArchives(repo, archiveRel, archived);
327
+ const { order, ties, history } = await orderArchives(repo, archiveRel, archived);
328
+ // Same-day archives the history cannot order sit in one group. A scope verdict that a group peer could reverse
329
+ // (it touches the same requirement) depends on an order nobody knows, so it is unresolved, not a violation. Without
330
+ // git history (a worktree upload, a plain copy, an export) every same-day pair is such a group.
331
+ const peers = new Map();
332
+ for (const [a, b] of ties) {
333
+ const group = peers.get(a) ?? peers.get(b) ?? new Set();
334
+ group.add(a).add(b);
335
+ peers.set(a, group).set(b, group);
336
+ }
337
+ const touches = new Map();
338
+ for (const name of peers.keys()) {
339
+ const keys = new Set();
340
+ for (const feature of await dirs(join(repo, archiveRel, name, "specs"))) {
341
+ const text = (await readText(join(repo, archiveRel, name, "specs", feature, "spec.md"))) ?? "";
342
+ for (const r of parseRequirements(text))
343
+ if (r.operation)
344
+ keys.add(`${feature}::${r.name}`);
345
+ for (const from of renamedFrom(text))
346
+ keys.add(`${feature}::${from}`);
347
+ }
348
+ touches.set(name, keys);
349
+ }
350
+ const orderDecides = (name, key) => [...(peers.get(name) ?? [])].some((p) => p !== name && touches.get(p)?.has(key));
351
+ let scopeUnresolved = 0;
289
352
  const servedBy = baselines > 0 ? await catalogueContracts(repo) : null;
290
353
  let surfacesChecked = 0;
291
354
  const lastTouch = new Map();
@@ -333,7 +396,11 @@ export async function checkBehaviourStore(repo) {
333
396
  if (isBaseline) {
334
397
  scopeChecked++;
335
398
  const last = lastTouch.get(key);
336
- if (last !== "baseline") {
399
+ if (last !== "baseline" && orderDecides(name, key)) {
400
+ scopeUnresolved++;
401
+ failures.push(`${dir}: scope unresolved for "${t}" (${feature}): the verdict depends on the order of same-day archives the history cannot give${history ? "" : " (no git history here: run from a clone)"}`);
402
+ }
403
+ else if (last !== "baseline") {
337
404
  failures.push(`${dir}: a baseline changes "${t}" (${feature}), which ${last === "change" ? "a judged change last shipped" : "no earlier archived change admitted"}; a baseline may remove or modify only what a baseline admitted, and anything else takes a change (M-ADR 0222 §4.4)`);
338
405
  }
339
406
  }
@@ -352,8 +419,55 @@ export async function checkBehaviourStore(repo) {
352
419
  const unseen = servedBy === null ? "" : `; repositories with no catalogue contracts: ${[...new Set(await observedInAll(repo, archiveRel, order))].filter((r) => (servedBy.get(r) ?? []).length === 0).join(", ") || "none"}`;
353
420
  lines.push(baselines === 0 ? "surfaces: vacuous (no baseline)" : `surfaces: ${baselines} baseline(s), ${surfacesChecked} served contract(s) checked against catalogues/repo_contract.csv${unseen}`);
354
421
  lines.push(scopeChecked === 0 ? "scope: vacuous (no baseline removes, modifies or renames a requirement)" : `scope: ${scopeChecked} requirement(s) a baseline removes, modifies or renames, checked against their lineage`);
422
+ if (!history && archived.length > 0)
423
+ lines.push("order: no git history (not a git work tree, or git log failed), so same-day archives cannot be ordered");
424
+ if (scopeUnresolved > 0)
425
+ lines.push(`scope: ${scopeUnresolved} verdict(s) unresolved, depending on an order the history cannot give`);
355
426
  for (const [a, b] of ties)
356
427
  lines.push(`order: ${a} and ${b} were archived the same day and the history does not order them; ordered by name`);
428
+ // 7. living specs keyed by a catalogue feature
429
+ const livingSpecs = await dirs(join(repo, STORE_DIR, "specs"));
430
+ if (livingSpecs.length > 0) {
431
+ const featuresCsv = await readText(join(repo, "catalogues", "features.csv"));
432
+ if (featuresCsv === null) {
433
+ failures.push(`${STORE_DIR}/specs: living specs cannot be checked against catalogue features: catalogues/features.csv is missing; build the catalogue`);
434
+ }
435
+ else {
436
+ const featureIds = new Set(parseCatalogueCsv(featuresCsv).rows.map((r) => r["id"] ?? ""));
437
+ const unkeyed = livingSpecs.filter((f) => !featureIds.has(f));
438
+ for (const f of unkeyed) {
439
+ failures.push(`${STORE_DIR}/specs/${f}: no catalogue feature has the id "${f}", so its requirements are not catalogued; give the behaviour a feature first (M-ADR 0222 §4.4)`);
440
+ }
441
+ lines.push(`features: ${livingSpecs.length} living spec(s), ${livingSpecs.length - unkeyed.length} keyed by a catalogue feature`);
442
+ }
443
+ }
444
+ else {
445
+ lines.push("features: vacuous (no living spec)");
446
+ }
447
+ // 9. schema: the store uses the method's sdd-change schema, and its copy is the one the SDD's bundle
448
+ // shipped (M-ADR 0223 §4.2). OpenSpec reads the copy, so an edited or stale copy changes what every
449
+ // change is asked for, with nothing else noticing.
450
+ const selected = await storeSchemaName(repo);
451
+ if (selected !== SCHEMA_NAME) {
452
+ failures.push(`${STORE_CONFIG}: ${selected === null ? "missing" : selected === "" ? "names no schema" : `selects schema "${selected}"`}; a behaviour store uses the method's ${SCHEMA_NAME} schema (M-ADR 0223 §4.2)`);
453
+ }
454
+ else {
455
+ const c = await compareStoreSchema(repo);
456
+ if (!c.shipped) {
457
+ failures.push(`schema unresolved: this SDD holds no shipped ${SCHEMA_NAME} schema (${SHIPPED_SCHEMA_DIR}/); sync a method bundle that carries it`);
458
+ }
459
+ else {
460
+ const fix = "sdd-cli sync refreshes it; put adopter guidance in the store's config.yaml rules, not in the schema";
461
+ for (const f of c.missing)
462
+ failures.push(`${STORE_SCHEMA_DIR}/${f}: missing from the store's copy of the schema; ${fix}`);
463
+ for (const f of c.differing)
464
+ failures.push(`${STORE_SCHEMA_DIR}/${f}: differs from the shipped ${SHIPPED_SCHEMA_DIR}/${f}; ${fix}`);
465
+ for (const f of c.extra)
466
+ failures.push(`${STORE_SCHEMA_DIR}/${f}: not in the shipped schema; ${fix}`);
467
+ const drift = c.missing.length + c.differing.length + c.extra.length;
468
+ lines.push(drift === 0 ? `schema: ${SCHEMA_NAME}, identical to the shipped copy` : `schema: ${SCHEMA_NAME}, ${drift} file(s) differ from the shipped copy`);
469
+ }
470
+ }
357
471
  const population = recordFiles.length + open.length + archived.length;
358
472
  const body = lines.map((l) => ` ${l}`).join("\n") + "\n";
359
473
  if (failures.length > 0) {
@@ -361,7 +475,7 @@ export async function checkBehaviourStore(repo) {
361
475
  }
362
476
  if (population === 0)
363
477
  return { exitCode: 0, stdout: body + `[N/A] the behaviour store has no changes and no agreement records yet\n` };
364
- return { exitCode: 0, stdout: body + "[PASS] behaviour store: records, agreement, stale, verdict, surfaces and scope checks hold\n" };
478
+ return { exitCode: 0, stdout: body + "[PASS] behaviour store: records, agreement, stale, overlap, verdict, surfaces, scope, feature and schema checks hold\n" };
365
479
  }
366
480
  /** Per repository, the contracts the catalogue says it serves (repo_contract ⋈ contracts.spec_path); null when either file is missing. */
367
481
  async function catalogueContracts(repo) {
@@ -452,6 +566,47 @@ export async function checkBehaviourStoreOpenspec(repo) {
452
566
  if (r.code !== 0 && (t.failed ?? 0) === 0)
453
567
  failures.push(`${label}: OpenSpec exited ${r.code} with no failed item reported`);
454
568
  }
569
+ // Each open, agreed change, archived in a scratch copy: the specs it would leave must validate --strict.
570
+ let dryArchived = 0;
571
+ for (const change of (await dirs(join(repo, STORE_DIR, "changes"))).filter((d) => d !== "archive")) {
572
+ const rel = `${AGREEMENTS_DIR}/${change}.yaml`;
573
+ const text = await readText(join(repo, rel));
574
+ if (text === null || parseAgreementRecord(rel, text).record?.status !== "agreed")
575
+ continue;
576
+ const scratch = await mkdtemp(join(tmpdir(), "sdd-dry-archive-"));
577
+ try {
578
+ await cp(join(repo, STORE_DIR), join(scratch, STORE_DIR), { recursive: true });
579
+ const label = `specs after archiving ${change} (dry, in a copy)`;
580
+ const a = await runOpenspec(scratch, ["archive", change, "--yes", "--json"]);
581
+ if (a.code !== 0) {
582
+ const said = [...a.raw.matchAll(/"(?:message|error)":\s*"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1]);
583
+ failures.push(`${label}: the change does not archive (exit ${a.code}): ${said.length > 0 ? said.join("; ") : a.raw.trim().split("\n").slice(-3).join(" | ")}`);
584
+ continue;
585
+ }
586
+ dryArchived++;
587
+ const v = await runOpenspec(scratch, ["validate", "--specs", "--strict", "--json", "--no-interactive"]);
588
+ const t = v.json?.summary?.totals;
589
+ if (!t) {
590
+ failures.push(`${label}: OpenSpec returned no report (exit ${v.code}): ${v.raw.trim().split("\n").slice(-3).join(" | ")}`);
591
+ continue;
592
+ }
593
+ lines.push(`${label}: ${t.items ?? 0} spec(s), ${t.passed ?? 0} passed, ${t.failed ?? 0} failed`);
594
+ for (const item of v.json?.items ?? []) {
595
+ if (item.valid)
596
+ continue;
597
+ for (const i of item.issues ?? [])
598
+ failures.push(`${label}: ${item.id}${i.path ? ` (${i.path})` : ""}: ${i.level} ${i.message}`);
599
+ if ((item.issues ?? []).length === 0)
600
+ failures.push(`${label}: ${item.id}: invalid`);
601
+ }
602
+ if (v.code !== 0 && (t.failed ?? 0) === 0)
603
+ failures.push(`${label}: OpenSpec exited ${v.code} with no failed spec reported`);
604
+ }
605
+ finally {
606
+ await rm(scratch, { recursive: true, force: true });
607
+ }
608
+ }
609
+ lines.push(`dry archive: ${dryArchived} open, agreed change(s) archived in a copy`);
455
610
  const body = [` OpenSpec ${version}`, ...lines.map((l) => ` ${l}`)].join("\n") + "\n";
456
611
  if (failures.length > 0)
457
612
  return { exitCode: 1, stdout: body + failures.map((f) => `[FAIL] ${f}`).join("\n") + "\n" };