cliewen-openspec 0.0.0-stage → 0.1.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 (60) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/LICENSE +21 -0
  3. package/README.md +101 -2
  4. package/adapters/node-test.mjs +65 -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 +81 -0
  11. package/dist/core.d.ts +55 -0
  12. package/dist/core.js +651 -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/quality.d.ts +27 -0
  18. package/dist/quality.js +412 -0
  19. package/dist/schema-source.d.ts +3 -0
  20. package/dist/schema-source.js +9 -0
  21. package/docs/configuration.md +278 -0
  22. package/docs/testing/evidence.md +88 -0
  23. package/docs/testing/pilot-prompt.md +20 -0
  24. package/docs/testing/test-quality.md +84 -0
  25. package/package.json +63 -4
  26. package/schemas/README.md +25 -0
  27. package/schemas/all/instructions/apply.md +4 -0
  28. package/schemas/all/instructions/approval.md +4 -0
  29. package/schemas/all/instructions/decision.md +7 -0
  30. package/schemas/all/instructions/investigation.md +1 -0
  31. package/schemas/all/instructions/proposal.md +3 -0
  32. package/schemas/all/instructions/specs.md +2 -0
  33. package/schemas/all/instructions/tasks.md +2 -0
  34. package/schemas/all/templates/decision.md +20 -0
  35. package/schemas/all/templates/proposal.md +19 -0
  36. package/schemas/all/templates/tasks.md +9 -0
  37. package/schemas/base/instructions/diagrams.md +7 -0
  38. package/schemas/base/instructions/humanizer.md +7 -0
  39. package/schemas/base/instructions/learnings.md +6 -0
  40. package/schemas/base/instructions/routing.md +5 -0
  41. package/schemas/base/instructions/testing-approach.md +13 -0
  42. package/schemas/base/instructions/writing.md +24 -0
  43. package/schemas/base/templates/decision.md +18 -0
  44. package/schemas/base/templates/learning.md +19 -0
  45. package/schemas/delivery/instructions/apply.md +10 -0
  46. package/schemas/delivery/instructions/design.md +9 -0
  47. package/schemas/delivery/instructions/proposal.md +3 -0
  48. package/schemas/delivery/instructions/specs.md +11 -0
  49. package/schemas/delivery/instructions/tasks.md +13 -0
  50. package/schemas/delivery/templates/design.md +9 -0
  51. package/schemas/delivery/templates/proposal.md +13 -0
  52. package/schemas/delivery/templates/spec.md +13 -0
  53. package/schemas/delivery/templates/tasks.md +17 -0
  54. package/schemas/discovery/instructions/apply.md +5 -0
  55. package/schemas/discovery/instructions/decision.md +7 -0
  56. package/schemas/discovery/instructions/investigation.md +8 -0
  57. package/schemas/discovery/instructions/proposal.md +4 -0
  58. package/schemas/discovery/templates/decision.md +17 -0
  59. package/schemas/discovery/templates/investigation.md +11 -0
  60. package/schemas/discovery/templates/proposal.md +9 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,69 @@
1
+ # Changelog
2
+
3
+ Changes that matter to projects using Cliewen for OpenSpec.
4
+
5
+ ## 0.1.0 (2026-11-09)
6
+
7
+ - Optional indexed project learnings help agents retrieve relevant lessons and maintain or retire stale guidance. Notes remain project-owned and survive disabling the facility, updates, and uninstall. Learnings are off by default. Agents that gather context before reading schema instructions may need the [project instruction example](docs/configuration.md#instructions-before-context-collection).
8
+ - Optional Humanizer guidance defaults to automatic host discovery, with explicit on/off modes, one status per session, and a clear-writing fallback. Missing skills never block writing or install automatically. See [configuration and host limits](docs/configuration.md#humanizer-and-writing).
9
+ - Shared writing guidance asks agents to validate local document links before handoff and describe future files as planned paths until they exist. This requests an agent check; the CLI does not validate every Markdown link.
10
+ - Technical explanations should distinguish supported inputs from observed runtime behavior and describe what each verification command actually checked. These are review instructions, not an automatic guarantee of factual correctness.
11
+
12
+ - Evidence-first verification plans acceptance cases before implementation, verifies small tasks, reviews effective assertions, and maintains tests as requirements change. It records execution evidence without requiring an order of test and production edits. See [the verification approach](docs/configuration.md#evidence-first-verification).
13
+ - Delivery guidance asks agents to test relevant combinations of input content and options, including preservation on default and disabled paths. These combinations require review; passing case counts do not establish their coverage. See [planning interacting cases](docs/testing/test-quality.md#plan-interacting-cases).
14
+
15
+ - Independently configurable checks for positive/negative case coverage, assertion-effectiveness reviews, and test maintenance when requirements change or are retired. The default warns about missing assessments; projects can disable individual policies or make them blocking.
16
+ - Case IDs and coverage categories in Node test reports, plus scoped exceptions and review records tied to inspected file contents. Passing record checks still require review of assertion meaning and approval claims. See [test quality and lifecycle](docs/testing/test-quality.md) for development-source usage and limitations.
17
+ - The first non-prerelease release starts with the current configuration. Upgrading earlier alpha installations is outside its supported scope; authored-file preservation remains part of the installer contract.
18
+
19
+ ## 0.1.0-alpha.1 (2026-11-01)
20
+
21
+ The first public alpha was published as `cliewen-openspec@0.1.0-alpha.1`, with the `alpha` tag. Its features and limitations below describe that historical snapshot. Follow the [installation guide](docs/guide/getting-started.md) for 0.1.0.
22
+
23
+ ### OpenSpec workflows
24
+
25
+ Choose from three schemas, which define the documents and instructions for a change:
26
+
27
+ - `cliewen-delivery` takes an understood change through a proposal, behavior specifications, design, implementation tasks, and verification.
28
+ - `cliewen-discovery` helps investigate a question and recommend what to do next. The recommendation can be to make no change.
29
+ - `cliewen-all` combines investigation and delivery. It calls for human agreement before implementation and also supports ending an investigation without changing the product.
30
+
31
+ 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.
32
+
33
+ ### Installation and project settings
34
+
35
+ - `init` installs the schemas and supporting resources. Preview changes before writing files, and keep your existing default schema unless you explicitly select a replacement.
36
+ - `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.
37
+ - `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.
38
+ - 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.
39
+ - 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.
40
+
41
+ See the [configuration reference](docs/configuration.md) and [CLI guide](docs/guide/cli.md) for defaults and commands.
42
+
43
+ ### Acceptance criteria and tests
44
+
45
+ - 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.
46
+ - 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.
47
+ - Test each implementation task as you go, or configure testing at the end of a change. The default allows tests before or after code.
48
+ - 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.
49
+
50
+ ### Test results before archive
51
+
52
+ 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.
53
+
54
+ 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.
55
+
56
+ See the [evidence guide](docs/testing/evidence.md) for collection commands and help resolving findings.
57
+
58
+ ### Guide and examples
59
+
60
+ 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.
61
+
62
+ ### Current limitations
63
+
64
+ - 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.
65
+ - 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.
66
+ - Discovery findings and combined-workflow approval fields require review. A recorded status cannot prove that a person approved the change.
67
+ - Documentation and diagram guidance does not validate your project's document metadata or diagram syntax.
68
+ - Acceptance ID allocation supports sequential work. Parallel branches may allocate the same number and need conflict resolution.
69
+ - 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,102 @@
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
+ **Version `0.1.0`.** 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.
6
+
7
+ The release includes [test quality and lifecycle checks](docs/testing/test-quality.md), optional project learnings, and Humanizer guidance. Follow [Your first change](docs/guide/getting-started.md) to build and install its local tarball. The published `0.1.0-alpha.1` is an earlier snapshot and does not include these additions; its manifest is not supported by 0.1.0.
8
+
9
+ ## Schema collection
10
+
11
+ - **cliewen-delivery** — recommended workflow for understood changes.
12
+ - **cliewen-discovery** — investigation, alternatives and decision handoff.
13
+ - **cliewen-all** — combined discovery and delivery, with explicit no-delivery closure.
14
+
15
+ `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.
16
+
17
+ 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. The package supplies documentation and decision guidance; structural metadata and Mermaid validators remain planned.
18
+
19
+ 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.
20
+
21
+ ## Install
22
+
23
+ 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.
24
+
25
+ In your project, install the versioned packages and initialize OpenSpec:
26
+
27
+ ```sh
28
+ npm install --save-dev @fission-ai/openspec@1.15.0
29
+ npx --no-install openspec init
30
+ npm install --save-dev cliewen-openspec@0.1.0
31
+ npx --no-install cliewen-openspec init --default
32
+ npx --no-install openspec new change add-export --schema cliewen-delivery
33
+ ```
34
+
35
+ Register the capability in `.cliewen-openspec/config.yaml`:
36
+
37
+ ```yaml
38
+ ac:
39
+ padding: 3
40
+ capabilities:
41
+ export: EXPORT
42
+ ```
43
+
44
+ Then allocate its first ID:
45
+
46
+ ```sh
47
+ npx --no-install cliewen-openspec ac next --capability export
48
+ ```
49
+
50
+ `--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.
51
+
52
+ The explicit version selects 0.1.0. Earlier alpha installation manifests are unsupported; use a fresh installation rather than editing a manifest version. For the complete CSV example, follow [your first change](docs/guide/getting-started.md).
53
+
54
+ For an existing installation, install the desired package version 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).
55
+
56
+ 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.
57
+
58
+ Use **spec-driven development with evidence-first verification**: plan acceptance cases before implementation, verify small tasks, assess assertion effectiveness, and maintain tests as requirements change. See [the verification approach](docs/configuration.md#evidence-first-verification).
59
+
60
+ After implementation, commit the project inputs and collect evidence from Node tests:
61
+
62
+ ```sh
63
+ node node_modules/cliewen-openspec/adapters/node-test.mjs test/export.test.mjs
64
+ npx --no-install cliewen-openspec check --change add-export --json
65
+ ```
66
+
67
+ 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.
68
+
69
+ `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.
70
+
71
+ ## Project documents
72
+
73
+ - [User guide source](docs/guide/index.md) and [published documentation](https://cliewen-openspec.github.io/cliewen-openspec/)
74
+ - [Decisions](docs/decisions/README.md)
75
+ - [Changelog](CHANGELOG.md)
76
+ - [Project configuration](docs/configuration.md)
77
+ - [Pilot reference prompt](docs/testing/pilot-prompt.md)
78
+ - [Implementation plan](plan.md)
79
+ - [Practice mapping](docs/cliewen-mapping.md)
80
+ - [Architecture](docs/architecture/README.md)
81
+ - [Website](https://cliewen-openspec.github.io/cliewen-openspec/)
82
+ - [Credits](CREDITS.md)
83
+
84
+ 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.
85
+
86
+ ## Development checks
87
+
88
+ `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.
89
+
90
+ 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.
91
+
92
+ 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).
93
+
94
+ ## Feedback
95
+
96
+ [Report a bug](https://github.com/cliewen-openspec/cliewen-openspec/issues/new?template=bug_report.yml) or [suggest an improvement](https://github.com/cliewen-openspec/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.
97
+
98
+ Maintainers use the [feedback triage guide](docs/feedback-triage.md) to reproduce problems, record decisions, and link accepted work to OpenSpec changes.
99
+
100
+ ## License
101
+
102
+ [MIT](LICENSE).
@@ -0,0 +1,65 @@
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, markdowns } 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
+ let removedRequirements = 0, activeRequirements = 0;
30
+ if (selected?.size === 0) for (const file of markdowns(local(process.cwd(), `openspec/changes/${change}/specs`))) {
31
+ let fence = '', section = '';
32
+ for (const line of fs.readFileSync(file, 'utf8').replace(/<!--[\s\S]*?-->/g, '').split(/\r?\n/)) {
33
+ const boundary = line.match(/^\s*(`{3,}|~{3,})/);
34
+ if (boundary) { if (!fence) fence = boundary[1]; else if (fence[0] === boundary[1][0] && boundary[1].length >= fence.length) fence = ''; continue; }
35
+ if (fence) continue;
36
+ if (/^## /.test(line)) section = line.trim();
37
+ if (/^### Requirement:/.test(line)) { if (section === '## REMOVED Requirements') removedRequirements++; else activeRequirements++; }
38
+ }
39
+ }
40
+ const retirementOnly = selected?.size === 0 && removedRequirements > 0 && activeRequirements === 0;
41
+ if (selected && ((!selected.size && !retirementOnly) || selected.has(''))) throw Error('Selected change requires scenarios with AC IDs');
42
+ const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap', ...files], { encoding: 'utf8' });
43
+ if (run.error) throw run.error;
44
+ process.stdout.write(run.stdout ?? ''); process.stderr.write(run.stderr ?? '');
45
+ const results = [];
46
+ for (const line of (run.stdout ?? '').split(/\r?\n/)) {
47
+ const m = line.match(/^\s*(not ok|ok) \d+ - (.*\[([A-Z][A-Z0-9]*-\d+)\].*)$/);
48
+ if (m) {
49
+ const tags = [...m[2].matchAll(/\[Test-type: ([^\]\r\n]+)\]/g)];
50
+ if (tags.length !== 1 || !Object.hasOwn(settings.testing.types, tags[0][1])) throw Error(`Test ${m[2]} requires one configured [Test-type: NAME] tag`);
51
+ const metadata = {};
52
+ for (const [tag, field] of [['Case', 'caseId'], ['Coverage', 'coverage']]) {
53
+ const values = [...m[2].matchAll(new RegExp(`\\[${tag}: ([^\\]\\r\\n]*)\\]`, 'g'))];
54
+ if (values.length) metadata[field] = values.length === 1 ? values[0][1] : null;
55
+ }
56
+ if (!selected || selected.has(m[3])) results.push({ scenario: m[3], test: m[2], testType: tags[0][1], ...metadata, outcome: /#\s*(SKIP|TODO)/i.test(m[2]) ? 'skipped' : m[1] === 'ok' ? 'passed' : 'failed' });
57
+ }
58
+ }
59
+ 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.');
60
+ if (run.status === null) throw Error('Test runner did not complete; no report produced');
61
+ if (!results.length && !retirementOnly) throw Error('No AC-tagged test results found for the selected scope; no report produced');
62
+ fs.mkdirSync(path.dirname(output), { recursive: true });
63
+ fs.writeFileSync(output, JSON.stringify({ version: 1, revision, ...(change === undefined ? {} : { scope: { change } }), execution: { exitCode: run.status }, results }, null, 2) + '\n');
64
+ process.exitCode = run.status === 0 ? 0 : 1;
65
+ } 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,81 @@
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
+ const args = process.argv.slice(2);
5
+ const wantsJson = args.includes('--json');
6
+ function option(name) { const i = args.indexOf(name); if (i < 0)
7
+ return undefined; const value = args[i + 1]; if (!value || value.startsWith('--'))
8
+ throw Error(`Missing value for ${name}`); args.splice(i, 2); return value; }
9
+ function flag(name) { const i = args.indexOf(name); if (i < 0)
10
+ return false; args.splice(i, 1); return true; }
11
+ try {
12
+ const root = path.resolve(option('--root') ?? process.cwd());
13
+ const json = flag('--json'), dry = flag('--dry-run'), makeDefault = flag('--default'), failPending = flag('--fail-on-pending');
14
+ const change = option('--change');
15
+ const capability = option('--capability');
16
+ const replacement = option('--default-schema');
17
+ const command = args.shift();
18
+ if (dry && !['init', 'update', 'uninstall'].includes(command ?? ''))
19
+ throw Error('--dry-run is supported only by init, update, and uninstall');
20
+ if (replacement !== undefined && command !== 'uninstall')
21
+ throw Error('--default-schema is supported only by uninstall');
22
+ if (makeDefault && command !== 'init')
23
+ throw Error('--default is supported only by init');
24
+ if (change && command !== 'check')
25
+ throw Error('--change is supported only by check');
26
+ if (failPending && command !== 'check')
27
+ throw Error('--fail-on-pending is supported only by check');
28
+ if (change && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(change))
29
+ throw Error('Change must be a kebab-case name');
30
+ if (json && !['init', 'update', 'uninstall', 'check'].includes(command ?? ''))
31
+ throw Error('--json is supported only by init, update, uninstall, and check');
32
+ if (capability && (command !== 'ac' || args[0] !== 'next'))
33
+ throw Error('--capability is supported only by ac next');
34
+ if (command === 'ac') {
35
+ const action = args.shift();
36
+ if (action === 'next') {
37
+ if (capability ? args.length !== 0 : args.length !== 1)
38
+ throw Error('Use ac next --capability NAME (or ac next PREFIX for a registered active prefix)');
39
+ console.log(nextId(root, capability ?? capabilityForPrefix(root, args[0])));
40
+ }
41
+ else if (action === 'rename-prefix' && args.length === 2) {
42
+ renamePrefix(root, args[0], args[1]);
43
+ console.log(`Prefix updated for ${args[0]}: ${args[1]}`);
44
+ }
45
+ else
46
+ throw Error('Use ac next --capability NAME or ac rename-prefix CAPABILITY PREFIX');
47
+ }
48
+ else if (args.length)
49
+ throw Error(`Unexpected arguments: ${args.join(' ')}`);
50
+ else if (command === '--version')
51
+ console.log(version);
52
+ else if (command === 'init')
53
+ console.log(JSON.stringify({ dryRun: dry, writes: init(root, dry, makeDefault) }, null, 2));
54
+ else if (command === 'update')
55
+ console.log(JSON.stringify({ dryRun: dry, ...update(root, dry) }, null, 2));
56
+ else if (command === 'uninstall')
57
+ console.log(JSON.stringify({ dryRun: dry, ...uninstall(root, dry, replacement) }, null, 2));
58
+ else if (command === 'recover') {
59
+ if (!dry)
60
+ recover(root);
61
+ console.log('Recovery complete');
62
+ }
63
+ else if (command === 'check') {
64
+ const findings = check(root, change, failPending);
65
+ const ok = !findings.some(f => f.severity === 'error');
66
+ console.log(json ? JSON.stringify({ ok, findings }, null, 2) : findings.map(f => `${f.severity.toUpperCase()} ${f.code}: ${f.message}`).join('\n'));
67
+ process.exitCode = ok ? 0 : 1;
68
+ }
69
+ else if (!command || command === '--help')
70
+ console.log('cliewen-openspec\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\ncheck [--change NAME] [--json] [--fail-on-pending]\nrecover\nAll commands accept --root PATH.');
71
+ else
72
+ throw Error(`Unknown command: ${command}`);
73
+ }
74
+ catch (e) {
75
+ const message = e instanceof Error ? e.message : String(e);
76
+ if (wantsJson)
77
+ console.log(JSON.stringify({ ok: false, error: message }));
78
+ else
79
+ console.error(message);
80
+ process.exitCode = 2;
81
+ }
package/dist/core.d.ts ADDED
@@ -0,0 +1,55 @@
1
+ import { type QualitySettings } from './quality.js';
2
+ export { nextId, renamePrefix, capabilityForPrefix } from './ac.js';
3
+ export declare const version = "0.1.0";
4
+ export type Config = {
5
+ docsRoot: string;
6
+ learnings: {
7
+ enabled: boolean;
8
+ directory: string;
9
+ };
10
+ writing: {
11
+ humanizer: 'auto' | 'on' | 'off';
12
+ };
13
+ features: Record<string, boolean>;
14
+ evidence: {
15
+ report: string;
16
+ };
17
+ ac: {
18
+ capabilities: Record<string, string>;
19
+ padding: number;
20
+ };
21
+ testing: QualitySettings & {
22
+ placement: 'per-task' | 'end-of-change';
23
+ types: Record<string, {
24
+ description: string;
25
+ }>;
26
+ };
27
+ };
28
+ export type Finding = {
29
+ code: string;
30
+ severity: 'error' | 'warning' | 'info';
31
+ message: string;
32
+ };
33
+ export declare function local(root: string, relative: string): string;
34
+ export declare function defaults(): Config;
35
+ export declare function config(root: string): Config;
36
+ export declare function transaction(root: string, writes: Record<string, string | null>, dryRun?: boolean): string[];
37
+ export declare function recover(root: string): void;
38
+ export declare function uninstall(root: string, dryRun?: boolean, replacement?: string): {
39
+ writes: string[];
40
+ deletes: string[];
41
+ };
42
+ export declare function update(root: string, dryRun?: boolean): {
43
+ writes: string[];
44
+ deletes: string[];
45
+ };
46
+ export declare function init(root: string, dryRun: boolean, makeDefault: boolean): string[];
47
+ export declare function markdowns(dir: string): string[];
48
+ export declare function scenarios(root: string, change?: string): {
49
+ id: string;
50
+ title: string;
51
+ file: string;
52
+ testTypes: string[];
53
+ }[];
54
+ export declare function git(root: string, args: string[]): string;
55
+ export declare function check(root: string, change?: string, failPending?: boolean): Finding[];