π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix: correct coverage reporting and plugin workflow contracts
rUv6fe5706dfb17
diff --git a/docs/validation/oct12-fix-report.md b/docs/validation/oct12-fix-report.mdnew file mode 100644index 0000000000..849b3c2d52--- /dev/null+++ b/docs/validation/oct12-fix-report.md@@ -0,0 +1,96 @@+# October 12 issue fixes and verification++Worktree: `/home/ruv/work/ruflo-fixes-20261012`+Branch: `fix/oct12-verified-issues`+Final base: `3209ba266750908ea88fb0bc69672e106478bbef` (parent fast-forwarded main during review). All repair changes remain uncommitted. No push, merge, publication, credential changes, or Anthropic execution was performed by this worker.++## Issue mapping++| Issue | Change | Verification |+|---|---|---|+| #4082 | Extracted the CLI disk reader into `coverage-reader.ts`; corrected summary percentage precedence and explicit empty-file coverage. Valid supplied percentages, including zero, are preserved. Istanbul `Unknown` becomes 100 only with explicit valid empty counts. Missing, partial, or invalid counts remain conservative 0 when no authoritative aggregate is available. | Disk-reader cases plus actual coverage hook actions. |+| #4083 | LCOV aggregates original hit/found counts for lines, branches, and functions; statement coverage retains its existing line proxy. Includes final records without a terminator. | Unequal-size files produce 11/101 coverage, not the old 55% average. |+| #4084 | Added Istanbul `coverage-final.json` discovery at coverage/root locations and raw NYC counter parsing. Lines combine statement hits by start line; branch arms and functions use their own counters. Preserved legacy NYC summaries and existing summary/LCOV precedence. Empty reports do not hide usable fallback data. | Disk fixtures and all three coverage hooks; no MCP fallback on valid disk data. |+| #4085 | Fixed `plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md`, replacing unconditional success with observed final target and regression outcomes. Records commands, exit codes, failing test names, and interruption/abandonment reasons. | Executed the documented outcome example against seven cases. MCP `testgen-tools.ts` is unchanged. |+| #4086 | SPARC status uses paginated `memory_list`, exact `memory_retrieve`, and current-state keys; distinguishes gate history from current state and reports incomplete reads. Active status excludes explicit complete records and sorts newest state updatedAt with listing metadata updatedAt/storedAt fallback; legacy phase 5 alone remains active. Initialization sets active status and ISO timestamps; phase/gate state writes refresh updatedAt. Advance refuses completed records. After final gate success, advance and refine preserve state at the exact current-phase key, retain phase 5, and set complete/completedAt/updatedAt; failure never completes. Repeated completed refinement does not rewrite timestamps. | Seven prompt-contract checks pass, including four new lifecycle regressions (3 passed / 4 failed before the lifecycle fix). Checks cover listing, pagination, exact keys, absence of semantic state search, lifecycle timestamps, active ordering/filtering, final-gate completion and failure guards. These are instruction checks, not a live model/MCP session. |+| #4087 | Qualified phase agents, including exactly `ruflo-goals:goal-planner` and `ruflo-swarm:architect`; added missing-plugin preflight without silent substitutions or expanded permissions. | Checks assert the exact six phase-agent references and resolve each shipped agent file/frontmatter. |+| #4088 | Qualified SPARC command and skill invocations throughout command text, skill instructions, README, and examples, including init's specification suggestion. | Recursive command/skill Markdown scan rejects unqualified aliases and resolves qualified references to shipped files. The separately registered `/sparc-mod` stays unchanged. |++Both plugin smoke scripts now run their prompt regression contracts. No dependency, version, lockfile, SONA, mission, or MCP testgen runtime changes are included.++## Reproduction and results++Receipts are in [oct12-receipts](oct12-receipts/).++| Check | Before | Final candidate |+|---|---|---|+| Original coverage regressions | 0 passed / 5 failed (`coverage-before.txt`) | Expanded public disk-reader suite: 12 passed / 0 failed (`coverage-after.txt`) |+| Coverage CLI integration plus existing router suite | 39 passed / 3 failed (`coverage-integration-baseline.txt`) | 42 passed / 0 failed (`coverage-integration.txt`) |+| TDD skill outcomes | 1 passed / 6 failed (`tdd-workflow-before.txt`) | 7 passed / 0 failed (`tdd-workflow-after.txt`) |+| Original SPARC contracts | 0 passed / 3 failed (`sparc-before.txt`) | Strengthened contracts: 3 passed / 0 failed (`sparc-after.txt`) |+| Final review: unknown coverage counts | 9 passed / 3 failed (`coverage-review-before.txt`) | 12 passed / 0 failed |+| Final review: skill alias in examples | 2 passed / 1 failed (`sparc-review-before.txt`) | 3 passed / 0 failed |+| Final review: SPARC lifecycle | 3 passed / 4 failed (`sparc-lifecycle-before.txt`) | 7 passed / 0 failed (`sparc-lifecycle-after.txt`) |+| SPARC smoke | β | 15 passed / 0 failed |+| Testgen smoke | β | 14 passed / 0 failed |+| Coverage reader strict type-check | β | Exit 0, no diagnostics |+| Witness marker smoke | 18 present, 0 drift, 99 missing/skipped | Same: exit 0; not a full signed-artifact verification |+| `git diff --check` | β | Exit 0 |++Initial reproductions ran on `aac16fbdb3af21c0ddb989aaff4513a9ec1aaca5`. The coverage integration baseline temporarily loaded `git show HEAD:v3/@claude-flow/cli/src/commands/hooks.ts`, then restored candidate bytes in a `finally` block. The original hooks blob is identical on old and final base: `b3ec30cd1049cec5ce7ed25ab6b5b4ee88e7de0a`. Initial parser tests used esbuild to load the original private reader; final tests import the actual extracted TypeScript module and exercise it through filesystem inputs. Initial prompt tests lived under `tests/regression`; final plugin-local paths below are also used by smoke scripts. Counts from different suite revisions are not represented as identical test sets.++Validation commands (all run from the worktree root; each candidate run exited 0). Coverage, TDD, type-check and witness results below predate the final SPARC-only lifecycle edit; they were not rerun because those files did not change:++```bash+node --import /home/ruv/work/ruflo-fixes-20261012-task/validation-tools/node_modules/tsx/dist/loader.mjs tests/regression/oct12-coverage.test.cjs+node plugins/ruflo-sparc/tests/contracts.regression.cjs+node plugins/ruflo-testgen/tests/tdd-workflow.regression.cjs+node /home/ruv/work/ruflo-fixes-20261012-task/validation-tools/node_modules/vitest/vitest.mjs run --config tests/regression/oct12.vitest.config.mjs+bash plugins/ruflo-sparc/scripts/smoke.sh+bash plugins/ruflo-testgen/scripts/smoke.sh+node scripts/smoke-witness-marker-drift.mjs+node /home/ruv/work/ruflo-fixes-20261012-task/validation-tools/node_modules/typescript/bin/tsc --noEmit --strict --skipLibCheck --target ES2022 --module NodeNext --moduleResolution NodeNext --types node --typeRoots /usr/lib/node_modules/@claude-flow/cli/node_modules/@types v3/@claude-flow/cli/src/commands/coverage-reader.ts+git diff --check+```++Final #4086 lifecycle follow-up reran only the SPARC tests, plus whitespace validation. Exact commands and receipts:++```bash+node plugins/ruflo-sparc/tests/contracts.regression.cjs > docs/validation/oct12-receipts/sparc-lifecycle-before.txt 2>&1+# Before implementation: exit 1, 3 passed / 4 failed.+node plugins/ruflo-sparc/tests/contracts.regression.cjs > docs/validation/oct12-receipts/sparc-lifecycle-after.txt 2>&1+# After implementation: exit 0, 7 passed / 0 failed.+bash plugins/ruflo-sparc/scripts/smoke.sh > docs/validation/oct12-receipts/sparc-smoke.txt 2>&1+# Exit 0, 15 passed / 0 failed (includes the seven contract tests).+git diff --check+```++The lifecycle changes are prompt contracts, not executable transactional storage. Refine checks existing completion before writing and gates success on evidence; no distributed exactly-once or atomic read/write guarantee is claimed. Explicit phase re-entry reopens the workflow and clears stale completedAt. Reports can still include completed workflows.++Initial red commands, captured before implementing each corresponding fix:++```bash+ESBUILD_MODULE=/home/ruv/.npm/_npx/fd45a72a545557e9/node_modules/esbuild node tests/regression/oct12-coverage.test.cjs+node tests/regression/oct12-sparc.test.cjs+node tests/regression/oct12-tdd-workflow.test.cjs+```++These historical paths/harness versions explain the paths in the before receipts; use the final commands for current validation. The final review red checks used the same coverage import command and plugin-local SPARC command shown above. `coverage-compat-before.txt` records the intermediate empty-total sentinel and legacy NYC failures. `sparc-intended-agents-before.txt` records rejection of the earlier substitute agent mapping.++## Separately assessed upstream work++The parent supplied current issue #4085/#4087 bodies, `pr4081.patch`, and `pr4081-checks.txt` under `/home/ruv/work/ruflo-fixes-20261012-task/`. Local `gh api repos/ruvnet/ruflo/issues/4082` could not reach GitHub. The authorized ruOS desktop shell read was rejected because approval is required and policy is `never`; it was not retried or escalated. External reads and integration were handled by the parent.++**#4080 / PR4081:** inspected the supplied patch. It restores serialized SONA state when `LearningBridge` loads its neural instance, persists synchronously before cleanup, exposes `NeuralLearningSystem.serialize/deserialize`, and includes persistence/restore/degradation regressions. The current patch pins CLI memory exactly to `3.1.0`, rather than a caret range. Its synchronous best-effort save is not a concurrency/crash-durability guarantee. No part of this patch was duplicated or applied here.++Parent-supplied checks for head `4059c29`: **119 passed, 3 skipped, zero failures**. This is remote CI evidence, not a claim of local SONA execution. It includes [witness marker drift](https://github.com/ruvnet/ruflo/actions/runs/38216907105/job/114703664674), [Test V3 Packages](https://github.com/ruvnet/ruflo/actions/runs/38216907105/job/114703664604), and [Type Check V3](https://github.com/ruvnet/ruflo/actions/runs/38216907105/job/114703664734). PR4081 remains separate/open per parent instructions. Earlier caret-marker and mission SIGKILL failures are not asserted to be current failures; no mission test weakening or speculative runtime changes were made.++**PR4079:** parent reports merged with passing checks and included in the new main. No console changes were made here.++## Limits and handoff++- Focused checks passed; no whole-monorepo build/test or live model-driven SPARC session is claimed. CLI integration mocks presentation/MCP boundaries while executing the real hook actions and disk reader. The existing coverage-router suite also passes.+- Witness smoke skipped 99 absent generated files; it does not establish full artifact integrity.+- The initial out-of-scope testgen runtime experiment and mock tests were removed. Missing-plugin graceful degradation remains its existing deliberate contract. Signal-termination/result parsing observations are deferred for a separately scoped review, not counted as #4085 fixes.+- Required parent/repository/nested instructions were read before edits. Existing coordination was inspected: policy `legacy`, zero rules, valid empty ledger; no tracked collaboration-session adapter was found in `.harness`. A one-agent coordination record was initialized. Memory recall returned `Database not found`; no learning-memory success receipt is claimed. The installed CLI reported daemon auto-start during recall; `ruflo daemon stop` then reported it was not running, and subsequent CLI coordination disabled auto-start. No AI worker or external model execution was requested.+- `source-sha256.txt` binds the final modified source/tests/configuration, including untracked files, to their bytes. Parent inspection and independent rerun are the next integration step. All changes remain uncommitted.diff --git a/docs/validation/oct12-receipts/coverage-after.txt b/docs/validation/oct12-receipts/coverage-after.txtnew file mode 100644index 0000000000..346b21570d--- /dev/null+++ b/docs/validation/oct12-receipts/coverage-after.txt@@ -0,0 +1,70 @@+TAP version 13+# Subtest: \#4082 empty instrumented file is fully covered, not a gap+ok 1 - \#4082 empty instrumented file is fully covered, not a gap+ ---+ duration_ms: 3.701742+ ...+# Subtest: \#4082 pct-only summaries preserve explicit zero and nonzero percentages+ok 2 - \#4082 pct-only summaries preserve explicit zero and nonzero percentages+ ---+ duration_ms: 1.758291+ ...+# Subtest: \#4083 LCOV aggregates counts for every metric, including unterminated last record+ok 3 - \#4083 LCOV aggregates counts for every metric, including unterminated last record+ ---+ duration_ms: 1.33052+ ...+# Subtest: \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+ok 4 - \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+ ---+ duration_ms: 1.902941+ ...+# Subtest: empty or malformed reports do not hide a valid fallback+ok 5 - empty or malformed reports do not hide a valid fallback+ ---+ duration_ms: 1.154881+ ...+# Subtest: Istanbul empty-file Unknown sentinel yields numeric 100% in totals and entries+ok 6 - Istanbul empty-file Unknown sentinel yields numeric 100% in totals and entries+ ---+ duration_ms: 0.8879+ ...+# Subtest: legacy NYC summary reports remain readable+ok 7 - legacy NYC summary reports remain readable+ ---+ duration_ms: 0.889371+ ...+# Subtest: pct-only files retain their percentage but unknown aggregate counts stay conservative+ok 8 - pct-only files retain their percentage but unknown aggregate counts stay conservative+ ---+ duration_ms: 0.87474+ ...+# Subtest: mixed counted and uncounted files cannot claim a fully covered aggregate+ok 9 - mixed counted and uncounted files cannot claim a fully covered aggregate+ ---+ duration_ms: 1.678731+ ...+# Subtest: valid supplied aggregate percentages including zero take precedence+ok 10 - valid supplied aggregate percentages including zero take precedence+ ---+ duration_ms: 1.477791+ ...+# Subtest: incomplete or invalid counts do not manufacture a percentage+ok 11 - incomplete or invalid counts do not manufacture a percentage+ ---+ duration_ms: 3.907532+ ...+# Subtest: explicit empty counts across every file remain fully covered+ok 12 - explicit empty counts across every file remain fully covered+ ---+ duration_ms: 0.99171+ ...+1..12+# tests 12+# suites 0+# pass 12+# fail 0+# cancelled 0+# skipped 0+# todo 0+# duration_ms 41.4124diff --git a/docs/validation/oct12-receipts/coverage-before.txt b/docs/validation/oct12-receipts/coverage-before.txtnew file mode 100644index 0000000000..3e36ccbdc6--- /dev/null+++ b/docs/validation/oct12-receipts/coverage-before.txt@@ -0,0 +1,144 @@+TAP version 13+# Subtest: \#4082 empty instrumented file is fully covered, not a gap+not ok 1 - \#4082 empty instrumented file is fully covered, not a gap+ ---+ duration_ms: 2.797531+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:18:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ 0 !== 100++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 100+ actual: 0+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:20:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ node:internal/test_runner/harness:255:12+ node:internal/process/task_queues:140:7+ AsyncResource.runInAsyncScope (node:async_hooks:206:9)+ AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)+ process.processTicksAndRejections (node:internal/process/task_queues:95:5)+ ...+# Subtest: \#4082 pct-only summaries preserve explicit zero and nonzero percentages+not ok 2 - \#4082 pct-only summaries preserve explicit zero and nonzero percentages+ ---+ duration_ms: 0.32945+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:23:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ 0 !== 75++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 75+ actual: 0+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:25:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ process.processTicksAndRejections (node:internal/process/task_queues:95:5)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4083 LCOV aggregates counts for every metric, including unterminated last record+not ok 3 - \#4083 LCOV aggregates counts for every metric, including unterminated last record+ ---+ duration_ms: 0.659871+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:28:1'+ failureType: 'testCodeFailure'+ error: |-+ overallLineCoverage+ + actual - expected++ + 55+ - 10.891089108910892+ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 10.891089108910892+ actual: 55+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:31:130)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ process.processTicksAndRejections (node:internal/process/task_queues:95:5)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+not ok 4 - \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+ ---+ duration_ms: 3.514771+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:33:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ false !== true++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: true+ actual: false+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:41:14)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ process.processTicksAndRejections (node:internal/process/task_queues:95:5)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: empty or malformed reports do not hide a valid fallback+not ok 5 - empty or malformed reports do not hide a valid fallback+ ---+ duration_ms: 1.672041+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:48:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:+ + actual - expected++ + 'coverage/coverage-summary.json'+ - 'coverage/lcov.info'+ ^+ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 'coverage/lcov.info'+ actual: 'coverage/coverage-summary.json'+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:55:12)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ process.processTicksAndRejections (node:internal/process/task_queues:95:5)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+1..5+# tests 5+# suites 0+# pass 0+# fail 5+# cancelled 0+# skipped 0+# todo 0+# duration_ms 22.939821diff --git a/docs/validation/oct12-receipts/coverage-compat-before.txt b/docs/validation/oct12-receipts/coverage-compat-before.txtnew file mode 100644index 0000000000..9dcf79ed87--- /dev/null+++ b/docs/validation/oct12-receipts/coverage-compat-before.txt@@ -0,0 +1,85 @@+TAP version 13+# Subtest: \#4082 empty instrumented file is fully covered, not a gap+ok 1 - \#4082 empty instrumented file is fully covered, not a gap+ ---+ duration_ms: 4.028692+ ...+# Subtest: \#4082 pct-only summaries preserve explicit zero and nonzero percentages+ok 2 - \#4082 pct-only summaries preserve explicit zero and nonzero percentages+ ---+ duration_ms: 1.0368+ ...+# Subtest: \#4083 LCOV aggregates counts for every metric, including unterminated last record+ok 3 - \#4083 LCOV aggregates counts for every metric, including unterminated last record+ ---+ duration_ms: 1.210651+ ...+# Subtest: \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+ok 4 - \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+ ---+ duration_ms: 1.798471+ ...+# Subtest: empty or malformed reports do not hide a valid fallback+ok 5 - empty or malformed reports do not hide a valid fallback+ ---+ duration_ms: 1.277701+ ...+# Subtest: Istanbul empty-file Unknown sentinel yields numeric 100% in totals and entries+not ok 6 - Istanbul empty-file Unknown sentinel yields numeric 100% in totals and entries+ ---+ duration_ms: 3.057651+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:64:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ 'Unknown' !== 100++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 100+ actual: 'Unknown'+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:68:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: legacy NYC summary reports remain readable+not ok 7 - legacy NYC summary reports remain readable+ ---+ duration_ms: 1.124631+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:71:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ false !== true++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: true+ actual: false+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:73:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+1..7+# tests 7+# suites 0+# pass 5+# fail 2+# cancelled 0+# skipped 0+# todo 0+# duration_ms 33.309396diff --git a/docs/validation/oct12-receipts/coverage-integration-baseline.txt b/docs/validation/oct12-receipts/coverage-integration-baseline.txtnew file mode 100644index 0000000000..23d4bbcd3d--- /dev/null+++ b/docs/validation/oct12-receipts/coverage-integration-baseline.txt@@ -0,0 +1,88 @@++ RUN v4.1.0 /home/ruv/work/ruflo-fixes-20261012++ β― v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts (3 tests | 3 failed) 25ms+ Γ does not route or suggest tests for empty instrumented files 18ms+ Γ propagates weighted LCOV totals to gaps and routing 2ms+ Γ reads Istanbul final counters through every coverage hook without MCP fallback 3ms++β―β―β―β―β―β―β― Failed Tests 3 β―β―β―β―β―β―β―++ FAIL v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts > coverage hooks disk integration (#4082β#4084) > does not route or suggest tests for empty instrumented files+AssertionError: expected { success: true, data: { β¦(6) } } to match object { success: true, β¦(1) }+(9 matching properties omitted from actual)++- Expected++ Received++ {+ "data": {+- "gaps": [],++ "gaps": [++ {++ "complexity": 10,++ "coveragePercent": 0,++ "filePath": "src/empty.ts",++ "gapType": "critical",++ "priority": 10,++ "reason": "Line coverage 0.0% below 80% threshold",++ "suggestedAgents": [++ "tester",++ "coder",++ ],++ },++ ],+ "summary": {+- "overallLineCoverage": 100,++ "overallLineCoverage": "Unknown",+ },+ },+ "success": true,+ }++ β― v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts:42:18+ 40| writeFileSync('coverage/coverage-summary.json', JSON.stringify({ tβ¦+ 41| const gaps = await run('coverage-gaps');+ 42| expect(gaps).toMatchObject({ success: true, data: { gaps: [], summβ¦+ | ^+ 43| const route = await run('coverage-route', { task: 'write tests forβ¦+ 44| expect(route).toMatchObject({ success: true, data: { gaps: [], metβ¦++β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―[1/3]β―++ FAIL v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts > coverage hooks disk integration (#4082β#4084) > propagates weighted LCOV totals to gaps and routing+AssertionError: expected 55 to be close to 10.891089108910892, received difference is 44.10891089108911, but expected 0.005+ β― v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts:52:60+ 50| writeFileSync('coverage/lcov.info', 'SF:large.ts\nLF:100\nLH:10\nBβ¦+ 51| const gaps = await run('coverage-gaps');+ 52| expect((gaps.data as any).summary.overallLineCoverage).toBeCloseToβ¦+ | ^+ 53| expect((gaps.data as any).summary.overallBranchCoverage).toBeCloseβ¦+ 54| const route = await run('coverage-route', { task: 'write tests' });++β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―[2/3]β―++ FAIL v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts > coverage hooks disk integration (#4082β#4084) > reads Istanbul final counters through every coverage hook without MCP fallback+AssertionError: expected false to be true // Object.is equality++- Expected++ Received++- true++ false++ β― v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts:65:30+ 63| for (const name of ['coverage-gaps', 'coverage-route', 'coverage-sβ¦+ 64| const result = await run(name, { task: 'test auth', path: 'src/aβ¦+ 65| expect(result.success).toBe(true);+ | ^+ 66| expect((result.data as any).source).toBe('coverage/coverage-finaβ¦+ 67| }++β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―β―[3/3]β―+++ Test Files 1 failed | 1 passed (2)+ Tests 3 failed | 39 passed (42)+ Start at 13:18:41+ Duration 1.03s (transform 539ms, setup 0ms, import 617ms, tests 51ms, environment 0ms)diff --git a/docs/validation/oct12-receipts/coverage-integration.txt b/docs/validation/oct12-receipts/coverage-integration.txtnew file mode 100644index 0000000000..de4a602dd9--- /dev/null+++ b/docs/validation/oct12-receipts/coverage-integration.txt@@ -0,0 +1,8 @@++ RUN v4.1.0 /home/ruv/work/ruflo-fixes-20261012+++ Test Files 2 passed (2)+ Tests 42 passed (42)+ Start at 13:20:48+ Duration 942ms (transform 485ms, setup 0ms, import 558ms, tests 42ms, environment 0ms)diff --git a/docs/validation/oct12-receipts/coverage-review-before.txt b/docs/validation/oct12-receipts/coverage-review-before.txtnew file mode 100644index 0000000000..8557ba6b83--- /dev/null+++ b/docs/validation/oct12-receipts/coverage-review-before.txt@@ -0,0 +1,130 @@+TAP version 13+# Subtest: \#4082 empty instrumented file is fully covered, not a gap+ok 1 - \#4082 empty instrumented file is fully covered, not a gap+ ---+ duration_ms: 3.302621+ ...+# Subtest: \#4082 pct-only summaries preserve explicit zero and nonzero percentages+ok 2 - \#4082 pct-only summaries preserve explicit zero and nonzero percentages+ ---+ duration_ms: 0.96361+ ...+# Subtest: \#4083 LCOV aggregates counts for every metric, including unterminated last record+ok 3 - \#4083 LCOV aggregates counts for every metric, including unterminated last record+ ---+ duration_ms: 1.219651+ ...+# Subtest: \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+ok 4 - \#4084 Istanbul final and NYC counters count unique lines and individual branch arms+ ---+ duration_ms: 1.928131+ ...+# Subtest: empty or malformed reports do not hide a valid fallback+ok 5 - empty or malformed reports do not hide a valid fallback+ ---+ duration_ms: 1.23548+ ...+# Subtest: Istanbul empty-file Unknown sentinel yields numeric 100% in totals and entries+ok 6 - Istanbul empty-file Unknown sentinel yields numeric 100% in totals and entries+ ---+ duration_ms: 0.884351+ ...+# Subtest: legacy NYC summary reports remain readable+ok 7 - legacy NYC summary reports remain readable+ ---+ duration_ms: 0.9545+ ...+# Subtest: pct-only files retain their percentage but unknown aggregate counts stay conservative+not ok 8 - pct-only files retain their percentage but unknown aggregate counts stay conservative+ ---+ duration_ms: 2.672092+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:75:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ 100 !== 0++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 0+ actual: 100+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:78:69)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: mixed counted and uncounted files cannot claim a fully covered aggregate+not ok 9 - mixed counted and uncounted files cannot claim a fully covered aggregate+ ---+ duration_ms: 1.4818+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:81:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ 100 !== 0++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 0+ actual: 100+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:84:12)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: valid supplied aggregate percentages including zero take precedence+ok 10 - valid supplied aggregate percentages including zero take precedence+ ---+ duration_ms: 1.604111+ ...+# Subtest: incomplete or invalid counts do not manufacture a percentage+not ok 11 - incomplete or invalid counts do not manufacture a percentage+ ---+ duration_ms: 7.111804+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:93:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ 100 !== 0++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: 0+ actual: 100+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-coverage.test.cjs:97:12)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: explicit empty counts across every file remain fully covered+ok 12 - explicit empty counts across every file remain fully covered+ ---+ duration_ms: 1.02833+ ...+1..12+# tests 12+# suites 0+# pass 9+# fail 3+# cancelled 0+# skipped 0+# todo 0+# duration_ms 40.28002diff --git a/docs/validation/oct12-receipts/coverage-typecheck.txt b/docs/validation/oct12-receipts/coverage-typecheck.txtnew file mode 100644index 0000000000..e69de29bb2diff --git a/docs/validation/oct12-receipts/source-sha256.txt b/docs/validation/oct12-receipts/source-sha256.txtnew file mode 100644index 0000000000..c3b526076d--- /dev/null+++ b/docs/validation/oct12-receipts/source-sha256.txt@@ -0,0 +1,16 @@+9eabdf4a85d7ee886a739111ab0b9d672b583d9f022bceb3bcfde4c096b5a247 plugins/ruflo-sparc/README.md+c8f6649785cd4db873db6c5cd0a8bab10e9723b0169eaaeb56f181048860751b plugins/ruflo-sparc/agents/sparc-orchestrator.md+45f6b279c9e9324784cfe647d1b8f21fdcd1b3b5dc01f2ee6324b3de56d46090 plugins/ruflo-sparc/commands/ruflo-sparc.md+48669a82242a9c6282dc99fc5b0e31373a1cb30384afc44056ad7d9658a4ea40 plugins/ruflo-sparc/scripts/smoke.sh+6045d3935db44c5ef7b8894e2f5b64fa3026d23f3fb2b9bddfae6d1bf3cc7035 plugins/ruflo-sparc/skills/sparc-implement/SKILL.md+a8715151546e13364c675eb5b05ee2fcb01ccf00e814fb78145c4b999d108450 plugins/ruflo-sparc/skills/sparc-refine/SKILL.md+7fbdc9421c1615710b055726631f9d4c254d4ccc86b027e7741c0f106d9f9785 plugins/ruflo-sparc/skills/sparc-spec/SKILL.md+42a946a15fb148605027b5dcf411dcf9a8b270816bafe0b1919ac05d2a905c04 plugins/ruflo-sparc/tests/contracts.regression.cjs+60ca114fef3a07ade71b64aeaf19184f3e09d44955468f952a74a215e5e16132 plugins/ruflo-testgen/scripts/smoke.sh+cdda45b22786949b0fa6b868f6359bc7b076e50103324e36629734f404258698 plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md+d944185ff23f8d785707183e36369bd5949b7ecfa6bc34c8622900c1ff954f1e plugins/ruflo-testgen/tests/tdd-workflow.regression.cjs+c1b6a56edac48a488e2d8b177369ea34f3a51764531a58af612bcbe50ea6a96b tests/regression/oct12-coverage.test.cjs+5809b47e66cb57648354f34c30a38d1bbd3425d09868ee9c2ed59726b730f661 tests/regression/oct12.vitest.config.mjs+41800cb3372635fcddca8a7727b2f6ed0c243a7de52a342c30d588dd2a098454 v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts+e48ed0fdf0fb8b4ba5087da35d2e64e2e9de28519cd59b9fb7d34e022fc8c3ac v3/@claude-flow/cli/src/commands/coverage-reader.ts+0eb346b13cd805eeb92e6a558a1fe8a584772c78c258bfc4a84efd4d14d08eb9 v3/@claude-flow/cli/src/commands/hooks.tsdiff --git a/docs/validation/oct12-receipts/sparc-after.txt b/docs/validation/oct12-receipts/sparc-after.txtnew file mode 100644index 0000000000..982d4b6083--- /dev/null+++ b/docs/validation/oct12-receipts/sparc-after.txt@@ -0,0 +1,25 @@+TAP version 13+# Subtest: \#4086 status enumerates all keys and retrieves exact current values+ok 1 - \#4086 status enumerates all keys and retrieves exact current values+ ---+ duration_ms: 1.839651+ ...+# Subtest: \#4087 every explicit phase agent resolves to a shipped plugin agent+ok 2 - \#4087 every explicit phase agent resolves to a shipped plugin agent+ ---+ duration_ms: 1.769331+ ...+# Subtest: \#4088 SPARC command references resolve to the shipped command filename+ok 3 - \#4088 SPARC command references resolve to the shipped command filename+ ---+ duration_ms: 3.271131+ ...+1..3+# tests 3+# suites 0+# pass 3+# fail 0+# cancelled 0+# skipped 0+# todo 0+# duration_ms 18.665419diff --git a/docs/validation/oct12-receipts/sparc-before.txt b/docs/validation/oct12-receipts/sparc-before.txtnew file mode 100644index 0000000000..87749cc531--- /dev/null+++ b/docs/validation/oct12-receipts/sparc-before.txt@@ -0,0 +1,202 @@+TAP version 13+# Subtest: \#4086 status enumerates all keys and retrieves exact current values+not ok 1 - \#4086 status enumerates all keys and retrieves exact current values+ ---+ duration_ms: 3.527511+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:8:1'+ failureType: 'testCodeFailure'+ error: |-+ The input did not match the regular expression /memory_list/. Input:++ 'sparc status`\n' ++ 'Show current SPARC phase and gate check results:\n' ++ '1. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` and query `current-phase` to list all active SPARC workflows\n' ++ '2. For each workflow, display:\n' ++ ' - Feature name and slug\n' ++ ' - Current phase number and name (1-Specification, 2-Pseudocode, 3-Architecture, 4-Refinement, 5-Completion)\n' ++ ' - Phase start time and duration\n' ++ ' - Gate attempt count\n' ++ '3. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-gates` and query matching the feature slug to list gate check history\n' ++ '4. For each gate result, show: phase, passed/failed, criteria details, blockers if any\n' ++ '5. Display a progress bar: `[=====> ] Phase 3/5 β Architecture`\n' ++ '\n'++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: |-+ sparc status`+ Show current SPARC phase and gate check results:+ 1. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` and query `current-phase` to list all active SPARC workflows+ 2. For each workflow, display:+ - Feature name and slug+ - Current phase number and name (1-Specification, 2-Pseudocode, 3-Architecture, 4-Refinement, 5-Completion)+ - Phase start time and duration+ - Gate attempt count+ 3. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-gates` and query matching the feature slug to list gate check history+ 4. For each gate result, show: phase, passed/failed, criteria details, blockers if any+ 5. Display a progress bar: `[=====> ] Phase 3/5 β Architecture`+++ operator: 'match'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:10:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ node:internal/test_runner/harness:255:12+ node:internal/process/task_queues:140:7+ AsyncResource.runInAsyncScope (node:async_hooks:206:9)+ AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)+ ...+# Subtest: \#4087 every explicit phase agent resolves to a shipped plugin agent+not ok 2 - \#4087 every explicit phase agent resolves to a shipped plugin agent+ ---+ duration_ms: 0.52273+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:15:1'+ failureType: 'testCodeFailure'+ error: |-+ The input did not match the regular expression /^ruflo-[a-z-]+:[a-z-]+$/. Input:++ 'researcher'++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: 'researcher'+ operator: 'match'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:19:12)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4088 SPARC command references resolve to the shipped command filename+not ok 3 - \#4088 SPARC command references resolve to the shipped command filename+ ---+ duration_ms: 0.52056+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:25:1'+ failureType: 'testCodeFailure'+ error: 'plugins/ruflo-sparc/commands/ruflo-sparc.md'+ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: |-+ ---+ name: ruflo-sparc+ description: SPARC methodology commands β initialize, track, advance, and report on Specification-Pseudocode-Architecture-Refinement-Completion workflows+ ---+ $ARGUMENTS++ Handle SPARC methodology commands based on the subcommand:++ ## Subcommands++ ### `sparc init <feature>`+ Initialize a new SPARC workflow for the given feature:+ 1. Create a feature slug from the feature name (lowercase, hyphenated)+ 2. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, key `current-phase-{slug}`, value `{ "phase": 1, "phaseName": "Specification", "feature": "<feature>", "startedAt": "<ISO timestamp>", "gateAttempts": 0, "artifacts": [] }`+ 3. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `spec-{slug}`, value `{ "status": "pending", "requirements": [], "acceptanceCriteria": [], "constraints": [], "edgeCases": [] }`+ 4. Display: "SPARC workflow initialized for **<feature>**. Current phase: **1 - Specification**. Run `/sparc status` to view progress or begin the specification phase with `/sparc-spec <feature-description>`."++ ### `sparc status`+ Show current SPARC phase and gate check results:+ 1. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` and query `current-phase` to list all active SPARC workflows+ 2. For each workflow, display:+ - Feature name and slug+ - Current phase number and name (1-Specification, 2-Pseudocode, 3-Architecture, 4-Refinement, 5-Completion)+ - Phase start time and duration+ - Gate attempt count+ 3. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-gates` and query matching the feature slug to list gate check history+ 4. For each gate result, show: phase, passed/failed, criteria details, blockers if any+ 5. Display a progress bar: `[=====> ] Phase 3/5 β Architecture`++ ### `sparc advance`+ Attempt to pass the current gate and advance to the next phase:+ 1. Retrieve current state from `sparc-state` namespace+ 2. Retrieve phase artifacts from `sparc-phases` namespace+ 3. Run the gate check for the current phase:+ - **Phase 1 gate**: Verify spec has >= 3 acceptance criteria, explicit constraints, and edge cases identified+ - **Phase 2 gate**: Verify pseudocode covers all acceptance criteria, error paths are explicit, complexity annotated+ - **Phase 3 gate**: Verify architecture addresses all constraints, API contracts are typed, no circular dependencies+ - **Phase 4 gate**: Verify all acceptance criteria have passing tests, code review approved, coverage >= 80%+ - **Phase 5 gate**: Verify all tests green, docs complete, deployment checklist verified, traceability matrix complete+ 4. Store gate result in `sparc-gates` namespace with key `gate-{phase}-{slug}-{timestamp}`+ 5. If gate passes:+ - Increment phase in `sparc-state`+ - Display: "Gate **passed**. Advancing to Phase {N} β {PhaseName}."+ - If advancing past Phase 5: "SPARC workflow **complete** for {feature}. All gates passed."+ 6. If gate fails:+ - Increment `gateAttempts` in state+ - Display: "Gate **failed**. Blockers:" followed by the list of failing criteria+ - Suggest specific actions to address each blocker++ ### `sparc phase <phase-name>`+ Jump to a specific phase (for re-entry or iteration):+ 1. Validate phase-name is one of: `specification`, `pseudocode`, `architecture`, `refinement`, `completion` (or `spec`, `pseudo`, `arch`, `refine`, `complete` as aliases, or a number 1-5)+ 2. Retrieve current state from `sparc-state` namespace+ 3. Update phase number and name in state+ 4. Store warning if jumping forward (skipping gates): "Jumping forward skips gate checks. Run `/sparc advance` from previous phases to ensure quality."+ 5. Display: "Phase set to **{N} β {PhaseName}** for {feature}."++ ### `sparc report`+ Generate a full SPARC methodology report:+ 1. Retrieve all data from `sparc-state`, `sparc-phases`, and `sparc-gates` namespaces for the active feature+ 2. Generate a structured report:+ ```+ # SPARC Report: {Feature}++ ## Phase Summary+ | Phase | Status | Gate | Attempts | Duration |+ |-------|--------|------|----------|----------|+ | 1 - Specification | Complete | Passed | 1 | 2h |+ | 2 - Pseudocode | Complete | Passed | 2 | 3h |+ | 3 - Architecture | In Progress | β | 0 | 1h |+ | 4 - Refinement | Pending | β | β | β |+ | 5 - Completion | Pending | β | β | β |++ ## Specification+ - Requirements: [list]+ - Acceptance Criteria: [list]+ - Constraints: [list]++ ## Pseudocode+ - Algorithms: [summary]+ - Data Structures: [summary]++ ## Architecture+ - Bounded Contexts: [list]+ - API Contracts: [summary]++ ## Gate History+ [chronological list of gate attempts with pass/fail details]++ ## Traceability Matrix+ | Acceptance Criterion | Test | Status |+ |---------------------|------|--------|+ | AC-1: ... | test_xxx | Pass |+ ```+ 3. Display the report++ operator: 'doesNotMatch'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:29:12)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+1..3+# tests 3+# suites 0+# pass 0+# fail 3+# cancelled 0+# skipped 0+# todo 0+# duration_ms 16.414047diff --git a/docs/validation/oct12-receipts/sparc-intended-agents-before.txt b/docs/validation/oct12-receipts/sparc-intended-agents-before.txtnew file mode 100644index 0000000000..d7085bb49f--- /dev/null+++ b/docs/validation/oct12-receipts/sparc-intended-agents-before.txt@@ -0,0 +1,66 @@+TAP version 13+# Subtest: \#4086 status enumerates all keys and retrieves exact current values+ok 1 - \#4086 status enumerates all keys and retrieves exact current values+ ---+ duration_ms: 1.954421+ ...+# Subtest: \#4087 every explicit phase agent resolves to a shipped plugin agent+not ok 2 - \#4087 every explicit phase agent resolves to a shipped plugin agent+ ---+ duration_ms: 3.304492+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:15:1'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly deep-equal:+ + actual - expected++ [+ 'ruflo-core:researcher',+ + 'ruflo-core:researcher',+ + 'ruflo-ddd:domain-modeler',+ - 'ruflo-goals:goal-planner',+ - 'ruflo-swarm:architect',+ 'ruflo-core:coder',+ 'ruflo-testgen:tester',+ 'ruflo-core:reviewer'+ ]+ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ 0: 'ruflo-core:researcher'+ 1: 'ruflo-goals:goal-planner'+ 2: 'ruflo-swarm:architect'+ 3: 'ruflo-core:coder'+ 4: 'ruflo-testgen:tester'+ 5: 'ruflo-core:reviewer'+ actual:+ 0: 'ruflo-core:researcher'+ 1: 'ruflo-core:researcher'+ 2: 'ruflo-ddd:domain-modeler'+ 3: 'ruflo-core:coder'+ 4: 'ruflo-testgen:tester'+ 5: 'ruflo-core:reviewer'+ operator: 'deepStrictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-sparc.test.cjs:17:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4088 SPARC command references resolve to the shipped command filename+ok 3 - \#4088 SPARC command references resolve to the shipped command filename+ ---+ duration_ms: 0.59254+ ...+1..3+# tests 3+# suites 0+# pass 2+# fail 1+# cancelled 0+# skipped 0+# todo 0+# duration_ms 19.109909diff --git a/docs/validation/oct12-receipts/sparc-lifecycle-after.txt b/docs/validation/oct12-receipts/sparc-lifecycle-after.txtnew file mode 100644index 0000000000..eb0755546b--- /dev/null+++ b/docs/validation/oct12-receipts/sparc-lifecycle-after.txt@@ -0,0 +1,45 @@+TAP version 13+# Subtest: \#4086 status enumerates all keys and retrieves exact current values+ok 1 - \#4086 status enumerates all keys and retrieves exact current values+ ---+ duration_ms: 1.84263+ ...+# Subtest: \#4087 every explicit phase agent resolves to a shipped plugin agent+ok 2 - \#4087 every explicit phase agent resolves to a shipped plugin agent+ ---+ duration_ms: 1.76782+ ...+# Subtest: \#4088 SPARC command references resolve to the shipped command filename+ok 3 - \#4088 SPARC command references resolve to the shipped command filename+ ---+ duration_ms: 4.568662+ ...+# Subtest: \#4086 initialize active state and timestamp every phase/gate state write+ok 4 - \#4086 initialize active state and timestamp every phase/gate state write+ ---+ duration_ms: 0.597+ ...+# Subtest: \#4086 active status filters explicit completion and orders legacy timestamps+ok 5 - \#4086 active status filters explicit completion and orders legacy timestamps+ ---+ duration_ms: 0.44562+ ...+# Subtest: \#4086 advance closes phase five only after its gate and refuses completed records+ok 6 - \#4086 advance closes phase five only after its gate and refuses completed records+ ---+ duration_ms: 0.30238+ ...+# Subtest: \#4086 refine closes exact state once only after final gate evidence passes+ok 7 - \#4086 refine closes exact state once only after final gate evidence passes+ ---+ duration_ms: 0.49909+ ...+1..7+# tests 7+# suites 0+# pass 7+# fail 0+# cancelled 0+# skipped 0+# todo 0+# duration_ms 24.779342diff --git a/docs/validation/oct12-receipts/sparc-lifecycle-before.txt b/docs/validation/oct12-receipts/sparc-lifecycle-before.txtnew file mode 100644index 0000000000..0c403ac7a0--- /dev/null+++ b/docs/validation/oct12-receipts/sparc-lifecycle-before.txt@@ -0,0 +1,449 @@+TAP version 13+# Subtest: \#4086 status enumerates all keys and retrieves exact current values+ok 1 - \#4086 status enumerates all keys and retrieves exact current values+ ---+ duration_ms: 1.917661+ ...+# Subtest: \#4087 every explicit phase agent resolves to a shipped plugin agent+ok 2 - \#4087 every explicit phase agent resolves to a shipped plugin agent+ ---+ duration_ms: 1.79896+ ...+# Subtest: \#4088 SPARC command references resolve to the shipped command filename+ok 3 - \#4088 SPARC command references resolve to the shipped command filename+ ---+ duration_ms: 3.720211+ ...+# Subtest: \#4086 initialize active state and timestamp every phase/gate state write+not ok 4 - \#4086 initialize active state and timestamp every phase/gate state write+ ---+ duration_ms: 2.341811+ location: '/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:41:1'+ failureType: 'testCodeFailure'+ error: |-+ The input did not match the regular expression /"status": "active"/. Input:++ ' <feature>`\n' ++ 'Initialize a new SPARC workflow for the given feature:\n' ++ '1. Create a feature slug from the feature name (lowercase, hyphenated)\n' ++ '2. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, key `current-phase-{slug}`, value `{ "phase": 1, "phaseName": "Specification", "feature": "<feature>", "startedAt": "<ISO timestamp>", "gateAttempts": 0, "artifacts": [] }`\n' ++ '3. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `spec-{slug}`, value `{ "status": "pending", "requirements": [], "acceptanceCriteria": [], "constraints": [], "edgeCases": [] }`\n' ++ '4. Display: "SPARC workflow initialized for **<feature>**. Current phase: **1 - Specification**. Run `/ruflo-sparc:ruflo-sparc status` to view progress or begin the specification phase with `/ruflo-sparc:sparc-spec <feature-description>`."\n'++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: |-+ <feature>`+ Initialize a new SPARC workflow for the given feature:+ 1. Create a feature slug from the feature name (lowercase, hyphenated)+ 2. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, key `current-phase-{slug}`, value `{ "phase": 1, "phaseName": "Specification", "feature": "<feature>", "startedAt": "<ISO timestamp>", "gateAttempts": 0, "artifacts": [] }`+ 3. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `spec-{slug}`, value `{ "status": "pending", "requirements": [], "acceptanceCriteria": [], "constraints": [], "edgeCases": [] }`+ 4. Display: "SPARC workflow initialized for **<feature>**. Current phase: **1 - Specification**. Run `/ruflo-sparc:ruflo-sparc status` to view progress or begin the specification phase with `/ruflo-sparc:sparc-spec <feature-description>`."++ operator: 'match'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:42:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4086 active status filters explicit completion and orders legacy timestamps+not ok 5 - \#4086 active status filters explicit completion and orders legacy timestamps+ ---+ duration_ms: 0.4607+ location: '/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:51:1'+ failureType: 'testCodeFailure'+ error: |-+ The input did not match the regular expression /Exclude.*status === "complete"/. Input:++ '`\n' ++ 'Show current SPARC phase and gate check results using exact reads:\n' ++ '1. Call `mcp__plugin_ruflo-core_ruflo__memory_list` with namespace `sparc-state`, `limit: 50`, `offset: 0`. Continue with `offset += entries.length` until offset reaches `total`. A listing error or an empty page before `total` means incomplete status; report it, never claim no workflows.\n' ++ '2. Keep keys starting with `current-phase-`. For each key call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with that exact key and namespace `sparc-state`. Listing metadata is not phase state. Decode the returned value if JSON-encoded and display the feature, slug, current phase, start time, gate attempts, and completion status. A missing/malformed value is unavailable, not a pending workflow. Do not infer the current phase from a gate or artifact.\n' ++ '3. Enumerate namespace `sparc-gates` with the same `limit`, `offset`, and `total` pagination. For each feature keep only keys matching `gate-{phase}-{exact-slug}-{timestamp}` (phase 1β5, complete slug match, timestamp suffix). Retrieve each matching key exactly from `sparc-gates`; sort chronologically. Do not mix a slug with its prefix neighbors.\n' ++ "4. Show each gate's phase, passed/failed status, criteria and blockers. Gate history describes past checks; only `current-phase-{slug}` defines current state. Report retrieval failures and concurrent changes as incomplete; a multi-call read is not an atomic snapshot.\n" ++ '5. Display a progress bar based on the retrieved current phase: `[=====> ] Phase 3/5 β Architecture`.\n'++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: |-+ `+ Show current SPARC phase and gate check results using exact reads:+ 1. Call `mcp__plugin_ruflo-core_ruflo__memory_list` with namespace `sparc-state`, `limit: 50`, `offset: 0`. Continue with `offset += entries.length` until offset reaches `total`. A listing error or an empty page before `total` means incomplete status; report it, never claim no workflows.+ 2. Keep keys starting with `current-phase-`. For each key call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with that exact key and namespace `sparc-state`. Listing metadata is not phase state. Decode the returned value if JSON-encoded and display the feature, slug, current phase, start time, gate attempts, and completion status. A missing/malformed value is unavailable, not a pending workflow. Do not infer the current phase from a gate or artifact.+ 3. Enumerate namespace `sparc-gates` with the same `limit`, `offset`, and `total` pagination. For each feature keep only keys matching `gate-{phase}-{exact-slug}-{timestamp}` (phase 1β5, complete slug match, timestamp suffix). Retrieve each matching key exactly from `sparc-gates`; sort chronologically. Do not mix a slug with its prefix neighbors.+ 4. Show each gate's phase, passed/failed status, criteria and blockers. Gate history describes past checks; only `current-phase-{slug}` defines current state. Report retrieval failures and concurrent changes as incomplete; a multi-call read is not an atomic snapshot.+ 5. Display a progress bar based on the retrieved current phase: `[=====> ] Phase 3/5 β Architecture`.++ operator: 'match'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:53:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4086 advance closes phase five only after its gate and refuses completed records+not ok 6 - \#4086 advance closes phase five only after its gate and refuses completed records+ ---+ duration_ms: 0.41762+ location: '/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:59:1'+ failureType: 'testCodeFailure'+ error: |-+ The input did not match the regular expression /status === "complete".*refuse/. Input:++ '`\n' ++ 'Attempt to pass the current gate and advance to the next phase:\n' ++ '1. Call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` in `sparc-state` with exact key `current-phase-{slug}`\n' ++ '2. Retrieve phase artifacts from `sparc-phases` namespace\n' ++ '3. Run the gate check for the current phase:\n' ++ ' - **Phase 1 gate**: Verify spec has >= 3 acceptance criteria, explicit constraints, and edge cases identified\n' ++ ' - **Phase 2 gate**: Verify pseudocode covers all acceptance criteria, error paths are explicit, complexity annotated\n' ++ ' - **Phase 3 gate**: Verify architecture addresses all constraints, API contracts are typed, no circular dependencies\n' ++ ' - **Phase 4 gate**: Verify all acceptance criteria have passing tests, code review approved, coverage >= 80%\n' ++ ' - **Phase 5 gate**: Verify all tests green, docs complete, deployment checklist verified, traceability matrix complete\n' ++ '4. Store gate result in `sparc-gates` namespace with key `gate-{phase}-{slug}-{timestamp}`\n' ++ '5. If gate passes:\n' ++ ' - Increment phase in `sparc-state`\n' ++ ' - Display: "Gate **passed**. Advancing to Phase {N} β {PhaseName}."\n' ++ ' - If advancing past Phase 5: "SPARC workflow **complete** for {feature}. All gates passed."\n' ++ '6. If gate fails:\n' ++ ' - Increment `gateAttempts` in state\n' ++ ' - Display: "Gate **failed**. Blockers:" followed by the list of failing criteria\n' ++ ' - Suggest specific actions to address each blocker\n'++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: |-+ `+ Attempt to pass the current gate and advance to the next phase:+ 1. Call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` in `sparc-state` with exact key `current-phase-{slug}`+ 2. Retrieve phase artifacts from `sparc-phases` namespace+ 3. Run the gate check for the current phase:+ - **Phase 1 gate**: Verify spec has >= 3 acceptance criteria, explicit constraints, and edge cases identified+ - **Phase 2 gate**: Verify pseudocode covers all acceptance criteria, error paths are explicit, complexity annotated+ - **Phase 3 gate**: Verify architecture addresses all constraints, API contracts are typed, no circular dependencies+ - **Phase 4 gate**: Verify all acceptance criteria have passing tests, code review approved, coverage >= 80%+ - **Phase 5 gate**: Verify all tests green, docs complete, deployment checklist verified, traceability matrix complete+ 4. Store gate result in `sparc-gates` namespace with key `gate-{phase}-{slug}-{timestamp}`+ 5. If gate passes:+ - Increment phase in `sparc-state`+ - Display: "Gate **passed**. Advancing to Phase {N} β {PhaseName}."+ - If advancing past Phase 5: "SPARC workflow **complete** for {feature}. All gates passed."+ 6. If gate fails:+ - Increment `gateAttempts` in state+ - Display: "Gate **failed**. Blockers:" followed by the list of failing criteria+ - Suggest specific actions to address each blocker++ operator: 'match'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:61:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4086 refine closes exact state once only after final gate evidence passes+not ok 7 - \#4086 refine closes exact state once only after final gate evidence passes+ ---+ duration_ms: 0.80853+ location: '/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:69:1'+ failureType: 'testCodeFailure'+ error: |-+ The input did not match the regular expression /final gate evidence.*passes/. Input:++ '---\n' ++ 'name: sparc-refine\n' ++ 'description: Run the SPARC Refinement and Completion phases β review code, improve test coverage, validate against specification, and generate documentation\n' ++ 'argument-hint: ""\n' ++ 'allowed-tools: mcp__plugin_ruflo-core_ruflo__memory_store mcp__plugin_ruflo-core_ruflo__memory_search mcp__plugin_ruflo-core_ruflo__memory_retrieve mcp__plugin_ruflo-core_ruflo__task_create mcp__plugin_ruflo-core_ruflo__task_update mcp__plugin_ruflo-core_ruflo__task_complete mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end mcp__plugin_ruflo-core_ruflo__neural_train mcp__plugin_ruflo-core_ruflo__neural_predict Bash Read Write Edit\n' ++ '---\n' ++ '\n' ++ '# SPARC Refinement + Completion\n' ++ '\n' ++ 'Run Phases 4 and 5 of the SPARC methodology: iteratively improve through code review and testing, then finalize with validation, documentation, and deployment readiness.\n' ++ '\n' ++ '## When to use\n' ++ '\n' ++ 'After the Architecture phase is complete and its gate has been passed. This skill covers the final two phases that bring a feature from implemented to production-ready.\n' ++ '\n' ++ '## Steps\n' ++ '\n' ++ '### Phase 4 β Refinement\n' ++ '\n' ++ '1. **Retrieve all prior artifacts** β call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-phases` and query for the feature slug. Load spec (acceptance criteria), pseudocode, and architecture.\n' ++ '\n' ++ '2. **Retrieve phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with namespace `sparc-state` and exact key `current-phase-{feature-slug}` to confirm we are in Phase 4.\n' ++ '\n' ++ '3. **Code review** β review the implementation against:\n' ++ ' a. **Specification compliance**: does every acceptance criterion have a corresponding code path?\n' ++ ' b. **Architecture adherence**: do modules follow the defined boundaries and dependency rules?\n' ++ ' c. **Pseudocode fidelity**: does the implementation match the designed algorithms?\n' ++ ' d. **Code quality**: naming conventions, single responsibility, error handling, no dead code\n' ++ ' e. Document findings as review comments\n' ++ '\n' ++ '4. **Test coverage analysis**:\n' ++ ' a. Run existing tests and measure coverage\n' ++ ' b. Identify uncovered acceptance criteria\n' ++ ' c. Write missing tests:\n' ++ ' - Unit tests for each public function\n' ++ ' - Integration tests for cross-module interactions\n' ++ ' - Edge case tests for each identified edge case from the spec\n' ++ ' d. Target coverage >= 80% on new code\n' ++ '\n' ++ '5. **Performance validation** β if the spec includes performance constraints:\n' ++ ' a. Profile critical paths identified in the pseudocode\n' ++ ' b. Compare measured performance against constraint thresholds\n' ++ ' c. Optimize if thresholds are not met\n' ++ '\n' ++ '6. **Iterate** β repeat steps 3-5 until:\n' ++ ' - All acceptance criteria have passing tests\n' ++ ' - Code review has no critical or high-severity issues\n' ++ ' - Coverage meets the threshold\n' ++ ' - Performance constraints are satisfied\n' ++ '\n' ++ '7. **Store refinement artifact** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `refine-{feature-slug}`, value: `{ status: "complete", reviewFindings: [...], coveragePercent: N, performanceResults: {...}, iterations: N }`\n' ++ '\n' ++ '8. **Record trajectory step** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step` with refinement summary\n' ++ '\n' ++ '### Phase 5 β Completion\n' ++ '\n' ++ '9. **Full regression** β run the complete test suite to verify no regressions from refinement changes\n' ++ '\n' ++ '10. **Traceability matrix** β build a matrix mapping every acceptance criterion to:\n' ++ ' - The test(s) that verify it\n' ++ ' - The code file(s) that implement it\n' ++ ' - The current pass/fail status\n' ++ '\n' ++ '11. **Documentation**:\n' ++ ' a. Generate API documentation from code comments and type definitions\n' ++ ' b. Write usage examples for key public interfaces\n' ++ ' c. Update any existing documentation affected by the changes\n' ++ '\n' ++ '12. **Deployment readiness checklist**:\n' ++ ' - [ ] All tests passing\n' ++ ' - [ ] Documentation complete\n' ++ ' - [ ] Database migrations prepared (if applicable)\n' ++ ' - [ ] Configuration changes documented\n' ++ ' - [ ] Feature flags configured (if applicable)\n' ++ ' - [ ] Rollback plan defined\n' ++ ' - [ ] Security review complete (no secrets, inputs validated)\n' ++ '\n' ++ '13. **Store completion artifact** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `complete-{feature-slug}`, value: `{ status: "complete", traceabilityMatrix: [...], documentationFiles: [...], deploymentChecklist: {...}, regressionResult: "pass" }`\n' ++ '\n' ++ '14. **End trajectory** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end` with the full SPARC cycle summary\n' ++ '\n' ++ '15. **Train neural patterns** β call `mcp__plugin_ruflo-core_ruflo__neural_train` with the successful SPARC cycle data to improve future predictions\n' ++ '\n' ++ '16. **Store learned pattern** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `patterns`, key `sparc-{feature-slug}`, value summarizing what worked, phase durations, and common blockers encountered\n' ++ '\n' ++ '17. **Present completion report** β display the traceability matrix, deployment checklist, and final status. Suggest running `/ruflo-sparc:ruflo-sparc advance` to pass the final gate, or `/ruflo-sparc:ruflo-sparc report` for the full methodology report.\n' ++ '\n' ++ '## Output format\n' ++ '\n' ++ '```\n' ++ '# Refinement: {Feature Name}\n' ++ '\n' ++ '## Code Review Summary\n' ++ '- Critical issues: {N} (must be 0 to pass gate)\n' ++ '- High issues: {N}\n' ++ '- Medium issues: {N}\n' ++ '- Resolved: {N}/{total}\n' ++ '\n' ++ '## Test Coverage\n' ++ '- Overall: {N}%\n' ++ '- New code: {N}%\n' ++ '- Acceptance criteria covered: {N}/{total}\n' ++ '\n' ++ '## Performance\n' ++ '| Constraint | Target | Measured | Status |\n' ++ '|-----------|--------|----------|--------|\n' ++ '| Response time | <200ms | 145ms | Pass |\n' ++ '\n' ++ '---\n' ++ '\n' ++ '# Completion: {Feature Name}\n' ++ '\n' ++ '## Traceability Matrix\n' ++ '| AC | Test | Code | Status |\n' ++ '|----|------|------|--------|\n' ++ '| AC-1 | test_xxx | service.ts:42 | Pass |\n' ++ '| AC-2 | test_yyy | controller.ts:18 | Pass |\n' ++ '| AC-3 | test_zzz | repository.ts:31 | Pass |\n' ++ '\n' ++ '## Deployment Checklist\n' ++ '- [x] All tests passing\n' ++ '- [x] Documentation complete\n' ++ '- [x] Migrations prepared\n' ++ '- [x] Config documented\n' ++ '- [x] Rollback plan defined\n' ++ '- [x] Security reviewed\n' ++ '\n' ++ '---\n' ++ 'SPARC workflow complete. Run `/ruflo-sparc:ruflo-sparc report` for the full methodology report.\n' ++ '```\n'++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: |-+ ---+ name: sparc-refine+ description: Run the SPARC Refinement and Completion phases β review code, improve test coverage, validate against specification, and generate documentation+ argument-hint: ""+ allowed-tools: mcp__plugin_ruflo-core_ruflo__memory_store mcp__plugin_ruflo-core_ruflo__memory_search mcp__plugin_ruflo-core_ruflo__memory_retrieve mcp__plugin_ruflo-core_ruflo__task_create mcp__plugin_ruflo-core_ruflo__task_update mcp__plugin_ruflo-core_ruflo__task_complete mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end mcp__plugin_ruflo-core_ruflo__neural_train mcp__plugin_ruflo-core_ruflo__neural_predict Bash Read Write Edit+ ---++ # SPARC Refinement + Completion++ Run Phases 4 and 5 of the SPARC methodology: iteratively improve through code review and testing, then finalize with validation, documentation, and deployment readiness.++ ## When to use++ After the Architecture phase is complete and its gate has been passed. This skill covers the final two phases that bring a feature from implemented to production-ready.++ ## Steps++ ### Phase 4 β Refinement++ 1. **Retrieve all prior artifacts** β call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-phases` and query for the feature slug. Load spec (acceptance criteria), pseudocode, and architecture.++ 2. **Retrieve phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with namespace `sparc-state` and exact key `current-phase-{feature-slug}` to confirm we are in Phase 4.++ 3. **Code review** β review the implementation against:+ a. **Specification compliance**: does every acceptance criterion have a corresponding code path?+ b. **Architecture adherence**: do modules follow the defined boundaries and dependency rules?+ c. **Pseudocode fidelity**: does the implementation match the designed algorithms?+ d. **Code quality**: naming conventions, single responsibility, error handling, no dead code+ e. Document findings as review comments++ 4. **Test coverage analysis**:+ a. Run existing tests and measure coverage+ b. Identify uncovered acceptance criteria+ c. Write missing tests:+ - Unit tests for each public function+ - Integration tests for cross-module interactions+ - Edge case tests for each identified edge case from the spec+ d. Target coverage >= 80% on new code++ 5. **Performance validation** β if the spec includes performance constraints:+ a. Profile critical paths identified in the pseudocode+ b. Compare measured performance against constraint thresholds+ c. Optimize if thresholds are not met++ 6. **Iterate** β repeat steps 3-5 until:+ - All acceptance criteria have passing tests+ - Code review has no critical or high-severity issues+ - Coverage meets the threshold+ - Performance constraints are satisfied++ 7. **Store refinement artifact** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `refine-{feature-slug}`, value: `{ status: "complete", reviewFindings: [...], coveragePercent: N, performanceResults: {...}, iterations: N }`++ 8. **Record trajectory step** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step` with refinement summary++ ### Phase 5 β Completion++ 9. **Full regression** β run the complete test suite to verify no regressions from refinement changes++ 10. **Traceability matrix** β build a matrix mapping every acceptance criterion to:+ - The test(s) that verify it+ - The code file(s) that implement it+ - The current pass/fail status++ 11. **Documentation**:+ a. Generate API documentation from code comments and type definitions+ b. Write usage examples for key public interfaces+ c. Update any existing documentation affected by the changes++ 12. **Deployment readiness checklist**:+ - [ ] All tests passing+ - [ ] Documentation complete+ - [ ] Database migrations prepared (if applicable)+ - [ ] Configuration changes documented+ - [ ] Feature flags configured (if applicable)+ - [ ] Rollback plan defined+ - [ ] Security review complete (no secrets, inputs validated)++ 13. **Store completion artifact** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `complete-{feature-slug}`, value: `{ status: "complete", traceabilityMatrix: [...], documentationFiles: [...], deploymentChecklist: {...}, regressionResult: "pass" }`++ 14. **End trajectory** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end` with the full SPARC cycle summary++ 15. **Train neural patterns** β call `mcp__plugin_ruflo-core_ruflo__neural_train` with the successful SPARC cycle data to improve future predictions++ 16. **Store learned pattern** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `patterns`, key `sparc-{feature-slug}`, value summarizing what worked, phase durations, and common blockers encountered++ 17. **Present completion report** β display the traceability matrix, deployment checklist, and final status. Suggest running `/ruflo-sparc:ruflo-sparc advance` to pass the final gate, or `/ruflo-sparc:ruflo-sparc report` for the full methodology report.++ ## Output format++ ```+ # Refinement: {Feature Name}++ ## Code Review Summary+ - Critical issues: {N} (must be 0 to pass gate)+ - High issues: {N}+ - Medium issues: {N}+ - Resolved: {N}/{total}++ ## Test Coverage+ - Overall: {N}%+ - New code: {N}%+ - Acceptance criteria covered: {N}/{total}++ ## Performance+ | Constraint | Target | Measured | Status |+ |-----------|--------|----------|--------|+ | Response time | <200ms | 145ms | Pass |++ ---++ # Completion: {Feature Name}++ ## Traceability Matrix+ | AC | Test | Code | Status |+ |----|------|------|--------|+ | AC-1 | test_xxx | service.ts:42 | Pass |+ | AC-2 | test_yyy | controller.ts:18 | Pass |+ | AC-3 | test_zzz | repository.ts:31 | Pass |++ ## Deployment Checklist+ - [x] All tests passing+ - [x] Documentation complete+ - [x] Migrations prepared+ - [x] Config documented+ - [x] Rollback plan defined+ - [x] Security reviewed++ ---+ SPARC workflow complete. Run `/ruflo-sparc:ruflo-sparc report` for the full methodology report.+ ```++ operator: 'match'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:71:10)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+1..7+# tests 7+# suites 0+# pass 3+# fail 4+# cancelled 0+# skipped 0+# todo 0+# duration_ms 26.771173diff --git a/docs/validation/oct12-receipts/sparc-review-before.txt b/docs/validation/oct12-receipts/sparc-review-before.txtnew file mode 100644index 0000000000..f4c6fb1ec0--- /dev/null+++ b/docs/validation/oct12-receipts/sparc-review-before.txt@@ -0,0 +1,201 @@+TAP version 13+# Subtest: \#4086 status enumerates all keys and retrieves exact current values+ok 1 - \#4086 status enumerates all keys and retrieves exact current values+ ---+ duration_ms: 1.739361+ ...+# Subtest: \#4087 every explicit phase agent resolves to a shipped plugin agent+ok 2 - \#4087 every explicit phase agent resolves to a shipped plugin agent+ ---+ duration_ms: 1.756661+ ...+# Subtest: \#4088 SPARC command references resolve to the shipped command filename+not ok 3 - \#4088 SPARC command references resolve to the shipped command filename+ ---+ duration_ms: 1.749161+ location: '/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:27:1'+ failureType: 'testCodeFailure'+ error: '/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/README.md'+ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected:+ actual: |-+ # ruflo-sparc++ SPARC methodology -- Specification, Pseudocode, Architecture, Refinement, Completion phases with quality gates between each phase.++ ## Overview++ Drives features through a rigorous five-phase development lifecycle. Each phase has a quality gate that must pass before advancing. The orchestrator spawns specialized agents per phase (ruflo-core:researcher, ruflo-goals:goal-planner, ruflo-swarm:architect, ruflo-core:coder, ruflo-testgen:tester, ruflo-core:reviewer) and stores all artifacts and gate results in memory for traceability.++ ## Installation++ ```bash+ claude --plugin-dir plugins/ruflo-sparc+ ```++ ## Agents++ | Agent | Model | Role |+ |-------|-------|------|+ | `sparc-orchestrator` | sonnet | Orchestrate 5-phase SPARC lifecycle, enforce gate checks, spawn phase-specific agents, track state in memory |++ ## Skills++ | Skill | Usage | Description |+ |-------|-------|-------------|+ | `sparc-spec` | `/sparc-spec <feature-description>` | Run the Specification phase -- gather requirements, define acceptance criteria, identify constraints |+ | `sparc-implement` | `/sparc-implement` | Run the Architecture and Implementation phases -- design modules, write pseudocode, implement, test |+ | `sparc-refine` | `/sparc-refine` | Run Refinement and Completion -- review code, improve coverage, validate against spec, generate docs |++ ## Commands (5 subcommands)++ ```bash+ /ruflo-sparc:ruflo-sparc init <feature> # Initialize a new SPARC workflow+ /ruflo-sparc:ruflo-sparc status # Show current phase and gate history+ /ruflo-sparc:ruflo-sparc advance # Attempt gate check, advance to next phase+ /ruflo-sparc:ruflo-sparc phase <phase-name> # Jump to a specific phase (spec/pseudo/arch/refine/complete)+ /ruflo-sparc:ruflo-sparc report # Generate full SPARC methodology report with traceability matrix+ ```++ ## The 5 Phases++ | Phase | Name | Gate Criteria | Spawned Agent |+ |-------|------|--------------|---------------|+ | 1 | Specification | >= 3 acceptance criteria, constraints, edge cases | `researcher` |+ | 2 | Pseudocode | Covers all ACs, error paths explicit, complexity annotated | `planner` |+ | 3 | Architecture | All constraints addressed, typed API contracts, no circular deps | `system-architect` |+ | 4 | Refinement | All ACs have passing tests, review approved, coverage >= 80% | `coder` + `tester` |+ | 5 | Completion | All tests green, docs complete, deployment checklist verified | `reviewer` |++ ## Memory Namespaces++ | Namespace | Purpose |+ |-----------|---------|+ | `sparc-state` | Current phase tracking per feature |+ | `sparc-phases` | Phase artifacts (specs, pseudocode, ADRs, reports) |+ | `sparc-gates` | Gate check results and history |+ | `patterns` | Learned SPARC execution patterns |++ ## Compatibility++ - **CLI:** pinned to `@claude-flow/cli` v3.6 major+minor.+ - **Verification:** `bash plugins/ruflo-sparc/scripts/smoke.sh` is the contract.++ ## Phase-to-plugin alignment++ Each SPARC phase has a canonical handoff plugin that owns its deeper tooling:++ | Phase | Owner | What it provides |+ |-------|-------|-----------------|+ | **Specification** | [ruflo-goals](../ruflo-goals/docs/adrs/0001-goals-contract.md) (deep-research) | Multi-source research orchestration to gather requirements |+ | **Pseudocode** | `ruflo-sparc` (this plugin) | Pseudocode generation + complexity annotation |+ | **Architecture** | [ruflo-adr](../ruflo-adr/docs/adrs/0001-adr-plugin-pattern.md) + [ruflo-ddd](../ruflo-ddd/docs/adrs/0001-ddd-contract.md) | ADR creation + bounded-context modeling |+ | **Refinement** | [ruflo-jujutsu](../ruflo-jujutsu/docs/adrs/0001-jujutsu-contract.md) + ruflo-testgen | Diff-aware refactor + test gap analysis |+ | **Completion** | [ruflo-docs](../ruflo-docs/docs/adrs/0001-docs-contract.md) | Auto-generated documentation |++ This plugin orchestrates the lifecycle; sibling plugins do the deep work per phase.++ ## Namespace coordination++ This plugin owns three AgentDB namespaces, all kebab-case compliant per [ruflo-agentdb ADR-0001 Β§"Namespace convention"](../ruflo-agentdb/docs/adrs/0001-agentdb-optimization.md):++ | Namespace | Purpose |+ |-----------|---------|+ | `sparc-state` | Current phase tracking per feature |+ | `sparc-phases` | Phase artifacts (specs, pseudocode, ADRs, reports) |+ | `sparc-gates` | Gate check results and history |++ Additionally, the shared `patterns` (plural) namespace is consumed (not owned) for cross-feature SPARC pattern learning β note the pluralization (different from the singular `pattern` ReasoningBank target). Reserved namespaces (`pattern`, `claude-memories`, `default`) MUST NOT be shadowed.++ ## Verification++ ```bash+ bash plugins/ruflo-sparc/scripts/smoke.sh+ # Expected: "11 passed, 0 failed"+ ```++ ## Architecture Decisions++ - [`ADR-0001` β ruflo-sparc plugin contract (phase-to-plugin alignment, namespace coordination, smoke as contract)](./docs/adrs/0001-sparc-contract.md)++ ## Related Plugins++ - `ruflo-agentdb` β namespace convention owner; backing store for sparc-state/-phases/-gates+ - `ruflo-goals` β Specification phase deep-research+ - `ruflo-adr` -- Architecture decisions recorded as ADRs in Phase 3+ - `ruflo-ddd` -- Architecture phase uses DDD bounded context patterns+ - `ruflo-jujutsu` -- Refinement phase diff analysis+ - `ruflo-docs` -- Completion phase documentation generation++ ## License++ MIT++ ## As a mod++ This plugin also loads as a function-hook mod (ADR-445 pattern, `hooks/hooks.json` β `register.ts`). No network, no process spawn, no model call.++ - **Guard (default on, tighten-only).** It refuses to store a spec or phase artifact that holds a secret in a `sparc*` memory namespace. The refusal never repeats the secret.+ - **Status file.** `.claude-flow/sparc-mod/status.json` (`{version: 1, updatedMs, guard, checked, blocked, seen}`), written at session start and when a counter changes.+ - **`/sparc-mod`** answers locally: `status`, `scan <text>`, `phases`. (The plugin's own commands are prompt commands, which a hook cannot answer, so the mod has its own name.)+ - **Option.** `guard` (`on` | `off`, default `on`) in the plugin's `userConfig`.++ Test it: `claude plugin validate plugins/ruflo-sparc`, `claude plugin test plugins/ruflo-sparc`, `bash plugins/ruflo-sparc/scripts/smoke.sh`.++ ## Native Codex hooks++ The separate `.codex-plugin/plugin.json` selects `hooks/codex-hooks.json`, replacing+ the Claude-only module entry for Codex. Claude's manifest and `register.ts` remain+ unchanged. The synchronous native `PreToolUse` adapter bundles the existing pure+ guard and shared secret screen; it preserves their tool/namespace scope and emits+ the native permission-denial envelope before a guarded write. `SessionStart` and+ guarded calls maintain private per-session counters in `PLUGIN_DATA`; the existing+ version-1 project status file remains a best-effort courtesy view. Status failure+ does not permit a denied write. Guarding is enabled for the native adapter.++ Existing skills and command files remain available. Claude's dynamic+ `$.command.register` / `command.run` mod interception has no native command-hook+ equivalent: Codex does **not** get that interception. The same deterministic local+ command helpers are available explicitly via+ `node <plugin-root>/hooks/codex-hook.cjs --command status` (and the helper's existing+ subcommands). This is guard/status compatibility, not full SDK-mod parity.++ Maintainers rebuild the committed standalone bundles with+ `ESBUILD=<esbuild executable> node scripts/build-codex-mod-hooks.mjs`, then run+ `node --test tests/plugins/codex-mod-hooks.test.mjs`. Set `ESBUILD` in that test run+ to check byte reproducibility using the same installed builder. Run+ `scripts/sync-mod-screen.mjs --check` before bundling when the shared screen changes.+ The adapters need Node.js and contain no runtime SDK dependency.++ This source change requires a released upstream package or an explicitly owned+ source projection to reach installations. It does not patch foreign cache entries,+ pin upstream updates, disable plugins, or claim an already published repair.++ Release both host manifests with the same patch version. Codex 0.160's published+ remote-bundle sync skips downloading a release whose version equals the installed+ version; merging same-version source does not establish automatic cache refresh.+ Its explicit native plugin install replaces the cached root atomically even at the+ same version. An owned projection must therefore refresh its upstream source+ generation and explicitly reinstall it; refreshing a marketplace catalog alone+ is not installation proof. No foreign cache entry should be edited in place.++ operator: 'doesNotMatch'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/plugins/ruflo-sparc/tests/contracts.regression.cjs:32:12)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+1..3+# tests 3+# suites 0+# pass 2+# fail 1+# cancelled 0+# skipped 0+# todo 0+# duration_ms 17.591238diff --git a/docs/validation/oct12-receipts/sparc-smoke.txt b/docs/validation/oct12-receipts/sparc-smoke.txtnew file mode 100644index 0000000000..dd0cae0f11--- /dev/null+++ b/docs/validation/oct12-receipts/sparc-smoke.txt@@ -0,0 +1,17 @@+β 1. plugin.json declares 0.3.4 with new keywords ... PASS+β 2. all 3 skills + agent + command present with valid frontmatter ... PASS+β 3. all 5 SPARC phase names documented (Specification/Pseudocode/Architecture/Refinement/Completion) ... PASS+β 4. /sparc command covers 5 subcommands ... PASS+β 5. README pins @claude-flow/cli to v3.6 ... PASS+β 6. README defers to ruflo-agentdb namespace convention ... PASS+β 7. sparc-* namespaces claimed (state, phases, gates) ... PASS+β 8. phase-to-plugin alignment table present (cross-references to adr/ddd/jujutsu/docs/goals) ... PASS+β 9. ADR-0001 exists with status Accepted ... PASS+β 10. 5 phase gate criteria documented ... PASS+β 11. no wildcard tool grants in skills ... PASS+β M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines ... PASS+β M2. mod: userConfig defaults are safe (guard defaults on) ... PASS+β M3. mod: hooks never touch the network or spawn a process ... PASS+β R. SPARC exact reads and registered names ... PASS++15 passed, 0 faileddiff --git a/docs/validation/oct12-receipts/tdd-workflow-after.txt b/docs/validation/oct12-receipts/tdd-workflow-after.txtnew file mode 100644index 0000000000..1804cdec1f--- /dev/null+++ b/docs/validation/oct12-receipts/tdd-workflow-after.txt@@ -0,0 +1,45 @@+TAP version 13+# Subtest: \#4085 green target and regression records observed outcome+ok 1 - \#4085 green target and regression records observed outcome+ ---+ duration_ms: 3.536922+ ...+# Subtest: \#4085 target still red records observed outcome+ok 2 - \#4085 target still red records observed outcome+ ---+ duration_ms: 0.77447+ ...+# Subtest: \#4085 regression broken records observed outcome+ok 3 - \#4085 regression broken records observed outcome+ ---+ duration_ms: 0.826051+ ...+# Subtest: \#4085 abandoned records observed outcome+ok 4 - \#4085 abandoned records observed outcome+ ---+ duration_ms: 0.79806+ ...+# Subtest: \#4085 interrupted runner records observed outcome+ok 5 - \#4085 interrupted runner records observed outcome+ ---+ duration_ms: 0.75474+ ...+# Subtest: \#4085 target not run records observed outcome+ok 6 - \#4085 target not run records observed outcome+ ---+ duration_ms: 1.685641+ ...+# Subtest: \#4085 regression not run records observed outcome+ok 7 - \#4085 regression not run records observed outcome+ ---+ duration_ms: 0.830791+ ...+1..7+# tests 7+# suites 0+# pass 7+# fail 0+# cancelled 0+# skipped 0+# todo 0+# duration_ms 24.251362diff --git a/docs/validation/oct12-receipts/tdd-workflow-before.txt b/docs/validation/oct12-receipts/tdd-workflow-before.txtnew file mode 100644index 0000000000..6f0ddbbbd2--- /dev/null+++ b/docs/validation/oct12-receipts/tdd-workflow-before.txt@@ -0,0 +1,165 @@+TAP version 13+# Subtest: \#4085 green target and regression records observed outcome+ok 1 - \#4085 green target and regression records observed outcome+ ---+ duration_ms: 2.736772+ ...+# Subtest: \#4085 target still red records observed outcome+not ok 2 - \#4085 target still red records observed outcome+ ---+ duration_ms: 2.004941+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:19:48'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ true !== false++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: false+ actual: true+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:26:30)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4085 regression broken records observed outcome+not ok 3 - \#4085 regression broken records observed outcome+ ---+ duration_ms: 0.74057+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:19:48'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ true !== false++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: false+ actual: true+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:26:30)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4085 abandoned records observed outcome+not ok 4 - \#4085 abandoned records observed outcome+ ---+ duration_ms: 0.801321+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:19:48'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ true !== false++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: false+ actual: true+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:26:30)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4085 interrupted runner records observed outcome+not ok 5 - \#4085 interrupted runner records observed outcome+ ---+ duration_ms: 0.81648+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:19:48'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ true !== false++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: false+ actual: true+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:26:30)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4085 target not run records observed outcome+not ok 6 - \#4085 target not run records observed outcome+ ---+ duration_ms: 1.910411+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:19:48'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ true !== false++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: false+ actual: true+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:26:30)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+# Subtest: \#4085 regression not run records observed outcome+not ok 7 - \#4085 regression not run records observed outcome+ ---+ duration_ms: 0.765121+ location: '/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:19:48'+ failureType: 'testCodeFailure'+ error: |-+ Expected values to be strictly equal:++ true !== false++ code: 'ERR_ASSERTION'+ name: 'AssertionError'+ expected: false+ actual: true+ operator: 'strictEqual'+ stack: |-+ TestContext.<anonymous> (/home/ruv/work/ruflo-fixes-20261012/tests/regression/oct12-tdd-workflow.test.cjs:26:30)+ Test.runInAsyncScope (node:async_hooks:206:9)+ Test.run (node:internal/test_runner/test:796:25)+ Test.processPendingSubtests (node:internal/test_runner/test:526:18)+ Test.postRun (node:internal/test_runner/test:889:19)+ Test.run (node:internal/test_runner/test:835:12)+ async Test.processPendingSubtests (node:internal/test_runner/test:526:7)+ ...+1..7+# tests 7+# suites 0+# pass 1+# fail 6+# cancelled 0+# skipped 0+# todo 0+# duration_ms 25.436882diff --git a/docs/validation/oct12-receipts/testgen-smoke.txt b/docs/validation/oct12-receipts/testgen-smoke.txtnew file mode 100644index 0000000000..24849719b7--- /dev/null+++ b/docs/validation/oct12-receipts/testgen-smoke.txt@@ -0,0 +1,16 @@+β 1. plugin.json declares 0.3.2 with new keywords ... PASS+β 2. all skills + agent + command present with valid frontmatter ... PASS+β 3. hooks_worker-dispatch + testgaps trigger documented ... PASS+β 4. all 3 coverage CLI commands referenced ... PASS+β 5. README pins @claude-flow/cli to v3.6 ... PASS+β 6. README defers to ruflo-agentdb namespace convention ... PASS+β 7. test-gaps namespace claimed ... PASS+β 8. SPARC Refinement-phase ownership cross-reference ... PASS+β 9. ADR-0001 exists with status Accepted ... PASS+β 10. no wildcard tool grants in skills ... PASS+β M1. mod: hooks.json names register.ts, every hook file is present and under 500 lines ... PASS+β M2. mod: userConfig defaults are safe (none to configure: observe-only) ... PASS+β M3. mod: hooks never touch the network or spawn a process ... PASS+β R. TDD outcome reporting ... PASS++14 passed, 0 faileddiff --git a/docs/validation/oct12-receipts/witness-baseline.txt b/docs/validation/oct12-receipts/witness-baseline.txtnew file mode 100644index 0000000000..ba5704d98c--- /dev/null+++ b/docs/validation/oct12-receipts/witness-baseline.txt@@ -0,0 +1,7 @@+smoke-witness-marker-drift: scanning 117 markers via verification/macos/manifest.md.json++ pass: 18+ drifted: 0+ file-missing (skipped β see #1880): 99++smoke-witness-marker-drift: all markers present in cited filesdiff --git a/docs/validation/oct12-receipts/witness-final.txt b/docs/validation/oct12-receipts/witness-final.txtnew file mode 100644index 0000000000..ba5704d98c--- /dev/null+++ b/docs/validation/oct12-receipts/witness-final.txt@@ -0,0 +1,7 @@+smoke-witness-marker-drift: scanning 117 markers via verification/macos/manifest.md.json++ pass: 18+ drifted: 0+ file-missing (skipped β see #1880): 99++smoke-witness-marker-drift: all markers present in cited filesdiff --git a/plugins/ruflo-sparc/README.md b/plugins/ruflo-sparc/README.mdindex 8bb100b51e..23bf52f620 100644--- a/plugins/ruflo-sparc/README.md+++ b/plugins/ruflo-sparc/README.md@@ -4,7 +4,7 @@ SPARC methodology -- Specification, Pseudocode, Architecture, Refinement, Comple## Overview-Drives features through a rigorous five-phase development lifecycle. Each phase has a quality gate that must pass before advancing. The orchestrator spawns specialized agents per phase (researcher, planner, system-architect, coder/tester, reviewer) and stores all artifacts and gate results in memory for traceability.+Drives features through a rigorous five-phase development lifecycle. Each phase has a quality gate that must pass before advancing. The orchestrator spawns specialized agents per phase (ruflo-core:researcher, ruflo-goals:goal-planner, ruflo-swarm:architect, ruflo-core:coder, ruflo-testgen:tester, ruflo-core:reviewer) and stores all artifacts and gate results in memory for traceability.## Installation@@ -22,18 +22,18 @@ claude --plugin-dir plugins/ruflo-sparc| Skill | Usage | Description ||-------|-------|-------------|-| `sparc-spec` | `/sparc-spec <feature-description>` | Run the Specification phase -- gather requirements, define acceptance criteria, identify constraints |-| `sparc-implement` | `/sparc-implement` | Run the Architecture and Implementation phases -- design modules, write pseudocode, implement, test |-| `sparc-refine` | `/sparc-refine` | Run Refinement and Completion -- review code, improve coverage, validate against spec, generate docs |+| `sparc-spec` | `/ruflo-sparc:sparc-spec <feature-description>` | Run the Specification phase -- gather requirements, define acceptance criteria, identify constraints |+| `sparc-implement` | `/ruflo-sparc:sparc-implement` | Run the Architecture and Implementation phases -- design modules, write pseudocode, implement, test |+| `sparc-refine` | `/ruflo-sparc:sparc-refine` | Run Refinement and Completion -- review code, improve coverage, validate against spec, generate docs |## Commands (5 subcommands)```bash-sparc init <feature> # Initialize a new SPARC workflow-sparc status # Show current phase and gate history-sparc advance # Attempt gate check, advance to next phase-sparc phase <phase-name> # Jump to a specific phase (spec/pseudo/arch/refine/complete)-sparc report # Generate full SPARC methodology report with traceability matrix+/ruflo-sparc:ruflo-sparc init <feature> # Initialize a new SPARC workflow+/ruflo-sparc:ruflo-sparc status # Show current phase and gate history+/ruflo-sparc:ruflo-sparc advance # Attempt gate check, advance to next phase+/ruflo-sparc:ruflo-sparc phase <phase-name> # Jump to a specific phase (spec/pseudo/arch/refine/complete)+/ruflo-sparc:ruflo-sparc report # Generate full SPARC methodology report with traceability matrix```## The 5 Phasesdiff --git a/plugins/ruflo-sparc/agents/sparc-orchestrator.md b/plugins/ruflo-sparc/agents/sparc-orchestrator.mdindex ade4e69583..b322b07297 100644--- a/plugins/ruflo-sparc/agents/sparc-orchestrator.md+++ b/plugins/ruflo-sparc/agents/sparc-orchestrator.md@@ -17,7 +17,7 @@ You are the SPARC Methodology Orchestrator. You drive features through a rigorou- Map stakeholder concerns and edge cases- Produce a Specification Document stored in memory**Gate check**: Spec must include at least 3 acceptance criteria, explicit constraints, and identified edge cases. Stakeholder sign-off recorded.-**Spawned agent**: `researcher` β domain analysis, requirement elicitation, prior art search+**Spawned agent**: `ruflo-core:researcher` β domain analysis, requirement elicitation, prior art search### Phase 2 β Pseudocode**Goal**: Design algorithms and data flows before writing production code.@@ -28,7 +28,7 @@ You are the SPARC Methodology Orchestrator. You drive features through a rigorou- Identify algorithmic complexity and potential bottlenecks- Produce a Pseudocode Document stored in memory**Gate check**: Pseudocode covers all acceptance criteria from the spec, error paths are explicit, complexity is annotated.-**Spawned agent**: `planner` β algorithm design, data modeling, flowchart generation+**Spawned agent**: `ruflo-goals:goal-planner` β algorithm design, data modeling, flowchart generation### Phase 3 β Architecture**Goal**: Establish module boundaries, API contracts, and integration points.@@ -39,7 +39,7 @@ You are the SPARC Methodology Orchestrator. You drive features through a rigorou- Specify infrastructure concerns (persistence, caching, messaging)- Produce an Architecture Decision Record stored in memory**Gate check**: Architecture addresses all constraints from spec, API contracts are typed, no circular dependencies, DDD invariants documented.-**Spawned agent**: `system-architect` β module design, API contracts, DDD patterns+**Spawned agent**: `ruflo-swarm:architect` β module design, API contracts, DDD patterns### Phase 4 β Refinement**Goal**: Iteratively improve through code review, testing, and optimization.@@ -51,7 +51,7 @@ You are the SPARC Methodology Orchestrator. You drive features through a rigorou- Profile performance against constraints- Iterate until all acceptance criteria pass**Gate check**: All acceptance criteria have passing tests, code review approval with no critical issues, test coverage meets threshold.-**Spawned agent**: `coder` (implementation), `tester` (test writing and coverage)+**Spawned agent**: `ruflo-core:coder` (implementation), `ruflo-testgen:tester` (test writing and coverage)### Phase 5 β Completion**Goal**: Final validation, documentation, and deployment readiness.@@ -62,7 +62,7 @@ You are the SPARC Methodology Orchestrator. You drive features through a rigorou- Verify deployment prerequisites (migrations, config, feature flags)- Produce a Completion Report with traceability matrix**Gate check**: All tests green, documentation complete, deployment checklist verified, traceability matrix links every acceptance criterion to its test.-**Spawned agent**: `reviewer` β final audit, documentation review, deployment readiness check+**Spawned agent**: `ruflo-core:reviewer` β final audit, documentation review, deployment readiness check## Gate Check Protocol@@ -71,8 +71,8 @@ Each gate check follows this procedure:1. **Retrieve phase artifacts** from memory namespace `sparc-phases`2. **Evaluate gate criteria** β every criterion must pass; partial passes fail the gate3. **Record gate result** β store pass/fail with details in memory namespace `sparc-gates`-4. **On failure**: identify gaps, provide actionable feedback, return to current phase-5. **On success**: advance phase counter, notify user, begin next phase+4. **On failure**: preserve state and phase, increment gateAttempts and refresh updatedAt with the current ISO timestamp at the exact current-phase key; identify gaps and return to current phase without marking complete.+5. **On success**: preserve existing state fields at the exact current-phase key and refresh updatedAt with the current ISO timestamp. For phases 1β4 advance phase and phaseName. Only after the final Phase 5 gate passes, keep phase 5 (never 6), set status "complete" and completedAt to the same timestamp, and store once before announcing completion.Gate results are stored as:```@@ -84,21 +84,25 @@ Value: { phase, passed, criteria: [{name, passed, detail}], blockers: [] }Track current phase in memory:- `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, key `current-phase-{feature-slug}`-- Value: `{ phase: 1-5, phaseName, feature, startedAt, gateAttempts, artifacts: [] }`+- Value: `{ phase: 1-5, phaseName, feature, startedAt, status: "active", updatedAt, gateAttempts, artifacts: [] }`++Initialize startedAt and updatedAt with the current ISO timestamp. Refuse advance when status is already "complete"; do not repeat the completion write.Before any phase operation, retrieve current state to prevent drift:-- `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` and query for the feature slug+- `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with namespace `sparc-state` and exact key `current-phase-{feature-slug}`## Agent Spawning+Use the hostβs available-agent registry to confirm these plugin-qualified names before delegating. If an intended agent is unavailable, report the missing plugin and stop that delegation. Do not silently substitute a different agent or expand delegation permissions. Only proceed inline if the user explicitly requests that alternative.+Spawn phase-specific agents with clear handoff instructions:```-Phase 1 β researcher: "Analyze requirements for {feature}. Store spec in sparc-phases namespace."-Phase 2 β planner: "Design pseudocode based on spec. Store in sparc-phases namespace."-Phase 3 β system-architect: "Design architecture based on pseudocode. Store ADR in sparc-phases namespace."-Phase 4 β coder + tester: "Implement and test against spec. Store results in sparc-phases namespace."-Phase 5 β reviewer: "Final review against all acceptance criteria. Store report in sparc-phases namespace."+Phase 1 β ruflo-core:researcher: "Analyze requirements for {feature}. Store spec in sparc-phases namespace."+Phase 2 β ruflo-goals:goal-planner: "Design pseudocode based on spec. Store in sparc-phases namespace."+Phase 3 β ruflo-swarm:architect: "Design architecture based on pseudocode. Store ADR in sparc-phases namespace."+Phase 4 β ruflo-core:coder + ruflo-testgen:tester: "Implement and test against spec. Store results in sparc-phases namespace."+Phase 5 β ruflo-core:reviewer: "Final review against all acceptance criteria. Store report in sparc-phases namespace."```Each agent receives the artifacts from all previous phases via memory retrieval.diff --git a/plugins/ruflo-sparc/commands/ruflo-sparc.md b/plugins/ruflo-sparc/commands/ruflo-sparc.mdindex 134bfd2dbf..7e2cecf8e5 100644--- a/plugins/ruflo-sparc/commands/ruflo-sparc.md+++ b/plugins/ruflo-sparc/commands/ruflo-sparc.md@@ -8,28 +8,25 @@ Handle SPARC methodology commands based on the subcommand:## Subcommands-### `sparc init <feature>`+### `/ruflo-sparc:ruflo-sparc init <feature>`Initialize a new SPARC workflow for the given feature:1. Create a feature slug from the feature name (lowercase, hyphenated)-2. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, key `current-phase-{slug}`, value `{ "phase": 1, "phaseName": "Specification", "feature": "<feature>", "startedAt": "<ISO timestamp>", "gateAttempts": 0, "artifacts": [] }`+2. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, key `current-phase-{slug}`, value `{ "phase": 1, "phaseName": "Specification", "feature": "<feature>", "startedAt": "<ISO timestamp>", "status": "active", "updatedAt": "<ISO timestamp>", "gateAttempts": 0, "artifacts": [] }`3. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `spec-{slug}`, value `{ "status": "pending", "requirements": [], "acceptanceCriteria": [], "constraints": [], "edgeCases": [] }`-4. Display: "SPARC workflow initialized for **<feature>**. Current phase: **1 - Specification**. Run `/sparc status` to view progress or begin the specification phase with `/sparc-spec <feature-description>`."+4. Display: "SPARC workflow initialized for **<feature>**. Current phase: **1 - Specification**. Run `/ruflo-sparc:ruflo-sparc status` to view progress or begin the specification phase with `/ruflo-sparc:sparc-spec <feature-description>`."-### `sparc status`-Show current SPARC phase and gate check results:-1. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` and query `current-phase` to list all active SPARC workflows-2. For each workflow, display:- - Feature name and slug- - Current phase number and name (1-Specification, 2-Pseudocode, 3-Architecture, 4-Refinement, 5-Completion)- - Phase start time and duration- - Gate attempt count-3. Call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-gates` and query matching the feature slug to list gate check history-4. For each gate result, show: phase, passed/failed, criteria details, blockers if any-5. Display a progress bar: `[=====> ] Phase 3/5 β Architecture`+### `/ruflo-sparc:ruflo-sparc status`+Show current SPARC phase and gate check results using exact reads:+1. Call `mcp__plugin_ruflo-core_ruflo__memory_list` with namespace `sparc-state`, `limit: 50`, `offset: 0`. Continue with `offset += entries.length` until offset reaches `total`. A listing error or an empty page before `total` means incomplete status; report it, never claim no workflows.+2. Keep keys starting with `current-phase-`. For each key call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with that exact key and namespace `sparc-state`. Listing metadata is not phase state. Decode the returned value if JSON-encoded and display the feature, slug, current phase, start time, gate attempts, and completion status. A missing/malformed value is unavailable, not a pending workflow. Do not infer the current phase from a gate or artifact.+ Exclude records with `status === "complete"` from active status. Legacy records without status remain active. Do not infer completion from phase 5 alone. Sort active records newest first by valid state `updatedAt`; for legacy/malformed timestamps fall back to listing metadata `updatedAt`, then `storedAt` (parse ISO strings or numeric epoch milliseconds). Put unknown timestamps last, breaking ties by exact key.+3. Enumerate namespace `sparc-gates` with the same `limit`, `offset`, and `total` pagination. For each feature keep only keys matching `gate-{phase}-{exact-slug}-{timestamp}` (phase 1β5, complete slug match, timestamp suffix). Retrieve each matching key exactly from `sparc-gates`; sort chronologically. Do not mix a slug with its prefix neighbors.+4. Show each gate's phase, passed/failed status, criteria and blockers. Gate history describes past checks; only `current-phase-{slug}` defines current state. Report retrieval failures and concurrent changes as incomplete; a multi-call read is not an atomic snapshot.+5. Display a progress bar based on the retrieved current phase: `[=====> ] Phase 3/5 β Architecture`.-### `sparc advance`+### `/ruflo-sparc:ruflo-sparc advance`Attempt to pass the current gate and advance to the next phase:-1. Retrieve current state from `sparc-state` namespace+1. Call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` in `sparc-state` with exact key `current-phase-{slug}`. Decode state; if `status === "complete"`, refuse advance without writing state or another gate. Stop on missing/malformed state.2. Retrieve phase artifacts from `sparc-phases` namespace3. Run the gate check for the current phase:- **Phase 1 gate**: Verify spec has >= 3 acceptance criteria, explicit constraints, and edge cases identified@@ -39,25 +36,25 @@ Attempt to pass the current gate and advance to the next phase:- **Phase 5 gate**: Verify all tests green, docs complete, deployment checklist verified, traceability matrix complete4. Store gate result in `sparc-gates` namespace with key `gate-{phase}-{slug}-{timestamp}`5. If gate passes:- - Increment phase in `sparc-state`- - Display: "Gate **passed**. Advancing to Phase {N} β {PhaseName}."- - If advancing past Phase 5: "SPARC workflow **complete** for {feature}. All gates passed."+ - Preserve all existing state fields on every write to namespace `sparc-state`, exact key `current-phase-{slug}`, using `mcp__plugin_ruflo-core_ruflo__memory_store`; set `now = new Date().toISOString()`.+ - **Phases 1β4**: increment phase and update phaseName, retaining other state with `status: "active", updatedAt: now`. Display the next phase.+ - **Phase 5**: only after the final gate passes, write `{ ...state, phase: 5, phaseName: "Completion", status: "complete", completedAt: now, updatedAt: now }` once to that same exact key. Keep phase 5, never increment to 6. Display completion only after the state write succeeds.6. If gate fails:- - Increment `gateAttempts` in state+ - Preserve existing state and phase, increment `gateAttempts`, and set `updatedAt` to the current ISO timestamp in `sparc-state` at exact key `current-phase-{slug}` via `mcp__plugin_ruflo-core_ruflo__memory_store`. Do not mark state complete or set `completedAt`.- Display: "Gate **failed**. Blockers:" followed by the list of failing criteria- Suggest specific actions to address each blocker-### `sparc phase <phase-name>`+### `/ruflo-sparc:ruflo-sparc phase <phase-name>`Jump to a specific phase (for re-entry or iteration):1. Validate phase-name is one of: `specification`, `pseudocode`, `architecture`, `refinement`, `completion` (or `spec`, `pseudo`, `arch`, `refine`, `complete` as aliases, or a number 1-5)-2. Retrieve current state from `sparc-state` namespace-3. Update phase number and name in state-4. Store warning if jumping forward (skipping gates): "Jumping forward skips gate checks. Run `/sparc advance` from previous phases to ensure quality."+2. Call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` in `sparc-state` with exact key `current-phase-{slug}`+3. Preserve existing state fields and update phase number and name at exact key `current-phase-{slug}` in `sparc-state` via `mcp__plugin_ruflo-core_ruflo__memory_store`; set `updatedAt` to the current ISO timestamp. Explicit re-entry reopens the workflow with `status: "active"` and removes stale `completedAt`; selecting phase 5 alone does not complete it.+4. Store warning if jumping forward (skipping gates): "Jumping forward skips gate checks. Run `/ruflo-sparc:ruflo-sparc advance` from previous phases to ensure quality."5. Display: "Phase set to **{N} β {PhaseName}** for {feature}."-### `sparc report`+### `/ruflo-sparc:ruflo-sparc report`Generate a full SPARC methodology report:-1. Retrieve all data from `sparc-state`, `sparc-phases`, and `sparc-gates` namespaces for the active feature+1. Use the status pagination and exact retrieval procedure above for `sparc-state` and `sparc-gates`. Retrieve the exact artifact keys recorded in current state from `sparc-phases` for the selected feature. A report may include completed workflows; the active-only status filter does not apply to reports.2. Generate a structured report:```# SPARC Report: {Feature}diff --git a/plugins/ruflo-sparc/scripts/smoke.sh b/plugins/ruflo-sparc/scripts/smoke.shindex d60d920769..e2ecf315bc 100755--- a/plugins/ruflo-sparc/scripts/smoke.sh+++ b/plugins/ruflo-sparc/scripts/smoke.sh@@ -106,5 +106,8 @@ process.exit(c.guard && c.guard.default === "on" ? 0 : 1)step "M3. mod: hooks never touch the network or spawn a process"if grep -nE '\$\.(http|process)\.|child_process|fetch\(' "$ROOT"/hooks/*.ts >/dev/null; then bad "network or process call in hooks"; else ok; fi+step "R. SPARC exact reads and registered names"+node "$ROOT/tests/contracts.regression.cjs" > /dev/null 2>&1 && ok || bad "regression contract failed"+printf "\n%s passed, %s failed\n" "$PASS" "$FAIL"[[ $FAIL -eq 0 ]] || exit 1diff --git a/plugins/ruflo-sparc/skills/sparc-implement/SKILL.md b/plugins/ruflo-sparc/skills/sparc-implement/SKILL.mdindex a8bbec42fd..9887af0a94 100644--- a/plugins/ruflo-sparc/skills/sparc-implement/SKILL.md+++ b/plugins/ruflo-sparc/skills/sparc-implement/SKILL.md@@ -17,7 +17,7 @@ After the Specification phase is complete and its gate has been passed. This ski1. **Retrieve specification** β call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-phases` and query for the feature's spec. Extract requirements, acceptance criteria, constraints, and edge cases.-2. **Retrieve phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` and query for the feature to confirm we are in Phase 2 or 3.+2. **Retrieve phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with namespace `sparc-state` and exact key `current-phase-{feature-slug}` to confirm we are in Phase 2 or 3.3. **Search for architectural patterns** β call `mcp__plugin_ruflo-core_ruflo__neural_predict` with the feature description to find relevant architectural decisions from past projects@@ -54,7 +54,7 @@ After the Specification phase is complete and its gate has been passed. This ski- Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `arch-{feature-slug}`- Value: `{ status: "complete", boundedContexts: [...], apiContracts: [...], moduleBoundaries: {...}, infrastructure: {...} }`-6. **Update phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, updating current phase to 3 (Architecture) with both artifacts recorded+6. **Update phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state`, exact key `current-phase-{feature-slug}`; preserve existing state fields, update current phase to 3 (Architecture) with both artifacts recorded, and set `updatedAt` to the current ISO timestamp7. **Record trajectory step** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step` with architecture summary@@ -65,7 +65,7 @@ After the Specification phase is complete and its gate has been passed. This skid. Write unit tests alongside implementation (TDD when possible)e. Run tests to verify acceptance criteria-9. **Present architecture** β display the architecture decision record and suggest running `/sparc advance` to pass the Phase 3 gate+9. **Present architecture** β display the architecture decision record and suggest running `/ruflo-sparc:ruflo-sparc advance` to pass the Phase 3 gate## Output format@@ -118,5 +118,5 @@ src/{feature}/- Events: {strategy}----Phases 2-3 complete. Run `/sparc advance` to pass the gate check.+Phases 2-3 complete. Run `/ruflo-sparc:ruflo-sparc advance` to pass the gate check.```diff --git a/plugins/ruflo-sparc/skills/sparc-refine/SKILL.md b/plugins/ruflo-sparc/skills/sparc-refine/SKILL.mdindex 3cc766c22e..96c5d9ce6a 100644--- a/plugins/ruflo-sparc/skills/sparc-refine/SKILL.md+++ b/plugins/ruflo-sparc/skills/sparc-refine/SKILL.md@@ -19,7 +19,7 @@ After the Architecture phase is complete and its gate has been passed. This skil1. **Retrieve all prior artifacts** β call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-phases` and query for the feature slug. Load spec (acceptance criteria), pseudocode, and architecture.-2. **Retrieve phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` to confirm we are in Phase 4.+2. **Retrieve phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with namespace `sparc-state` and exact key `current-phase-{feature-slug}` to confirm we are in Phase 4 (or Phase 5 when resuming completion). If `status === "complete"`, report the existing completion and do not write again; stop on missing/malformed state.3. **Code review** β review the implementation against:a. **Specification compliance**: does every acceptance criterion have a corresponding code path?@@ -50,6 +50,8 @@ After the Architecture phase is complete and its gate has been passed. This skil7. **Store refinement artifact** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `refine-{feature-slug}`, value: `{ status: "complete", reviewFindings: [...], coveragePercent: N, performanceResults: {...}, iterations: N }`+ Before moving to Phase 5, evaluate the Phase 4 gate (passing acceptance tests, approved review, coverage >= 80%) and store its evidence in `sparc-gates`. On failure preserve phase, increment gateAttempts, refresh `updatedAt` with the current ISO timestamp at the exact current-phase key, report blockers and stop. On pass preserve existing state fields, set phase 5, phaseName "Completion", status "active", and `updatedAt` to the current ISO timestamp at the same key in `sparc-state`. When resuming Phase 5, do not repeat the Phase 4 transition.+8. **Record trajectory step** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step` with refinement summary### Phase 5 β Completion@@ -75,7 +77,11 @@ After the Architecture phase is complete and its gate has been passed. This skil- [ ] Rollback plan defined- [ ] Security review complete (no secrets, inputs validated)-13. **Store completion artifact** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `complete-{feature-slug}`, value: `{ status: "complete", traceabilityMatrix: [...], documentationFiles: [...], deploymentChecklist: {...}, regressionResult: "pass" }`+13. **Evaluate the final Phase 5 gate** β completion is allowed only when final gate evidence for every criterion passes: full regression actually ran and passed, documentation is complete, deployment checklist is verified, and traceability links every acceptance criterion to passing tests. Store the actual pass/fail evidence at `gate-5-{feature-slug}-{timestamp}` in `sparc-gates`. If evidence is missing, failed, interrupted, or unrun, preserve state and phase, increment gateAttempts, refresh `updatedAt` to the current ISO timestamp at the exact current-phase key, report blockers and stop. Do not store a complete artifact or complete the state, set completedAt, or train a successful cycle on failure.++ **After the final gate passes, store completion artifact** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-phases`, key `complete-{feature-slug}`, value: `{ status: "complete", traceabilityMatrix: [...], documentationFiles: [...], deploymentChecklist: {...}, regressionResult: "pass" }`++ **Close the workflow** β retrieve `current-phase-{feature-slug}` exactly from `sparc-state` again and decode it as `state`. If `status === "complete"`, do not write again or change its timestamps. Otherwise require phase 5 and the successful final gate evidence above; stop on missing/malformed or changed state. Preserve all existing state fields and set `now = new Date().toISOString()`. Call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `sparc-state` and exact key `current-phase-{feature-slug}`, value `{ ...state, phase: 5, phaseName: "Completion", status: "complete", completedAt: now, updatedAt: now }` once. Keep phase 5, never increment to 6. Report completion only after this write succeeds. A completion artifact alone does not close state; this read/write sequence is not an atomic concurrency guarantee.14. **End trajectory** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-end` with the full SPARC cycle summary@@ -83,10 +89,12 @@ After the Architecture phase is complete and its gate has been passed. This skil16. **Store learned pattern** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with namespace `patterns`, key `sparc-{feature-slug}`, value summarizing what worked, phase durations, and common blockers encountered-17. **Present completion report** β display the traceability matrix, deployment checklist, and final status. Suggest running `/sparc advance` to pass the final gate, or `/sparc report` for the full methodology report.+17. **Present completion report** β display the traceability matrix, deployment checklist, and final status. After the final gate and state write succeed, suggest `/ruflo-sparc:ruflo-sparc report` for the full methodology report. Otherwise show active status and blockers, never a completion claim.## Output format+Success example only: use actual evidence and show completion only after the final gate and state write succeed.+```# Refinement: {Feature Name}@@ -126,5 +134,5 @@ After the Architecture phase is complete and its gate has been passed. This skil- [x] Security reviewed----SPARC workflow complete. Run `/sparc report` for the full methodology report.+SPARC workflow complete. Run `/ruflo-sparc:ruflo-sparc report` for the full methodology report.```diff --git a/plugins/ruflo-sparc/skills/sparc-spec/SKILL.md b/plugins/ruflo-sparc/skills/sparc-spec/SKILL.mdindex 9a5c6d78ed..d5dd02347e 100644--- a/plugins/ruflo-sparc/skills/sparc-spec/SKILL.md+++ b/plugins/ruflo-sparc/skills/sparc-spec/SKILL.md@@ -17,7 +17,7 @@ When starting a new feature or project that needs structured requirements gather1. **Initialize phase tracking** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-start` with metadata `{ "phase": "specification", "feature": "$ARGUMENTS" }`-2. **Check for prior work** β call `mcp__plugin_ruflo-core_ruflo__memory_search` with namespace `sparc-state` and query for the feature to see if a SPARC workflow already exists. If it does, retrieve existing artifacts. If not, initialize state with phase 1.+2. **Check for prior work** β call `mcp__plugin_ruflo-core_ruflo__memory_retrieve` with namespace `sparc-state` and exact key `current-phase-{feature-slug}` to see if this workflow exists. If it does, retrieve existing artifacts. If not, initialize state at that exact key with phase 1, `status: "active"`, and `startedAt` and `updatedAt` set to the current ISO timestamp.3. **Search for similar patterns** β call `mcp__plugin_ruflo-core_ruflo__neural_predict` with the feature description to find relevant past specifications and learned patterns@@ -53,11 +53,11 @@ When starting a new feature or project that needs structured requirements gather9. **Update phase state** β call `mcp__plugin_ruflo-core_ruflo__memory_store` with:- Namespace: `sparc-state`- Key: `current-phase-{feature-slug}`- - Value: updated state with artifacts list including the spec key+ - Value: preserve existing state fields, update artifacts list to include the spec key, and set `updatedAt` to the current ISO timestamp10. **Record trajectory step** β call `mcp__plugin_ruflo-core_ruflo__hooks_intelligence_trajectory-step` with the specification summary-11. **Present specification** β display the full specification document to the user with a summary table and suggest running `/sparc advance` to pass the gate and move to the Pseudocode phase+11. **Present specification** β display the full specification document to the user with a summary table and suggest running `/ruflo-sparc:ruflo-sparc advance` to pass the gate and move to the Pseudocode phase## Output format@@ -91,5 +91,5 @@ When starting a new feature or project that needs structured requirements gather- IP-1: ...----Phase 1 complete. Run `/sparc advance` to pass the gate check.+Phase 1 complete. Run `/ruflo-sparc:ruflo-sparc advance` to pass the gate check.```diff --git a/plugins/ruflo-sparc/tests/contracts.regression.cjs b/plugins/ruflo-sparc/tests/contracts.regression.cjsnew file mode 100644index 0000000000..8f1e84af1a--- /dev/null+++ b/plugins/ruflo-sparc/tests/contracts.regression.cjs@@ -0,0 +1,78 @@+const {test} = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const root = path.resolve(__dirname, '..');+const command = fs.readFileSync(`${root}/commands/ruflo-sparc.md`,'utf8');+const agent = fs.readFileSync(`${root}/agents/sparc-orchestrator.md`,'utf8');+test('#4086 status enumerates all keys and retrieves exact current values', () => {+ const status = command.split('### `')[2];+ assert.match(status, /memory_list/); assert.match(status, /offset/); assert.match(status, /total/);+ assert.match(status, /memory_retrieve/); assert.match(status, /current-phase-/);+ assert.doesNotMatch(status, /memory_search/);+ assert.match(agent, /memory_retrieve.*current-phase-/);+});+test('#4087 every explicit phase agent resolves to a shipped plugin agent', () => {+ const names = [...agent.matchAll(/\*\*Spawned agent\*\*: ([^\n]+)/g)].flatMap(m => [...m[1].matchAll(/`([^`]+)`/g)].map(x => x[1]));+ assert.deepEqual(names, ['ruflo-core:researcher', 'ruflo-goals:goal-planner', 'ruflo-swarm:architect', 'ruflo-core:coder', 'ruflo-testgen:tester', 'ruflo-core:reviewer']);+ assert.match(agent, /available-agent registry/);+ assert.match(agent, /missing plugin/i);+ for (const name of names) {+ assert.match(name, /^ruflo-[a-z-]+:[a-z-]+$/);+ const [plugin, local] = name.split(':');+ const source = fs.readFileSync(path.join(root, '..', plugin, 'agents', `${local}.md`),'utf8');+ assert.match(source, new RegExp(`^name: ${local}$`, 'm'));+ }+});+test('#4088 SPARC command references resolve to the shipped command filename', () => {+ const markdown = dir => fs.readdirSync(dir, { withFileTypes: true }).flatMap(e => e.isDirectory() ? markdown(path.join(dir, e.name)) : e.name.endsWith('.md') ? [path.join(dir, e.name)] : []);+ const files = [`${root}/README.md`, ...markdown(`${root}/commands`), ...markdown(`${root}/skills`)];+ for (const file of files) {+ const text = fs.readFileSync(file,'utf8');+ assert.doesNotMatch(text, /\/sparc(?:-(?:spec|implement|refine))?(?=[\s`<])/, file);+ for (const [, name] of text.matchAll(/\/ruflo-sparc:([a-z-]+)/g)) {+ const target = name === 'ruflo-sparc' ? `${root}/commands/${name}.md` : `${root}/skills/${name}/SKILL.md`;+ assert.match(fs.readFileSync(target, 'utf8'), new RegExp(`^name: ${name}$`, 'm'));+ }+ }+ assert.match(command, /\/ruflo-sparc:ruflo-sparc status/);+});+const section = name => command.split(`### \`/ruflo-sparc:ruflo-sparc ${name}`)[1].split('\n### ')[0];+test('#4086 initialize active state and timestamp every phase/gate state write', () => {+ assert.match(section('init'), /"status": "active"/);+ assert.match(section('init'), /"updatedAt": "<ISO timestamp>"/);+ assert.match(section('phase'), /updatedAt.*ISO/);+ for (const skill of ['sparc-spec', 'sparc-implement']) {+ const text = fs.readFileSync(`${root}/skills/${skill}/SKILL.md`, 'utf8');+ assert.match(text, /updatedAt.*ISO/);+ assert.match(text, /preserv\w* (?:all )?(?:other |existing )?state/i);+ }+});+test('#4086 active status filters explicit completion and orders legacy timestamps', () => {+ const status = section('status');+ assert.match(status, /Exclude.*status === "complete"/);+ assert.match(status, /Do not infer completion from phase 5/);+ assert.match(status, /Sort.*newest.*updatedAt/);+ assert.match(status, /metadata.*updatedAt.*storedAt/);+ assert.match(status, /unknown timestamps last/);+});+test('#4086 advance closes phase five only after its gate and refuses completed records', () => {+ const advance = section('advance');+ assert.match(advance, /status === "complete".*refuse/);+ assert.match(advance, /Phases 1β4.*increment/);+ assert.match(advance, /Phase 5.*final gate passes/);+ assert.match(advance, /\.\.\.state, phase: 5, phaseName: "Completion", status: "complete", completedAt: now, updatedAt: now/);+ assert.match(advance, /never.*6/);+ assert.match(advance, /If gate fails:[\s\S]*updatedAt[\s\S]*Do not.*complete/);+ assert.doesNotMatch(advance, /advancing past Phase 5/);+});+test('#4086 refine closes exact state once only after final gate evidence passes', () => {+ const refine = fs.readFileSync(`${root}/skills/sparc-refine/SKILL.md`, 'utf8');+ assert.match(refine, /final gate evidence.*passes/);+ assert.match(refine, /missing, failed, interrupted, or unrun/);+ assert.match(refine, /Do not.*complete.*state/);+ assert.match(refine, /status === "complete".*do not write again/);+ assert.match(refine, /memory_store.*namespace `sparc-state`.*exact key `current-phase-\{feature-slug\}`/);+ assert.match(refine, /\.\.\.state, phase: 5, phaseName: "Completion", status: "complete", completedAt: now, updatedAt: now/);+ assert.match(refine, /never.*6/);+});diff --git a/plugins/ruflo-testgen/scripts/smoke.sh b/plugins/ruflo-testgen/scripts/smoke.shindex a2682ef174..fb3c303eb8 100755--- a/plugins/ruflo-testgen/scripts/smoke.sh+++ b/plugins/ruflo-testgen/scripts/smoke.sh@@ -94,5 +94,8 @@ process.exit(Object.keys(c).length === 0 ? 0 : 1)step "M3. mod: hooks never touch the network or spawn a process"if grep -nE '\$\.(http|process)\.|child_process|fetch\(' "$ROOT"/hooks/*.ts >/dev/null; then bad "network or process call in hooks"; else ok; fi+step "R. TDD outcome reporting"+node "$ROOT/tests/tdd-workflow.regression.cjs" > /dev/null 2>&1 && ok || bad "regression contract failed"+printf "\n%s passed, %s failed\n" "$PASS" "$FAIL"[[ $FAIL -eq 0 ]] || exit 1diff --git a/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md b/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.mdindex a5845af6a7..c099a704c9 100644--- a/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md+++ b/plugins/ruflo-testgen/skills/tdd-workflow/SKILL.md@@ -13,7 +13,28 @@ Follow the TDD London School (mock-first) approach:5. **Repeat** -- add the next behaviorBefore starting: `mcp__plugin_ruflo-core_ruflo__hooks_pre-task({ description: "TDD: FEATURE_NAME" })`-After completing: `mcp__plugin_ruflo-core_ruflo__hooks_post-task({ taskId: "tdd-FEATURE", success: true, storeResults: true })`+Before reporting the outcome, run the final target tests and the regression suite after the last edit. Record the actual commands, exit codes, whether tests ran, and failing test names. The initial red test is expected during TDD; only the final validation determines success.++Call `mcp__plugin_ruflo-core_ruflo__hooks_post-task` with the observed result, including when the task is abandoned or validation is interrupted. Set `completed`, `targetTestsRan`, and `regressionTestsRan` to true only when observed; use null for missing exit codes. Skipped or unrun validation is not success. Never substitute an expected result for an observed one.++The following example maps those observations to the hook input (tool-call notation):+```javascript+const success = completed && targetTestsRan && regressionTestsRan+ && targetExitCode === 0 && regressionExitCode === 0;+mcp__plugin_ruflo-core_ruflo__hooks_post-task({+ taskId: "tdd-FEATURE",+ success,+ storeResults: true,+ task: JSON.stringify({+ feature: "FEATURE",+ targetCommand, targetExitCode, targetTestsRan,+ regressionCommand, regressionExitCode, regressionTestsRan,+ failingTestNames,+ failureReason: success ? null : failureReason+ })+});+```+On failure, report `success: false` and the failing test names in `task`. If the runner failed before identifying tests, or the task was abandoned, state that reason instead of inventing test names.Principles:- Mock external dependencies at boundariesdiff --git a/plugins/ruflo-testgen/tests/tdd-workflow.regression.cjs b/plugins/ruflo-testgen/tests/tdd-workflow.regression.cjsnew file mode 100644index 0000000000..ea43bb0fe3--- /dev/null+++ b/plugins/ruflo-testgen/tests/tdd-workflow.regression.cjs@@ -0,0 +1,28 @@+const { test } = require('node:test');+const assert = require('node:assert/strict');+const { readFileSync } = require('node:fs');+const vm = require('node:vm');+const source = readFileSync(require('node:path').join(__dirname, '../skills/tdd-workflow/SKILL.md'), 'utf8');+// Execute the documented hook example against observed outcomes, with no model/tool call.+const example = source.match(/```javascript\n([\s\S]*?)```/)?.[1]+ ?? source.match(/After completing: `([^`]+)`/)?.[1];+assert.ok(example, 'skill must provide a post-task example');+const cases = [+ ['green target and regression', {}, true],+ ['target still red', { targetExitCode: 1, failingTestNames: ['target rejects invalid input'] }, false],+ ['regression broken', { regressionExitCode: 1, failingTestNames: ['existing auth test'] }, false],+ ['abandoned', { completed: false }, false],+ ['interrupted runner', { targetExitCode: null }, false],+ ['target not run', { targetTestsRan: false }, false],+ ['regression not run', { regressionTestsRan: false }, false],+];+for (const [name, changes, expected] of cases) test(`#4085 ${name} records observed outcome`, () => {+ const observation = { completed: true, targetTestsRan: true, regressionTestsRan: true,+ targetExitCode: 0, regressionExitCode: 0, failingTestNames: [],+ targetCommand: 'npm test -- target', regressionCommand: 'npm test',+ failureReason: 'task incomplete or validation failed', ...changes };+ let receipt;+ vm.runInNewContext(example.replaceAll('mcp__plugin_ruflo-core_ruflo__hooks_post-task', 'mcp__plugin_ruflo_core_ruflo__hooks_post_task'), { ...observation, mcp__plugin_ruflo_core_ruflo__hooks_post_task: r => { receipt = r; } });+ assert.ok(receipt); assert.equal(receipt.success, expected);+ for (const failing of observation.failingTestNames) assert.ok(receipt.task.includes(failing));+});diff --git a/tests/regression/oct12-coverage.test.cjs b/tests/regression/oct12-coverage.test.cjsnew file mode 100644index 0000000000..a32aef7524--- /dev/null+++ b/tests/regression/oct12-coverage.test.cjs@@ -0,0 +1,103 @@+const { test } = require('node:test');+const assert = require('node:assert/strict');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const { readCoverageFromDisk } = require('../../v3/@claude-flow/cli/src/commands/coverage-reader.ts');+function fromDisk(relative, data) {+ const cwd = process.cwd();+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'oct12-reader-'));+ try {+ process.chdir(root);+ fs.mkdirSync(path.dirname(relative), { recursive: true });+ fs.writeFileSync(relative, typeof data === 'string' ? data : JSON.stringify(data));+ return readCoverageFromDisk();+ } finally { process.chdir(cwd); fs.rmSync(root, { recursive: true, force: true }); }+}+const reader = {+ readCoverageFromDisk,+ parseCoverageSummaryJson: data => fromDisk('coverage/coverage-summary.json', data),+ parseLcovInfo: raw => fromDisk('coverage/lcov.info', raw),+};+const metric = (total, covered, pct = total ? covered / total * 100 : 100) => ({ total, covered, pct });+const file = (total, covered) => Object.fromEntries(['lines','branches','functions','statements'].map(k => [k, metric(total, covered)]));+test('#4082 empty instrumented file is fully covered, not a gap', () => {+ const report = reader.parseCoverageSummaryJson({ 'empty.ts': file(0, 0) }, 'fixture');+ assert.equal(report.entries[0].lines, 100);+ assert.equal(report.summary.overallLineCoverage, 100);+});+test('#4082 pct-only summaries preserve explicit zero and nonzero percentages', () => {+ const report = reader.parseCoverageSummaryJson({ 'a.ts': { lines: { pct: 75 } }, 'b.ts': { lines: { pct: 0 } } }, 'fixture');+ assert.equal(report.entries.find(e => e.filePath === 'a.ts').lines, 75);+ assert.equal(report.entries.find(e => e.filePath === 'b.ts').lines, 0);+});+test('#4083 LCOV aggregates counts for every metric, including unterminated last record', () => {+ const raw = 'SF:large.ts\nLF:100\nLH:10\nBRF:100\nBRH:10\nFNF:100\nFNH:10\nend_of_record\nSF:small.ts\nLF:1\nLH:1\nBRF:1\nBRH:1\nFNF:1\nFNH:1';+ const report = reader.parseLcovInfo(raw, 'fixture');+ for (const key of ['overallLineCoverage','overallBranchCoverage','overallFunctionCoverage','overallStatementCoverage']) assert.equal(report.summary[key], 1100 / 101, key);+});+test('#4084 Istanbul final and NYC counters count unique lines and individual branch arms', () => {+ const cwd = process.cwd(); const root = fs.mkdtempSync(path.join(os.tmpdir(), 'oct12-coverage-'));+ const raw = { 'a.ts': { path: 'a.ts', statementMap: { 0: { start: { line: 1 } }, 1: { start: { line: 1 } }, 2: { start: { line: 2 } } }, s: {0: 1, 1: 0, 2: 0}, f: {0: 0}, b: {0: [1,0]} } };+ try {+ process.chdir(root);+ for (const relative of ['coverage/coverage-final.json', '.nyc_output/out.json']) {+ fs.mkdirSync(path.dirname(relative), {recursive: true}); fs.writeFileSync(relative, JSON.stringify(raw));+ const report = reader.readCoverageFromDisk();+ assert.equal(report.found, true); assert.equal(report.entries.length, 1);+ assert.equal(report.entries[0].lines, 50); assert.equal(report.entries[0].branches, 50);+ assert.equal(report.entries[0].functions, 0); assert.ok(Math.abs(report.entries[0].statements - 100 / 3) < 1e-10);+ fs.unlinkSync(relative);+ }+ } finally { process.chdir(cwd); fs.rmSync(root, { recursive: true, force: true }); }+});+test('empty or malformed reports do not hide a valid fallback', () => {+ const cwd = process.cwd(); const root = fs.mkdtempSync(path.join(os.tmpdir(), 'oct12-coverage-'));+ try {+ process.chdir(root); fs.mkdirSync('coverage');+ fs.writeFileSync('coverage/coverage-summary.json', '{}');+ fs.writeFileSync('coverage/lcov.info', 'SF:a.ts\nLF:2\nLH:1\nend_of_record\n');+ const report = reader.readCoverageFromDisk();+ assert.equal(report.source, 'coverage/lcov.info'); assert.equal(report.summary.overallLineCoverage, 50);+ } finally { process.chdir(cwd); fs.rmSync(root, {recursive: true, force: true}); }+});+test('Istanbul empty-file Unknown sentinel yields numeric 100% in totals and entries', () => {+ const empty = Object.fromEntries(['lines', 'branches', 'functions', 'statements'].map(k => [k, { total: 0, covered: 0, pct: 'Unknown' }]));+ const report = reader.parseCoverageSummaryJson({ total: empty, 'empty.ts': empty });+ assert.equal(report.entries[0].lines, 100);+ assert.equal(report.summary.overallLineCoverage, 100);+ assert.equal(report.summary.overallBranchCoverage, 100);+});+test('legacy NYC summary reports remain readable', () => {+ const report = fromDisk('.nyc_output/out.json', { 'old.ts': file(4, 1) });+ assert.equal(report.found, true); assert.equal(report.entries[0].lines, 25);+});+test('pct-only files retain their percentage but unknown aggregate counts stay conservative', () => {+ const report = reader.parseCoverageSummaryJson({ 'a.ts': { lines: { pct: 75 } } });+ assert.equal(report.entries[0].lines, 75);+ for (const key of ['branches', 'functions', 'statements']) assert.equal(report.entries[0][key], 0);+ for (const [key, value] of Object.entries(report.summary)) if (key !== 'totalFiles') assert.equal(value, 0, key);+});+test('mixed counted and uncounted files cannot claim a fully covered aggregate', () => {+ for (const missing of [{ lines: { pct: 0 } }, { branches: { total: 0, covered: 0 } }]) {+ const report = reader.parseCoverageSummaryJson({ 'counted.ts': file(100, 100), 'unknown.ts': missing });+ assert.equal(report.summary.overallLineCoverage, 0);+ }+});+test('valid supplied aggregate percentages including zero take precedence', () => {+ for (const pct of [0, 75]) {+ const report = reader.parseCoverageSummaryJson({ total: { lines: { pct } }, 'a.ts': { lines: { pct: 75 } } });+ assert.equal(report.summary.overallLineCoverage, pct);+ }+});+test('incomplete or invalid counts do not manufacture a percentage', () => {+ for (const lines of [{ total: 10 }, { covered: 4 }, { total: -1, covered: 0 }, { total: 10, covered: -1 }, { total: 10, covered: 11 }, { total: null, covered: 0 }]) {+ const report = reader.parseCoverageSummaryJson({ 'a.ts': { lines } });+ assert.equal(report.entries[0].lines, 0);+ assert.equal(report.summary.overallLineCoverage, 0);+ }+});+test('explicit empty counts across every file remain fully covered', () => {+ const report = reader.parseCoverageSummaryJson({ 'a.ts': file(0, 0), 'b.ts': file(0, 0) });+ for (const [key, value] of Object.entries(report.summary)) if (key !== 'totalFiles') assert.equal(value, 100, key);+});diff --git a/tests/regression/oct12.vitest.config.mjs b/tests/regression/oct12.vitest.config.mjsnew file mode 100644index 0000000000..acfe364486--- /dev/null+++ b/tests/regression/oct12.vitest.config.mjs@@ -0,0 +1,12 @@+// Isolated validation: no optional native engines, model downloads or CLI services.+export default {+ test: {+ include: [+ 'v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts',+ 'v3/@claude-flow/cli/__tests__/ruvector/coverage-router.test.ts',+ ],+ pool: 'forks',+ maxWorkers: 1,+ fileParallelism: false,+ },+};diff --git a/v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts b/v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.tsnew file mode 100644index 0000000000..364d700c34--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/hooks-coverage-disk.test.ts@@ -0,0 +1,70 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { CommandContext } from '../src/types.js';++vi.mock('../src/output.js', () => ({ output: new Proxy({}, {+ get: (_target, name) => name === 'createSpinner'+ ? () => ({ start() {}, succeed() {}, stop() {}, fail() {} })+ : vi.fn((value) => value),+}) }));+vi.mock('../src/prompt.js', () => ({ select: vi.fn(), confirm: vi.fn(), input: vi.fn() }));+vi.mock('../src/mcp-client.js', () => ({ callMCPTool: vi.fn(), MCPClientError: class extends Error {} }));+vi.mock('../src/commands/transfer-store.js', () => ({ storeCommand: {} }));+vi.mock('../src/funnel/local-signals.js', () => ({+ getSecurityStatus: vi.fn(), getSwarmStatus: vi.fn(), getGitUncommittedCount: vi.fn(),+}));+import { hooksCommand } from '../src/commands/hooks.js';+import { callMCPTool } from '../src/mcp-client.js';++const cwd = process.cwd();+let root: string;+beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), 'hooks-coverage-disk-'));+ process.chdir(root);+ mkdirSync('coverage');+ vi.mocked(callMCPTool).mockReset();+});+afterEach(() => { process.chdir(cwd); rmSync(root, { recursive: true, force: true }); });++async function run(name: string, flags: Record<string, unknown> = {}) {+ const command = hooksCommand.subcommands!.find(c => c.name === name)!;+ return command.action!({ flags: { format: 'json', ...flags }, args: [] } as unknown as CommandContext);+}++describe('coverage hooks disk integration (#4082β#4084)', () => {+ it('does not route or suggest tests for empty instrumented files', async () => {+ const metric = { total: 0, covered: 0, pct: 'Unknown' };+ const empty = { lines: metric, branches: metric, functions: metric, statements: metric };+ writeFileSync('coverage/coverage-summary.json', JSON.stringify({ total: empty, 'src/empty.ts': empty }));+ const gaps = await run('coverage-gaps');+ expect(gaps).toMatchObject({ success: true, data: { gaps: [], summary: { overallLineCoverage: 100 } } });+ const route = await run('coverage-route', { task: 'write tests for empty' });+ expect(route).toMatchObject({ success: true, data: { gaps: [], metrics: { avgCoverage: 100 } } });+ const suggest = await run('coverage-suggest', { path: 'src/empty.ts' });+ expect(suggest.success).toBe(true);+ expect(callMCPTool).not.toHaveBeenCalled();+ });+ it('propagates weighted LCOV totals to gaps and routing', async () => {+ writeFileSync('coverage/lcov.info', 'SF:large.ts\nLF:100\nLH:10\nBRF:100\nBRH:10\nend_of_record\nSF:small.ts\nLF:1\nLH:1\nBRF:1\nBRH:1\nend_of_record\n');+ const gaps = await run('coverage-gaps');+ expect((gaps.data as any).summary.overallLineCoverage).toBeCloseTo(1100 / 101);+ expect((gaps.data as any).summary.overallBranchCoverage).toBeCloseTo(1100 / 101);+ const route = await run('coverage-route', { task: 'write tests' });+ expect((route.data as any).metrics.avgCoverage).toBeCloseTo(1100 / 101);+ expect(callMCPTool).not.toHaveBeenCalled();+ });+ it('reads Istanbul final counters through every coverage hook without MCP fallback', async () => {+ writeFileSync('coverage/coverage-final.json', JSON.stringify({ 'src/auth.ts': {+ s: { 0: 1, 1: 0 }, f: { 0: 0 }, b: { 0: [1, 0] },+ statementMap: { 0: { start: { line: 1 } }, 1: { start: { line: 2 } } },+ } }));+ for (const name of ['coverage-gaps', 'coverage-route', 'coverage-suggest']) {+ const result = await run(name, { task: 'test auth', path: 'src/auth.ts' });+ expect(result.success).toBe(true);+ expect((result.data as any).source).toBe('coverage/coverage-final.json');+ }+ expect(callMCPTool).not.toHaveBeenCalled();+ });+});diff --git a/v3/@claude-flow/cli/src/commands/coverage-reader.ts b/v3/@claude-flow/cli/src/commands/coverage-reader.tsnew file mode 100644index 0000000000..10f9fbe50e--- /dev/null+++ b/v3/@claude-flow/cli/src/commands/coverage-reader.ts@@ -0,0 +1,236 @@+import { existsSync, readFileSync } from 'node:fs';+import { join } from 'node:path';++interface CoverageFileEntry {+ filePath: string;+ lines: number;+ branches: number;+ functions: number;+ statements: number;+}++interface CoverageData {+ found: boolean;+ source: string;+ entries: CoverageFileEntry[];+ summary: {+ totalFiles: number;+ overallLineCoverage: number;+ overallBranchCoverage: number;+ overallFunctionCoverage: number;+ overallStatementCoverage: number;+ };+}++/**+ * Read coverage data from disk. Checks these locations in order:+ * 1. coverage/coverage-summary.json (Jest/Istanbul)+ * 2. coverage/lcov.info (lcov format)+ * 3. coverage/coverage-final.json (Istanbul counters)+ * 4. .nyc_output/out.json (nyc counters or legacy summary)+ */+export function readCoverageFromDisk(): CoverageData {+ const cwd = process.cwd();+ const noData: CoverageData = {+ found: false,+ source: 'none',+ entries: [],+ summary: { totalFiles: 0, overallLineCoverage: 0, overallBranchCoverage: 0, overallFunctionCoverage: 0, overallStatementCoverage: 0 },+ };++ // 1. Try coverage-summary.json (Jest/Istanbul)+ for (const relPath of ['coverage/coverage-summary.json', 'coverage-summary.json']) {+ const summaryPath = join(cwd, relPath);+ if (existsSync(summaryPath)) {+ try {+ const raw = JSON.parse(readFileSync(summaryPath, 'utf-8'));+ const report = parseCoverageSummaryJson(raw, relPath);+ if (report.found) return report;+ } catch {+ // malformed, try next+ }+ }+ }++ // 2. Try lcov.info+ for (const relPath of ['coverage/lcov.info', 'lcov.info']) {+ const lcovPath = join(cwd, relPath);+ if (existsSync(lcovPath)) {+ try {+ const raw = readFileSync(lcovPath, 'utf-8');+ const report = parseLcovInfo(raw, relPath);+ if (report.found) return report;+ } catch {+ // malformed, try next+ }+ }+ }++ // Istanbul's raw counter map (Jest, Vitest, nyc).+ for (const relPath of ['coverage/coverage-final.json', 'coverage-final.json', '.nyc_output/out.json']) {+ try {+ const raw = JSON.parse(readFileSync(join(cwd, relPath), 'utf-8'));+ const report = parseIstanbulCoverage(raw, relPath);+ if (report.found) return report;+ const legacy = parseCoverageSummaryJson(raw, relPath);+ if (legacy.found) return legacy;+ } catch {+ // Missing or malformed, try the next supported report.+ }+ }++ return noData;+}++function parseCoverageSummaryJson(data: Record<string, unknown>, source: string): CoverageData {+ const entries: CoverageFileEntry[] = [];+ const metricsByFile: Record<string, Metric>[] = [];++ for (const [filePath, metrics] of Object.entries(data)) {+ if (filePath === 'total') continue;+ const m = metrics as Record<string, Metric>;+ if (!m || typeof m !== 'object') continue;++ if (!['lines', 'branches', 'functions', 'statements'].some(key => m[key])) continue;+ metricsByFile.push(m);+ const linePct = percentage(m.lines) ?? 0;+ const branchPct = (percentage(m.branches) ?? 0);+ const funcPct = (percentage(m.functions) ?? 0);+ const stmtPct = (percentage(m.statements) ?? 0);++ entries.push({ filePath, lines: linePct, branches: branchPct, functions: funcPct, statements: stmtPct });++ }++ // Only aggregate complete counts. A missing denominator is unknown, not empty.+ const total = data['total'] as Record<string, Metric> | undefined;+ const aggregate = (key: string): number => {+ const supplied = percentage(total?.[key]);+ if (supplied !== undefined) return supplied;+ const metrics = metricsByFile.map(file => file[key]);+ if (metrics.length === 0 || !metrics.every(hasCounts)) return 0;+ return ratio(metrics.reduce((sum, m) => sum + m.covered, 0),+ metrics.reduce((sum, m) => sum + m.total, 0));+ };++ // Sort by lowest line coverage+ entries.sort((a, b) => a.lines - b.lines);++ return {+ found: entries.length > 0,+ source,+ entries,+ summary: {+ totalFiles: entries.length,+ overallLineCoverage: aggregate('lines'),+ overallBranchCoverage: aggregate('branches'),+ overallFunctionCoverage: aggregate('functions'),+ overallStatementCoverage: aggregate('statements'),+ },+ };+}++function parseLcovInfo(raw: string, source: string): CoverageData {+ const entries: CoverageFileEntry[] = [];+ let currentFile = '';+ let linesHit = 0, linesFound = 0;+ let branchesHit = 0, branchesFound = 0;+ let functionsHit = 0, functionsFound = 0;++ let totalLH = 0, totalLF = 0, totalBH = 0, totalBF = 0, totalFH = 0, totalFF = 0;+ const flushRecord = () => {+ if (currentFile) {+ totalLH += linesHit; totalLF += linesFound;+ totalBH += branchesHit; totalBF += branchesFound;+ totalFH += functionsHit; totalFF += functionsFound;+ entries.push({+ filePath: currentFile,+ lines: linesFound > 0 ? (linesHit / linesFound) * 100 : 100,+ branches: branchesFound > 0 ? (branchesHit / branchesFound) * 100 : 100,+ functions: functionsFound > 0 ? (functionsHit / functionsFound) * 100 : 100,+ statements: linesFound > 0 ? (linesHit / linesFound) * 100 : 100,+ });+ }+ };++ for (const line of raw.split('\n')) {+ const trimmed = line.trim();+ if (trimmed.startsWith('SF:')) {+ flushRecord();+ currentFile = trimmed.slice(3);+ linesHit = 0; linesFound = 0;+ branchesHit = 0; branchesFound = 0;+ functionsHit = 0; functionsFound = 0;+ } else if (trimmed.startsWith('LH:')) {+ linesHit = parseInt(trimmed.slice(3), 10) || 0;+ } else if (trimmed.startsWith('LF:')) {+ linesFound = parseInt(trimmed.slice(3), 10) || 0;+ } else if (trimmed.startsWith('BRH:')) {+ branchesHit = parseInt(trimmed.slice(4), 10) || 0;+ } else if (trimmed.startsWith('BRF:')) {+ branchesFound = parseInt(trimmed.slice(4), 10) || 0;+ } else if (trimmed.startsWith('FNH:')) {+ functionsHit = parseInt(trimmed.slice(4), 10) || 0;+ } else if (trimmed.startsWith('FNF:')) {+ functionsFound = parseInt(trimmed.slice(4), 10) || 0;+ } else if (trimmed === 'end_of_record') {+ flushRecord();+ currentFile = '';+ }+ }+ flushRecord();++ entries.sort((a, b) => a.lines - b.lines);++ return {+ found: entries.length > 0,+ source,+ entries,+ summary: {+ totalFiles: entries.length,+ overallLineCoverage: ratio(totalLH, totalLF),+ overallBranchCoverage: ratio(totalBH, totalBF),+ overallFunctionCoverage: ratio(totalFH, totalFF),+ overallStatementCoverage: ratio(totalLH, totalLF),+ },+ };+}+++type Metric = { total?: number; covered?: number; pct?: number | string };+function ratio(covered: number, total: number): number {+ return total > 0 ? covered / total * 100 : 100;+}+function hasCounts(metric?: Metric): metric is Metric & { total: number; covered: number } {+ return typeof metric?.total === 'number' && Number.isFinite(metric.total) && metric.total >= 0+ && typeof metric.covered === 'number' && Number.isFinite(metric.covered)+ && metric.covered >= 0 && metric.covered <= metric.total;+}+function percentage(metric?: Metric): number | undefined {+ if (typeof metric?.pct === 'number' && Number.isFinite(metric.pct)+ && metric.pct >= 0 && metric.pct <= 100) return metric.pct;+ return hasCounts(metric) ? ratio(metric.covered, metric.total) : undefined;+}++/** Istanbul line coverage uses the maximum statement hit count on each start line. */+function parseIstanbulCoverage(data: Record<string, unknown>, source: string): CoverageData {+ const summary: Record<string, unknown> = {};+ for (const [filePath, value] of Object.entries(data)) {+ const cov = value as { s?: Record<string, number>; f?: Record<string, number>; b?: Record<string, number[]>; statementMap?: Record<string, { start: { line: number } }> };+ if (!cov || !cov.s || !cov.f || !cov.b || !cov.statementMap) continue;+ const lines = new Map<number, number>();+ for (const [id, hits] of Object.entries(cov.s)) {+ const line = cov.statementMap[id]?.start?.line;+ if (!Number.isInteger(line) || line! < 1) throw new Error('Invalid Istanbul statement location');+ lines.set(line!, Math.max(lines.get(line!) ?? 0, hits));+ }+ const metric = (hits: number[]) => {+ if (hits.some(n => !Number.isFinite(n) || n < 0)) throw new Error('Invalid Istanbul counter');+ const covered = hits.filter(n => n > 0).length;+ return { total: hits.length, covered, pct: ratio(covered, hits.length) };+ };+ summary[filePath] = { lines: metric([...lines.values()]), statements: metric(Object.values(cov.s)),+ functions: metric(Object.values(cov.f)), branches: metric(Object.values(cov.b).flat()) };+ }+ return parseCoverageSummaryJson(summary, source);+}diff --git a/v3/@claude-flow/cli/src/commands/hooks.ts b/v3/@claude-flow/cli/src/commands/hooks.tsindex b3ec30cd10..037c338a65 100644--- a/v3/@claude-flow/cli/src/commands/hooks.ts+++ b/v3/@claude-flow/cli/src/commands/hooks.ts@@ -1,10 +1,11 @@-import { validateFeedbackPatterns } from '../memory/feedback-patterns.js';/*** V3 CLI Hooks Command* Self-learning hooks system for intelligent workflow automation*/import type { Command, CommandContext, CommandResult } from '../types.js';+import { validateFeedbackPatterns } from '../memory/feedback-patterns.js';+import { readCoverageFromDisk } from './coverage-reader.js';import { output } from '../output.js';import { select, confirm, input } from '../prompt.js';import { callMCPTool, MCPClientError } from '../mcp-client.js';@@ -28,210 +29,6 @@ function safeNum(value: unknown, fallback = 0): number {return Number.isFinite(n) ? n : fallback;}-// ============================================================================-// Coverage Data Reader - reads Jest/Istanbul coverage files from disk-// ============================================================================--interface CoverageFileEntry {- filePath: string;- lines: number;- branches: number;- functions: number;- statements: number;-}--interface CoverageData {- found: boolean;- source: string;- entries: CoverageFileEntry[];- summary: {- totalFiles: number;- overallLineCoverage: number;- overallBranchCoverage: number;- overallFunctionCoverage: number;- overallStatementCoverage: number;- };-}--/**- * Read coverage data from disk. Checks these locations in order:- * 1. coverage/coverage-summary.json (Jest/Istanbul)- * 2. coverage/lcov.info (lcov format)- * 3. .nyc_output/out.json (nyc)- */-function readCoverageFromDisk(): CoverageData {- const cwd = process.cwd();- const noData: CoverageData = {- found: false,- source: 'none',- entries: [],- summary: { totalFiles: 0, overallLineCoverage: 0, overallBranchCoverage: 0, overallFunctionCoverage: 0, overallStatementCoverage: 0 },- };-- // 1. Try coverage-summary.json (Jest/Istanbul)- for (const relPath of ['coverage/coverage-summary.json', 'coverage-summary.json']) {- const summaryPath = join(cwd, relPath);- if (existsSync(summaryPath)) {- try {- const raw = JSON.parse(readFileSync(summaryPath, 'utf-8'));- return parseCoverageSummaryJson(raw, relPath);- } catch {- // malformed, try next- }- }- }-- // 2. Try lcov.info- for (const relPath of ['coverage/lcov.info', 'lcov.info']) {- const lcovPath = join(cwd, relPath);- if (existsSync(lcovPath)) {- try {- const raw = readFileSync(lcovPath, 'utf-8');- return parseLcovInfo(raw, relPath);- } catch {- // malformed, try next- }- }- }-- // 3. Try .nyc_output/out.json- const nycPath = join(cwd, '.nyc_output', 'out.json');- if (existsSync(nycPath)) {- try {- const raw = JSON.parse(readFileSync(nycPath, 'utf-8'));- return parseCoverageSummaryJson(raw, '.nyc_output/out.json');- } catch {- // malformed- }- }-- return noData;-}--function parseCoverageSummaryJson(data: Record<string, unknown>, source: string): CoverageData {- const entries: CoverageFileEntry[] = [];- let totalLines = 0, coveredLines = 0;- let totalBranches = 0, coveredBranches = 0;- let totalFunctions = 0, coveredFunctions = 0;- let totalStatements = 0, coveredStatements = 0;-- for (const [filePath, metrics] of Object.entries(data)) {- if (filePath === 'total') continue;- const m = metrics as Record<string, { total?: number; covered?: number; pct?: number }>;- if (!m || typeof m !== 'object') continue;-- const linePct = m.lines?.pct ?? m.lines?.covered != null ? ((m.lines?.covered ?? 0) / Math.max(m.lines?.total ?? 1, 1)) * 100 : 0;- const branchPct = m.branches?.pct ?? (m.branches?.total ? ((m.branches?.covered ?? 0) / m.branches.total) * 100 : 100);- const funcPct = m.functions?.pct ?? (m.functions?.total ? ((m.functions?.covered ?? 0) / m.functions.total) * 100 : 100);- const stmtPct = m.statements?.pct ?? (m.statements?.total ? ((m.statements?.covered ?? 0) / m.statements.total) * 100 : 100);-- entries.push({ filePath, lines: linePct, branches: branchPct, functions: funcPct, statements: stmtPct });-- totalLines += m.lines?.total ?? 0;- coveredLines += m.lines?.covered ?? 0;- totalBranches += m.branches?.total ?? 0;- coveredBranches += m.branches?.covered ?? 0;- totalFunctions += m.functions?.total ?? 0;- coveredFunctions += m.functions?.covered ?? 0;- totalStatements += m.statements?.total ?? 0;- coveredStatements += m.statements?.covered ?? 0;- }-- // Also read the total key if present- const total = data['total'] as Record<string, { pct?: number }> | undefined;- const overallLine = total?.lines?.pct ?? (totalLines > 0 ? (coveredLines / totalLines) * 100 : 0);- const overallBranch = total?.branches?.pct ?? (totalBranches > 0 ? (coveredBranches / totalBranches) * 100 : 0);- const overallFunction = total?.functions?.pct ?? (totalFunctions > 0 ? (coveredFunctions / totalFunctions) * 100 : 0);- const overallStatement = total?.statements?.pct ?? (totalStatements > 0 ? (coveredStatements / totalStatements) * 100 : 0);-- // Sort by lowest line coverage- entries.sort((a, b) => a.lines - b.lines);-- return {- found: true,- source,- entries,- summary: {- totalFiles: entries.length,- overallLineCoverage: overallLine,- overallBranchCoverage: overallBranch,- overallFunctionCoverage: overallFunction,- overallStatementCoverage: overallStatement,- },- };-}--function parseLcovInfo(raw: string, source: string): CoverageData {- const entries: CoverageFileEntry[] = [];- let currentFile = '';- let linesHit = 0, linesFound = 0;- let branchesHit = 0, branchesFound = 0;- let functionsHit = 0, functionsFound = 0;-- const flushRecord = () => {- if (currentFile) {- entries.push({- filePath: currentFile,- lines: linesFound > 0 ? (linesHit / linesFound) * 100 : 0,- branches: branchesFound > 0 ? (branchesHit / branchesFound) * 100 : 100,- functions: functionsFound > 0 ? (functionsHit / functionsFound) * 100 : 100,- statements: linesFound > 0 ? (linesHit / linesFound) * 100 : 0,- });- }- };-- for (const line of raw.split('\n')) {- const trimmed = line.trim();- if (trimmed.startsWith('SF:')) {- currentFile = trimmed.slice(3);- linesHit = 0; linesFound = 0;- branchesHit = 0; branchesFound = 0;- functionsHit = 0; functionsFound = 0;- } else if (trimmed.startsWith('LH:')) {- linesHit = parseInt(trimmed.slice(3), 10) || 0;- } else if (trimmed.startsWith('LF:')) {- linesFound = parseInt(trimmed.slice(3), 10) || 0;- } else if (trimmed.startsWith('BRH:')) {- branchesHit = parseInt(trimmed.slice(4), 10) || 0;- } else if (trimmed.startsWith('BRF:')) {- branchesFound = parseInt(trimmed.slice(4), 10) || 0;- } else if (trimmed.startsWith('FNH:')) {- functionsHit = parseInt(trimmed.slice(4), 10) || 0;- } else if (trimmed.startsWith('FNF:')) {- functionsFound = parseInt(trimmed.slice(4), 10) || 0;- } else if (trimmed === 'end_of_record') {- flushRecord();- currentFile = '';- }- }- flushRecord();-- entries.sort((a, b) => a.lines - b.lines);-- let totalLH = 0, totalLF = 0, totalBH = 0, totalBF = 0;- for (const e of entries) {- // Approximate from percentages (we lost exact counts after flush, but summaries are okay)- totalLH += e.lines;- totalLF += 100;- totalBH += e.branches;- totalBF += 100;- }- const n = entries.length || 1;-- return {- found: true,- source,- entries,- summary: {- totalFiles: entries.length,- overallLineCoverage: totalLH / n,- overallBranchCoverage: totalBH / n,- overallFunctionCoverage: 0,- overallStatementCoverage: totalLH / n,- },- };-}-/*** Classify a coverage gap by priority type based on coverage percentage and threshold*/@@ -3635,7 +3432,7 @@ const coverageRouteCommand: Command = {'c8: npx c8 npm test',]);output.writeln();- output.writeln(output.dim('Expected files: coverage/coverage-summary.json, coverage/lcov.info, or .nyc_output/out.json'));+ output.writeln(output.dim('Expected files: coverage/coverage-summary.json, coverage/lcov.info, coverage/coverage-final.json, or .nyc_output/out.json'));return { success: false, exitCode: 1 };}}@@ -3870,7 +3667,7 @@ const coverageSuggestCommand: Command = {'c8: npx c8 npm test',]);output.writeln();- output.writeln(output.dim('Expected files: coverage/coverage-summary.json, coverage/lcov.info, or .nyc_output/out.json'));+ output.writeln(output.dim('Expected files: coverage/coverage-summary.json, coverage/lcov.info, coverage/coverage-final.json, or .nyc_output/out.json'));return { success: false, exitCode: 1 };}}@@ -4129,7 +3926,7 @@ const coverageGapsCommand: Command = {'c8: npx c8 npm test',]);output.writeln();- output.writeln(output.dim('Expected files: coverage/coverage-summary.json, coverage/lcov.info, or .nyc_output/out.json'));+ output.writeln(output.dim('Expected files: coverage/coverage-summary.json, coverage/lcov.info, coverage/coverage-final.json, or .nyc_output/out.json'));return { success: false, exitCode: 1 };}}