Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions USAGE.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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: <reason>.
[--format json] One JSON document on stdout, per the published
schema/fold.v1.schema.json; exit codes unchanged.
[--check-message <file> [--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
Expand Down
90 changes: 83 additions & 7 deletions bin/ewc3-docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -80,6 +95,7 @@ function configLabel() {
}

function fail(message) {
if (JSON_MODE) { jsonDidNotRun(message); }
console.error(`ewc3-docs: ${message}`);
process.exit(2);
}
Expand Down Expand Up @@ -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; }
Expand All @@ -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 <dir>: the register a message's trailers answer to, when it is not the repository being committed to
Expand Down Expand Up @@ -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).
Expand All @@ -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` : ''}`);
Expand All @@ -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);

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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':
Expand Down
24 changes: 24 additions & 0 deletions docs/Reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ the wrap has to see the result. Running `format` then `values` can leave a line
| `--check-message <file>` | `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: <reason>` 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 <file\|->` | `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: <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 <name>` | 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 <dir>` | 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 <rev>` | `fold --check` only. Malformed trailers in commits after `<rev>` are errors; older ones, which history cannot remove, are warnings. For pull-request CI, e.g. `--since origin/main`. |
Expand Down Expand Up @@ -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 <path>`. **Two
Expand Down Expand Up @@ -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
4 changes: 3 additions & 1 deletion docs/project/EWC3_Docs_Tools_Roadmap.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ not a summary of them.

| Prefix | Scope | Owner | Last Used | Series |
| --- | --- | --- | --- | --- |
| DOCS | global | ewc3-docs-tools | <!--ewc3:lastDOCS-->DOCS-089<!--/ewc3:lastDOCS--> | toolkit features and fixes |
| DOCS | global | ewc3-docs-tools | <!--ewc3:lastDOCS-->DOCS-090<!--/ewc3:lastDOCS--> | toolkit features and fixes |
| FIX | repo-local | ewc3-docs-tools | <!--ewc3:lastFIX-->FIX-1<!--/ewc3:lastFIX--> | small corrections not worth a slice |
| W | repo-local | ewc3-docs-tools | <!--ewc3:lastW-->W-8<!--/ewc3:lastW--> | decisions owed to the owner, never reused — [Decisions](Decisions.md) |

Expand Down Expand Up @@ -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 | 🟦 tested | fold --format json: a versioned, published schema so wrappers never parse English | M | [DOCS-090][docs-090] | |

## Done

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading