@sabaiway/agent-workflow-kit 23.8.0 → 23.9.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,29 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
4
4
  is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
5
5
  every `migrations/<version>-<slug>.md` newer than it, in semver order.
6
6
 
7
+ ## 23.9.0 — a failed coverage check shows what failed and the fix first (AD-237)
8
+
9
+ **After `/agent-workflow-kit upgrade`, a red `coverage-check.mjs --check` run opens with its failure, and so do a
10
+ usage mistake and an unexpected error.** Before, a red run printed its machine lines and notes first and its failures
11
+ after them in indented groups, a refused attestation context as a `REFUSED` line; a usage mistake and an unexpected
12
+ error went to standard error.
13
+
14
+ - **A red run prints one block on standard output:** `coverage-check: FAIL — <what failed>`, naming each class it
15
+ meets in a fixed order (the declared list, the lcov file, changed Node lines or files uncovered with their count,
16
+ red-proof obligations unmet with their count, the evidence store, the attestation context refused); then each
17
+ finding at column one starting with its place (`file:line`, a file, or `.` with the path leading its text when the
18
+ path cannot stand as a place); then one `coverage-check: REMEDY — …` line per class; then the lines a green run
19
+ prints, in their old order.
20
+ - **A usage mistake** prints the verdict line and the `Usage:` lines (exit 2); **an unexpected error** prints the
21
+ verdict line naming it, a REMEDY line and the stack, with no machine line (exit 1). Standard error stays empty.
22
+ - **What stays:** every exit code, everything the check judges, both machine lines (`lcov-sha256=` and `attested=`)
23
+ in count and content, and every run that exits 0, byte for byte. Two stated exceptions: `--help` says
24
+ "attestation context refused" where it said `REFUSED`; and in a red run with no attestation context
25
+ the `NO VERDICT` line says the findings stand above it.
26
+ - **A new kit module, `tools/checker-block/`,** places each finding and makes the verdict text, each finding's
27
+ text, the remedies and the after lines safe before the shared composer; the later checkers of the kit's tools will
28
+ use it too.
29
+
7
30
  ## 23.8.0 — the size record's reasons stay honest, and every run says what its scope left out (AD-236)
8
31
 
9
32
  **After `/agent-workflow-kit upgrade`, the kit writes its own reason `initial adoption` only into record entries the
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: agent-workflow-kit
3
3
  description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow". New to the epic, story and task tier? Run `/agent-workflow-kit tier`. A typed decision with a confidence from Jev? Run `/agent-workflow-kit jev`.
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '23.8.0'
6
+ version: '23.9.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "23.8.0",
6
+ "version": "23.9.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "23.8.0",
3
+ "version": "23.9.0",
4
4
  "description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -6,10 +6,12 @@ The **final-run checker** (strip-the-kit D3(c)+(d)) — two deterministic arms o
6
6
 
7
7
  Run `node ${CLAUDE_SKILL_DIR}/tools/coverage-check.mjs --check [--cwd <dir>]`:
8
8
 
9
- 0. **Attestation precondition (the provenance arm).** An lcov on disk carries no evidence of the tree it came from, so reading one and issuing a verdict certifies whatever happens to be there — the false GREEN direction is the dangerous one, because a line appended AFTER the suite ran has no `DA` entry and therefore reads non-executable ("nothing to cover"). Provenance is a CONSEQUENCE in exactly one context: a `run-gates --final` run deletes the artifact before any gate spawns. That runner mints a random nonce and writes `final-start.attempt` as a ONE-WAY COMMITMENT over `{nonce, tree fingerprint, base}`; the raw nonce rides the environment to this child, which recomputes the commitment and requires the record to carry it. Neither half suffices alone — a bare nonce is unverifiable, a persisted attempt id is reconstructible from public repo state — and the commitment is also the only place the BASE is bound, since no record stores it. The raw nonce is stripped from the red-proof probe environment so no descendant retains a live capability. `attested=` states whether a coverage VERDICT was ISSUED — pass **or** fail — never whether coverage passed: a valid handshake over an lcov that lists uncovered lines still reads `attested=yes` and still exits 1. Outcomes: **attested** → the coverage verdict is issued; **no handshake** → `attested=no` + `NO VERDICT` (exit 0, findings still printed, uncovered lines still exit 1 — the findings contract is unchanged); **a valid handshake over a run that read NO lcov BYTES** (the file is absent, or the path was refused as a non-regular file) → `attested=no` + `NO VERDICT`: the run owned the artifact's lifetime and read nothing, so it certifies NOTHING — reading `yes` there would be the false green this arm exists to close, one layer up. The predicate is the consumed bytes (`lcov-sha256` is a digest, not `none`), never the skip flag, so a refused path can never attest either. The two halves are independent: WITHHOLDING the verdict never changes an exit code — an absent file stays exit 0 (the loud `skipped-no-lcov`), and the refused non-regular path keeps its OWN fail-closed exit 1; **a handshake describing another tree or matching no recorded attempt** → `REFUSED` (exit 1), never a verdict in either direction. One fully anchored `coverage-check: attested=<yes|no>` machine line rides every run, on the same exactly-once contract as the sha line — and a withheld verdict TRAVELS: `run-gates` carries it as `coverage=not-run` on the summary line and names it on the checker's table row, and `core-evidence summary` never renders an unqualified GREEN over a final record that consumed no lcov. Stated residuals, both named rather than implied: (a) an operator who runs both processes can forge the store or the code — the kit's standing self-discipline posture, not a security boundary; (b) **"the run owns the artifact" is exclusive by CONVENTION over the fixed path, not enforced** — a writer outside the run (a second `run-gates`, a hand-run `--only unit-tests`, an orphaned test process) can place foreign evidence between the deletion and the checker's read, and every check then agrees. Closing (b) needs an attempt-unique artifact path, which the runner can name but the declared producer cmd must reference — queued as LCOV-EXCLUSIVE-OWNERSHIP. What this arm removes is the false green that needs no second process and nobody trying: evidence that predates the edit.
10
- 1. **Coverage arm (D3(d)):** every CHANGED executable Node line (`.mjs`/`.cjs`/`.js`, tracked working-vs-HEAD changes + untracked-not-ignored files) must be covered — uncovered lines are LISTED `file:line` and fail; a changed file ABSENT from the lcov map is a file-level red (never "non-executable" by silence); changed out-of-domain files (e.g. `.sh`) and unsupported-source files (e.g. `.ts`) are LISTED — the claim is narrowed honestly, not widened. NO lcov file at the path (ENOENT) = a LOUD `skipped-no-lcov` (exit 0, stated — produce the file via the unit-tests gate's lcov reporters); any other status failure exits 1 naming the path and the code where it has one; a symlink at the path is a refusal (lstat, no-follow). **The declared list:** a project may name in `docs/ai/coverage-declared.json` — a strict config written by hand, `{ "schema": 1, "entries": [{ "path": "<exact repo path>", "reason": "<one line>" }] }` — changed files nothing runs at their repository path (a fixture a test copies out and runs elsewhere). A listed changed file with no executed line in the lcov this run read is not judged and is printed with its reason; one with an executed line is judged as any other file; every line about the list prints on every run. An unreadable or malformed list fails (exit 1) and applies nothing. Under a final run the list must be the one the run started with, or the checker REFUSES.
9
+ 0. **Attestation precondition (the provenance arm).** An lcov on disk carries no evidence of the tree it came from, so reading one and issuing a verdict certifies whatever happens to be there — the false GREEN direction is the dangerous one, because a line appended AFTER the suite ran has no `DA` entry and therefore reads non-executable ("nothing to cover"). Provenance is a CONSEQUENCE in exactly one context: a `run-gates --final` run deletes the artifact before any gate spawns. That runner mints a random nonce and writes `final-start.attempt` as a ONE-WAY COMMITMENT over `{nonce, tree fingerprint, base}`; the raw nonce rides the environment to this child, which recomputes the commitment and requires the record to carry it. Neither half suffices alone — a bare nonce is unverifiable, a persisted attempt id is reconstructible from public repo state — and the commitment is also the only place the BASE is bound, since no record stores it. The raw nonce is stripped from the red-proof probe environment so no descendant retains a live capability. `attested=` states whether a coverage VERDICT was ISSUED — pass **or** fail — never whether coverage passed: a valid handshake over an lcov that lists uncovered lines still reads `attested=yes` and still exits 1. Outcomes: **attested** → the coverage verdict is issued; **no handshake** → `attested=no` + `NO VERDICT` (exit 0, findings still printed, uncovered lines still exit 1 — the findings contract is unchanged); **a valid handshake over a run that read NO lcov BYTES** (the file is absent, or the path was refused as a non-regular file) → `attested=no` + `NO VERDICT`: the run owned the artifact's lifetime and read nothing, so it certifies NOTHING — reading `yes` there would be the false green this arm exists to close, one layer up. The predicate is the consumed bytes (`lcov-sha256` is a digest, not `none`), never the skip flag, so a refused path can never attest either. The two halves are independent: WITHHOLDING the verdict never changes an exit code — an absent file stays exit 0 (the loud `skipped-no-lcov`), and the refused non-regular path keeps its OWN fail-closed exit 1; **a handshake describing another tree or matching no recorded attempt** → the class attestation context refused (exit 1), never a verdict in either direction. One fully anchored `coverage-check: attested=<yes|no>` machine line rides every run, on the same exactly-once contract as the sha line — and a withheld verdict TRAVELS: `run-gates` carries it as `coverage=not-run` on the summary line and names it on the checker's table row, and `core-evidence summary` never renders an unqualified GREEN over a final record that consumed no lcov. Stated residuals, both named rather than implied: (a) an operator who runs both processes can forge the store or the code — the kit's standing self-discipline posture, not a security boundary; (b) **"the run owns the artifact" is exclusive by CONVENTION over the fixed path, not enforced** — a writer outside the run (a second `run-gates`, a hand-run `--only unit-tests`, an orphaned test process) can place foreign evidence between the deletion and the checker's read, and every check then agrees. Closing (b) needs an attempt-unique artifact path, which the runner can name but the declared producer cmd must reference — queued as LCOV-EXCLUSIVE-OWNERSHIP. What this arm removes is the false green that needs no second process and nobody trying: evidence that predates the edit.
10
+ 1. **Coverage arm (D3(d)):** every CHANGED executable Node line (`.mjs`/`.cjs`/`.js`, tracked working-vs-HEAD changes + untracked-not-ignored files) must be covered — uncovered lines are LISTED `file:line` and fail; a changed file ABSENT from the lcov map is a file-level red (never "non-executable" by silence); changed out-of-domain files (e.g. `.sh`) and unsupported-source files (e.g. `.ts`) are LISTED — the claim is narrowed honestly, not widened. NO lcov file at the path (ENOENT) = a LOUD `skipped-no-lcov` (exit 0, stated — produce the file via the unit-tests gate's lcov reporters); any other status failure exits 1 naming the path and the code where it has one; a symlink at the path is a refusal (lstat, no-follow). **The declared list:** a project may name in `docs/ai/coverage-declared.json` — a strict config written by hand, `{ "schema": 1, "entries": [{ "path": "<exact repo path>", "reason": "<one line>" }] }` — changed files nothing runs at their repository path (a fixture a test copies out and runs elsewhere). A listed changed file with no executed line in the lcov this run read is not judged and is printed with its reason; one with an executed line is judged as any other file; every line about the list prints on every run. An unreadable or malformed list fails (exit 1) and applies nothing. Under a final run the list must be the one the run started with, or the attestation context is refused (exit 1).
11
11
  2. **Red-proof arm (D3(c)):** every authoritative current-base `red-proof` declaration must verify — the bound test file exists (deleted fails), its content sha256 matches the declaration (custody), the test resolves (zero-match fails) and runs green N/N NOW, and the declaration's pre-fix fingerprint differs from the current tree (equal = reuse/forgery, refused). A malformed evidence store fails CLOSED.
12
12
 
13
+ **The red output.** A red run prints ONE block on standard output and nothing on standard error. Its first line, `coverage-check: FAIL — …`, names each class the run meets, in this order: the declared list, the lcov file, changed Node lines or files uncovered (with their count), red-proof obligations unmet (with their count), the evidence store, the attestation context refused. Then each finding at its place — `file:line`, a file, or `.` with the path leading its text when the path cannot stand as a place — then one `coverage-check: REMEDY — …` line per class met, then the lines a green run also prints: `lcov-sha256=`, the notes, the declared list's lines, the verified red-proof line, `attested=` and, where no verdict was issued and the context was not refused, the `NO VERDICT` line. A usage mistake prints the verdict line and the `Usage:` lines (exit 2); an unexpected error prints the verdict line naming it, a remedy line and the stack, with no machine line (exit 1). Every green run but `--help` prints what it printed before; `--help` says "attestation context refused" where it said `REFUSED`.
14
+
13
15
  Wire it as the LAST declared gate in `docs/ai/gates.json` — `run-gates --final` REFUSES a declaration where the canonical coverage-check gate is not last (nothing may run after the checker consumed the lcov) or where its cmd is not ONE plain invocation of the kit's OWN tool (a masked form or a lookalike path never counts).
14
16
 
15
17
  **Invariants:** writes nothing · spawns read-only `git` queries + the bound-test probes (`node --test`, shell-free) · no network · exit 0 pass / 1 fail (locations listed) / 2 usage.
@@ -0,0 +1,2 @@
1
+ export { composeCheckerBlock } from './place.mjs';
2
+ export { runCheckerTail } from './tail.mjs';
@@ -0,0 +1,71 @@
1
+ import { composeRedBlock } from '../../references/scripts/shared/index.mjs';
2
+
3
+ const ROOT_PLACE = '.';
4
+ const PARENT_SEGMENT = '..';
5
+ const PATH_SEPARATOR = '/';
6
+ const LINE_MARKER = ':';
7
+ const FINDING_SEPARATOR = ': ';
8
+ const EMPTY_TEXT = '';
9
+ const SPACE = ' ';
10
+ const MIN_LINE = 1;
11
+ const TRAILING_SLASH = /\/$/;
12
+ const UNSAFE_PLACE = /[\\:\r\n]/;
13
+ const CARRIAGE_RETURN = /\r/g;
14
+ const LINE_FEED = /\n/g;
15
+ const LEADING_SPACE = /^ /;
16
+ const SHOWN_CARRIAGE_RETURN = '\\r';
17
+ const SHOWN_LINE_FEED = '\\n';
18
+ const SHOWN_LEADING_SPACE = '\\u0020';
19
+
20
+ const escapeLineBreaks = (text) => typeof text === 'string'
21
+ ? text.replace(CARRIAGE_RETURN, SHOWN_CARRIAGE_RETURN).replace(LINE_FEED, SHOWN_LINE_FEED)
22
+ : text;
23
+
24
+ export const escapeLineText = (text) => typeof text === 'string'
25
+ ? escapeLineBreaks(text).replace(LEADING_SPACE, SHOWN_LEADING_SPACE) : text;
26
+
27
+ export const placeFinding = ({ root, name, path, line, laterLines = [] }) => {
28
+ const rootPrefix = root.replace(TRAILING_SLASH, EMPTY_TEXT);
29
+ const relative = path === (rootPrefix || PATH_SEPARATOR) ? ROOT_PLACE
30
+ : typeof path === 'string' && path.startsWith(`${rootPrefix}${PATH_SEPARATOR}`)
31
+ ? path.slice(rootPrefix.length + PATH_SEPARATOR.length) : path;
32
+ if (relative === ROOT_PLACE && line === undefined) return { place: ROOT_PLACE, lead: EMPTY_TEXT };
33
+ const lineSuffix = line === undefined ? EMPTY_TEXT : `${LINE_MARKER}${String(line)}`;
34
+ const place = String(relative) + lineSuffix;
35
+ const segments = typeof path === 'string'
36
+ ? (path.startsWith(PATH_SEPARATOR) ? path.slice(PATH_SEPARATOR.length) : path).split(PATH_SEPARATOR)
37
+ : [];
38
+ const ownPlace = typeof path === 'string'
39
+ && segments.every((segment) => segment !== EMPTY_TEXT && segment !== ROOT_PLACE && segment !== PARENT_SEGMENT)
40
+ && relative !== EMPTY_TEXT && relative !== ROOT_PLACE && !UNSAFE_PLACE.test(relative)
41
+ && !relative.startsWith(SPACE) && relative !== name
42
+ && (line === undefined || (Number.isSafeInteger(line) && line >= MIN_LINE))
43
+ && !laterLines.some((text) => typeof text === 'string' && text.startsWith(`${place}${FINDING_SEPARATOR}`));
44
+ return ownPlace ? { place, lead: EMPTY_TEXT }
45
+ : { place: ROOT_PLACE, lead: `${escapeLineText(String(path) + lineSuffix)}${FINDING_SEPARATOR}` };
46
+ };
47
+
48
+ const mapList = (list, transform) => Array.isArray(list) ? Array.from(list, transform) : list;
49
+
50
+ export const composeCheckerBlock = ({ name, root, failed, findings = [], remedies, after = [] }) => {
51
+ const afterLines = mapList(after, escapeLineBreaks);
52
+ const findingList = mapList(findings, (finding) => {
53
+ if (finding === null || typeof finding !== 'object') return finding;
54
+ const { path, line, text, detail } = finding;
55
+ const { place, lead } = placeFinding({
56
+ root, name, path, line, laterLines: Array.isArray(afterLines) ? afterLines : [],
57
+ });
58
+ return {
59
+ place,
60
+ text: typeof text === 'string' && text.length ? lead + escapeLineText(text) : text,
61
+ ...(detail === undefined ? {} : { detail }),
62
+ };
63
+ });
64
+ return composeRedBlock({
65
+ name,
66
+ failed: escapeLineText(failed),
67
+ findings: findingList,
68
+ remedies: mapList(remedies, escapeLineText),
69
+ after: afterLines,
70
+ });
71
+ };
@@ -0,0 +1,16 @@
1
+ import { guardChecker } from '../../references/scripts/shared/index.mjs';
2
+
3
+ const LINE_FEED = '\n';
4
+
5
+ export const runCheckerTail = ({ name, exitCode, remedy }, run, host) => {
6
+ const answer = guardChecker({ name, exitCode, remedy }, run);
7
+ const writeAnswer = (result) => {
8
+ const lines = result.lines ?? result.stdout.split(LINE_FEED);
9
+ const text = lines.join(LINE_FEED);
10
+ if (text.length) host.stdout.write(text.endsWith(LINE_FEED) ? text : `${text}${LINE_FEED}`);
11
+ const code = result.code ?? result.exitCode;
12
+ host.exitCode = code;
13
+ return code;
14
+ };
15
+ return answer instanceof Promise ? answer.then(writeAnswer) : writeAnswer(answer);
16
+ };
@@ -0,0 +1,75 @@
1
+ import { composeCheckerBlock } from '../checker-block/index.mjs';
2
+ import { COVERAGE_DECLARED_REL } from '../coverage-declared/index.mjs';
3
+
4
+ export const CHECKER_NAME = 'coverage-check';
5
+ const ZERO = 0;
6
+ const CLASS_SEPARATOR = '; ';
7
+ const WITHHELD_PREFIX = `${CHECKER_NAME}: NO VERDICT — `;
8
+ const RED_NO_CONTEXT = `${WITHHELD_PREFIX}no final-run attestation context — a verdict is issued only inside the run that owns the lcov (run-gates.mjs --final); findings above are informational`;
9
+ const CLASS_TEXTS = [
10
+ {
11
+ verdict: () => 'the declared list is unusable',
12
+ remedy: `fix what each finding above names in ${COVERAGE_DECLARED_REL}, then re-run`,
13
+ },
14
+ {
15
+ verdict: () => 'the lcov file is unusable',
16
+ remedy: 'let the declared unit-tests gate write the lcov file as a regular file this run can read, then re-run',
17
+ },
18
+ {
19
+ verdict: (count) => `${count} changed Node line(s) or file(s) uncovered`,
20
+ remedy: 'cover each changed line and file above with a test that executes it, then re-run',
21
+ },
22
+ {
23
+ verdict: (count) => `${count} red-proof obligation(s) unmet`,
24
+ remedy: 're-observe each red proof above on its pre-fix tree, or restore its bound test until it runs green N/N',
25
+ },
26
+ {
27
+ verdict: () => 'the evidence store is unusable',
28
+ remedy: 'repair or move aside the evidence store above, then re-run',
29
+ },
30
+ {
31
+ verdict: () => 'the attestation context was refused',
32
+ remedy: 're-run run-gates.mjs --final on a tree no gate changes',
33
+ },
34
+ ];
35
+
36
+ export const buildDeclaredFindings = ({ configFailure, failures }) => configFailure
37
+ ? [{ path: COVERAGE_DECLARED_REL, text: configFailure }] : failures;
38
+
39
+ export const buildLcovFindings = (failure) => failure ? [{
40
+ path: failure.path,
41
+ text: failure.error
42
+ ? `status could not be read (${failure.error.code ?? failure.error.message})`
43
+ : 'not a regular file (a symlink/device is never read — fail closed)',
44
+ }] : [];
45
+
46
+ export const buildUncoveredFindings = (failures) => failures.map(({ path, line }) => ({
47
+ path,
48
+ ...(line === undefined ? {} : { line }),
49
+ text: line === undefined ? 'absent from coverage — the suite never executed this changed file'
50
+ : 'changed line not executed by the suite',
51
+ }));
52
+
53
+ export const buildRedProofFindings = (failures) => failures.map(({ file, testId, reason }) => ({
54
+ path: file, text: `${testId}: ${reason}`,
55
+ }));
56
+
57
+ export const buildEvidenceFindings = (path, failure) => failure ? [{ path, text: failure }] : [];
58
+
59
+ export const buildAttestationFindings = (root, refusal) => refusal ? [{ path: root, text: refusal }] : [];
60
+
61
+ export const isRed = (classes) => classes.some((findings) => findings.length > ZERO);
62
+
63
+ export const composeCoverageBlock = ({ root, classes, after, withoutContext = false }) => {
64
+ if (!isRed(classes)) return after;
65
+ const met = classes.map((findings, index) => ({ findings, ...CLASS_TEXTS[index] }))
66
+ .filter(({ findings }) => findings.length > ZERO);
67
+ return composeCheckerBlock({
68
+ name: CHECKER_NAME,
69
+ root,
70
+ failed: met.map(({ findings, verdict }) => verdict(findings.length)).join(CLASS_SEPARATOR),
71
+ findings: met.flatMap(({ findings }) => findings),
72
+ remedies: met.map(({ remedy }) => remedy),
73
+ after: after.map((line) => withoutContext && line.startsWith(WITHHELD_PREFIX) ? RED_NO_CONTEXT : line),
74
+ });
75
+ };
@@ -0,0 +1,47 @@
1
+ import { COVERAGE_DECLARED_REL } from '../coverage-declared/index.mjs';
2
+
3
+ export const LCOV_BASENAME = 'agent-workflow-lcov.info';
4
+ const USAGE = 'Usage:\n node coverage-check.mjs --check [--cwd <dir>]';
5
+ const HELP = `coverage-check — the D3(c)+(d) final-run checker (agent-workflow family).
6
+
7
+ ${USAGE}
8
+
9
+ Reads the FIXED kit-owned lcov file (<git dir>/${LCOV_BASENAME}; AW_LCOV_FILE overrides —
10
+ produced by the declared unit-tests gate cmd's --experimental-test-coverage lcov reporters and
11
+ deleted fresh by run-gates --final), lists uncovered CHANGED executable Node lines file:line,
12
+ lists changed out-of-domain files (the coverage claim is narrowed to Node lines), and VERIFIES
13
+ every current-base red-proof record: bound test present, content hash unchanged, green N/N
14
+ (AW_CORE_EVIDENCE_RERUNS, default 3), pre-fix fingerprint differing from the current tree.
15
+ An absent lcov file (ENOENT) is a LOUD skipped-no-lcov (exit 0 — NO coverage check ran, stated).
16
+ Any other lcov status failure, a symlinked lcov path, an uncovered line, a broken red-proof
17
+ obligation, or a malformed evidence store fails (exit 1).
18
+ A changed file listed in ${COVERAGE_DECLARED_REL} (one { path, reason } entry per file nothing
19
+ runs at its repository path) with no executed line in the lcov read is not judged; it and every
20
+ other list line print on every run. An unreadable or malformed list fails (exit 1); with a context
21
+ the list must be the one the final run started with (AW_FINAL_ATTEST_DECLARED), else the run
22
+ fails as attestation context refused (exit 1).
23
+
24
+ A coverage VERDICT is issued ONLY inside the run that owns the artifact's lifetime: run-gates
25
+ --final deletes the lcov before any gate spawns and hands this checker an attestation context
26
+ (a nonce whose one-way commitment over {nonce, fingerprint, base} is the final-start attempt id).
27
+ One anchored machine line rides every run: coverage-check: attested=<yes|no>. It states whether a
28
+ coverage VERDICT was ISSUED — pass OR fail — never that coverage passed.
29
+ attested=yes → a verdict was issued over the lcov BYTES this run read (a failing one still
30
+ exits 1); the predicate is the consumed digest, never the skip flag.
31
+ attested=no → NO VERDICT: no handshake, or no lcov bytes were read at all (an absent file or a
32
+ refused path — nothing read, nothing certified). Withholding a verdict never
33
+ changes an exit code: an absent lcov stays exit 0, a refused non-regular path
34
+ keeps its own fail-closed exit 1, and uncovered lines still exit 1. Findings are
35
+ still printed; run-gates carries the withheld verdict as coverage=not-run.
36
+ attestation context refused (exit 1) → the context describes another tree or another declared
37
+ list, or matches no recorded attempt.
38
+ Residual, stated: ownership of the fixed path is CONVENTION, not enforcement — a concurrent writer
39
+ to it can still place foreign evidence (queued as LCOV-EXCLUSIVE-OWNERSHIP).
40
+
41
+ Sandbox-safe: no network; writes nothing; spawns read-only git queries and the bound-test
42
+ probes (node --test, shell-free) — the D4 sandbox lane. The attestation variables are consumed and
43
+ removed from this process's environment before anything spawns, so no child inherits the capability.
44
+ Read-only. Exit codes: 0 pass / no-verdict / skipped-loud; 1 fail or attestation context refused; 2 usage.`;
45
+
46
+ export const composeHelp = () => HELP;
47
+ export const composeUsage = () => USAGE;
@@ -0,0 +1,5 @@
1
+ export {
2
+ CHECKER_NAME, composeCoverageBlock, isRed, buildDeclaredFindings, buildLcovFindings,
3
+ buildUncoveredFindings, buildRedProofFindings, buildEvidenceFindings, buildAttestationFindings,
4
+ } from './block.mjs';
5
+ export { LCOV_BASENAME, composeHelp, composeUsage } from './help.mjs';
@@ -22,13 +22,20 @@
22
22
 
23
23
  import { lstatSync, readFileSync, realpathSync } from 'node:fs';
24
24
  import { createHash } from 'node:crypto';
25
- import { join } from 'node:path';
25
+ import { join, resolve } from 'node:path';
26
26
  import { spawnSync } from 'node:child_process';
27
27
  import { GIT_MAX_BUFFER } from './git-env.mjs';
28
28
  import { computeChangedSurface } from './changed-surface.mjs';
29
29
  import { isDirectRun } from './direct-run.mjs';
30
30
  import { lcovCoveredMap, uncoveredChangedFromLcov } from './lcov.mjs';
31
- import { COVERAGE_DECLARED_REL, resolveDeclaredListPath, readDeclaredList, judgeDeclaredList, compareDeclaredAttest, declaredPassLine } from './coverage-declared/index.mjs';
31
+ import { resolveDeclaredListPath, readDeclaredList, judgeDeclaredList, compareDeclaredAttest, declaredPassLine } from './coverage-declared/index.mjs';
32
+ import { composeUsageRefusal } from '../references/scripts/shared/index.mjs';
33
+ import { runCheckerTail } from './checker-block/index.mjs';
34
+ import {
35
+ CHECKER_NAME, LCOV_BASENAME, composeCoverageBlock, isRed, composeHelp, composeUsage,
36
+ buildDeclaredFindings, buildLcovFindings, buildUncoveredFindings, buildRedProofFindings,
37
+ buildEvidenceFindings, buildAttestationFindings,
38
+ } from './coverage-check/index.mjs';
32
39
  import {
33
40
  computeTreeFingerprint,
34
41
  resolveBase,
@@ -45,9 +52,12 @@ import {
45
52
  } from './core-evidence.mjs';
46
53
 
47
54
  export const COVERAGE_CHECK_STOP = 'COVERAGE_CHECK_STOP';
48
- const usageFail = (message) => Object.assign(new Error(`[agent-workflow-kit] ${message}`), { exitCode: 2 });
49
-
50
- export const LCOV_BASENAME = 'agent-workflow-lcov.info';
55
+ export { LCOV_BASENAME };
56
+ const USAGE_EXIT_CODE = 2;
57
+ const ERROR_EXIT_CODE = 1;
58
+ const NOT_FOUND = -1;
59
+ const LINE_FEED = '\n';
60
+ const ERROR_REMEDY = 'fix the cause the stack below names, then re-run';
51
61
 
52
62
  const gitLine = (args, cwd) => {
53
63
  const r = spawnSync('git', args, { cwd, maxBuffer: GIT_MAX_BUFFER, windowsHide: true });
@@ -70,19 +80,18 @@ export const resolveLcovPath = (cwd, env = process.env) => {
70
80
  const checkCoverage = ({ rootTop, lcovPath, judgeDeclared }) => {
71
81
  const notes = [];
72
82
  const failures = [];
73
- let st = null;
74
- try {
75
- st = lstatSync(lcovPath);
76
- } catch (error) {
77
- if (error?.code === 'ENOENT') {
78
- return { failures, notes: [`skipped-no-lcov: no lcov file at ${lcovPath} — NO coverage check ran (produce it via the declared unit-tests gate cmd's lcov reporters)`], skipped: true, lcovSha256: null, declared: judgeDeclared(null) };
83
+ const status = (() => {
84
+ try {
85
+ return { file: lstatSync(lcovPath) };
86
+ } catch (error) {
87
+ return { error };
79
88
  }
80
- failures.push(`${lcovPath}: status could not be read (${error?.code ?? 'fs error'})`);
81
- return { failures, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
89
+ })();
90
+ if (status.error?.code === 'ENOENT') {
91
+ return { failures, notes: [`skipped-no-lcov: no lcov file at ${lcovPath} — NO coverage check ran (produce it via the declared unit-tests gate cmd's lcov reporters)`], skipped: true, lcovSha256: null, declared: judgeDeclared(null) };
82
92
  }
83
- if (!st.isFile()) {
84
- failures.push(`${lcovPath}: not a regular file (a symlink/device is never read — fail closed)`);
85
- return { failures, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
93
+ if (status.error || !status.file.isFile()) {
94
+ return { failures, lcovFailure: { path: resolve(lcovPath), error: status.error }, notes, skipped: false, lcovSha256: null, declared: judgeDeclared(null) };
86
95
  }
87
96
  const surface = computeChangedSurface(rootTop);
88
97
  const lcovBytes = readFileSync(lcovPath);
@@ -94,10 +103,10 @@ const checkCoverage = ({ rootTop, lcovPath, judgeDeclared }) => {
94
103
  const key = keyFor(rootTop, rel);
95
104
  const uncovered = uncoveredChangedFromLcov(covered, key, lines);
96
105
  if (uncovered === null) {
97
- failures.push(`${rel}: absent from coverage — the suite never executed this changed file`);
106
+ failures.push({ path: rel });
98
107
  continue;
99
108
  }
100
- for (const n of uncovered) failures.push(`${rel}:${n}`);
109
+ for (const n of uncovered) failures.push({ path: rel, line: n });
101
110
  }
102
111
  if (surface.outOfDomain.length > 0) {
103
112
  notes.push(`out-of-domain changed files (no Node-line coverage claim; covered by their own suites): ${surface.outOfDomain.join(', ')}`);
@@ -209,17 +218,17 @@ const verifyRedProofs = ({ rootTop, cwd, env }) => {
209
218
  for (const record of bound) {
210
219
  const id = record.testId;
211
220
  if (record.fingerprint === fingerprint) {
212
- failures.push(`${id}: the record's pre-fix fingerprint EQUALS the current tree — nothing changed since the observed red (reuse/forgery); re-observe on the pre-fix tree`);
221
+ failures.push({ file: record.file, testId: id, reason: "the record's pre-fix fingerprint EQUALS the current tree — nothing changed since the observed red (reuse/forgery); re-observe on the pre-fix tree" });
213
222
  continue;
214
223
  }
215
224
  const resolved = resolveTestFile(rootTop, record.file);
216
225
  if (!resolved.ok) {
217
- failures.push(`${id}: the bound test file ${resolved.reason.includes('does not exist') ? 'was deleted — ' : ''}${resolved.reason}`);
226
+ failures.push({ file: record.file, testId: id, reason: `the bound test file ${resolved.reason.includes('does not exist') ? 'was deleted — ' : ''}${resolved.reason}` });
218
227
  continue;
219
228
  }
220
229
  const currentHash = hashFileBytes(resolved.abs);
221
230
  if (currentHash !== record.fileHash) {
222
- failures.push(`${id}: the bound test file's content changed since the observed red (hash mismatch) — re-observe red at the new expectations`);
231
+ failures.push({ file: record.file, testId: id, reason: "the bound test file's content changed since the observed red (hash mismatch) — re-observe red at the new expectations" });
223
232
  continue;
224
233
  }
225
234
  let greens = 0;
@@ -232,11 +241,11 @@ const verifyRedProofs = ({ rootTop, cwd, env }) => {
232
241
  if (p.resolvable && p.baselineGreen) greens += 1;
233
242
  }
234
243
  if (executed === 0) {
235
- failures.push(`${id}: the pattern selects no test (zero-match) — the declared red→green pin is gone`);
244
+ failures.push({ file: record.file, testId: id, reason: 'the pattern selects no test (zero-match) — the declared red→green pin is gone' });
236
245
  continue;
237
246
  }
238
247
  if (greens !== reruns) {
239
- failures.push(`${id}: not green ${reruns}/${reruns} at the final run (${greens}/${reruns} green) — the declared fix is red`);
248
+ failures.push({ file: record.file, testId: id, reason: `not green ${reruns}/${reruns} at the final run (${greens}/${reruns} green) — the declared fix is red` });
240
249
  }
241
250
  }
242
251
  return { failures, verified: bound.length };
@@ -250,7 +259,6 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
250
259
  const read = readDeclaredList(resolveDeclaredListPath(rootTop));
251
260
  const lcovPath = resolveLcovPath(cwd, env);
252
261
  const lines = [];
253
- let failed = false;
254
262
  // The identity is read BEFORE the coverage arm and again AFTER it: a single up-front comparison
255
263
  // leaves a window in which the tree moves between the surface walk and the verdict.
256
264
  const identityBefore = { fingerprint: computeTreeFingerprint(cwd), base: resolveBase(cwd) };
@@ -264,29 +272,10 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
264
272
  lines.push(`coverage-check: lcov-sha256=${cov.lcovSha256 ?? 'none'}`);
265
273
  for (const note of cov.notes) lines.push(`coverage-check: ${note}`);
266
274
  lines.push(...declared.lines);
267
- if (declared.configFailure) {
268
- failed = true;
269
- lines.push(declared.configFailure);
270
- }
271
- const failures = [...cov.failures, ...declared.failures];
272
- if (failures.length > 0) {
273
- failed = true;
274
- lines.push('coverage-check: FAIL — uncovered/unattributed changed Node lines:');
275
- for (const f of failures) lines.push(` ${f}`);
276
- }
277
275
  // The probes must never inherit a live attestation capability (a detached descendant could keep it).
278
276
  const red = verifyRedProofs({ rootTop, cwd, env: withoutAttestEnv(env) });
279
- if (red.storeFailure) {
280
- failed = true;
281
- lines.push(`coverage-check: FAIL — ${red.storeFailure}`);
282
- } else {
283
- if (red.failures.length > 0) {
284
- failed = true;
285
- lines.push('coverage-check: FAIL — red-proof obligations not satisfied:');
286
- for (const f of red.failures) lines.push(` ${f}`);
287
- } else if (red.verified > 0) {
288
- lines.push(`coverage-check: ${red.verified} red-proof record(s) verified green N/N with custody intact`);
289
- }
277
+ if (!red.storeFailure && red.failures.length === 0 && red.verified > 0) {
278
+ lines.push(`coverage-check: ${red.verified} red-proof record(s) verified green N/N with custody intact`);
290
279
  }
291
280
  // Re-read the identity AFTER the coverage arm and re-decide: the attestation must describe the
292
281
  // tree the verdict was actually computed over, not the one it started over.
@@ -303,10 +292,16 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
303
292
  // EXACTLY ONE fully anchored machine line, the lcov-sha256 contract's sibling — the runner binds
304
293
  // it, so a missing/duplicated/injected one is an integrity failure rather than a silent green.
305
294
  lines.push(`coverage-check: attested=${attesting ? 'yes' : 'no'}`);
306
- if (attestation.refusal) {
307
- failed = true;
308
- lines.push(`coverage-check: REFUSED — ${attestation.refusal}`);
309
- } else if (!attesting) {
295
+ const classes = [
296
+ buildDeclaredFindings(declared),
297
+ buildLcovFindings(cov.lcovFailure),
298
+ buildUncoveredFindings(cov.failures),
299
+ buildRedProofFindings(red.failures ?? []),
300
+ buildEvidenceFindings(red.storeFailure ? resolve(storePath) : storePath, red.storeFailure),
301
+ buildAttestationFindings(rootTop, attestation.refusal),
302
+ ];
303
+ const failed = isRed(classes);
304
+ if (!attestation.refusal && !attesting) {
310
305
  lines.push(`coverage-check: NO VERDICT — ${contextValid ? NO_BYTES_NO_VERDICT : attestation.reason}`);
311
306
  }
312
307
  // The attestation gates ONLY the coverage claim. Every pre-existing fail-closed refusal above
@@ -314,71 +309,28 @@ export const runCheck = ({ cwd = process.cwd(), env = process.env } = {}) => {
314
309
  if (attesting && !failed && cov.failures.length === 0) {
315
310
  lines.push(declaredPassLine(declared.notJudged.length));
316
311
  }
317
- return { code: failed ? 1 : 0, lines };
312
+ return { code: failed ? 1 : 0, lines: composeCoverageBlock({ root: rootTop, classes, after: lines, withoutContext: !contextValid }) };
318
313
  };
319
314
 
320
315
  // ── CLI ───────────────────────────────────────────────────────────────────────────────────────────
321
316
 
322
- const HELP = `coverage-check — the D3(c)+(d) final-run checker (agent-workflow family).
323
-
324
- Usage:
325
- node coverage-check.mjs --check [--cwd <dir>]
326
-
327
- Reads the FIXED kit-owned lcov file (<git dir>/${LCOV_BASENAME}; AW_LCOV_FILE overrides —
328
- produced by the declared unit-tests gate cmd's --experimental-test-coverage lcov reporters and
329
- deleted fresh by run-gates --final), lists uncovered CHANGED executable Node lines file:line,
330
- lists changed out-of-domain files (the coverage claim is narrowed to Node lines), and VERIFIES
331
- every current-base red-proof record: bound test present, content hash unchanged, green N/N
332
- (AW_CORE_EVIDENCE_RERUNS, default 3), pre-fix fingerprint differing from the current tree.
333
- An absent lcov file (ENOENT) is a LOUD skipped-no-lcov (exit 0 — NO coverage check ran, stated).
334
- Any other lcov status failure, a symlinked lcov path, an uncovered line, a broken red-proof
335
- obligation, or a malformed evidence store fails (exit 1).
336
- A changed file listed in ${COVERAGE_DECLARED_REL} (one { path, reason } entry per file nothing
337
- runs at its repository path) with no executed line in the lcov read is not judged; it and every
338
- other list line print on every run. An unreadable or malformed list fails (exit 1); with a context
339
- the list must be the one the final run started with (AW_FINAL_ATTEST_DECLARED), else REFUSED.
340
-
341
- A coverage VERDICT is issued ONLY inside the run that owns the artifact's lifetime: run-gates
342
- --final deletes the lcov before any gate spawns and hands this checker an attestation context
343
- (a nonce whose one-way commitment over {nonce, fingerprint, base} is the final-start attempt id).
344
- One anchored machine line rides every run: coverage-check: attested=<yes|no>. It states whether a
345
- coverage VERDICT was ISSUED — pass OR fail — never that coverage passed.
346
- attested=yes → a verdict was issued over the lcov BYTES this run read (a failing one still
347
- exits 1); the predicate is the consumed digest, never the skip flag.
348
- attested=no → NO VERDICT: no handshake, or no lcov bytes were read at all (an absent file or a
349
- refused path — nothing read, nothing certified). Withholding a verdict never
350
- changes an exit code: an absent lcov stays exit 0, a refused non-regular path
351
- keeps its own fail-closed exit 1, and uncovered lines still exit 1. Findings are
352
- still printed; run-gates carries the withheld verdict as coverage=not-run.
353
- REFUSED (exit 1) → the context describes another tree or another declared list, or matches no recorded attempt.
354
- Residual, stated: ownership of the fixed path is CONVENTION, not enforcement — a concurrent writer
355
- to it can still place foreign evidence (queued as LCOV-EXCLUSIVE-OWNERSHIP).
356
-
357
- Sandbox-safe: no network; writes nothing; spawns read-only git queries and the bound-test
358
- probes (node --test, shell-free) — the D4 sandbox lane. The attestation variables are consumed and
359
- removed from this process's environment before anything spawns, so no child inherits the capability.
360
- Read-only. Exit codes: 0 pass / no-verdict / skipped-loud; 1 fail or REFUSED; 2 usage.`;
361
-
362
317
  export const main = (argv, ctx = {}) => {
318
+ if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: composeHelp(), stderr: '' };
363
319
  const env = ctx.env ?? process.env;
364
- try {
365
- if (argv.includes('--help') || argv.includes('-h')) return { code: 0, stdout: HELP, stderr: '' };
366
- let cwd = ctx.cwd ?? process.cwd();
367
- const rest = [...argv];
368
- const cwdAt = rest.indexOf('--cwd');
369
- if (cwdAt !== -1) {
370
- cwd = rest[cwdAt + 1];
371
- if (cwd === undefined) throw usageFail('--cwd needs a directory');
372
- rest.splice(cwdAt, 2);
373
- }
374
- const checkAt = rest.indexOf('--check');
375
- if (checkAt !== -1) rest.splice(checkAt, 1);
376
- if (rest.length > 0) throw usageFail(`unknown argument: ${rest[0]}`);
377
- const { code, lines } = runCheck({ cwd, env });
378
- return { code, stdout: lines.join('\n'), stderr: '' };
379
- } catch (err) {
380
- return { code: err.exitCode ?? 1, stdout: '', stderr: `coverage-check: ${err.message}` };
381
- }
320
+ const rest = [...argv];
321
+ const cwdAt = rest.indexOf('--cwd');
322
+ const refuseUsage = (failed) => ({
323
+ code: USAGE_EXIT_CODE,
324
+ stdout: composeUsageRefusal({ name: CHECKER_NAME, failed, usage: composeUsage() }).join(LINE_FEED),
325
+ stderr: '',
326
+ });
327
+ if (cwdAt !== NOT_FOUND && rest[cwdAt + 1] === undefined) return refuseUsage('--cwd needs a directory');
328
+ const cwd = cwdAt === NOT_FOUND ? ctx.cwd ?? process.cwd() : rest.splice(cwdAt, 2)[1];
329
+ const checkAt = rest.indexOf('--check');
330
+ if (checkAt !== NOT_FOUND) rest.splice(checkAt, 1);
331
+ if (rest.length > 0) return refuseUsage(`unknown argument: ${JSON.stringify(rest[0])}`);
332
+ const { code, lines } = runCheck({ cwd, env });
333
+ return { code, stdout: lines.join(LINE_FEED), stderr: '' };
382
334
  };
383
335
 
384
336
  if (isDirectRun(import.meta.url)) {
@@ -391,8 +343,6 @@ if (isDirectRun(import.meta.url)) {
391
343
  .map((k) => [k, process.env[k]]),
392
344
  );
393
345
  for (const k of Object.keys(attest)) delete process.env[k];
394
- const r = main(process.argv.slice(2), { env: { ...process.env, ...attest } });
395
- if (r.stdout) process.stdout.write(r.stdout.endsWith('\n') ? r.stdout : `${r.stdout}\n`);
396
- if (r.stderr) process.stderr.write(r.stderr.endsWith('\n') ? r.stderr : `${r.stderr}\n`);
397
- process.exitCode = r.code;
346
+ runCheckerTail({ name: CHECKER_NAME, exitCode: ERROR_EXIT_CODE, remedy: ERROR_REMEDY },
347
+ () => main(process.argv.slice(2), { env: { ...process.env, ...attest } }), process);
398
348
  }
@@ -18,11 +18,10 @@ const HEX_RADIX = 16;
18
18
  const ESCAPE_WIDTH = 4;
19
19
  const ESCAPE_PADDING = '0';
20
20
  const EMPTY_TEXT = '';
21
- const CONFIG_FAILURE_PREFIX = `coverage-check: FAIL — ${COVERAGE_DECLARED_REL}: `;
22
21
  const PASS_LINE = 'coverage-check: PASS — every changed Node line is covered';
23
22
 
24
23
  const makeResult = (configFailure = null) => ({ configFailure, notJudged: [], lines: [], failures: [] });
25
- const makeConfigFailure = (defect) => makeResult(`${CONFIG_FAILURE_PREFIX}${defect}`);
24
+ const makeConfigFailure = (defect) => makeResult(defect);
26
25
  const renderAsciiLine = (value) => Array.from(String(value), (character) => {
27
26
  const codePoint = character.codePointAt(ZERO);
28
27
  return codePoint >= ASCII_FIRST && codePoint <= ASCII_LAST
@@ -55,7 +54,7 @@ export const judgeDeclaredList = ({ top, read, changed, spawn }) => {
55
54
  continue;
56
55
  }
57
56
  if (probe.outcome === FOREIGN || probe.outcome === ERROR) {
58
- result.failures.push(`${entry.path}: listed in ${COVERAGE_DECLARED_REL} but not a regular file`);
57
+ result.failures.push({ path: entry.path, text: `listed in ${COVERAGE_DECLARED_REL} but not a regular file` });
59
58
  continue;
60
59
  }
61
60
  if (changed === null) continue;