From 0a4f15fb12806ffd05edb7f61819a77d0dfe1d33 Mon Sep 17 00:00:00 2001 From: Wilson Cook Date: Fri, 16 Oct 2026 01:10:11 -0500 Subject: [PATCH 1/2] feat: fold --format json - a versioned, published schema so wrappers never parse English (DOCS-090) One JSON document on stdout in every fold mode, naming schema ewc3-docs/fold@1 and matching schema/fold.v1.schema.json (JSON Schema 2020-12, shipped in the package). Additive within v1; a rename or removal is v2. Every problem carries a stable code, set where it is raised. Did-not-run is JSON however early the tool stops. Text output is unchanged. Tests validate real output against the closed schema, and compare its codes with the source. Slice: DOCS-090 State: tested Co-Authored-By: Claude Opus 5.5 --- USAGE.txt | 2 + bin/ewc3-docs.js | 90 ++++++++- docs/Reference.md | 24 +++ docs/project/EWC3_Docs_Tools_Roadmap.md | 4 +- ..._versioned_published_schema_so_wrappers.md | 42 ++++ lib/fold.js | 90 +++++---- package.json | 1 + schema/fold.v1.schema.json | 188 ++++++++++++++++++ test/run.js | 174 +++++++++++++++- 9 files changed, 568 insertions(+), 47 deletions(-) create mode 100644 docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md create mode 100644 schema/fold.v1.schema.json diff --git a/USAGE.txt b/USAGE.txt index add3df7..82377c0 100644 --- a/USAGE.txt +++ b/USAGE.txt @@ -64,6 +64,8 @@ EWC3 Labs documentation tools Config `progression` (an ordered list of states) refuses a backwards move unless the commit carries State-Override: . + [--format json] One JSON document on stdout, per the published + schema/fold.v1.schema.json; exit codes unchanged. [--check-message [--staged]] Check a commit message BEFORE committing, by the same grammar: every Slice: names a document, every State: is a legend word. --staged: every staged slice document diff --git a/bin/ewc3-docs.js b/bin/ewc3-docs.js index 6bf69c0..06afe2e 100644 --- a/bin/ewc3-docs.js +++ b/bin/ewc3-docs.js @@ -32,6 +32,21 @@ const { frozenViolations: frozenSeriesViolations, contestedPrefixes } = require('../lib/series'); +// --format json (DOCS-090). A wrapper that parses this tool's English breaks the first time a message is reworded, so +// fold can emit ONE JSON document on stdout instead, versioned and published: schema/fold.v1.schema.json, whose +// `schema` field every document carries. Within v1 changes are additive only; a rename or removal is v2. +const FOLD_SCHEMA = 'ewc3-docs/fold@1'; +const JSON_MODE = process.argv[2] === 'fold' && process.argv.some((a, i) => a === 'json' && process.argv[i - 1] === '--format'); +const jsonMode = () => { + const has = (f) => process.argv.includes(f); + return has('--check-message') ? 'check-message' : has('--check') ? 'check' : has('--write') ? 'write' : 'dry-run'; +}; +/** Did not run, as JSON: a caller never falls back to reading text, however early the tool died. */ +function jsonDidNotRun(reason) { + process.stdout.write(`${JSON.stringify({ schema: FOLD_SCHEMA, mode: jsonMode(), ran: false, ok: false, reason: String(reason).trim() })}\n`); + process.exit(2); +} + // Where the config may live. A repository that keeps whole-repo configuration in one folder should // not have to make an exception for this tool, so `config/` is a first-class location rather than a // fallback. Both are searched, and finding TWO is an error - a second config that is silently @@ -80,6 +95,7 @@ function configLabel() { } function fail(message) { + if (JSON_MODE) { jsonDidNotRun(message); } console.error(`ewc3-docs: ${message}`); process.exit(2); } @@ -1119,9 +1135,9 @@ function cmdIndex(root, config, argv) { * trailer is an ERROR for commits after `--since` (for pull-request CI) and a WARNING in full history, which * cannot be rewritten. Writes slice frontmatter only - never STATUS or anything cross-repository. */ -function cmdFold(root, config, argv) { - const KNOWN = new Set(['--write', '--check', '--since', '--repo', '--config', '--check-message', '--staged', '--register', '--commits-from', '--source-repo']); - const VALUED = new Set(['--since', '--repo', '--config', '--check-message', '--register', '--commits-from', '--source-repo']); +function cmdFold(root, config, argv, report = {}) { + const KNOWN = new Set(['--write', '--check', '--since', '--repo', '--config', '--check-message', '--staged', '--register', '--commits-from', '--source-repo', '--format']); + const VALUED = new Set(['--since', '--repo', '--config', '--check-message', '--register', '--commits-from', '--source-repo', '--format']); for (const [i, a] of argv.entries()) { if (a.startsWith('--') && !KNOWN.has(a)) { console.error(`fold: unknown option ${a}`); return 2; } if (VALUED.has(a) && (argv[i + 1] === undefined || argv[i + 1].startsWith('--'))) { console.error(`fold: ${a} needs a value`); return 2; } @@ -1130,6 +1146,8 @@ function cmdFold(root, config, argv) { const write = argv.includes('--write'); const check = argv.includes('--check'); if (write && check) { console.error('fold: --write and --check are exclusive.'); return 2; } + const formatAt = argv.indexOf('--format'); + if (formatAt > -1 && !['json', 'text'].includes(argv[formatAt + 1])) { console.error(`fold: --format is json or text, not ${argv[formatAt + 1]}`); return 2; } const flag = (name) => { const i = argv.indexOf(name); return i > -1 ? argv[i + 1] : undefined; }; const repo = path.resolve(flag('--repo') || root); // --register : the register a message's trailers answer to, when it is not the repository being committed to @@ -1229,8 +1247,16 @@ function cmdFold(root, config, argv) { console.error(`fold: did not run: the committing repository keeps its own slice documents, so its staged documents answer to it, not to --register ${registerFlag}`); return 2; } - if (mode === 'roadmap-rows') { console.log('fold: rows register: nothing to fold - the Delivery Index is kept as rows, not slice documents'); return 0; } - if (!mode) { console.log('fold: no register: nothing to fold - no Delivery Index and no slice documents; Slice: trailers here are evidence only'); return 0; } + if (mode === 'roadmap-rows') { + report.notApplicable = 'rows register: nothing to fold - the Delivery Index is kept as rows, not slice documents'; + console.log(`fold: ${report.notApplicable}`); + return 0; + } + if (!mode) { + report.notApplicable = 'no register: nothing to fold - no Delivery Index and no slice documents; Slice: trailers here are evidence only'; + console.log(`fold: ${report.notApplicable}`); + return 0; + } const rel = (p) => path.relative(register, p).split(path.sep).join('/'); // A legend fold cannot fully read is a register defect, not a stale document: did not run, never exit 1 (DOCS-074). @@ -1245,10 +1271,12 @@ function cmdFold(root, config, argv) { const r = checkMessage({ repo, registerRoot: register, sliceDir, roadmaps, message, staged, registry: registerConfig.registry, progression: registerConfig.progression }); if (r.unreadable) { return legendUnreadable(r.unreadable); } if (r.failed) { console.error(`fold: did not run: ${r.failed}`); return 2; } + report.message = { trailers: r.pairs, stagedDocs: staged ? r.stagedDocs : null, notes: r.notes, + problems: r.problems.map((p) => ({ code: p.code, message: p.message, file: p.file || null })) }; r.notes.forEach((n) => console.log(`fold --check-message: ${n}`)); if (r.problems.length) { console.error(`fold --check-message: refused - ${r.problems.length} problem(s):`); - r.problems.forEach((p) => console.error(` ${p}`)); + r.problems.forEach((p) => console.error(` ${p.message}`)); return 1; } console.log(`fold --check-message: ok - ${r.pairs} Slice: trailer(s)${staged ? `, ${r.stagedDocs} staged slice document(s) checked` : ''}`); @@ -1267,6 +1295,8 @@ function cmdFold(root, config, argv) { if (plan.unreadable) { return legendUnreadable(plan.unreadable); } // A progression that cannot be read would refuse nothing it was meant to: did not run (DOCS-084). if (plan.configError) { console.error(`fold: did not run: ${plan.configError}`); return 2; } + report.plan = plan; + report.rel = rel; const errors = plan.issues.filter((i) => i.inScope); const warnings = plan.issues.filter((i) => !i.inScope); @@ -1327,10 +1357,55 @@ function cmdFold(root, config, argv) { console.error('fold: rolled back - the index refused to render the rows, so no slice document was changed either'); return indexCode; } + report.written = { changes: plan.changes.length, provenance: plan.provenance.length }; console.log(`fold: wrote ${plan.changes.length} state change(s) and ${plan.provenance.length} provenance update(s)`); return Math.max(indexCode, errors.length ? 1 : 0); } +/** + * `fold --format json`: run fold with its text captured, then write ONE document matching schema/fold.v1.schema.json. + * The exit code is the text mode's, unchanged: 0 consistent, 1 diverged, 2 did not run. + */ +function foldAsJson(root, config, argv) { + const said = { out: [], err: [] }; + const { log, error } = console; + console.log = (...a) => said.out.push(a.join(' ')); + console.error = (...a) => said.err.push(a.join(' ')); + const report = {}; + let code; + try { code = cmdFold(root, config, argv, report); } finally { console.log = log; console.error = error; } + const mode = jsonMode(); + const base = { schema: FOLD_SCHEMA, mode }; + if (code === 2) { + const reason = said.err.join('\n').replace(/^fold: (did not run: )?/, '') || 'fold did not run'; + process.stdout.write(`${JSON.stringify({ ...base, ran: false, ok: false, reason })}\n`); + return 2; + } + let doc; + if (report.notApplicable) { + doc = { ...base, ran: true, ok: code === 0, applicable: false, reason: report.notApplicable }; + } else if (mode === 'check-message') { + doc = { ...base, ran: true, ok: code === 0, applicable: true, ...report.message }; + } else { + const { plan, rel } = report; + const shape = (e) => ({ id: e.written, from: e.from || null, to: e.to, sha: e.sha, repo: e.repo || null, + date: e.dateText || null, source: e.source, override: e.override || null, file: rel(e.file) }); + doc = { ...base, ran: true, ok: code === 0, applicable: true, + legendSource: plan.legendSource, + changes: plan.changes.map(shape), + provenance: plan.provenance.map(shape), + conflicts: plan.conflicts.map((c) => ({ id: c.written, kept: c.human, trailer: c.to || c.trailer, sha: c.sha, file: rel(c.file) })), + issues: plan.issues.map((i) => ({ code: i.code, severity: i.inScope ? 'error' : 'warning', sha: i.sha, message: i.message })), + foreign: plan.foreign.map((f) => ({ sha: f.sha, written: f.written })), + unowned: plan.unowned ? [...plan.unowned].map(([prefix, u]) => ({ prefix, count: u.count, first: u.first })) : [], + quiet: plan.quiet || [], + alreadyLocal: plan.local || 0, + written: report.written || null }; + } + process.stdout.write(`${JSON.stringify(doc)}\n`); + return code; +} + function cmdSlice(root, config, argv) { const flag = (name) => { const i = argv.indexOf(name); return i > -1 ? argv[i + 1] : undefined; }; // `--state --write` must not store the state "--write" and then mint (Codex, PR #12). @@ -1423,6 +1498,7 @@ function cmdTables(root, config, argv) { // it is handled where it is read, and exits 1 naming the file. const didNotRun = (err) => { const reason = err && err.message ? err.message : String(err); + if (JSON_MODE) { jsonDidNotRun(reason); } console.error(`ewc3-docs: did not run: ${reason}`); if (process.env.EWC3_DOCS_DEBUG && err && err.stack) { console.error(err.stack); } process.exit(2); @@ -1462,7 +1538,7 @@ switch (command) { case 'tables': code = cmdTables(root, config, argv); break; case 'index': code = cmdIndex(root, config, argv); break; case 'slice': code = cmdSlice(root, config, argv); break; - case 'fold': code = cmdFold(root, config, argv); break; + case 'fold': code = JSON_MODE ? foldAsJson(root, config, argv) : cmdFold(root, config, argv); break; // The write-mode mirror of `check`. Values first, then format: substituting a number changes the // line, and the wrap has to see the result. Links and series never write, so they are not here. case 'fix': diff --git a/docs/Reference.md b/docs/Reference.md index a7f06cf..972115e 100644 --- a/docs/Reference.md +++ b/docs/Reference.md @@ -35,6 +35,7 @@ the wrap has to see the result. Running `format` then `values` can leave a line | `--check-message ` | `fold` only, and alone (not with `--write`, `--check` or `--since`). Checks a commit message **before** the commit exists, as git will store it: comment lines and everything below a scissors line are cut, and the trailer block is read by `git interpret-trailers --parse`, the parser behind the `%(trailers)` fold reads history with. Every `Slice:` must name a slice document (live or archived), every `State:` must resolve in the legend, and each `State:` needs a `Slice:` above it. `No-Slice: ` says why a commit names no slice; the reason is required, and it cannot stand with a `Slice:`. One slice per `Slice:` line: a comma or space list is refused. A `Slice:`, `State:` or `No-Slice:` line in a `Key: value` paragraph that is not the last one is refused as **stranded** - git reads trailers only from the last paragraph, so a blank line above `Co-Authored-By:` would otherwise pass as zero trailers (DOCS-088); `fold --check` reports the same per commit. Exit 0 accepted, or nothing applies (a rows register, no register), with the reason; 1 refused, naming each trailer or file; 2 did not run (unreadable file, not a repository, an unreadable legend). Reads no history. For a commit command or a `commit-msg` hook. | | `--commits-from ` | `fold` (dry run, `--write` or `--check`), not with `--check-message`. Trailers from **other** repositories, as NDJSON the caller assembled, one `{ "sha", "repo", "committer_date", "message" }` per line (`-` reads stdin). `committer_date` is ISO 8601 with a time and zone, as `git log --format=%cI` writes it. Each message is read by git's own trailer parser, as `--check-message` reads one. The list **adds** to local history: local commits keep topological order among themselves, and across repositories the newest is by committer date, then repository name, then sha - a weaker order than topology, so the dry run prints `repo@sha date` for every transition. A prefix the register does not declare is reported `unowned` with a count and applied to nothing; a frozen prefix is refused by name; a commit already in local history is read once; a commit with no trailers is named. An imported transition records `state_sha`, `state_repo: ` and `state_source: trailer-remote` - this repository could not verify it. Any bad line (not JSON, no sha, no repo, a date without a time or zone, one sha listed twice with different messages) refuses the whole list, exit 2, naming each line. Committing an import's frontmatter needs `Slice:`/`State:` trailers or `No-Slice:` under `--check-message --staged`, because the sha it records is not in this repository. (DOCS-084) | | `--source-repo ` | With `--commits-from` only. The repository for list lines that omit `repo`. | +| `--format json` | `fold` in every mode. One JSON document on stdout instead of text, matching the published schema - see [Machine-readable output](#machine-readable-output). Exit codes are unchanged. `--format text` is the default. | | `--register ` | With `--check-message` only. The register the trailers are validated against, when it is not the repository being committed to (a hub owning a series whose work lands elsewhere). Defaults to `--repo`; its own config supplies `registry`, `planning` and the roadmap globs. `--repo` stays the committing repository: `--staged` and `MERGE_HEAD` always read `--repo`, never `--register`. Strict: a `--register` holding no slice-document register exits 2 naming the path (an implicit absence still exits 0), and `--staged` with a different `--register` exits 2 when the committing repository keeps slice documents of its own, since those answer to it. | | `--staged` | With `--check-message` only. Every slice document added, modified or renamed in the index must be named by a `Slice:` (or the message carries `No-Slice:`), and one whose frontmatter `state` changed needs a `State:` for it that resolves to the new value. Exempt: a document where only `state`, `state_sha`, `state_repo` and `state_source` changed and the commit `state_sha` names has a trailer giving that state (`fold --write` recording history), and every document during a merge (`MERGE_HEAD`), which says so. Deleted documents are not checked. | | `--since ` | `fold --check` only. Malformed trailers in commits after `` are errors; older ones, which history cannot remove, are warnings. For pull-request CI, e.g. `--since origin/main`. | @@ -92,6 +93,28 @@ register with **no Doc column**, a document that leaves the last column empty re always links to its documents. A row whose ID was renamed while its cells were edited is refused. A slice document whose frontmatter cannot be read exits `1` and names the file. +## Machine-readable output + +`fold --format json` writes **one** JSON document to stdout, for wrappers and CI that must not parse +English. Every document carries `"schema": "ewc3-docs/fold@1"` and matches +[`schema/fold.v1.schema.json`][schema-fold-v1], a JSON Schema (draft 2020-12) shipped in the npm +package. + +- **Exit codes are the contract, unchanged by the format:** 0 consistent, 1 diverged, 2 did not run. + `ok` is `true` exactly when the exit code is 0. +- **Did not run is JSON too**, however early the tool stopped - a bad flag, an unreadable config or + commit list, a crash: `{ "ran": false, "ok": false, "reason": ... }`. +- **Branch on `code`, never on `message`.** Every issue and problem carries a stable `code` + (`stranded-trailer`, `ambiguous-state`, `backwards`, ...); the schema lists them all. Messages are + for people and may be reworded within a version. +- **Versioning.** Within version 1, changes are additive only: a new optional field, a new code. + Renaming or removing a field or a code is version 2, published as `fold.v2.schema.json` beside v1, + which stays. A consumer ignores fields it does not know and treats an unknown code by its + `severity`. +- The schema is **closed** (`additionalProperties: false`): the toolkit's tests validate real output + against it, so the tool cannot emit a field the schema does not publish, and the list of codes in + the schema is checked against the codes the source can emit. + ## Configuration `.ewc3-docs.json` in the repository root, or `config/ewc3-docs.json`, or `--config `. **Two @@ -286,3 +309,4 @@ a specific failure, not a style preference. A check that fires on something nobo is noise, and noise is how a green build stops meaning anything. [for-agents]: For_Agents.md#things-you-will-get-wrong +[schema-fold-v1]: ../schema/fold.v1.schema.json diff --git a/docs/project/EWC3_Docs_Tools_Roadmap.md b/docs/project/EWC3_Docs_Tools_Roadmap.md index 3871d93..b2e1774 100644 --- a/docs/project/EWC3_Docs_Tools_Roadmap.md +++ b/docs/project/EWC3_Docs_Tools_Roadmap.md @@ -21,7 +21,7 @@ not a summary of them. | Prefix | Scope | Owner | Last Used | Series | | --- | --- | --- | --- | --- | -| DOCS | global | ewc3-docs-tools | DOCS-089 | toolkit features and fixes | +| DOCS | global | ewc3-docs-tools | DOCS-090 | toolkit features and fixes | | FIX | repo-local | ewc3-docs-tools | FIX-1 | small corrections not worth a slice | | W | repo-local | ewc3-docs-tools | W-8 | decisions owed to the owner, never reused β€” [Decisions](Decisions.md) | @@ -112,6 +112,7 @@ is never referenced from outside the repository it fixes. | DOCS-087 | ⬜ planned | a converted register's Last Used is emitted by the tool, from slice documents and the archive | M | [DOCS-087][docs-087] | | | DOCS-088 | 🟦 tested | a trailer cut off by a blank line is refused, not passed as zero trailers | S | [DOCS-088][docs-088] | | | DOCS-089 | 🟦 tested | one State: under several Slice: lines is refused - it reads as all of them and moves only the last | S | [DOCS-089][docs-089] | | +| DOCS-090 | ⬜ planned | fold --format json: a versioned, published schema so wrappers never parse English | M | [DOCS-090][docs-090] | | ## Done @@ -222,6 +223,7 @@ caught. [docs-087]: slices/DOCS-087_a_converted_register_s_Last_Used_is_emitted_by_the_tool_fr.md [docs-088]: slices/DOCS-088_a_trailer_cut_off_by_a_blank_line_is_refused_not_passed_as.md [docs-089]: slices/DOCS-089_one_State_under_several_Slice_lines_is_refused_it_reads_as.md +[docs-090]: slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md [epqe]: https://github.com/ewc3labs/excel-power-query-editor [frontmatter-is-the]: ../design/frontmatter-is-the-declaration.md [one-template-beats]: ../design/one-template-beats-three-parsers.md diff --git a/docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md b/docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md new file mode 100644 index 0000000..c021e6b --- /dev/null +++ b/docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md @@ -0,0 +1,42 @@ +--- +id: DOCS-090 +state: ⬜ planned +title: "fold --format json: a versioned, published schema so wrappers never parse English" +est: M +doc: "[DOCS-090](slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md)" +status: "" +--- + +# DOCS-090 β€” fold --format json: a versioned, published schema so wrappers never parse English + +A CI wrapper around `fold` read its text: one regex on the `ok -` line of `--check-message`. Every +rewording of a message is then a silent break in someone else's tool. The owner asked for the output +to be machine-readable and machine-written, with **contract versioning and a place to store the +schema**. + +## Built + +- `fold --format json` in every mode: dry run, `--write`, `--check`, `--check-message`, and with + `--commits-from`. One document on stdout; exit codes unchanged; `ok` equals exit 0. +- **The schema is a file**, `schema/fold.v1.schema.json` (JSON Schema 2020-12), shipped in the npm + package. Its `$id` is a stable URL, and every document names it with + `"schema": "ewc3-docs/fold@1"`. +- **Versioning:** additive within v1; a rename or removal is v2, published beside v1, never over it. +- **Stable codes, set where each problem is raised.** Every problem in `lib/fold.js` is built by one + constructor, `problem(code, message)`, at the place it is detected. There is no classifier reading + the messages afterwards - that would be a second reader of this tool's English, the thing this + slice removes. +- **Did not run is JSON however early it happens:** an unknown flag, an unreadable config, a missing + commit list or a crash. A caller never falls back to text. +- `from` is `null` for a slice's first state, so a consumer can tell "new" from "moved". +- The text output is byte-for-byte unchanged; every existing test passes unmodified except where it + read a problem as a bare string. + +## How the contract is kept + +- The tests validate **real output** from every mode against the schema file, with a validator in + the test file. The validator implements a fixed set of keywords, and a test refuses a schema that + uses any other - a validator silently skipping a keyword would pass output the schema forbids. +- The schema is **closed** (`additionalProperties: false`), so a field added to the output without + being published fails the suite. Measured: one stray field fails three tests. +- The schema's list of codes is compared with the codes in the source, so neither can drift. diff --git a/lib/fold.js b/lib/fold.js index b3a6d96..0f39857 100644 --- a/lib/fold.js +++ b/lib/fold.js @@ -87,9 +87,17 @@ function registryName(texts, configured) { return !silent && names.size === 1 ? [...names.values()][0] : null; } +/** + * A problem with a STABLE CODE beside its words (DOCS-090). Callers that branch - a CI wrapper reading `--format json` - + * branch on `code`, which is part of the published schema; `message` is for people and may be reworded. + */ +function problem(code, message) { + return { code, message }; +} + /** * Pair a commit's trailer lines. Each `State:` belongs to the nearest `Slice:` above it. - * Returns `{ pairs: [{ slice, state|null }], errors: [message], override: reason|null }` - `State-Override: ` + * Returns `{ pairs: [{ slice, state|null }], errors: [{ code, message }], override: reason|null }` - `State-Override: ` * lets this commit's transitions move a slice backwards in a declared `progression` (DOCS-084). */ function parseTrailers(lines) { @@ -106,11 +114,11 @@ function parseTrailers(lines) { if (key === 'slice') { pairs.push({ slice: value, state: null }); } else if (key === 'state-override') { - if (!value) { errors.push('State-Override: needs a reason - it is the record of why a slice moved backwards'); } else { override = value; } + if (!value) { errors.push(problem('override-without-reason', 'State-Override: needs a reason - it is the record of why a slice moved backwards')); } else { override = value; } } else if (key === 'state') { const last = pairs[pairs.length - 1]; - if (!last) { errors.push(`State: with no Slice: above it (State: ${value})`); } else if (last.state !== null) { - errors.push(`a second State: for Slice: ${last.slice} (State: ${value})`); + if (!last) { errors.push(problem('state-without-slice', `State: with no Slice: above it (State: ${value})`)); } else if (last.state !== null) { + errors.push(problem('second-state', `a second State: for Slice: ${last.slice} (State: ${value})`)); } else { last.state = value; // ONE State: UNDER SEVERAL Slice: LINES READS AS "ALL OF THEM", AND MEANS "ONLY THE LAST" (DOCS-089). @@ -119,7 +127,7 @@ function parseTrailers(lines) { // ambiguous only: a timeline Slice written BELOW a paired one, or a commit with no State: at all, is not. const above = pairs.slice(settled, -1).map((p) => p.slice); if (above.length) { - errors.push(`State: ${value} applies only to Slice: ${last.slice} - ${above.map((s) => `Slice: ${s}`).join(', ')} above it ${above.length > 1 ? 'get' : 'gets'} no state change. Give each Slice: its own State:, or move a timeline-only Slice: below the State:`); + errors.push(problem('ambiguous-state', `State: ${value} applies only to Slice: ${last.slice} - ${above.map((s) => `Slice: ${s}`).join(', ')} above it ${above.length > 1 ? 'get' : 'gets'} no state change. Give each Slice: its own State:, or move a timeline-only Slice: below the State:`)); } settled = pairs.length; } @@ -167,10 +175,20 @@ function strandedMessage(line) { } /** "names no slice document", or - for `Slice: A, B` - the one-per-line rule it actually broke. */ -function unnamedMessage(value) { +function unnamedProblem(value) { return /[,;]|\S\s+\S/.test(value) - ? `Slice: ${value} names more than one slice in one trailer - write one Slice: per line, each with its own State:` - : `Slice: ${value} names no slice document`; + ? problem('multi-slice-trailer', `Slice: ${value} names more than one slice in one trailer - write one Slice: per line, each with its own State:`) + : problem('unnamed-slice', `Slice: ${value} names no slice document`); +} + +/** A stranded trailer line as a problem. */ +function strandedProblem(line) { + return problem('stranded-trailer', strandedMessage(line)); +} + +/** A state word that did not resolve, as a problem naming the trailer it came from. */ +function stateProblem(resolved, slice) { + return problem(resolved.code, `${resolved.error} (Slice: ${slice})`); } /** The first word of a state value, lowercased: `πŸ’¨ smoked` -> `smoked`, `⏸️ deferred` -> `deferred`. */ @@ -290,11 +308,11 @@ function spellingsOf(roadmapTexts, docs) { function resolveState(word, legend, spellings) { const w = String(word).trim().toLowerCase(); if (legend.size) { - return legend.has(w) ? { value: legend.get(w) } : { error: `State: ${word} is not in the legend (${[...legend.keys()].join(', ')})` }; + return legend.has(w) ? { value: legend.get(w) } : { code: 'unknown-state', error: `State: ${word} is not in the legend (${[...legend.keys()].join(', ')})` }; } const found = spellings.get(w); - if (!found || !found.size) { return { error: `State: ${word} is not in the legend - no row or document uses it, and the register has no State Legend` }; } - if (found.size > 1) { return { error: `State: ${word} is ambiguous - this register spells it ${[...found].map((s) => JSON.stringify(s)).join(' and ')}` }; } + if (!found || !found.size) { return { code: 'unknown-state', error: `State: ${word} is not in the legend - no row or document uses it, and the register has no State Legend` }; } + if (found.size > 1) { return { code: 'ambiguous-state-spelling', error: `State: ${word} is ambiguous - this register spells it ${[...found].map((s) => JSON.stringify(s)).join(' and ')}` }; } return { value: [...found][0] }; } @@ -355,20 +373,20 @@ function planFold({ repo, sliceDir, roadmaps, sinceShas = null, registry = null, const inScope = sinceShas ? sinceShas.has(sha) : false; const short = sha.slice(0, 12); const { pairs, errors, override } = parseTrailers(lines); - errors.forEach((message) => issues.push({ sha: short, message, inScope })); - strandedTrailers(body, lines).forEach((l) => issues.push({ sha: short, message: strandedMessage(l), inScope })); + errors.forEach((e) => issues.push({ sha: short, ...e, inScope })); + strandedTrailers(body, lines).forEach((l) => issues.push({ sha: short, ...strandedProblem(l), inScope })); for (const p of pairs) { // Another register's slice is not this register's to fold: reported, never an issue (DOCS-040). const ref = sliceRef(p.slice, reg.ownName); if (ref.kind === 'foreign') { foreign.push({ sha: short, written: ref.written }); continue; } const id = ref.id; if (!id || (!docs.has(id) && !archived.has(id))) { - issues.push({ sha: short, message: unnamedMessage(p.slice), inScope }); + issues.push({ sha: short, ...unnamedProblem(p.slice), inScope }); continue; } if (p.state === null) { continue; } const resolved = stateFor(p.state, reg); - if (resolved.error) { issues.push({ sha: short, message: `${resolved.error} (Slice: ${p.slice})`, inScope }); continue; } + if (resolved.error) { issues.push({ sha: short, ...stateProblem(resolved, p.slice), inScope }); continue; } if (!newest.has(id)) { newest.set(id, { sha: short, value: resolved.value, repo: null, source: 'trailer', date, override, inScope }); } } } @@ -439,19 +457,19 @@ function importCommits({ repo, reg, commits, local: localEvents, issues, foreign const matches = localEvents.filter((e) => e.sha.startsWith(c.sha)); if (matches.length === 1 && matches[0].body.trimEnd() === String(c.message).trimEnd()) { local += 1; continue; } const tag = `${c.repo}@${c.sha.slice(0, 12)}`; - const issue = (message) => issues.push({ sha: tag, message, inScope: true }); + const issue = (found) => issues.push({ sha: tag, ...found, inScope: true }); const lines = committedTrailers(repo, c.message); - if (lines === null) { issue('git interpret-trailers could not parse the message'); continue; } + if (lines === null) { issue(problem('unparseable-message', 'git interpret-trailers could not parse the message')); continue; } const { pairs, errors, override } = parseTrailers(lines); const stranded = strandedTrailers(c.message, lines); errors.forEach(issue); - stranded.forEach((l) => issue(strandedMessage(l))); + stranded.forEach((l) => issue(strandedProblem(l))); if (!pairs.length && !stranded.length) { quiet.push(tag); } for (const p of pairs) { const ref = sliceRef(p.slice, reg.ownName); if (ref.kind === 'foreign') { foreign.push({ sha: tag, written: ref.written }); continue; } const id = ref.id; - if (!id) { issue(unnamedMessage(p.slice)); continue; } + if (!id) { issue(unnamedProblem(p.slice)); continue; } const prefix = /^([A-Z][A-Z0-9]*)-/.exec(id)[1]; if (!owned(prefix)) { const u = unowned.get(prefix) || { count: 0, first: tag }; @@ -460,13 +478,13 @@ function importCommits({ repo, reg, commits, local: localEvents, issues, foreign continue; } if (reg.frozenPrefixes.has(prefix)) { - issue(`Slice: ${p.slice} - ${prefix} is frozen in this register; a retired series accepts no new state`); + issue(problem('frozen-prefix', `Slice: ${p.slice} - ${prefix} is frozen in this register; a retired series accepts no new state`)); continue; } - if (!docs.has(id) && !archived.has(id)) { issue(unnamedMessage(p.slice)); continue; } + if (!docs.has(id) && !archived.has(id)) { issue(unnamedProblem(p.slice)); continue; } if (p.state === null) { continue; } const resolved = stateFor(p.state, reg); - if (resolved.error) { issue(`${resolved.error} (Slice: ${p.slice})`); continue; } + if (resolved.error) { issue(stateProblem(resolved, p.slice)); continue; } if (!newest.has(id)) { newest.set(id, { sha: c.sha.slice(0, 12), value: resolved.value, repo: c.repo, source: 'trailer-remote', date: c.date, dateText: c.dateText, override }); } @@ -566,7 +584,7 @@ function loadRegister({ repo, sliceDir, roadmaps, registry = null }) { function stateFor(word, reg) { const w = String(word).trim().toLowerCase(); if (reg.conflicting.has(w)) { - return { error: `State: ${word} is ambiguous - two State Legends spell it ${[...reg.conflicting.get(w)].map((s) => JSON.stringify(s)).join(' and ')}` }; + return { code: 'ambiguous-state-spelling', error: `State: ${word} is ambiguous - two State Legends spell it ${[...reg.conflicting.get(w)].map((s) => JSON.stringify(s)).join(' and ')}` }; } return resolveState(word, reg.legend, reg.spellings); } @@ -609,7 +627,7 @@ function decide(docs, newest, issues, legend, order = null) { continue; } const entry = { id, written: String(doc.data.id), file: doc.file, text: doc.text, data: doc.data, from: current, to: ev.value, - sha: ev.sha, repo: ev.repo || null, source: ev.source || 'trailer', dateText: ev.dateText || null, override: null }; + sha: ev.sha, repo: ev.repo || null, source: ev.source || 'trailer', dateText: ev.dateText || (ev.date ? new Date(ev.date).toISOString() : null), override: null }; // A DECLARED progression refuses a backwards move unless the winning commit says why (DOCS-084). Only words in // the list are ordered: `blocked` or `deferred` outside it are never "backwards". const pending = order && current !== ev.value && backwards(order, current, ev.value); @@ -619,8 +637,8 @@ function decide(docs, newest, issues, legend, order = null) { if (back && !ev.override) { const sha = ev.repo ? `${ev.repo}@${ev.sha}` : ev.sha; issues.push(pending - ? { sha, inScope: true, message: `${doc.data.id}: ${wordOf(current)} -> ${wordOf(ev.value)} moves BACKWARDS in progression (${order.join(', ')}) - refused, not written; a commit that means it carries State-Override: ` } - : { sha, inScope: Boolean(ev.inScope), message: `${doc.data.id}: ${wordOf(ev.before)} -> ${wordOf(ev.value)} was committed BACKWARDS in progression (${order.join(', ')}) with no State-Override:` }); + ? { sha, inScope: true, code: 'backwards', message: `${doc.data.id}: ${wordOf(current)} -> ${wordOf(ev.value)} moves BACKWARDS in progression (${order.join(', ')}) - refused, not written; a commit that means it carries State-Override: ` } + : { sha, inScope: Boolean(ev.inScope), code: 'backwards-committed', message: `${doc.data.id}: ${wordOf(ev.before)} -> ${wordOf(ev.value)} was committed BACKWARDS in progression (${order.join(', ')}) with no State-Override:` }); continue; } if (back) { entry.override = ev.override; } @@ -702,7 +720,7 @@ function checkMessage({ repo, registerRoot = repo, sliceDir, roadmaps, message, if (lines === null) { return { failed: 'git interpret-trailers could not parse the message' }; } const { pairs, errors, override } = parseTrailers(lines); errors.forEach((e) => problems.push(e)); - strandedTrailers(storedMessage(repo, message), lines).forEach((l) => problems.push(strandedMessage(l))); + strandedTrailers(storedMessage(repo, message), lines).forEach((l) => problems.push(strandedProblem(l))); const named = new Map(); let unnamed = false; for (const p of pairs) { @@ -723,23 +741,23 @@ function checkMessage({ repo, registerRoot = repo, sliceDir, roadmaps, message, const prefix = id && /^([A-Z][A-Z0-9]*)-/.exec(id); const usedHere = prefix && [...reg.docs.keys(), ...reg.archived].some((k) => k.startsWith(`${prefix[1]}-`)); problems.push(prefix && reg.declaredPrefixes.size && !reg.declaredPrefixes.has(prefix[1]) && !usedHere - ? `Slice: ${p.slice} - ${prefix[1]} is not a prefix this register owns. If it is another register's slice, qualify it as :${id}; otherwise check the prefix for a typo` - : unnamedMessage(p.slice)); + ? problem('unowned-prefix', `Slice: ${p.slice} - ${prefix[1]} is not a prefix this register owns. If it is another register's slice, qualify it as :${id}; otherwise check the prefix for a typo`) + : unnamedProblem(p.slice)); } if (id && !named.has(id)) { named.set(id, []); } if (p.state === null) { continue; } const resolved = stateFor(p.state, reg); - if (resolved.error) { problems.push(`${resolved.error} (Slice: ${p.slice})`); continue; } + if (resolved.error) { problems.push(stateProblem(resolved, p.slice)); continue; } if (known) { named.get(id).push(resolved.value); } } // No-Slice: - a commit either names its slices or says why it names none. const exemptions = lines.map((l) => /^No-Slice:\s*(.*)$/i.exec(l)).filter(Boolean); for (const e of exemptions) { - if (!e[1].trim()) { problems.push('No-Slice: needs a reason - say why this commit names no slice'); } + if (!e[1].trim()) { problems.push(problem('no-slice-without-reason', 'No-Slice: needs a reason - say why this commit names no slice')); } } if (exemptions.length && pairs.length) { - problems.push('No-Slice: cannot stand with Slice: trailers - name every slice the commit touches, or none with a reason'); + problems.push(problem('no-slice-with-slice', 'No-Slice: cannot stand with Slice: trailers - name every slice the commit touches, or none with a reason')); } let stagedDocs = 0; @@ -768,7 +786,7 @@ function checkMessage({ repo, registerRoot = repo, sliceDir, roadmaps, message, // A document that WAS a slice and no longer declares one is a broken document, not a non-document: it // used to be skipped as "not a slice document" and passed unchecked (Codex, PR #22). if (prior && prior.had && normalizeId(prior.data.id)) { - problems.push(`${file}: the staged document for ${prior.data.id} has no readable id: in its frontmatter`); + problems.push({ ...problem('staged-no-id', `${file}: the staged document for ${prior.data.id} has no readable id: in its frontmatter`), file }); } continue; } @@ -788,14 +806,14 @@ function checkMessage({ repo, registerRoot = repo, sliceDir, roadmaps, message, } if (!named.has(id) && !exemptions.length) { - problems.push(`${file}: staged slice document ${now.data.id} is not named by a Slice: trailer (or add No-Slice: )`); + problems.push({ ...problem('staged-unnamed', `${file}: staged slice document ${now.data.id} is not named by a Slice: trailer (or add No-Slice: )`), file }); } if (prior && priorState !== nowState && !(named.get(id) || []).includes(nowState)) { - problems.push(`${file}: state changed ${priorState || '(none)'} -> ${nowState || '(none)'}, but no State: for ${now.data.id} resolves to it`); + problems.push({ ...problem('staged-state-mismatch', `${file}: state changed ${priorState || '(none)'} -> ${nowState || '(none)'}, but no State: for ${now.data.id} resolves to it`), file }); } // The staged edit itself moves backwards: refused here, before it is history (DOCS-084). if (order && prior && !override && backwards(order, priorState, nowState)) { - problems.push(`${file}: ${now.data.id} moves BACKWARDS ${wordOf(priorState)} -> ${wordOf(nowState)} in progression (${order.join(', ')}) - add State-Override: if it is meant`); + problems.push({ ...problem('staged-backwards', `${file}: ${now.data.id} moves BACKWARDS ${wordOf(priorState)} -> ${wordOf(nowState)} in progression (${order.join(', ')}) - add State-Override: if it is meant`), file }); } } } diff --git a/package.json b/package.json index e092a73..9ebe211 100644 --- a/package.json +++ b/package.json @@ -15,6 +15,7 @@ "files": [ "bin/", "lib/", + "schema/", "USAGE.txt", "README.md", "LICENSE" diff --git a/schema/fold.v1.schema.json b/schema/fold.v1.schema.json new file mode 100644 index 0000000..f79e88c --- /dev/null +++ b/schema/fold.v1.schema.json @@ -0,0 +1,188 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/ewc3labs/ewc3-docs-tools/main/schema/fold.v1.schema.json", + "title": "ewc3-docs fold --format json, version 1", + "description": "One document on stdout per run of `ewc3-docs fold --format json`, identified by `schema: \"ewc3-docs/fold@1\"`. The exit code is unchanged by the format: 0 consistent, 1 diverged, 2 did not run. VERSIONING: within version 1, changes are ADDITIVE only - a new optional field, a new issue code. Renaming or removing a field or a code is version 2, published as fold.v2.schema.json beside this file, which stays. CONSUMERS must ignore fields they do not know and treat an unknown code by its severity. This schema is CLOSED (additionalProperties: false) so the producer cannot emit a field it has not published; the toolkit's tests validate real output against it.", + "oneOf": [ + { "$ref": "#/$defs/didNotRun" }, + { "$ref": "#/$defs/notApplicable" }, + { "$ref": "#/$defs/checkMessage" }, + { "$ref": "#/$defs/fold" } + ], + "$defs": { + "schemaId": { "const": "ewc3-docs/fold@1" }, + "mode": { "enum": ["dry-run", "write", "check", "check-message"] }, + "code": { + "description": "A stable machine name for a problem. Branch on this, never on `message`.", + "enum": [ + "ambiguous-state", + "ambiguous-state-spelling", + "backwards", + "backwards-committed", + "frozen-prefix", + "multi-slice-trailer", + "no-slice-with-slice", + "no-slice-without-reason", + "override-without-reason", + "second-state", + "staged-backwards", + "staged-no-id", + "staged-state-mismatch", + "staged-unnamed", + "state-without-slice", + "stranded-trailer", + "unknown-state", + "unnamed-slice", + "unowned-prefix", + "unparseable-message" + ] + }, + "didNotRun": { + "description": "Exit 2: the check could not be performed - a bad flag, an unreadable config, legend or commit list, a crash. Emitted however early the tool stopped.", + "type": "object", + "required": ["schema", "mode", "ran", "ok", "reason"], + "additionalProperties": false, + "properties": { + "schema": { "$ref": "#/$defs/schemaId" }, + "mode": { "$ref": "#/$defs/mode" }, + "ran": { "const": false }, + "ok": { "const": false }, + "reason": { "type": "string" } + } + }, + "notApplicable": { + "description": "Exit 0: this repository keeps its register as rows, or has none, so there is nothing to fold.", + "type": "object", + "required": ["schema", "mode", "ran", "ok", "applicable", "reason"], + "additionalProperties": false, + "properties": { + "schema": { "$ref": "#/$defs/schemaId" }, + "mode": { "$ref": "#/$defs/mode" }, + "ran": { "const": true }, + "ok": { "const": true }, + "applicable": { "const": false }, + "reason": { "type": "string" } + } + }, + "checkMessage": { + "description": "`fold --check-message [--staged]`: a commit message checked before the commit exists. ok is true exactly when problems is empty, and matches exit 0/1.", + "type": "object", + "required": ["schema", "mode", "ran", "ok", "applicable", "trailers", "stagedDocs", "notes", "problems"], + "additionalProperties": false, + "properties": { + "schema": { "$ref": "#/$defs/schemaId" }, + "mode": { "const": "check-message" }, + "ran": { "const": true }, + "ok": { "type": "boolean" }, + "applicable": { "const": true }, + "trailers": { "type": "integer", "description": "Slice: trailers read from the message." }, + "stagedDocs": { "type": ["integer", "null"], "description": "Staged slice documents checked; null without --staged." }, + "notes": { "type": "array", "items": { "type": "string" } }, + "problems": { + "type": "array", + "items": { + "type": "object", + "required": ["code", "message", "file"], + "additionalProperties": false, + "properties": { + "code": { "$ref": "#/$defs/code" }, + "message": { "type": "string" }, + "file": { "type": ["string", "null"] } + } + } + } + } + }, + "transition": { + "type": "object", + "required": ["id", "from", "to", "sha", "repo", "date", "source", "override", "file"], + "additionalProperties": false, + "properties": { + "id": { "type": "string", "description": "The slice id as its document writes it." }, + "from": { "type": ["string", "null"], "description": "The state before; null for a slice's first state." }, + "to": { "type": "string" }, + "sha": { "type": "string", "description": "The commit whose trailer decided it." }, + "repo": { "type": ["string", "null"], "description": "Where sha lives; null for this repository." }, + "date": { "type": ["string", "null"], "description": "That commit's committer date, ISO 8601." }, + "source": { "enum": ["trailer", "trailer-remote"] }, + "override": { "type": ["string", "null"], "description": "The State-Override: reason, for a backwards move a declared progression allowed." }, + "file": { "type": "string", "description": "The slice document, relative to the register." } + } + }, + "fold": { + "description": "`fold` as a dry run, --write or --check, with or without --commits-from.", + "type": "object", + "required": ["schema", "mode", "ran", "ok", "applicable", "legendSource", "changes", "provenance", "conflicts", "issues", "foreign", "unowned", "quiet", "alreadyLocal", "written"], + "additionalProperties": false, + "properties": { + "schema": { "$ref": "#/$defs/schemaId" }, + "mode": { "enum": ["dry-run", "write", "check"] }, + "ran": { "const": true }, + "ok": { "type": "boolean", "description": "Exit code 0." }, + "applicable": { "const": true }, + "legendSource": { "enum": ["State Legend", "spellings the register already uses"] }, + "changes": { "type": "array", "items": { "$ref": "#/$defs/transition" }, "description": "State changes: written under --write, pending otherwise." }, + "provenance": { "type": "array", "items": { "$ref": "#/$defs/transition" }, "description": "State already right; state_sha/state_repo/state_source to record." }, + "conflicts": { + "type": "array", + "description": "state_source: human, kept; the newest trailer disagrees.", + "items": { + "type": "object", + "required": ["id", "kept", "trailer", "sha", "file"], + "additionalProperties": false, + "properties": { + "id": { "type": "string" }, + "kept": { "type": "string" }, + "trailer": { "type": "string" }, + "sha": { "type": "string" }, + "file": { "type": "string" } + } + } + }, + "issues": { + "type": "array", + "items": { + "type": "object", + "required": ["code", "severity", "sha", "message"], + "additionalProperties": false, + "properties": { + "code": { "$ref": "#/$defs/code" }, + "severity": { "enum": ["error", "warning"], "description": "error: after --since, or a listed commit, or a refused transition. warning: older history." }, + "sha": { "type": "string", "description": "A local sha, or repo@sha for a listed commit." }, + "message": { "type": "string" } + } + } + }, + "foreign": { + "type": "array", + "description": "Qualified trailers naming another register's slice: reported, never folded.", + "items": { + "type": "object", + "required": ["sha", "written"], + "additionalProperties": false, + "properties": { "sha": { "type": "string" }, "written": { "type": "string" } } + } + }, + "unowned": { + "type": "array", + "description": "--commits-from: prefixes this register does not declare, counted and applied to nothing.", + "items": { + "type": "object", + "required": ["prefix", "count", "first"], + "additionalProperties": false, + "properties": { "prefix": { "type": "string" }, "count": { "type": "integer" }, "first": { "type": "string" } } + } + }, + "quiet": { "type": "array", "items": { "type": "string" }, "description": "--commits-from: listed commits with no trailers, as repo@sha." }, + "alreadyLocal": { "type": "integer", "description": "--commits-from: listed commits already in local history, read there once." }, + "written": { + "type": ["object", "null"], + "description": "--write only: what was written; null otherwise.", + "required": ["changes", "provenance"], + "additionalProperties": false, + "properties": { "changes": { "type": "integer" }, "provenance": { "type": "integer" } } + } + } + } + } +} diff --git a/test/run.js b/test/run.js index fa13e21..a2d78f3 100644 --- a/test/run.js +++ b/test/run.js @@ -3467,7 +3467,7 @@ test('[fold] parseTrailers pairs each State with the nearest Slice above it', () { pairs: [{ slice: 'VS-1', state: 'coded' }, { slice: 'VS-2', state: 'smoked' }], errors: [], override: null }); assert.deepStrictEqual(parseTrailers(['Slice: VS-1', 'Slice: VS-2', 'State: go']).pairs, [{ slice: 'VS-1', state: null }, { slice: 'VS-2', state: 'go' }], 'a Slice with no State is a timeline event'); - assert.ok(/State: with no Slice:/.test(parseTrailers(['State: coded']).errors[0]), 'a State with no Slice is an error'); + assert.ok(/State: with no Slice:/.test(parseTrailers(['State: coded']).errors[0].message), 'a State with no Slice is an error'); }); test('[fold] DOCS-089: one State: under several Slice: lines is refused, naming the Slices it does NOT move; unambiguous timelines stay legal', () => { @@ -3475,9 +3475,9 @@ test('[fold] DOCS-089: one State: under several Slice: lines is refused, naming // Read as "all three are coded"; it means "only VS-3". The pairing itself is unchanged. const three = parseTrailers(['Slice: VS-1', 'Slice: VS-2', 'Slice: VS-3', 'State: coded']); assert.deepStrictEqual(three.pairs.map((p) => p.state), [null, null, 'coded']); - assert.deepStrictEqual(three.errors, ['State: coded applies only to Slice: VS-3 - Slice: VS-1, Slice: VS-2 above it get no state change. Give each Slice: its own State:, or move a timeline-only Slice: below the State:']); + assert.deepStrictEqual(three.errors, [{ code: 'ambiguous-state', message: 'State: coded applies only to Slice: VS-3 - Slice: VS-1, Slice: VS-2 above it get no state change. Give each Slice: its own State:, or move a timeline-only Slice: below the State:' }]); // Only the state-less Slices since the last State: are ambiguous. - assert.deepStrictEqual(parseTrailers(['Slice: VS-1', 'State: go', 'Slice: VS-2', 'Slice: VS-3', 'State: coded']).errors, + assert.deepStrictEqual(parseTrailers(['Slice: VS-1', 'State: go', 'Slice: VS-2', 'Slice: VS-3', 'State: coded']).errors.map((e) => e.message), ['State: coded applies only to Slice: VS-3 - Slice: VS-2 above it gets no state change. Give each Slice: its own State:, or move a timeline-only Slice: below the State:']); // Legal: a timeline Slice BELOW a paired one, a commit with no State at all, each Slice paired. for (const lines of [['Slice: VS-1', 'State: coded', 'Slice: VS-2'], ['Slice: VS-1', 'Slice: VS-2'], ['Slice: VS-1', 'State: coded', 'Slice: VS-2', 'State: go']]) { @@ -4564,6 +4564,174 @@ test('[progression] DOCS-084: an imported backwards move is refused too, named b assert.ok(r.out.includes('error: api@aaaaaaa1 VS-1: smoked -> coded moves BACKWARDS'), r.out); }); +// --- DOCS-090: fold --format json, validated against the PUBLISHED schema --- + +const FOLD_SCHEMA_FILE = path.join(__dirname, '..', 'schema', 'fold.v1.schema.json'); +/** The JSON Schema keywords validateSchema implements. A schema using any other is refused by a test below: + * a validator that silently skips a keyword it does not know would pass output the schema forbids. */ +const SCHEMA_KEYWORDS = new Set(['$schema', '$id', 'title', 'description', '$defs', '$ref', 'oneOf', 'type', 'const', 'enum', + 'required', 'properties', 'additionalProperties', 'items']); +function validateSchema(schema, value, root = schema, at = '$') { + if (schema.$ref) { return validateSchema(root.$defs[schema.$ref.replace('#/$defs/', '')], value, root, at); } + const errors = []; + if (schema.oneOf) { + const passing = schema.oneOf.filter((s) => !validateSchema(s, value, root, at).length).length; + if (passing !== 1) { errors.push(`${at}: matches ${passing} of oneOf, not exactly 1`); } + } + if ('const' in schema && JSON.stringify(schema.const) !== JSON.stringify(value)) { errors.push(`${at}: is ${JSON.stringify(value)}, not ${JSON.stringify(schema.const)}`); } + if (schema.enum && !schema.enum.some((e) => JSON.stringify(e) === JSON.stringify(value))) { errors.push(`${at}: ${JSON.stringify(value)} is not one of the enum`); } + if (schema.type) { + const kind = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value === 'number' && Number.isInteger(value) ? 'integer' : typeof value; + const allowed = [].concat(schema.type); + if (!allowed.includes(kind) && !(kind === 'integer' && allowed.includes('number'))) { errors.push(`${at}: is ${kind}, not ${allowed.join('|')}`); } + } + if (value && typeof value === 'object' && !Array.isArray(value)) { + for (const k of schema.required || []) { if (!(k in value)) { errors.push(`${at}: lacks ${k}`); } } + for (const [k, v] of Object.entries(value)) { + if (schema.properties && schema.properties[k]) { errors.push(...validateSchema(schema.properties[k], v, root, `${at}.${k}`)); } + else if (schema.additionalProperties === false) { errors.push(`${at}: ${k} is not in the schema`); } + } + } + if (Array.isArray(value) && schema.items) { value.forEach((v, i) => errors.push(...validateSchema(schema.items, v, root, `${at}[${i}]`))); } + return errors; +} +/** Run fold --format json; parse its ONE stdout document and validate it against the published schema. */ +function foldJson(args, dir, input) { + const r = require('child_process').spawnSync(process.execPath, + [path.join(__dirname, '..', 'bin', 'ewc3-docs.js'), 'fold', ...args, '--format', 'json', '--repo', dir], { encoding: 'utf8', input }); + const lines = r.stdout.trim().split('\n'); + assert.strictEqual(lines.length, 1, `exactly one JSON document on stdout, got:\n${r.stdout}`); + const doc = JSON.parse(lines[0]); + const errors = validateSchema(JSON.parse(fs.readFileSync(FOLD_SCHEMA_FILE, 'utf8')), doc); + assert.deepStrictEqual(errors, [], `${JSON.stringify(doc)}\nfails the schema`); + assert.strictEqual(doc.ok, r.status === 0, `ok must match exit 0 (exit ${r.status})`); + return { code: r.status, doc, stderr: r.stderr }; +} + +test('[json] DOCS-090: the schema uses only keywords the validator implements, and lists exactly the codes the code can emit', () => { + const schema = JSON.parse(fs.readFileSync(FOLD_SCHEMA_FILE, 'utf8')); + const used = new Set(); + const walk = (node, inProperties) => { + if (!node || typeof node !== 'object') { return; } + if (Array.isArray(node)) { node.forEach((n) => walk(n, false)); return; } + for (const [k, v] of Object.entries(node)) { + if (!inProperties) { used.add(k); } + walk(v, (k === 'properties' || k === '$defs') && !inProperties); + } + }; + walk(schema, false); + assert.deepStrictEqual([...used].filter((k) => !SCHEMA_KEYWORDS.has(k)), [], 'a keyword the validator would silently skip'); + // The codes in the schema are the codes in the source - read from every problem(...) and code: '...' in lib/fold.js. + const source = fs.readFileSync(path.join(__dirname, '..', 'lib', 'fold.js'), 'utf8'); + const emitted = [...new Set([...source.matchAll(/problem\('([a-z-]+)'/g), ...source.matchAll(/code: '([a-z-]+)'/g)].map((m) => m[1]))].sort(); + assert.deepStrictEqual([...schema.$defs.code.enum].sort(), emitted); + assert.strictEqual(schema.$defs.schemaId.const, 'ewc3-docs/fold@1'); + // Published with the package, or a consumer of the npm release cannot find it. + assert.ok(require('../package.json').files.includes('schema/'), 'schema/ is in package.json files'); +}); + +test('[json] DOCS-090: dry run, --write and --check validate; a first state has from: null; ok follows the exit code', () => { + const dir = foldRepo(); + // VS-2's document carries no state at all: its first state, so `from` is null. + const doc2 = gateDoc(dir, 'VS-2'); + fs.writeFileSync(doc2, fs.readFileSync(doc2, 'utf8').replace(/state: .*\n/, '')); + git(dir, 'commit', '-qam', 'stateless'); + const sha = trailerCommit(dir, 'work', ['Slice: VS-1', 'State: coded', 'Slice: VS-2', 'State: smoked']).slice(0, 12); + + const dry = foldJson([], dir); + assert.strictEqual(dry.doc.mode, 'dry-run'); + assert.deepStrictEqual(dry.doc.changes.map((c) => [c.id, c.from, c.to, c.sha, c.repo, c.source]), + [['VS-1', '⬜ planned', '🟦 coded', sha, null, 'trailer'], ['VS-2', null, 'πŸ’¨ smoked', sha, null, 'trailer']]); + assert.ok(/^\d{4}-\d{2}-\d{2}T/.test(dry.doc.changes[0].date), 'a local change carries its committer date'); + assert.strictEqual(dry.doc.written, null); + + const check = foldJson(['--check'], dir); + assert.strictEqual(check.code, 1); + assert.strictEqual(check.doc.changes.length, 2); + + const w = foldJson(['--write'], dir); + assert.strictEqual(w.code, 0); + assert.deepStrictEqual(w.doc.written, { changes: 2, provenance: 0 }); + assert.strictEqual(foldData(dir, 'VS-1').state, '🟦 coded', 'JSON mode writes exactly as text mode does'); +}); + +test('[json] DOCS-090: issues carry a code and a severity - error after --since, warning in history', () => { + const dir = foldRepo(); + trailerCommit(dir, 'old', ['Slice: VS-9', 'State: coded']); + const base = git(dir, 'rev-parse', 'HEAD'); + trailerCommit(dir, 'new', ['Slice: VS-1', 'Slice: VS-2', 'State: coded']); + const r = foldJson(['--check', '--since', base], dir); + assert.strictEqual(r.code, 1); + assert.deepStrictEqual(r.doc.issues.map((i) => [i.code, i.severity]).sort(), [['ambiguous-state', 'error'], ['unnamed-slice', 'warning']]); +}); + +test('[json] DOCS-090: a human conflict and an imported list - unowned, quiet, foreign, remote provenance - validate', () => { + const dir = hubRegister(); + const doc = gateDoc(dir, 'VS-2'); + fs.writeFileSync(doc, fs.readFileSync(doc, 'utf8').replace('status: y', 'status: y\nstate_source: human')); + git(dir, 'commit', '-qam', 'decided by hand'); + const list = commitList(dir, [ + listed('api', 'aaaaaaa1', '2026-10-01T10:00:00Z', 'Slice: VS-1', 'State: coded', 'Slice: XY-5', 'Slice: other:DT-3'), + listed('ui', 'bbbbbbb1', '2026-10-01T11:00:00Z', 'Slice: VS-2', 'State: go'), + { sha: 'ccccccc1', repo: 'ui', committer_date: '2026-10-01T09:00:00Z', message: 'docs only\n' }, + ]); + const r = foldJson(['--commits-from', list], dir); + assert.strictEqual(r.code, 0, JSON.stringify(r.doc)); + assert.deepStrictEqual(r.doc.changes.map((c) => [c.id, c.repo, c.source, c.date]), [['VS-1', 'api', 'trailer-remote', '2026-10-01T10:00:00Z']]); + assert.deepStrictEqual(r.doc.conflicts.map((c) => [c.id, c.kept, c.trailer]), [['VS-2', '⬜ planned', '🟩 go']]); + assert.deepStrictEqual(r.doc.unowned, [{ prefix: 'XY', count: 1, first: 'api@aaaaaaa1' }]); + assert.deepStrictEqual(r.doc.foreign, [{ sha: 'api@aaaaaaa1', written: 'other:DT-3' }]); + assert.deepStrictEqual(r.doc.quiet, ['ui@ccccccc1']); +}); + +test('[json] DOCS-090: --check-message, with and without --staged, validates; trailers counts what the text ok-line counts', () => { + const dir = foldRepo(); + const file = path.join(dir, '.git', 'TEST_EDITMSG'); + fs.writeFileSync(file, msg('Slice: VS-1', 'State: coded', 'Slice: VS-2', 'State: go')); + const ok = foldJson(['--check-message', file], dir); + assert.deepStrictEqual([ok.code, ok.doc.mode, ok.doc.trailers, ok.doc.stagedDocs, ok.doc.problems], [0, 'check-message', 2, null, []]); + + const doc = gateDoc(dir, 'VS-1'); + fs.writeFileSync(doc, `${fs.readFileSync(doc, 'utf8')}\nMore.\n`); + git(dir, 'add', '-A'); + fs.writeFileSync(file, msg('Slice: VS-9', 'State: shipped')); + const bad = foldJson(['--check-message', file, '--staged'], dir); + assert.strictEqual(bad.code, 1); + assert.deepStrictEqual(bad.doc.problems.map((p) => [p.code, p.file]), + [['unnamed-slice', null], ['unknown-state', null], ['staged-unnamed', 'docs/project/slices/VS-1_first.md']]); + assert.strictEqual(bad.doc.stagedDocs, 1); +}); + +test('[json] DOCS-090: did-not-run is JSON however early the tool stops, and nothing else reaches stdout', () => { + const dir = foldRepo(); + for (const [args, why] of [ + [['--bogus'], /unknown option --bogus/], + [['--write', '--check'], /exclusive/], + [['--config', path.join(dir, 'missing.json')], /no config at/], + [['--commits-from', path.join(dir, 'missing.ndjson')], /cannot read the commit list/], + ]) { + const r = foldJson(args, dir); + assert.strictEqual(r.code, 2, args.join(' ')); + assert.deepStrictEqual([r.doc.ran, r.doc.ok], [false, false]); + assert.ok(why.test(r.doc.reason), r.doc.reason); + } + // A bad --format value is not JSON mode at all, and says so in text. + assert.strictEqual(cli(['fold', '--format', 'yaml'], dir).code, 2); +}); + +test('[json] DOCS-090: a rows register and no register are not-applicable, exit 0', () => { + const rows = fs.mkdtempSync(path.join(os.tmpdir(), 'rows-')); + fs.mkdirSync(path.join(rows, 'docs', 'project'), { recursive: true }); + fs.writeFileSync(path.join(rows, 'docs', 'project', 'R_Roadmap.md'), '# R\n\n## Delivery Index\n\n| ID | State |\n| --- | --- |\n| VS-1 | planned |\n'); + git(rows, 'init', '-q'); git(rows, 'add', '-A'); git(rows, 'commit', '-qm', 'rows'); + const r = foldJson(['--check'], rows); + assert.deepStrictEqual([r.code, r.doc.applicable], [0, false]); + assert.ok(/rows register/.test(r.doc.reason), r.doc.reason); + const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'none-')); + git(empty, 'init', '-q'); git(empty, 'commit', '-q', '--allow-empty', '-m', 'x'); + assert.ok(/no register/.test(foldJson([], empty).doc.reason)); +}); + test('[slices] normalizeId: zero-padding never makes two ids of one slice', () => { const { normalizeId } = require('../lib/slices'); assert.strictEqual(normalizeId('VS-4'), 'VS-4'); From 8af459cb4de791c026e14d4c69ada98c7c15b111 Mon Sep 17 00:00:00 2001 From: Wilson Cook Date: Fri, 16 Oct 2026 01:10:12 -0500 Subject: [PATCH 2/2] fold: record DOCS-090 tested Co-Authored-By: Claude Opus 5.5 --- docs/project/EWC3_Docs_Tools_Roadmap.md | 2 +- ...ld_format_json_a_versioned_published_schema_so_wrappers.md | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/project/EWC3_Docs_Tools_Roadmap.md b/docs/project/EWC3_Docs_Tools_Roadmap.md index b2e1774..e66b9d9 100644 --- a/docs/project/EWC3_Docs_Tools_Roadmap.md +++ b/docs/project/EWC3_Docs_Tools_Roadmap.md @@ -112,7 +112,7 @@ is never referenced from outside the repository it fixes. | DOCS-087 | ⬜ planned | a converted register's Last Used is emitted by the tool, from slice documents and the archive | M | [DOCS-087][docs-087] | | | DOCS-088 | 🟦 tested | a trailer cut off by a blank line is refused, not passed as zero trailers | S | [DOCS-088][docs-088] | | | DOCS-089 | 🟦 tested | one State: under several Slice: lines is refused - it reads as all of them and moves only the last | S | [DOCS-089][docs-089] | | -| DOCS-090 | ⬜ planned | fold --format json: a versioned, published schema so wrappers never parse English | M | [DOCS-090][docs-090] | | +| DOCS-090 | 🟦 tested | fold --format json: a versioned, published schema so wrappers never parse English | M | [DOCS-090][docs-090] | | ## Done diff --git a/docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md b/docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md index c021e6b..2f26a4d 100644 --- a/docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md +++ b/docs/project/slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md @@ -1,10 +1,12 @@ --- id: DOCS-090 -state: ⬜ planned +state: 🟦 tested title: "fold --format json: a versioned, published schema so wrappers never parse English" est: M doc: "[DOCS-090](slices/DOCS-090_fold_format_json_a_versioned_published_schema_so_wrappers.md)" status: "" +state_sha: 0a4f15fb1280 +state_source: trailer --- # DOCS-090 β€” fold --format json: a versioned, published schema so wrappers never parse English