cliewen-openspec 0.1.0-alpha.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +87 -54
  2. package/README.md +106 -104
  3. package/adapters/node-test.mjs +21 -4
  4. package/dist/cli.js +7 -31
  5. package/dist/compatibility.d.ts +12 -0
  6. package/dist/compatibility.js +87 -0
  7. package/dist/core.d.ts +23 -4
  8. package/dist/core.js +107 -35
  9. package/dist/quality.d.ts +27 -0
  10. package/dist/quality.js +412 -0
  11. package/dist/release.d.ts +9 -0
  12. package/dist/release.js +23 -0
  13. package/dist/schema-source.js +1 -1
  14. package/docs/configuration.md +317 -265
  15. package/docs/testing/evidence.md +88 -86
  16. package/docs/testing/pilot-prompt.md +1 -1
  17. package/docs/testing/test-quality.md +84 -0
  18. package/package.json +9 -5
  19. package/schemas/all/templates/tasks.md +1 -5
  20. package/schemas/base/instructions/closure.md +33 -0
  21. package/schemas/base/instructions/humanizer.md +7 -0
  22. package/schemas/base/instructions/learnings.md +6 -0
  23. package/schemas/base/instructions/planning.md +31 -0
  24. package/schemas/base/instructions/product-context.md +31 -0
  25. package/schemas/base/instructions/prototyping.md +33 -0
  26. package/schemas/base/instructions/routing.md +1 -0
  27. package/schemas/base/instructions/testing-approach.md +14 -13
  28. package/schemas/base/instructions/work-scoping.md +12 -0
  29. package/schemas/base/instructions/writing.md +8 -0
  30. package/schemas/base/templates/learning.md +19 -0
  31. package/schemas/delivery/instructions/apply.md +2 -1
  32. package/schemas/delivery/instructions/tasks.md +3 -2
  33. package/schemas/delivery/templates/tasks.md +5 -7
  34. package/schemas/discovery/instructions/apply.md +1 -0
  35. package/schemas/discovery/instructions/investigation.md +1 -0
  36. package/dist/tdd.d.ts +0 -8
  37. package/dist/tdd.js +0 -276
@@ -1,13 +1,14 @@
1
- Read testing.approach from config (default flexible).
2
- Flexible permits tests before or after code within the selected placement.
3
- For tdd, each implementation task must describe one red-green-refactor cycle: write a focused test first, run it and observe failure for the intended missing behavior, implement the minimum behavior to make it pass, then refactor while keeping relevant tests green.
4
- Fix setup, import, or syntax errors rather than treating them as the intended red result.
5
- Record the red and green commands and observed outcomes in the task completion notes; if the test already passes, report that instead of claiming a red phase.
6
- Documentation-only tasks use suitable validation rather than a forced TDD cycle.
7
- Final passing evidence alone does not prove TDD was followed.
8
- With tdd selected for delivery, tasks.md must contain one fenced `yaml cliewen-tasks` block: version: 1 and tasks keyed by every checkbox's unique numeric ID (for example "1.1"). Each entry declares method (tdd, characterization, refactor, or verification), command as an executable/argument list, tests as explicit file paths, and implementation as explicit file paths. Non-tdd methods require a reason reviewed with the task plan; configuration and tooling changes that alter behavior still need tdd. Use the installed package's docs/configuration.md Test-driven development section for the complete format and executable examples.
9
- Before changing a task's declared files, run cliewen-openspec tdd start --change <name> --task <id>. Run the declared command through cliewen-openspec tdd run --change <name> --task <id> --phase red --reason "<intended missing behavior>" -- <command and args>, then implement and record --phase green. A red run keeps its nonzero exit code; inspect its output before proceeding. Keep the tests unchanged between red and green. Record another green run after refactoring; a new test change needs another start/red/green cycle.
10
- For characterization, start before adding the test, record a passing --phase baseline against unchanged production, then --phase green after any production work. For refactor, start with existing tests, record a passing baseline, then green with unchanged tests. For verification exceptions, start before work and record --phase verify using the agreed check. List every relevant file and review the declared verification boundary.
11
- The recorder appends command output and file hashes under .cliewen-openspec/tdd/<change>.jsonl. Preserve this local history and failed attempts; do not invent or hand-edit events. Ensure tdd/ is ignored by .cliewen-openspec/.gitignore before recording; existing ignores are preserved by update. Missing history is unverified. A changed task definition needs a new start and honest verification, never a retroactive red claim.
12
- After actual task verification, mark tasks complete and run cliewen-openspec check --change <name>. In tdd mode, completion checks remain active even when product evidence is disabled. Finish task notes and commit inputs before collecting final revision-bound evidence. History does not prove failure cause or human review and does not prevent production writes. Discovery and combined no-delivery closure do not require this delivery history.
13
- Keep final revision-bound evidence collection and the completion check as untracked workflow follow-up, outside numbered checkboxes. A final verification task can record a real regression or documentation check. Do not use cliewen-openspec check as a recorded task command: it would assess its own unfinished history while the recorder is locked.
1
+ Use spec-driven development with evidence-first verification.
2
+ Before implementation, describe acceptance criteria, relevant positive/negative/boundary cases, and the observations needed for acceptance. Refine this plan when new information changes the requirements.
3
+ Plan relevant interactions between supported input content, option states, boundaries, and execution paths. For preservation claims, assert exact content across relevant default, disabled, and enabled paths using inputs that could expose unintended transformation. Select combinations by behavioral risk and record relevant untested combinations; exhaustive combinations are not required. Separate tests of each dimension do not establish their interactions.
4
+ Develop and verify small tasks. Test code may be written before, alongside, or after production code. Give each task concrete tests, commands, and a completion check; inspect actual results before proceeding. Documentation-only tasks use suitable validation.
5
+ Review assertions against specifications independently of implementation assumptions. Check effectiveness with relevant controlled faults or observed behavior failures where useful; syntax, setup, and unrelated failures are not effectiveness evidence.
6
+ Maintain tests as accepted behavior changes. Preserve shared active obligations and retire assertions only after explicit criterion retirement. Keep actual observations and limitations; never invent results.
7
+ Read testing.quality.coverage.mode, testing.quality.effectiveness.mode, and testing.lifecycle.mode independently (each defaults to review). Off skips that policy; review requests assessments and warns; enforce requires complete records and execution evidence. Follow the installed package's docs/testing/test-quality.md for formats and limits.
8
+ In review mode, disclose unresolved case/record warnings and their impact in the handoff; zero warnings is not a completion requirement. Do not disable policies or invent behavior/cases to silence findings. Enforce mode requires resolving its blocking findings. Execution failures remain blocking in either mode.
9
+ When coverage is active, tag Node cases with [Case: kebab-case-id] and [Coverage: positive|negative|boundary], retaining AC and Test-type tags. Use meaningful distinct cases and scoped reviewed exceptions where appropriate; counts do not prove assertion quality.
10
+ When effectiveness is active, inspect assertions and record relevant controlled-fault or observed behavior failures. Fix setup or unrelated failures before making effectiveness claims. Do not claim recorded status authenticates approval.
11
+ Choose faults that exercise the claimed input and execution path. Credit only the cases and assertions that actually detect the fault; passing another option state or stopping at an earlier assertion does not establish detection elsewhere.
12
+ For a change that inserts, removes, normalizes, or escapes a pattern, include supported caller content containing that pattern in relevant positions and option states. When claiming preservation, consider a fault that accidentally removes or transforms legitimate input content while still producing the requested new output. Record surviving faults and their impact even when the actual implementation passes independent checks; unrelated successful faults do not cover that gap.
13
+ When lifecycle is active, review affected criteria and tests against a baseline. Retain valid behavior assertions through refactoring, update accepted behavior changes, and remove obsolete assertions only after explicit accepted retirement. Preserve shared active obligations and reserved IDs. Author fresh scoped review records, commit reviewed inputs, collect final evidence, and refresh the permanent-spec review after archive. Discovery-only and genuine no-delivery changes need no product-quality records.
14
+ Finish documentation and task notes, commit reviewed inputs, then collect revision-bound evidence and run check. Later commits require fresh evidence.
@@ -0,0 +1,12 @@
1
+ Assess whether the work needs an OpenSpec change from intended behavior, requirements, design impact, and uncertainty, following OpenSpec conventions. A small correction restoring unchanged accepted behavior can use relevant verification without a new proposal. Reassess if investigation reveals new behavior or material design choices.
2
+ Scope each change as a coherent result that can be understood and verified together. Small implementation tasks do not each need a proposal; independent changes can proceed in parallel. When splitting an oversized proposal, retain rationale and deferred obligations in the project's planning authority when enabled, and reconcile the current proposal, specs, design, and tasks so deferred work is not reported as delivered.
3
+ Before a consequential commitment, identify its riskiest assumption, a credible alternative, the cheapest useful investigation, and a stop or revision condition where the reviewer reads the choice. Ask whether meeting every criterion could still fail the intended user. Routine understood work needs no challenge report or explanation for its absence.
4
+ On resumption or contradictory evidence, reassess goals, dependencies, and the next delivery. Surface mismatches and options and obtain direction for material changes in agreed scope before continuing affected work. Ordinary replanning does not automatically need a Decision Record.
5
+ For consequential unresolved choices, suggest optional grill-me when useful. Availability alone does not request an interview. On user request, use the host's exposed skill-loading mechanism to read grill-me and its grilling dependency before following their instructions. If unavailable, inaccessible, or declined, continue ordinary scoping and report relevant limits; do not install skills automatically. Confirm shared understanding before acting and preserve agreed conclusions in the relevant proposal, plan, or decision. Existing approval boundaries still apply.
6
+ For material uncertainty that needs something concrete to try, read .cliewen-openspec/prototyping.md. Suggest a bounded prototype only when useful; the user chooses it and understood work proceeds normally. Keep native explore read-only for code and continue an agreed experiment through the selected investigative change.
7
+ Use .cliewen-openspec/product-context.md for relevant product intent and cross-capability journeys during scoping, design, investigation, and review. Detect drift from the agreed outcome and distinguish in-scope corrections from new wishes through existing scope rules; optional records follow documentation/planning settings and routine work gains no new prerequisite.
8
+ Before requesting any manual step, assess whether available authorized tools can perform it reliably. Automate feasible checks, setup, and evidence collection while preserving verification quality and authorization. A previously manual procedure is not sufficient reason to ask a person to repeat it. Complete authorized preparation and explain the specific remaining need for human judgment, access, or authority; request only that contribution. Reassess when tools or access change. If automation fails or access is unavailable, report the actual limitation and smallest remaining action without claiming success or treating the limitation as permanent.
9
+ When useful human observations exist, preserve the supplied attribution, checked behavior or scenario, tested version, relevant environment and steps, actual results or problems, and limits. Keep unavailable details explicitly unknown. Faithfully summarize actual feedback; label illustrative examples and agent observations by their real origin. Automated checks cannot establish a real user's subjective experience. If no human feedback was collected, say so when relevant rather than inventing it or adding a routine gate.
10
+ Reuse an existing investigation, review, task note, ticket, or handoff for observations with descriptive references to the checked behavior. Optional durable documentation follows features.documentation and existing paths; when disabled, create no optional observation document but keep the handoff accurate. External records follow features.planning and existing access/authorization rules. Preserve an observation's original tested context when relevant behavior changes, identify it as historical, and assess whether the changed behavior needs another check.
11
+ Keep observation, change approval, and release authorization distinct. Positive feedback does not authorize unrelated scope or publication. Human involvement follows concrete verification needs and project policy; routine sufficiently verified authorized work proceeds independently. Discovery findings use existing investigation records without fabricated product ACs or execution evidence.
12
+ For existing manual execution results, reason can contain a concise observation or descriptive reference. Preserve the version-1 report contract: scenario identities, configured test types, scope, revision freshness, and manual-verification warnings still apply. A durable historical observation does not satisfy current revision-bound evidence. Never replace automated failures with a manual claim or report an unperformed check as passed. These instructions cannot authenticate feedback or establish automated proof.
@@ -13,6 +13,14 @@ Use diagrams only where the format supports them and they improve understanding.
13
13
  Preserve code behavior, structured data, required syntax, and exact identifiers.
14
14
  Apply the same diagram guidance across these texts.
15
15
  For PR descriptions, include relevant validation and limitations.
16
+ Before handing off authored or edited documents, resolve local Markdown links relative to each containing file, verify existing targets and any fragments with available link/render checks, and correct broken links. A proposal under openspec/changes/CHANGE/ reaches project-root docs/ with ../../../docs/, not ../../../../docs/. Describe planned files as planned paths until they exist instead of making broken links. Report the checks actually run and any unchecked link limits; passing tests alone does not validate document links.
16
17
  Check documented defaults, allowed inputs, and examples against the implementation and accepted requirements. Exercise the examples and boundary values covered by a claim; correct contradictions before finishing.
18
+ Distinguish the accepted contract from observed behavior on a particular runtime. Before claiming that an input cannot work based on an implementation detail, probe a relevant counterexample or state that the restriction is unverified.
19
+ Describe values at the boundary actually checked: producing text does not establish its encoded bytes or downstream behavior.
20
+ Name the verification command actually run and what it establishes. Artifact validation, installation health, test execution, and assertion review check different things; do not substitute one result for another.
17
21
  For unspecified inputs or unverified behavior, state the limit instead of promising an outcome.
22
+ Ground motivation and problem claims in the request, inspected project sources, or observed results. Mark an unverified hypothesis explicitly; do not turn plausible background knowledge into an observed project problem.
23
+ Before using universal claims such as "never starts with", "exactly one", or "no marker", check supported caller content that could already contain the character or pattern. Describe what the operation adds or changes separately from content it must preserve. A downstream benefit inferred from technical background remains a hypothesis unless inspected evidence supports it; the request for an option is sufficient motivation on its own.
24
+ When a request only asks for an option or capability, that request is sufficient motivation. Do not attribute consumer failures, business needs, or other inferred reasons to the requester. Label relevant technical background as unverified context rather than as a reported project defect or the requester's stated reason.
18
25
  Review clarity and brevity before finishing; do not impose a fixed word limit.
26
+ Before requesting a decision on a proposal, Decision Record, PR, or handoff, check that an unfamiliar reader can understand the problem, user-visible change, scope boundaries, and decision needed without the conversation or implementation code. Remove repeated detail and use descriptive links to supporting specs. Preserve required artifact sections, requirements, acceptance criteria, and important exceptions. Follow existing diagram settings; use a diagram with a short explanation when clearer, without requiring one or repeating each step in prose. This is agent review, not automatic proof of readability.
@@ -0,0 +1,19 @@
1
+ ---
2
+ type: learning
3
+ status: tentative
4
+ scope: []
5
+ lastVerified: null
6
+ ---
7
+ # <Lesson title>
8
+
9
+ ## Situation and observation
10
+
11
+ <!-- State the reusable mistake or finding and its scope, not a session transcript. -->
12
+
13
+ ## Evidence and correction
14
+
15
+ <!-- Link inspected sources or observations, explain the correction, and state limits. -->
16
+
17
+ ## Maintenance
18
+
19
+ <!-- Verify before marking verified and recording lastVerified as YYYY-MM-DD. Retire obsolete or duplicate guidance in place with a reason and replacement link. Current specs and accepted decisions remain authoritative. -->
@@ -1,5 +1,5 @@
1
1
  Implement tasks and maintain relevant documents. ${testingApproach} Follow testing.placement (default per-task): run each implementation task's relevant tests and fix failures before moving on.
2
- Only end-of-change explicitly defers tests to the final verification section.
2
+ End-of-change defers the automated suite to final verification; still perform a suitable check for each task before proceeding.
3
3
  Final regression and revision-bound evidence collection still follow implementation in either mode.
4
4
  With evidence enabled, run project tests and cliewen-openspec check --change <name> before archive.
5
5
  With the Node reference adapter, collect using node node_modules/cliewen-openspec/adapters/node-test.mjs --change <name> <test files> to scope results while preserving the full runner exit code. Pass the same change to check. After archive, commit and recollect without the adapter's --change before checking permanent specs.
@@ -8,3 +8,4 @@ After collection, any later commit, including documentation-only or metadata cha
8
8
  Archive requires its own authorization; do not infer it from implementation approval or a passing check.
9
9
  A successful traceability check does not establish assertion quality.
10
10
  Never mark missing or stale evidence as passed.
11
+ Before and after native OpenSpec archive, read .cliewen-openspec/closure.md and apply its outcome-appropriate guidance and existing feature settings.
@@ -1,8 +1,8 @@
1
1
  Use - [ ] numbered tasks, each with a completion check. ${testingApproach} Read testing.placement from config; the default is per-task.
2
- In per-task mode, every implementation task must include its own relevant tests, test command and completion check: complete a small slice in the configured testing.approach order, run its tests, fix failures, then proceed to the next task.
2
+ In per-task mode, every implementation task must include its own relevant tests, test command and completion check: complete a small slice with planned acceptance cases and actual verification, run its tests, fix failures, then proceed to the next task.
3
3
  Do not defer these tests to a final testing phase.
4
4
  Documentation-only tasks may use an appropriate validation check instead.
5
- In end-of-change mode, group implementation tests in a final verification section with explicit task-to-test links.
5
+ In end-of-change mode, group the automated suite in a final verification section with explicit task-to-test links; each task still needs a suitable completion check before continuing.
6
6
  Include relevant documentation with each task.
7
7
  Identify the concrete test, its configured type, and the verification boundary for each implementation task. With the Node adapter, tag mapped test titles with one AC ID and one [Test-type: NAME] tag matching the scenario. Other adapters must export the declared type as testType.
8
8
  With evidence enabled, name the AC IDs served and record execution outcomes for the tested revision.
@@ -10,3 +10,4 @@ Review whether assertions prove the scenario at the declared boundary, including
10
10
  Separate review is optional.
11
11
  Do not require post-implementation evidence before implementation.
12
12
  Archive is an untracked follow-up.
13
+ After writing tasks and before executing them, retrieve the active change's OpenSpec apply instructions with --json and read their contextFiles. Artifact-generation instructions do not replace apply instructions. If apply is blocked, resolve its prerequisites and retrieve it again before work; retain the response when the project requires instruction records.
@@ -1,17 +1,15 @@
1
1
  # Tasks
2
2
 
3
- ## 1. Implementation
4
-
5
- <!-- Follow testing.approach (default: flexible). With tdd, write each task as one red-green-refactor cycle: run the test first, observe the intended behavior failure, implement until green, then refactor with green tests. Include commands and observed red/green outcomes in completion notes. Follow testing.placement in config (default: per-task). For end-of-change, move tests to a final verification section and link them to each implementation task. -->
3
+ <!-- Use evidence-first verification: plan acceptance cases before implementation, verify each task, assess assertion effectiveness, and maintain tests against accepted requirements. -->
6
4
 
7
- <!-- When tdd is selected, add one fenced yaml cliewen-tasks block with version: 1 and metadata for every numbered checkbox. Declare method, command argument list, explicit tests/implementation file lists, and a reason for each exception. Follow the installed configuration reference. Record start and real runs through the tdd CLI before marking tasks complete. Omit this metadata in flexible mode. -->
5
+ ## 1. Implementation
8
6
 
9
- - [ ] 1.1 Complete one small behavior slice and its relevant tests in the configured testing.approach order; name the AC IDs, run <test command>, fix failures, and update relevant documentation before continuing.
10
- - [ ] 1.2 Complete the next behavior slice and its relevant tests in the configured testing.approach order; name the AC IDs, run <test command>, and fix failures before continuing.
7
+ - [ ] 1.1 Complete one small behavior slice and its relevant tests with evidence-first verification; name the AC IDs, run <test command>, fix failures, and update relevant documentation before continuing.
8
+ - [ ] 1.2 Complete the next behavior slice and its relevant tests with evidence-first verification; name the AC IDs, run <test command>, and fix failures before continuing.
11
9
 
12
10
  ## 2. Final verification
13
11
 
14
- - [ ] 2.1 Finish documentation and result notes, run the final regression command, and review assertion quality. In TDD mode, record this task's actual regression or documentation check with a justified verification method. This supplements each task's tests.
12
+ - [ ] 2.1 Finish documentation and result notes, run the final regression command, and review assertion quality. This supplements each task's tests.
15
13
 
16
14
  ## Workflow follow-up
17
15
 
@@ -3,3 +3,4 @@ Review sources, actual experiment observations, unresolved uncertainty, recommen
3
3
  It is valid to end with no code change. If delivery is agreed, create a separate cliewen-delivery change and link the investigation and decision.
4
4
  Before archive, preserve useful durable knowledge and resolve any temporary experiment cleanup. Use OpenSpec archive with --skip-specs after human review when no product spec deltas are intended.
5
5
  Cliewen check --change on a discovery change checks installation and registry health only and reports discovery-review-required; it does not validate investigation completeness or product test evidence.
6
+ Before and after native OpenSpec archive, read .cliewen-openspec/closure.md and apply its investigation guidance and existing feature settings.
@@ -6,3 +6,4 @@ Check that the measuring method actually observes the claimed quantity before us
6
6
  Distinguish peak memory from retained memory after garbage collection. If a measurement is invalid, report that quantity as unmeasured and revise conclusions that depended on it; an approximate label does not make it valid.
7
7
  Keep experiments isolated and respect the proposal's limits. Obtain agreement before production changes, purchases, or external actions outside the authorized investigation.
8
8
  Discovery evidence supports a recommendation, not claims about unimplemented product behavior. Preserve existing AC identities and product specs.
9
+ For an agreed prototype, read .cliewen-openspec/prototyping.md, work inside the proposal's experimental limits, and retain actual observations, feedback, uncertainty, and code disposition in this investigation. Neither a useful result nor a prototype request authorizes production implementation.
package/dist/tdd.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import type { Finding } from './core.js';
2
- export declare function startTask(root: string, change: string, id: string): void;
3
- export declare function runTask(root: string, change: string, id: string, phase: string, command: string[], reason?: string): {
4
- exitCode: number;
5
- stdout: string;
6
- stderr: string;
7
- };
8
- export declare function checkTdd(root: string, change?: string): Finding[];
package/dist/tdd.js DELETED
@@ -1,276 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { createHash } from 'node:crypto';
4
- import { spawnSync } from 'node:child_process';
5
- import { isDeepStrictEqual } from 'node:util';
6
- import { parse } from 'yaml';
7
- import { local } from './core.js';
8
- const digest = (value) => createHash('sha256').update(value).digest('hex');
9
- const name = (change) => { if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(change))
10
- throw Error('Change must be a kebab-case name'); return change; };
11
- const historyPath = (root, change) => local(root, `.cliewen-openspec/tdd/${name(change)}.jsonl`);
12
- const definition = ({ done, ...task }) => digest(JSON.stringify(task));
13
- function object(value) { return !!value && typeof value === 'object' && !Array.isArray(value); }
14
- function only(value, allowed) {
15
- for (const key of Object.keys(value))
16
- if (!allowed.includes(key))
17
- throw Error(`Unknown task metadata key: ${key}`);
18
- }
19
- function tasks(root, change) {
20
- const source = fs.readFileSync(local(root, `openspec/changes/${name(change)}/tasks.md`), 'utf8');
21
- const blocks = [...source.matchAll(/^```yaml cliewen-tasks\r?\n([\s\S]*?)^```\s*$/gm)];
22
- if (blocks.length !== 1)
23
- throw Error('tasks.md requires exactly one fenced yaml cliewen-tasks block');
24
- const metadata = parse(blocks[0][1]);
25
- if (!object(metadata) || metadata.version !== 1 || !object(metadata.tasks))
26
- throw Error('Expected version: 1 and a tasks mapping');
27
- only(metadata, ['version', 'tasks']);
28
- // OpenSpec owns checkbox syntax. Ignore examples inside code fences and comments.
29
- let fence = '';
30
- const rows = [];
31
- for (const line of source.replace(/<!--[\s\S]*?-->/g, '').split(/\r?\n/)) {
32
- const boundary = line.match(/^\s*(`{3,}|~{3,})/);
33
- if (boundary) {
34
- if (!fence)
35
- fence = boundary[1];
36
- else if (boundary[1][0] === fence[0] && boundary[1].length >= fence.length)
37
- fence = '';
38
- continue;
39
- }
40
- if (fence)
41
- continue;
42
- const checkbox = line.match(/^\s*- \[([ xX])\]\s+(.+)$/);
43
- if (!checkbox)
44
- continue;
45
- const label = checkbox[2].match(/^(\d+(?:\.\d+)+)\s+(.+)$/);
46
- if (!label || rows.some(row => row.id === label[1]))
47
- throw Error('Each task needs a unique numeric ID such as 1.1');
48
- rows.push({ id: label[1], done: checkbox[1].toLowerCase() === 'x', description: label[2] });
49
- }
50
- if (!rows.length)
51
- throw Error('No numbered tasks found');
52
- if (Object.keys(metadata.tasks).some(id => !rows.some(row => row.id === id)))
53
- throw Error('Metadata references an unknown task');
54
- return rows.map(row => {
55
- const entry = metadata.tasks[row.id];
56
- if (!object(entry))
57
- throw Error(`Missing metadata for task ${row.id}`);
58
- only(entry, ['method', 'command', 'tests', 'implementation', 'reason']);
59
- if (!['tdd', 'characterization', 'refactor', 'verification'].includes(entry.method))
60
- throw Error(`Invalid method for task ${row.id}`);
61
- if (!Array.isArray(entry.command) || !entry.command.length || entry.command.some((arg) => typeof arg !== 'string' || !arg.length))
62
- throw Error(`Task ${row.id} needs a command argument list`);
63
- for (const key of ['tests', 'implementation']) {
64
- if (!Array.isArray(entry[key]) || entry[key].some((file) => typeof file !== 'string' || !file.length))
65
- throw Error(`Task ${row.id} needs a ${key} file list`);
66
- entry[key] = entry[key].map((file) => {
67
- const canonical = path.relative(path.resolve(root), local(root, file)).split(path.sep).join('/');
68
- return canonical;
69
- });
70
- }
71
- const files = [...entry.tests, ...entry.implementation];
72
- const resolved = files.map(file => {
73
- const full = local(root, file);
74
- return process.platform === 'win32' ? full.toLowerCase() : full;
75
- });
76
- if (!files.length || new Set(resolved).size !== files.length)
77
- throw Error(`Task ${row.id} needs distinct test and implementation file paths`);
78
- if (files.some(file => /^(?:\.git|\.cliewen-openspec\/tdd)(?:[\\/]|$)/.test(file.replaceAll('\\', '/'))))
79
- throw Error('History and Git internals cannot be task inputs');
80
- if (entry.method !== 'verification' && !entry.tests.length)
81
- throw Error(`Task ${row.id} requires test files`);
82
- if (entry.method === 'tdd' && !entry.implementation.length)
83
- throw Error(`Task ${row.id} requires implementation files`);
84
- if (entry.reason !== undefined && (typeof entry.reason !== 'string' || !entry.reason.trim()))
85
- throw Error(`Invalid reason for task ${row.id}`);
86
- if (entry.method !== 'tdd' && !entry.reason?.trim())
87
- throw Error(`Task ${row.id} requires a reason for departing from the red-green cycle`);
88
- return { ...row, method: entry.method, command: entry.command, tests: entry.tests, implementation: entry.implementation, ...(entry.reason ? { reason: entry.reason } : {}) };
89
- });
90
- }
91
- function snapshot(root, task) {
92
- return Object.fromEntries([...task.tests, ...task.implementation].map(file => {
93
- const full = local(root, file);
94
- return [file, fs.existsSync(full) ? digest(fs.readFileSync(full)) : null];
95
- }));
96
- }
97
- function history(root, change) {
98
- const file = historyPath(root, change);
99
- if (!fs.existsSync(file))
100
- return [];
101
- return fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).map(line => {
102
- const entry = JSON.parse(line);
103
- if (!object(entry) || entry.version !== 1 || entry.change !== change || typeof entry.task !== 'string' || typeof entry.definition !== 'string' || !['start', 'red', 'green', 'baseline', 'verify'].includes(entry.phase) || !object(entry.before) || !object(entry.after) || typeof entry.time !== 'string' || !Number.isFinite(Date.parse(entry.time)))
104
- throw Error('Invalid history event');
105
- for (const values of [entry.before, entry.after])
106
- if (Object.values(values).some(value => value !== null && (typeof value !== 'string' || !/^[a-f0-9]{64}$/.test(value))))
107
- throw Error('Invalid history file hash');
108
- if (entry.phase !== 'start' && (!Array.isArray(entry.command) || !entry.command.length || entry.command.some((arg) => typeof arg !== 'string') || !Number.isInteger(entry.exitCode) || entry.exitCode < 0 || typeof entry.stdout !== 'string' || typeof entry.stderr !== 'string'))
109
- throw Error('Invalid recorded command result');
110
- return entry;
111
- });
112
- }
113
- function locked(root, change, action) {
114
- const file = historyPath(root, change);
115
- fs.mkdirSync(path.dirname(file), { recursive: true });
116
- const lock = local(root, `.cliewen-openspec/tdd/${change}.lock`);
117
- let handle;
118
- try {
119
- handle = fs.openSync(lock, 'wx');
120
- }
121
- catch {
122
- throw Error(`TDD recorder is locked for ${change}; check for a running command before removing ${lock}`);
123
- }
124
- try {
125
- return action();
126
- }
127
- finally {
128
- fs.closeSync(handle);
129
- fs.unlinkSync(lock);
130
- }
131
- }
132
- function taskFor(root, change, id) {
133
- const task = tasks(root, change).find(task => task.id === id);
134
- if (!task)
135
- throw Error(`Unknown task: ${id}`);
136
- return task;
137
- }
138
- function append(root, change, entry) { fs.appendFileSync(historyPath(root, change), JSON.stringify(entry) + '\n'); }
139
- export function startTask(root, change, id) {
140
- const task = taskFor(root, change, id);
141
- locked(root, change, () => {
142
- history(root, change);
143
- const current = snapshot(root, task);
144
- append(root, change, { version: 1, change, task: id, definition: definition(task), phase: 'start', time: new Date().toISOString(), before: current, after: current });
145
- });
146
- }
147
- export function runTask(root, change, id, phase, command, reason) {
148
- if (!['red', 'green', 'baseline', 'verify'].includes(phase))
149
- throw Error('Phase must be red, green, baseline, or verify');
150
- const task = taskFor(root, change, id);
151
- if (!isDeepStrictEqual(command, task.command))
152
- throw Error('Command must match the task metadata command argument list');
153
- if (phase === 'red' && !reason?.trim())
154
- throw Error('A red run requires --reason describing the intended missing behavior; review the actual failure');
155
- return locked(root, change, () => {
156
- const events = history(root, change);
157
- if (!events.some(event => event.task === id && event.phase === 'start' && event.definition === definition(task)))
158
- throw Error('Run tdd start for the current task definition first');
159
- const before = snapshot(root, task);
160
- const env = { ...process.env };
161
- delete env.NODE_TEST_CONTEXT;
162
- const result = spawnSync(command[0], command.slice(1), { cwd: root, env, encoding: 'utf8', maxBuffer: 10 * 1024 * 1024, windowsHide: true });
163
- // Failed launches and terminated processes cannot establish a test outcome.
164
- if (result.error || result.status === null)
165
- throw Error(`Cannot record test execution: ${result.error?.message ?? result.signal}`);
166
- const entry = { version: 1, change, task: id, definition: definition(task), phase: phase, time: new Date().toISOString(), before, after: snapshot(root, task), command, exitCode: result.status, stdout: result.stdout, stderr: result.stderr, ...(reason ? { reason } : {}) };
167
- append(root, change, entry);
168
- return { exitCode: result.status, stdout: result.stdout, stderr: result.stderr };
169
- });
170
- }
171
- function equalFiles(a, b, files) { return files.every(file => Object.hasOwn(a, file) && Object.hasOwn(b, file) && a[file] === b[file]); }
172
- function validSequence(task, events) {
173
- const first = events[0];
174
- const last = events.at(-1);
175
- if (!first || first.phase !== 'start' || !last || events.length < 2)
176
- return false;
177
- const files = [...task.tests, ...task.implementation];
178
- if (events.some(event => event.definition !== definition(task) || !isDeepStrictEqual(Object.keys(event.before).sort(), [...files].sort()) || !isDeepStrictEqual(Object.keys(event.after).sort(), [...files].sort()) || !equalFiles(event.before, event.after, files)))
179
- return false;
180
- if (events.slice(1).some(event => !isDeepStrictEqual(event.command, task.command)))
181
- return false;
182
- if (task.method === 'verification')
183
- return last.exitCode === 0 && events.slice(1).every(event => event.phase === 'verify');
184
- const second = events[1];
185
- if (task.method === 'tdd') {
186
- if (second.phase !== 'red' || !second.exitCode || !second.reason?.trim() || equalFiles(first.before, second.before, task.tests) || !equalFiles(first.before, second.before, task.implementation))
187
- return false;
188
- if (last.phase !== 'green' || last.exitCode !== 0 || equalFiles(second.after, last.after, task.implementation))
189
- return false;
190
- return events.slice(2).every(event => event.phase === 'green' && equalFiles(second.after, event.before, task.tests));
191
- }
192
- if (second.phase !== 'baseline' || second.exitCode !== 0 || !equalFiles(first.before, second.before, task.implementation))
193
- return false;
194
- if (task.method === 'refactor' && !equalFiles(first.before, second.before, task.tests))
195
- return false;
196
- return events.length >= 3 && last.phase === 'green' && last.exitCode === 0 && events.slice(2).every(event => event.phase === 'green' && equalFiles(second.after, event.before, task.tests));
197
- }
198
- export function checkTdd(root, change) {
199
- const findings = [];
200
- const add = (code, message, severity = 'error') => findings.push({ code, message, severity });
201
- if (!change) {
202
- add('tdd-change-required', 'Use --change NAME to assess task completion history. Permanent-spec checks do not assess TDD ordering.', 'warning');
203
- return findings;
204
- }
205
- let planned;
206
- try {
207
- planned = tasks(root, change);
208
- }
209
- catch (error) {
210
- add('tdd-task-metadata-invalid', String(error));
211
- return findings;
212
- }
213
- let recorded;
214
- try {
215
- recorded = history(root, change);
216
- }
217
- catch (error) {
218
- add('tdd-history-invalid', String(error));
219
- return findings;
220
- }
221
- if (fs.existsSync(local(root, `.cliewen-openspec/tdd/${name(change)}.lock`)))
222
- add('tdd-recording-in-progress', 'A recorder lock remains; do not assess completion while a command may still be running');
223
- const currentCycles = new Set();
224
- for (const task of planned) {
225
- if (!task.done)
226
- add('tdd-task-incomplete', `${task.id}: task remains unchecked`);
227
- const events = recorded.filter(event => event.task === task.id);
228
- let start = -1;
229
- for (let i = events.length - 1; i >= 0; i--)
230
- if (events[i].phase === 'start') {
231
- start = i;
232
- break;
233
- }
234
- if (start < 0) {
235
- add('tdd-history-missing', `${task.id}: no recorded start and execution history`);
236
- continue;
237
- }
238
- const cycle = events.slice(start);
239
- for (const event of cycle)
240
- currentCycles.add(event);
241
- try {
242
- if (cycle.some(event => event.definition !== definition(task))) {
243
- add('tdd-history-stale', `${task.id}: task definition changed after recording`);
244
- continue;
245
- }
246
- if (!validSequence(task, cycle))
247
- add('tdd-sequence-invalid', `${task.id}: recorded ${task.method} sequence is incomplete or out of order`);
248
- }
249
- catch (error) {
250
- add('tdd-history-invalid', `${task.id}: ${String(error)}`);
251
- }
252
- }
253
- // Later tasks may legitimately edit files verified by earlier tasks. Check
254
- // continuity at task starts and compare the final recorded state per file.
255
- const latest = {};
256
- for (const event of recorded.filter(event => currentCycles.has(event))) {
257
- if (event.phase === 'start')
258
- for (const [file, value] of Object.entries(event.before)) {
259
- if (Object.hasOwn(latest, file) && latest[file] !== value)
260
- add('tdd-sequence-invalid', `${event.task}: ${file} changed between recorded task cycles`);
261
- }
262
- Object.assign(latest, event.after);
263
- }
264
- for (const task of planned) {
265
- try {
266
- for (const [file, value] of Object.entries(snapshot(root, task)))
267
- if (Object.hasOwn(latest, file) && latest[file] !== value)
268
- add('tdd-history-stale', `${file}: changed after its last recorded run`);
269
- }
270
- catch (error) {
271
- add('tdd-history-invalid', String(error));
272
- }
273
- }
274
- add('tdd-review-required', 'Recorded commands and declared file hashes do not prove assertion quality, failure cause, complete file coverage, or exception suitability. Review the task plan and captured output; local history is not tamper-proof.', 'info');
275
- return findings;
276
- }