cliewen-openspec 0.0.0-stage → 0.1.0-alpha.1

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 (56) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/LICENSE +21 -0
  3. package/README.md +103 -2
  4. package/adapters/node-test.mjs +48 -0
  5. package/dist/ac.d.ts +16 -0
  6. package/dist/ac.js +124 -0
  7. package/dist/all.d.ts +1 -0
  8. package/dist/all.js +28 -0
  9. package/dist/cli.d.ts +2 -0
  10. package/dist/cli.js +105 -0
  11. package/dist/core.d.ts +48 -0
  12. package/dist/core.js +617 -0
  13. package/dist/delivery.d.ts +1 -0
  14. package/dist/delivery.js +21 -0
  15. package/dist/discovery.d.ts +1 -0
  16. package/dist/discovery.js +15 -0
  17. package/dist/schema-source.d.ts +3 -0
  18. package/dist/schema-source.js +9 -0
  19. package/dist/tdd.d.ts +8 -0
  20. package/dist/tdd.js +276 -0
  21. package/docs/configuration.md +265 -0
  22. package/docs/testing/evidence.md +86 -0
  23. package/docs/testing/pilot-prompt.md +20 -0
  24. package/package.json +59 -4
  25. package/schemas/README.md +25 -0
  26. package/schemas/all/instructions/apply.md +4 -0
  27. package/schemas/all/instructions/approval.md +4 -0
  28. package/schemas/all/instructions/decision.md +7 -0
  29. package/schemas/all/instructions/investigation.md +1 -0
  30. package/schemas/all/instructions/proposal.md +3 -0
  31. package/schemas/all/instructions/specs.md +2 -0
  32. package/schemas/all/instructions/tasks.md +2 -0
  33. package/schemas/all/templates/decision.md +20 -0
  34. package/schemas/all/templates/proposal.md +19 -0
  35. package/schemas/all/templates/tasks.md +13 -0
  36. package/schemas/base/instructions/diagrams.md +7 -0
  37. package/schemas/base/instructions/routing.md +4 -0
  38. package/schemas/base/instructions/testing-approach.md +13 -0
  39. package/schemas/base/instructions/writing.md +18 -0
  40. package/schemas/base/templates/decision.md +18 -0
  41. package/schemas/delivery/instructions/apply.md +10 -0
  42. package/schemas/delivery/instructions/design.md +9 -0
  43. package/schemas/delivery/instructions/proposal.md +3 -0
  44. package/schemas/delivery/instructions/specs.md +11 -0
  45. package/schemas/delivery/instructions/tasks.md +12 -0
  46. package/schemas/delivery/templates/design.md +9 -0
  47. package/schemas/delivery/templates/proposal.md +13 -0
  48. package/schemas/delivery/templates/spec.md +13 -0
  49. package/schemas/delivery/templates/tasks.md +19 -0
  50. package/schemas/discovery/instructions/apply.md +5 -0
  51. package/schemas/discovery/instructions/decision.md +7 -0
  52. package/schemas/discovery/instructions/investigation.md +8 -0
  53. package/schemas/discovery/instructions/proposal.md +4 -0
  54. package/schemas/discovery/templates/decision.md +17 -0
  55. package/schemas/discovery/templates/investigation.md +11 -0
  56. package/schemas/discovery/templates/proposal.md +9 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,55 @@
1
+ # Changelog
2
+
3
+ Changes that matter to projects using Cliewen for OpenSpec.
4
+
5
+ ## 0.1 (unreleased)
6
+
7
+ This first release is under development. The current package version is `0.1.0-alpha.1`; it has not been published to npm. To try it, follow the [local installation guide](docs/guide/getting-started.md).
8
+
9
+ ### OpenSpec workflows
10
+
11
+ Choose from three schemas, which define the documents and instructions for a change:
12
+
13
+ - `cliewen-delivery` takes an understood change through a proposal, behavior specifications, design, implementation tasks, and verification.
14
+ - `cliewen-discovery` helps investigate a question and recommend what to do next. The recommendation can be to make no change.
15
+ - `cliewen-all` combines investigation and delivery. It calls for human agreement before implementation and also supports ending an investigation without changing the product.
16
+
17
+ All three include guidance for maintaining documentation, recording durable decisions, writing clearly, and using diagrams where helpful. OpenSpec manages the change files and incorporates completed changes into the project's specifications when they are archived.
18
+
19
+ ### Installation and project settings
20
+
21
+ - `init` installs the schemas and supporting resources. Preview changes before writing files, and keep your existing default schema unless you explicitly select a replacement.
22
+ - `update` refreshes resources installed by Cliewen. It preserves project settings and authored documents, and stops if local edits conflict with the update. Updates support recognized alpha installations; general version migrations are not available yet.
23
+ - `uninstall` removes unchanged resources installed by Cliewen while preserving project documents and data. Resolve active changes using those schemas first, and select a replacement if removing the default schema. Removing the npm package is a separate step.
24
+ - Installation commands support previews and recovery after interrupted writes. Path checks keep managed files inside the project, and file comparisons tolerate Windows line-ending conversion.
25
+ - Project settings let you choose the documentation directory, test workflow, and evidence report location. You can turn individual facilities on or off without deleting authored documents.
26
+
27
+ See the [configuration reference](docs/configuration.md) and [CLI guide](docs/guide/cli.md) for defaults and commands.
28
+
29
+ ### Acceptance criteria and tests
30
+
31
+ - Give behavior scenarios stable acceptance criterion IDs so specifications, tests, and results can refer to the same requirement. Choose a prefix for each capability, such as `EXP-001` for an export feature. Allocate IDs and rename prefixes without reusing reserved numbers or losing historical references.
32
+ - Use the default Unit, Integration, and E2E test types, or define your own. Checks require the type declared by a scenario to match its test results.
33
+ - Test each implementation task as you go, or configure testing at the end of a change. The default allows tests before or after code.
34
+ - Optionally select test-driven development (TDD). The `tdd start` and `tdd run` commands record test commands, outcomes, and snapshots of declared files. Completion checks reject missing, stale, or inconsistent records. Tasks using another verification method need a reason.
35
+
36
+ ### Test results before archive
37
+
38
+ The Node test adapter runs tagged tests and records which scenarios they cover, whether they passed, and the Git revision tested. You can collect results for one change while retaining the exit status of the entire test run, so failures elsewhere in that run remain visible.
39
+
40
+ Before archive, `check` reports missing or duplicate references, mismatched test types, failed or skipped tests, pending work, and manual verification. It also checks that results belong to the current committed revision and that the working tree is clean. A later commit requires fresh results, including when only documentation changed.
41
+
42
+ See the [evidence guide](docs/testing/evidence.md) for collection commands and help resolving findings.
43
+
44
+ ### Guide and examples
45
+
46
+ The [user guide](docs/guide/index.md) covers installation, schema selection, existing projects, configuration, and troubleshooting. A worked CSV example takes a change through implementation, test results, and archive. The documentation site includes search, light and dark appearance, and diagrams.
47
+
48
+ ### Current limitations
49
+
50
+ - Passing checks establish test execution, references, and revision freshness. You still need to review whether the assertions prove the intended behavior. Configurable case coverage and test lifecycle checks are not implemented.
51
+ - TDD records check the declared command and file history. They cannot prove why a test failed, prevent every code write, or authenticate the recorded history. Ordinary task-by-task testing remains agent guidance.
52
+ - Discovery findings and combined-workflow approval fields require review. A recorded status cannot prove that a person approved the change.
53
+ - Documentation and diagram guidance does not validate your project's document metadata or diagram syntax.
54
+ - Acceptance ID allocation supports sequential work. Parallel branches may allocate the same number and need conflict resolution.
55
+ - Release validation across the supported coding agents is still incomplete. Treat the package as an alpha; review its output before relying on it.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flemming N. Larsen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # Cliewen for OpenSpec
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Durable decisions, living documentation, and evidence for OpenSpec.
4
+
5
+ **Alpha implementation.** Installs `cliewen-delivery`, `cliewen-discovery`, and `cliewen-all`, allocates acceptance IDs, and checks real delivery test evidence through OpenSpec archiving. Discovery supports investigation and recommendation without required production implementation. No npm release is published yet.
6
+
7
+ ## Schema collection
8
+
9
+ - **cliewen-delivery** — recommended workflow for understood changes.
10
+ - **cliewen-discovery** — investigation, alternatives and decision handoff.
11
+ - **cliewen-all** — combined discovery and delivery, with explicit no-delivery closure.
12
+
13
+ `cliewen-base` names the internal shared foundation used to build these bundles. It is not a separately selectable schema. Discovery remains the workflow for investigation and decision-making.
14
+
15
+ The shared design covers documentation, Decision Records, Mermaid, optional plans and evidence. Evidence is enabled by default. See the [discovery guide](docs/guide/discovery.md) for investigation, a no-change outcome, and delivery handoff. This alpha supplies documentation/DR guidance; structural metadata and Mermaid validators remain planned.
16
+
17
+ Use [the combined workflow](docs/guide/all.md) to investigate and deliver in one change, with a proposed decision and human approval before implementation. Its no-delivery branch uses native `skip_specs`, without fake product requirements.
18
+
19
+ ## Try the alpha locally
20
+
21
+ Requires Node.js 20.19 or newer and Git. The integration test uses OpenSpec 1.15.0. Windows and Linux CI exercise Node 22 and 24.
22
+
23
+ In this repository:
24
+
25
+ ```sh
26
+ npm ci
27
+ npm test
28
+ npm pack
29
+ ```
30
+
31
+ In a separate project, initialize OpenSpec and install the resulting tarball:
32
+
33
+ ```sh
34
+ npm install --save-dev @fission-ai/openspec@1.15.0
35
+ npx --no-install openspec init
36
+ npm install --save-dev /path/to/cliewen-openspec-0.1.0-alpha.1.tgz
37
+ npx --no-install cliewen-openspec init --default
38
+ npx --no-install openspec new change add-export --schema cliewen-delivery
39
+ ```
40
+
41
+ Register the capability in `.cliewen-openspec/config.yaml`:
42
+
43
+ ```yaml
44
+ ac:
45
+ padding: 3
46
+ capabilities:
47
+ export: EXPORT
48
+ ```
49
+
50
+ Then allocate its first ID:
51
+
52
+ ```sh
53
+ npx --no-install cliewen-openspec ac next --capability export
54
+ ```
55
+
56
+ `--default` explicitly selects delivery for future changes. Omit it to preserve the existing schema. `init --dry-run` previews writes. Use the generated ID in scenario headings and test titles; commit the ID registry along with specs.
57
+
58
+ For an existing installation, install the new tarball and use `cliewen-openspec update --dry-run --json`, then `cliewen-openspec update --json` after reviewing the plan. Update refreshes owned resources from supported manifests, preserving configuration, selected schemas, IDs, and authored files. See [updating an installation](docs/guide/updating.md).
59
+
60
+ Configure capability-specific AC prefixes and number padding, and choose test placement in `.cliewen-openspec/config.yaml`. Testing each implementation task before moving on is the default. Use `ac rename-prefix` to change an established prefix without resetting its sequence. See [project configuration](docs/configuration.md) for examples and prefix selection.
61
+
62
+ Optionally set `testing.approach: tdd` with `testing.placement: per-task` to plan red-green-refactor within every implementation task. The default `flexible` approach allows tests before or after code within the selected placement.
63
+
64
+ After implementation, commit the project inputs and collect evidence from Node tests:
65
+
66
+ ```sh
67
+ node node_modules/cliewen-openspec/adapters/node-test.mjs test/export.test.mjs
68
+ npx --no-install cliewen-openspec check --change add-export --json
69
+ ```
70
+
71
+ After reviewing the assertions and evidence, archive with OpenSpec. Commit the archived state, regenerate evidence and check permanent specs. See [the evidence guide](docs/testing/evidence.md) for outcomes, pending/manual verification and current limitations.
72
+
73
+ `npm test` includes an end-to-end example which installs the packed tarball in a temporary repository, creates a real OpenSpec change, runs tagged tests, verifies failure cases, archives the change and checks that the AC ID survives. It cleans up its temporary repository afterward.
74
+
75
+ ## Project documents
76
+
77
+ - [User guide source](docs/guide/index.md) and [published documentation](https://flemming-n-larsen.github.io/cliewen-openspec/)
78
+ - [Decisions](docs/decisions/README.md)
79
+ - [Changelog](CHANGELOG.md)
80
+ - [Project configuration](docs/configuration.md)
81
+ - [Pilot reference prompt](docs/testing/pilot-prompt.md)
82
+ - [Implementation plan](plan.md)
83
+ - [Practice mapping](docs/cliewen-mapping.md)
84
+ - [Alpha architecture](docs/architecture/README.md)
85
+ - [Website](https://flemming-n-larsen.github.io/cliewen-openspec/)
86
+ - [Credits](CREDITS.md)
87
+
88
+ Implemented commands: `init`, `update`, `uninstall`, `ac next`, `ac rename-prefix`, `check` and `recover`. Review generated/resource changes before applying them. [Uninstall](docs/guide/uninstalling.md) preserves project data and requires an explicit replacement when removing the selected default. Tests never establish assertion quality automatically.
89
+
90
+ ## Development checks
91
+
92
+ `npm test` builds TypeScript and runs unit and packed-installation integration tests. GitHub Actions runs the same suite on Windows and Linux with Node 22 and 24. These checks cover the alpha implementation; documentation semantic accuracy and assertion sufficiency still require review.
93
+
94
+ For actual agent trials, use the [CLI evaluation guide](docs/testing/cli-evaluation.md). `npm run trial:cli:prepare` creates matching projects for three pinned CLI profiles; `npm run trial:cli -- SUITE PROFILE SCHEMA` explicitly launches one case and saves raw logs. These commands use local agent authentication and may incur usage charges. CI uses fake CLIs and makes no model calls.
95
+
96
+ Build the documentation with `npm run docs:build` and preview it with `npm run docs:serve`. For browser checks, install Chromium with `npx playwright install chromium`, then run `npm run docs:check`. Documentation tooling uses Node 22.12+ (Node 22 or 24 recommended). See [documentation development](docs/guide/development.md).
97
+
98
+ ## Feedback
99
+
100
+ [Report a bug](https://github.com/flemming-n-larsen/cliewen-openspec/issues/new?template=bug_report.yml) or [suggest an improvement](https://github.com/flemming-n-larsen/cliewen-openspec/issues/new?template=idea.yml). Documentation problems and workflow ideas are welcome. A small example helps us understand the problem; a proposed implementation is optional.
101
+
102
+ ## License
103
+
104
+ [MIT](LICENSE).
@@ -0,0 +1,48 @@
1
+ #!/usr/bin/env node
2
+ // Reference adapter: run repository-owned Node tests tagged [PREFIX-001].
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { spawnSync, execFileSync } from 'node:child_process';
6
+ import { config, local, scenarios } from '../dist/core.js';
7
+ const git = (...args) => execFileSync('git', args, { encoding: 'utf8' }).trim();
8
+ try {
9
+ if (git('status', '--porcelain', '--untracked-files=all')) throw Error('Commit project inputs before collecting evidence.');
10
+ const revision = git('rev-parse', 'HEAD');
11
+ const settings = config(process.cwd());
12
+ const output = local(process.cwd(), settings.evidence.report);
13
+ const ignored = spawnSync('git', ['check-ignore', '-q', '--', output]);
14
+ if (ignored.status !== 0) throw Error('Evidence output must be Git-ignored and untracked before collecting results.');
15
+ // A failed/crashed new run must never leave an earlier passing report usable.
16
+ if (fs.existsSync(output)) fs.unlinkSync(output);
17
+ const files = [];
18
+ let change;
19
+ const args = process.argv.slice(2);
20
+ for (let i = 0; i < args.length; i++) {
21
+ if (args[i] === '--change') {
22
+ if (change !== undefined || !args[i + 1] || args[i + 1].startsWith('-')) throw Error('Pass --change NAME once');
23
+ change = args[++i];
24
+ } else if (args[i].startsWith('-')) throw Error(`Unknown adapter option: ${args[i]}`);
25
+ else files.push(args[i]);
26
+ }
27
+ if (!files.length) throw Error('Pass explicit test file paths');
28
+ const selected = change === undefined ? undefined : new Set(scenarios(process.cwd(), change).map(s => s.id));
29
+ if (selected && (!selected.size || selected.has(''))) throw Error('Selected change requires scenarios with AC IDs');
30
+ const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap', ...files], { encoding: 'utf8' });
31
+ if (run.error) throw run.error;
32
+ process.stdout.write(run.stdout ?? ''); process.stderr.write(run.stderr ?? '');
33
+ const results = [];
34
+ for (const line of (run.stdout ?? '').split(/\r?\n/)) {
35
+ const m = line.match(/^\s*(not ok|ok) \d+ - (.*\[([A-Z][A-Z0-9]*-\d+)\].*)$/);
36
+ if (m) {
37
+ const tags = [...m[2].matchAll(/\[Test-type: ([^\]\r\n]+)\]/g)];
38
+ if (tags.length !== 1 || !Object.hasOwn(settings.testing.types, tags[0][1])) throw Error(`Test ${m[2]} requires one configured [Test-type: NAME] tag`);
39
+ if (!selected || selected.has(m[3])) results.push({ scenario: m[3], test: m[2], testType: tags[0][1], outcome: /#\s*(SKIP|TODO)/i.test(m[2]) ? 'skipped' : m[1] === 'ok' ? 'passed' : 'failed' });
40
+ }
41
+ }
42
+ if (git('rev-parse', 'HEAD') !== revision || git('status', '--porcelain', '--untracked-files=all')) throw Error('Test execution changed repository inputs; evidence cannot be attributed to the original revision.');
43
+ if (run.status === null) throw Error('Test runner did not complete; no report produced');
44
+ if (!results.length) throw Error('No AC-tagged test results found for the selected scope; no report produced');
45
+ fs.mkdirSync(path.dirname(output), { recursive: true });
46
+ fs.writeFileSync(output, JSON.stringify({ version: 1, revision, ...(change === undefined ? {} : { scope: { change } }), execution: { exitCode: run.status }, results }, null, 2) + '\n');
47
+ process.exitCode = run.status === 0 ? 0 : 1;
48
+ } catch (e) { console.error(e.message); process.exitCode = 2; }
package/dist/ac.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { type Config } from './core.js';
2
+ type Sequence = {
3
+ prefix: string;
4
+ previousPrefixes: string[];
5
+ highWater: number;
6
+ };
7
+ type Registry = {
8
+ version: 2;
9
+ capabilities: Record<string, Sequence>;
10
+ unassignedPrefixes: Record<string, number>;
11
+ };
12
+ export declare function validateRegistry(root: string, c: Config): Registry;
13
+ export declare function nextId(root: string, capability: string): string;
14
+ export declare function capabilityForPrefix(root: string, prefix: string): string;
15
+ export declare function renamePrefix(root: string, capability: string, prefix: string): void;
16
+ export {};
package/dist/ac.js ADDED
@@ -0,0 +1,124 @@
1
+ import fs from 'node:fs';
2
+ import { parseDocument } from 'yaml';
3
+ import { config, local, markdowns, recover, transaction } from './core.js';
4
+ const registryPath = '.cliewen-openspec/ac-registry.json';
5
+ const configPath = '.cliewen-openspec/config.yaml';
6
+ const validPrefix = (s) => /^[A-Z][A-Z0-9]*$/.test(s);
7
+ const counter = (n) => Number.isSafeInteger(n) && n >= 0;
8
+ const read = (p) => fs.readFileSync(p, 'utf8');
9
+ const json = (o) => JSON.stringify(o, null, 2) + '\n';
10
+ // Read-only validation also prepares legacy prefix counters for adoption.
11
+ export function validateRegistry(root, c) {
12
+ const dest = local(root, registryPath);
13
+ const raw = fs.existsSync(dest) ? JSON.parse(read(dest)) : {};
14
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
15
+ throw Error('Invalid AC registry');
16
+ let r;
17
+ if (!Object.hasOwn(raw, 'version')) {
18
+ if (Object.entries(raw).some(([p, n]) => !validPrefix(p) || !counter(n)))
19
+ throw Error('Invalid legacy AC registry');
20
+ r = { version: 2, capabilities: {}, unassignedPrefixes: { ...raw } };
21
+ for (const [name, prefix] of Object.entries(c.ac.capabilities)) {
22
+ if (Object.hasOwn(r.unassignedPrefixes, prefix)) {
23
+ r.capabilities[name] = { prefix, previousPrefixes: [], highWater: r.unassignedPrefixes[prefix] };
24
+ delete r.unassignedPrefixes[prefix];
25
+ }
26
+ }
27
+ }
28
+ else {
29
+ if (raw.version !== 2)
30
+ throw Error('Unsupported AC registry version');
31
+ for (const map of [raw.capabilities, raw.unassignedPrefixes])
32
+ if (!map || typeof map !== 'object' || Array.isArray(map))
33
+ throw Error('Invalid AC registry mapping');
34
+ r = raw;
35
+ }
36
+ const occupied = new Map();
37
+ for (const [name, record] of Object.entries(r.capabilities)) {
38
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || !record || typeof record.prefix !== 'string' || !validPrefix(record.prefix) || !Array.isArray(record.previousPrefixes) || !counter(record.highWater))
39
+ throw Error('Invalid capability sequence');
40
+ for (const prefix of [record.prefix, ...record.previousPrefixes]) {
41
+ if (typeof prefix !== 'string' || !validPrefix(prefix) || occupied.has(prefix))
42
+ throw Error('Duplicate or invalid reserved AC prefix');
43
+ occupied.set(prefix, name);
44
+ }
45
+ }
46
+ for (const [prefix, n] of Object.entries(r.unassignedPrefixes)) {
47
+ if (!validPrefix(prefix) || !counter(n) || occupied.has(prefix))
48
+ throw Error('Invalid unassigned AC prefix');
49
+ occupied.set(prefix, '(legacy reservation)');
50
+ }
51
+ for (const [name, prefix] of Object.entries(c.ac.capabilities)) {
52
+ if (Object.hasOwn(r.capabilities, name)) {
53
+ if (r.capabilities[name].prefix !== prefix)
54
+ throw Error(`Prefix mismatch for ${name}; restore ${r.capabilities[name].prefix} in config, then use ac rename-prefix ${name} ${prefix}`);
55
+ }
56
+ else {
57
+ if (occupied.has(prefix))
58
+ throw Error(`AC prefix ${prefix} is reserved by ${occupied.get(prefix)}`);
59
+ r.capabilities[name] = { prefix, previousPrefixes: [], highWater: 0 };
60
+ occupied.set(prefix, name);
61
+ }
62
+ }
63
+ return r;
64
+ }
65
+ function maximum(root, record) {
66
+ let max = record.highWater;
67
+ const prefixes = new Set([record.prefix, ...record.previousPrefixes]);
68
+ for (const file of markdowns(local(root, 'openspec'))) {
69
+ for (const m of read(file).matchAll(/\[([A-Z][A-Z0-9]*)-(\d+)\]/g)) {
70
+ if (prefixes.has(m[1]))
71
+ max = Math.max(max, Number(m[2]));
72
+ }
73
+ }
74
+ if (!Number.isSafeInteger(max))
75
+ throw Error('AC sequence exhausted');
76
+ return max;
77
+ }
78
+ export function nextId(root, capability) {
79
+ recover(root);
80
+ const c = config(root), r = validateRegistry(root, c);
81
+ if (!Object.hasOwn(c.ac.capabilities, capability))
82
+ throw Error(`Unknown capability: ${capability}; register it in ac.capabilities first`);
83
+ const record = r.capabilities[capability];
84
+ const next = maximum(root, record) + 1;
85
+ if (!Number.isSafeInteger(next))
86
+ throw Error('AC sequence exhausted');
87
+ record.highWater = next;
88
+ transaction(root, { [registryPath]: json(r) });
89
+ return `${record.prefix}-${String(next).padStart(c.ac.padding, '0')}`;
90
+ }
91
+ export function capabilityForPrefix(root, prefix) {
92
+ const c = config(root), r = validateRegistry(root, c);
93
+ for (const [name, record] of Object.entries(r.capabilities)) {
94
+ if (record.previousPrefixes.includes(prefix))
95
+ throw Error(`Retired prefix ${prefix}; use --capability ${name} (current prefix ${record.prefix})`);
96
+ }
97
+ const entry = Object.entries(c.ac.capabilities).find(([, p]) => p === prefix);
98
+ if (!entry)
99
+ throw Error(`No active capability owns prefix ${prefix}; register ac.capabilities and use --capability NAME`);
100
+ return entry[0];
101
+ }
102
+ export function renamePrefix(root, capability, prefix) {
103
+ recover(root);
104
+ if (!validPrefix(prefix))
105
+ throw Error('Prefix must contain uppercase letters/digits and start with a letter');
106
+ const c = config(root), r = validateRegistry(root, c);
107
+ if (!Object.hasOwn(c.ac.capabilities, capability))
108
+ throw Error(`Unknown capability: ${capability}`);
109
+ const record = r.capabilities[capability];
110
+ if (record.prefix === prefix)
111
+ return;
112
+ if (Object.hasOwn(r.unassignedPrefixes, prefix) || Object.values(r.capabilities).some(v => v.prefix === prefix || v.previousPrefixes.includes(prefix)))
113
+ throw Error(`AC prefix is already reserved: ${prefix}`);
114
+ if (maximum(root, { prefix, previousPrefixes: [], highWater: 0 }) > 0)
115
+ throw Error(`AC prefix already occurs in OpenSpec documents: ${prefix}`);
116
+ record.highWater = maximum(root, record);
117
+ record.previousPrefixes.push(record.prefix);
118
+ record.prefix = prefix;
119
+ const doc = parseDocument(read(local(root, configPath)));
120
+ if (doc.errors.length)
121
+ throw Error(doc.errors[0].message);
122
+ doc.setIn(['ac', 'capabilities', capability], prefix);
123
+ transaction(root, { [configPath]: doc.toString(), [registryPath]: json(r) });
124
+ }
package/dist/all.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function allFiles(): Record<string, string>;
package/dist/all.js ADDED
@@ -0,0 +1,28 @@
1
+ import { stringify } from 'yaml';
2
+ import { template, instruction, routing } from './schema-source.js';
3
+ export function allFiles() {
4
+ const base = 'openspec/schemas/cliewen-all/';
5
+ const testing = instruction('base/instructions/testing-approach.md');
6
+ const approval = instruction('all/instructions/approval.md');
7
+ const artifacts = [
8
+ { id: 'proposal', generates: 'proposal.md', description: 'Question, intent, and limits', template: 'proposal.md', requires: [] },
9
+ { id: 'investigation', generates: 'investigation.md', description: 'Alternatives and observed evidence', template: 'investigation.md', requires: ['proposal'] },
10
+ { id: 'decision', generates: 'decision.md', description: 'Outcome, chosen approach, and approval', template: 'decision.md', requires: ['investigation'] },
11
+ { id: 'specs', generates: 'specs/**/*.md', description: 'Agreed behavior deltas, or native skip_specs', template: 'spec.md', requires: ['decision'] },
12
+ { id: 'tasks', generates: 'tasks.md', description: 'Delivery tasks or genuine closure checks', template: 'tasks.md', requires: ['decision', 'specs'] },
13
+ ].map(artifact => {
14
+ const shared = artifact.id === 'investigation' ? instruction('discovery/instructions/investigation.md')
15
+ : artifact.id === 'specs' ? instruction('delivery/instructions/specs.md')
16
+ : artifact.id === 'tasks' ? instruction('delivery/instructions/tasks.md').replace('${testingApproach}', testing) : '';
17
+ return { ...artifact, instruction: [routing, approval, instruction(`all/instructions/${artifact.id}.md`), shared].filter(Boolean).join(' ') };
18
+ });
19
+ return {
20
+ [base + 'schema.yaml']: stringify({ name: 'cliewen-all', version: 1, description: 'Investigation through delivery or explicit no-delivery closure in one change', artifacts,
21
+ apply: { requires: ['tasks'], tracks: 'tasks.md', instruction: [routing, approval, instruction('all/instructions/apply.md'), instruction('delivery/instructions/apply.md').replace('${testingApproach}', testing)].join(' ') } }),
22
+ [base + 'templates/proposal.md']: template('all/templates/proposal.md'),
23
+ [base + 'templates/investigation.md']: template('discovery/templates/investigation.md'),
24
+ [base + 'templates/decision.md']: template('all/templates/decision.md'),
25
+ [base + 'templates/spec.md']: template('delivery/templates/spec.md'),
26
+ [base + 'templates/tasks.md']: template('all/templates/tasks.md'),
27
+ };
28
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ import path from 'node:path';
3
+ import { check, init, update, uninstall, nextId, renamePrefix, capabilityForPrefix, recover, version } from './core.js';
4
+ import { startTask, runTask } from './tdd.js';
5
+ const args = process.argv.slice(2);
6
+ const separator = args.indexOf('--');
7
+ const forwarded = separator < 0 ? [] : args.splice(separator).slice(1);
8
+ const wantsJson = args.includes('--json');
9
+ function option(name) { const i = args.indexOf(name); if (i < 0)
10
+ return undefined; const value = args[i + 1]; if (!value || value.startsWith('--'))
11
+ throw Error(`Missing value for ${name}`); args.splice(i, 2); return value; }
12
+ function flag(name) { const i = args.indexOf(name); if (i < 0)
13
+ return false; args.splice(i, 1); return true; }
14
+ try {
15
+ const root = path.resolve(option('--root') ?? process.cwd());
16
+ const json = flag('--json'), dry = flag('--dry-run'), makeDefault = flag('--default'), failPending = flag('--fail-on-pending');
17
+ const change = option('--change');
18
+ const capability = option('--capability');
19
+ const replacement = option('--default-schema');
20
+ const task = option('--task'), phase = option('--phase'), reason = option('--reason');
21
+ const command = args.shift();
22
+ if (dry && !['init', 'update', 'uninstall'].includes(command ?? ''))
23
+ throw Error('--dry-run is supported only by init, update, and uninstall');
24
+ if (replacement !== undefined && command !== 'uninstall')
25
+ throw Error('--default-schema is supported only by uninstall');
26
+ if (makeDefault && command !== 'init')
27
+ throw Error('--default is supported only by init');
28
+ if (change && !['check', 'tdd'].includes(command ?? ''))
29
+ throw Error('--change is supported only by check and tdd');
30
+ if (failPending && command !== 'check')
31
+ throw Error('--fail-on-pending is supported only by check');
32
+ if ((task || phase || reason || separator >= 0) && command !== 'tdd')
33
+ throw Error('--task, --phase, --reason, and -- command are supported only by tdd');
34
+ if (change && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(change))
35
+ throw Error('Change must be a kebab-case name');
36
+ if (json && !['init', 'update', 'uninstall', 'check'].includes(command ?? ''))
37
+ throw Error('--json is supported only by init, update, uninstall, and check');
38
+ if (capability && (command !== 'ac' || args[0] !== 'next'))
39
+ throw Error('--capability is supported only by ac next');
40
+ if (command === 'tdd') {
41
+ if (!change || !task)
42
+ throw Error('tdd requires --change NAME and --task ID');
43
+ if (args.length !== 1)
44
+ throw Error('Use tdd start or tdd run');
45
+ if (args[0] === 'start' && !phase && !reason && separator < 0) {
46
+ startTask(root, change, task);
47
+ console.log(`Recorded starting files for ${change} task ${task}`);
48
+ }
49
+ else if (args[0] === 'run' && phase && forwarded.length) {
50
+ const result = runTask(root, change, task, phase, forwarded, reason);
51
+ process.stdout.write(result.stdout);
52
+ process.stderr.write(result.stderr);
53
+ process.exitCode = result.exitCode;
54
+ }
55
+ else
56
+ throw Error('Use tdd start --change NAME --task ID or tdd run --change NAME --task ID --phase PHASE [--reason TEXT] -- COMMAND ARGS');
57
+ }
58
+ else if (command === 'ac') {
59
+ const action = args.shift();
60
+ if (action === 'next') {
61
+ if (capability ? args.length !== 0 : args.length !== 1)
62
+ throw Error('Use ac next --capability NAME (or ac next PREFIX for a registered active prefix)');
63
+ console.log(nextId(root, capability ?? capabilityForPrefix(root, args[0])));
64
+ }
65
+ else if (action === 'rename-prefix' && args.length === 2) {
66
+ renamePrefix(root, args[0], args[1]);
67
+ console.log(`Prefix updated for ${args[0]}: ${args[1]}`);
68
+ }
69
+ else
70
+ throw Error('Use ac next --capability NAME or ac rename-prefix CAPABILITY PREFIX');
71
+ }
72
+ else if (args.length)
73
+ throw Error(`Unexpected arguments: ${args.join(' ')}`);
74
+ else if (command === '--version')
75
+ console.log(version);
76
+ else if (command === 'init')
77
+ console.log(JSON.stringify({ dryRun: dry, writes: init(root, dry, makeDefault) }, null, 2));
78
+ else if (command === 'update')
79
+ console.log(JSON.stringify({ dryRun: dry, ...update(root, dry) }, null, 2));
80
+ else if (command === 'uninstall')
81
+ console.log(JSON.stringify({ dryRun: dry, ...uninstall(root, dry, replacement) }, null, 2));
82
+ else if (command === 'recover') {
83
+ if (!dry)
84
+ recover(root);
85
+ console.log('Recovery complete');
86
+ }
87
+ else if (command === 'check') {
88
+ const findings = check(root, change, failPending);
89
+ const ok = !findings.some(f => f.severity === 'error');
90
+ console.log(json ? JSON.stringify({ ok, findings }, null, 2) : findings.map(f => `${f.severity.toUpperCase()} ${f.code}: ${f.message}`).join('\n'));
91
+ process.exitCode = ok ? 0 : 1;
92
+ }
93
+ else if (!command || command === '--help')
94
+ console.log('cliewen-openspec (alpha)\ninit [--default] [--dry-run]\nupdate [--dry-run] [--json]\nuninstall [--default-schema NAME] [--dry-run] [--json]\nac next --capability NAME\nac next PREFIX (registered active prefix only)\nac rename-prefix CAPABILITY PREFIX\ntdd start --change NAME --task ID\ntdd run --change NAME --task ID --phase PHASE [--reason TEXT] -- COMMAND ARGS\ncheck [--change NAME] [--json] [--fail-on-pending]\nrecover\nAll commands accept --root PATH (before -- when forwarding a test command).');
95
+ else
96
+ throw Error(`Unknown command: ${command}`);
97
+ }
98
+ catch (e) {
99
+ const message = e instanceof Error ? e.message : String(e);
100
+ if (wantsJson)
101
+ console.log(JSON.stringify({ ok: false, error: message }));
102
+ else
103
+ console.error(message);
104
+ process.exitCode = 2;
105
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ export { nextId, renamePrefix, capabilityForPrefix } from './ac.js';
2
+ export declare const version = "0.1.0-alpha.1";
3
+ export type Config = {
4
+ docsRoot: string;
5
+ features: Record<string, boolean>;
6
+ evidence: {
7
+ report: string;
8
+ };
9
+ ac: {
10
+ capabilities: Record<string, string>;
11
+ padding: number;
12
+ };
13
+ testing: {
14
+ placement: 'per-task' | 'end-of-change';
15
+ approach: 'flexible' | 'tdd';
16
+ types: Record<string, {
17
+ description: string;
18
+ }>;
19
+ };
20
+ };
21
+ export type Finding = {
22
+ code: string;
23
+ severity: 'error' | 'warning' | 'info';
24
+ message: string;
25
+ };
26
+ export declare function local(root: string, relative: string): string;
27
+ export declare function defaults(): Config;
28
+ export declare function config(root: string): Config;
29
+ export declare function transaction(root: string, writes: Record<string, string | null>, dryRun?: boolean): string[];
30
+ export declare function recover(root: string): void;
31
+ export declare function uninstall(root: string, dryRun?: boolean, replacement?: string): {
32
+ writes: string[];
33
+ deletes: string[];
34
+ };
35
+ export declare function update(root: string, dryRun?: boolean): {
36
+ writes: string[];
37
+ deletes: string[];
38
+ };
39
+ export declare function init(root: string, dryRun: boolean, makeDefault: boolean): string[];
40
+ export declare function markdowns(dir: string): string[];
41
+ export declare function scenarios(root: string, change?: string): {
42
+ id: string;
43
+ title: string;
44
+ file: string;
45
+ testTypes: string[];
46
+ }[];
47
+ export declare function git(root: string, args: string[]): string;
48
+ export declare function check(root: string, change?: string, failPending?: boolean): Finding[];