cliewen-openspec 0.2.0 → 0.4.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 (45) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +16 -12
  3. package/adapters/node-test.mjs +9 -4
  4. package/dist/ac-coordination.d.ts +33 -0
  5. package/dist/ac-coordination.js +318 -0
  6. package/dist/ac.d.ts +4 -3
  7. package/dist/ac.js +20 -1
  8. package/dist/ci-github.d.ts +19 -0
  9. package/dist/ci-github.js +70 -0
  10. package/dist/ci-inspection.d.ts +48 -0
  11. package/dist/ci-inspection.js +246 -0
  12. package/dist/ci-settings.d.ts +15 -0
  13. package/dist/ci-settings.js +50 -0
  14. package/dist/cli.js +73 -12
  15. package/dist/core.d.ts +32 -3
  16. package/dist/core.js +167 -15
  17. package/dist/documentation-settings.d.ts +16 -0
  18. package/dist/documentation-settings.js +65 -0
  19. package/dist/documentation.d.ts +47 -0
  20. package/dist/documentation.js +337 -0
  21. package/dist/mermaid-check.d.ts +10 -0
  22. package/dist/mermaid-check.js +40 -0
  23. package/dist/mermaid-worker.d.ts +1 -0
  24. package/dist/mermaid-worker.js +24 -0
  25. package/dist/quality.d.ts +1 -1
  26. package/dist/quality.js +22 -7
  27. package/dist/release.d.ts +2 -2
  28. package/dist/release.js +3 -3
  29. package/dist/schema-source.js +1 -1
  30. package/dist/setup-profile.d.ts +31 -0
  31. package/dist/setup-profile.js +59 -0
  32. package/dist/state-lock.d.ts +2 -0
  33. package/dist/state-lock.js +92 -0
  34. package/docs/configuration.md +170 -10
  35. package/docs/testing/evidence.md +14 -1
  36. package/docs/testing/test-quality.md +3 -1
  37. package/package.json +67 -65
  38. package/schemas/base/instructions/ci-inspection.md +9 -0
  39. package/schemas/base/instructions/closure.md +4 -2
  40. package/schemas/base/instructions/context-entry.md +1 -0
  41. package/schemas/base/instructions/context-selection.md +33 -0
  42. package/schemas/base/instructions/documentation-checks.md +2 -0
  43. package/schemas/base/instructions/humanizer.md +12 -5
  44. package/schemas/base/instructions/planning.md +60 -27
  45. package/schemas/delivery/instructions/apply.md +2 -0
package/CHANGELOG.md CHANGED
@@ -4,6 +4,34 @@ Changes that matter to projects using Cliewen for OpenSpec.
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.4.0 (2026-11-23)
8
+
9
+ - Delivery agents assess whether the request and verification are clear enough to start. When a decision is missing, the agent can leave the question on an existing ticket so another agent can resume after the answer. Projects can adjust the threshold or turn the assessment off. [Readiness settings](docs/configuration.md#implementation-readiness)
10
+
11
+ - Delivery guidance now asks agents to review the full plan before coding and the actual changes before archive. It helps catch unrequested work, missed requirements, and missing verification. [Review delivery scope](docs/guide/workflow.md#review-delivery-scope)
12
+
13
+ - Choose a solo or team setup profile during initialization and revisit it as your project grows. Preview the switch and select which recommendations to apply. [Set up a profile or switch to team](docs/guide/cli.md#choose-or-change-a-setup-profile)
14
+
15
+ - Check test evidence for one permanent OpenSpec capability with `cliewen-openspec check --capability NAME`. The check names active criteria that lack results, so a green test run can still reveal a missing test. [Collect capability evidence](docs/testing/evidence.md#collect-evidence-for-one-capability)
16
+
17
+ ## 0.3.0 (2026-11-21)
18
+
19
+ - Separate OpenSpec archive sessions now receive the same [Humanizer guidance](docs/configuration.md#humanizer-and-writing) as the workflows. Enabled modes report the result once, and `off` keeps the handoff free of skill status.
20
+
21
+ - Update an existing 0.1.0 or 0.2.0 installation to this version while keeping project configuration, authored files and reserved acceptance IDs. [Preview an update](docs/guide/updating.md#install-preview-and-apply).
22
+
23
+ - Inspect whether your selected GitHub CI checks are required before integration with `cliewen-openspec ci inspect`. Reports distinguish observed, missing and unknown requirements and show bypass visibility separately. Inspection is advisory, needs an explicitly selected repository and checks, and changes no host settings. See [setup and limits](docs/configuration.md#ci-requirement-inspection-in-development-source).
24
+
25
+ - Check local Markdown links, optional YAML frontmatter and Mermaid syntax with `cliewen-openspec docs check`. All categories warn by default and can independently block or be disabled; project roots, exclusions and metadata rules are configurable. Checks change no files and report incomplete work explicitly. The Mermaid parser is included. See [configuration and limits](docs/configuration.md#documentation-checks-in-development-source).
26
+
27
+ - The new package requires Node 22.12+ instead of 20.19+. Init/update reject older runtimes before recovery or installation writes. OpenSpec 1.15.0+ remains supported; already published packages retain their original requirements.
28
+
29
+ - Optional context-selection guidance helps agents find current specs, decisions and constraints through OpenSpec and existing project records. It defaults to guided, preserves explicit off choices and lesson gates, and offers selected roots, exclusions and an advisory additional-record budget. Existing filenames, folders and frontmatter help select candidates through project conventions. It does not scan files or enforce access boundaries. See [configuration and limits](docs/configuration.md#optional-context-selection-in-development-source).
30
+
31
+ - Projects can opt in to Git-backed acceptance-ID reservations for concurrent agents, branches, or contributors. Local allocation stays the default and now serializes writers in one worktree. Shared coordination preserves existing IDs and prefix history, fails without local fallback during outages, and supports resuming interrupted reservations. Git discovery failures stop allocation, and competing first-time setup can be retried safely. All participating clients need the new commands. See [setup and recovery](docs/guide/cli.md#ac-coordinate-sync-resume-and-abandon).
32
+
33
+ - Development now targets repository-local OpenSpec 2.0.0. Init and update reject external-store layouts before changing files or recovering transactions, with an explanation of the supported setup. See [upgrading OpenSpec](docs/guide/updating.md#move-to-openspec-2).
34
+
7
35
  ## 0.2.0 (2026-11-13)
8
36
 
9
37
  - Agents now assess automation before requesting manual work and explain any remaining human contribution. Shared guidance helps them prepare concise decision material and retain concrete human observations without treating feedback as release authorization. Existing configuration and evidence formats are unchanged. See [human review and verification](docs/guide/workflow.md#make-decisions-easy-to-assess).
package/README.md CHANGED
@@ -4,11 +4,13 @@ Durable decisions, living documentation, and evidence for OpenSpec.
4
4
 
5
5
  Built on [OpenSpec](https://openspec.dev/), using its custom-schema workflows. See [Fission-AI/OpenSpec on GitHub](https://github.com/Fission-AI/OpenSpec) for the engine's source and community.
6
6
 
7
- **Version `0.2.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.
7
+ Cliewen installs `cliewen-delivery`, `cliewen-discovery`, and `cliewen-all`, allocates acceptance IDs, and checks delivery test evidence through OpenSpec archiving.
8
8
 
9
- Version 0.2.0 adds work scoping, optional prototypes and product context, closure guidance, and guidance for automating checks and recording human observations. See [the 0.2.0 release notes](docs/releases/0.2.0-notes.md) for changes and upgrade requirements.
9
+ See [the changelog](CHANGELOG.md) for changes and upgrade requirements.
10
10
 
11
- The package also 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.2.0.
11
+ Optional [context-selection guidance](docs/configuration.md#optional-context-selection-in-development-source) helps agents find relevant project knowledge using native OpenSpec operations and host tools. Guided mode is enabled by default. Its roots, exclusions, and budget are advisory.
12
+
13
+ The package also 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) for a worked CSV example.
12
14
 
13
15
  ## Schema collection
14
16
 
@@ -18,20 +20,22 @@ The package also includes [test quality and lifecycle checks](docs/testing/test-
18
20
 
19
21
  `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.
20
22
 
21
- 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.
23
+ Evidence is enabled by default. [Read-only documentation checks](docs/configuration.md#documentation-checks-in-development-source) cover local references, optional frontmatter, and Mermaid syntax. Each check is advisory by default.
22
24
 
23
25
  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.
24
26
 
25
27
  ## Install
26
28
 
27
- Requires OpenSpec 1.15.0 or newer, Node.js 20.19 or newer, and Git. The npm commands below install OpenSpec 1.17.0, which requires Node 22.12 or newer. See [version compatibility](docs/configuration.md#version-compatibility) for the Node 20 installation path. Current integration tests target OpenSpec 1.17.0; Windows and Linux CI use Node 22 and 24.
29
+ Use [CI requirement inspection](docs/configuration.md#ci-requirement-inspection-in-development-source) to see whether selected GitHub checks are required and what information is unavailable.
30
+
31
+ The full workflow requires Node.js 22.12+, OpenSpec 1.15.0+, and Git. See [version compatibility](docs/configuration.md#version-compatibility).
28
32
 
29
- In your project, install the versioned packages and initialize OpenSpec:
33
+ In your project, install the packages and initialize OpenSpec:
30
34
 
31
35
  ```sh
32
- npm install --save-dev @fission-ai/openspec@1.17.0
36
+ npm install --save-dev @fission-ai/openspec@2
33
37
  npx --no-install openspec init
34
- npm install --save-dev cliewen-openspec@0.2.0
38
+ npm install --save-dev cliewen-openspec
35
39
  npx --no-install cliewen-openspec init --default
36
40
  npx --no-install openspec new change add-export --schema cliewen-delivery
37
41
  ```
@@ -53,7 +57,7 @@ npx --no-install cliewen-openspec ac next --capability export
53
57
 
54
58
  `--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.
55
59
 
56
- The explicit version selects 0.2.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).
60
+ For an earlier alpha installation, start with a fresh installation. Its ownership manifest cannot be upgraded.
57
61
 
58
62
  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).
59
63
 
@@ -74,7 +78,7 @@ After reviewing the assertions and evidence, archive with OpenSpec. Commit the a
74
78
 
75
79
  ## Project documents
76
80
 
77
- - [User guide source](docs/guide/index.md) and [published documentation](https://cliewen-openspec.github.io/cliewen-openspec/)
81
+ - [User guide source](docs/guide/index.md) and [published documentation](https://cliewen-openspec.github.io/guide/)
78
82
  - [Decisions](docs/decisions/README.md)
79
83
  - [Changelog](CHANGELOG.md)
80
84
  - [Project configuration](docs/configuration.md)
@@ -82,10 +86,10 @@ After reviewing the assertions and evidence, archive with OpenSpec. Commit the a
82
86
  - [Implementation plan](plan.md)
83
87
  - [Practice mapping](docs/cliewen-mapping.md)
84
88
  - [Architecture](docs/architecture/README.md)
85
- - [Website](https://cliewen-openspec.github.io/cliewen-openspec/)
89
+ - [Website](https://cliewen-openspec.github.io/)
86
90
  - [Credits](CREDITS.md)
87
91
 
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.
92
+ Use the [command reference](docs/guide/cli.md) for installation, verification, and [optional parallel allocation](docs/guide/cli.md#ac-coordinate-sync-resume-and-abandon). [Uninstall](docs/guide/uninstalling.md) preserves project data and requires an explicit replacement when removing the selected default.
89
93
 
90
94
  ## Development checks
91
95
 
@@ -16,16 +16,21 @@ try {
16
16
  if (fs.existsSync(output)) fs.unlinkSync(output);
17
17
  const files = [];
18
18
  let change;
19
+ let capability;
19
20
  const args = process.argv.slice(2);
20
21
  for (let i = 0; i < args.length; i++) {
21
22
  if (args[i] === '--change') {
22
23
  if (change !== undefined || !args[i + 1] || args[i + 1].startsWith('-')) throw Error('Pass --change NAME once');
23
24
  change = args[++i];
25
+ } else if (args[i] === '--capability') {
26
+ if (capability !== undefined || !args[i + 1] || args[i + 1].startsWith('-')) throw Error('Pass --capability NAME once');
27
+ capability = args[++i];
24
28
  } else if (args[i].startsWith('-')) throw Error(`Unknown adapter option: ${args[i]}`);
25
29
  else files.push(args[i]);
26
30
  }
27
31
  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));
32
+ const scope = capability !== undefined ? { capability } : change !== undefined ? { change } : undefined;
33
+ const selected = scope && new Set(scenarios(process.cwd(), change, capability).map(s => s.id));
29
34
  let removedRequirements = 0, activeRequirements = 0;
30
35
  if (selected?.size === 0) for (const file of markdowns(local(process.cwd(), `openspec/changes/${change}/specs`))) {
31
36
  let fence = '', section = '';
@@ -38,7 +43,7 @@ try {
38
43
  }
39
44
  }
40
45
  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');
46
+ if (selected && ((!selected.size && !retirementOnly) || selected.has(''))) throw Error('Selected scope requires scenarios with AC IDs');
42
47
  const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap', ...files], { encoding: 'utf8' });
43
48
  if (run.error) throw run.error;
44
49
  process.stdout.write(run.stdout ?? ''); process.stderr.write(run.stderr ?? '');
@@ -58,8 +63,8 @@ try {
58
63
  }
59
64
  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
65
  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');
66
+ if (!results.length && !retirementOnly && capability === undefined) throw Error('No AC-tagged test results found for the selected scope; no report produced');
62
67
  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');
68
+ fs.writeFileSync(output, JSON.stringify({ version: 1, revision, scope, execution: { exitCode: run.status }, results }, null, 2) + '\n');
64
69
  process.exitCode = run.status === 0 ? 0 : 1;
65
70
  } catch (e) { console.error(e.message); process.exitCode = 2; }
@@ -0,0 +1,33 @@
1
+ import { type Registry } from './ac.js';
2
+ export declare const authorityRef = "refs/heads/cliewen/ac-allocator";
3
+ type Settings = {
4
+ version: 1;
5
+ mode: 'git';
6
+ remote: string;
7
+ authority: string;
8
+ };
9
+ export declare function coordinationSettings(root: string): Settings | undefined;
10
+ export declare function coordinate(root: string, remote: string, apply?: boolean): {
11
+ mode: string;
12
+ remote: string;
13
+ ref: string;
14
+ action: string;
15
+ registry: Registry;
16
+ authority?: undefined;
17
+ } | {
18
+ action?: undefined;
19
+ registry?: undefined;
20
+ mode: string;
21
+ remote: string;
22
+ ref: string;
23
+ authority: string;
24
+ };
25
+ export declare function syncIds(root: string): {
26
+ mode: string;
27
+ remote: string;
28
+ };
29
+ export declare function reserve(root: string, kind: 'next' | 'rename', capability: string, prefix?: string): string | null;
30
+ export declare function resumeIds(root: string): string | null;
31
+ export declare function assertNoPendingLocal(root: string): void;
32
+ export declare function abandonRequest(root: string): string;
33
+ export {};
@@ -0,0 +1,318 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { isDeepStrictEqual } from 'node:util';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { parseDocument } from 'yaml';
7
+ import { config, local, recover, transaction } from './core.js';
8
+ import { parseRegistry, validateRegistry, maximum } from './ac.js';
9
+ import { runtimeDirectory, withStateLock } from './state-lock.js';
10
+ export const authorityRef = 'refs/heads/cliewen/ac-allocator';
11
+ const settingsPath = '.cliewen-openspec/ac-coordination.json';
12
+ const registryPath = '.cliewen-openspec/ac-registry.json';
13
+ const json = (v) => JSON.stringify(v, null, 2) + '\n';
14
+ const validRemote = (v) => typeof v === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(v);
15
+ const uuid = (v) => typeof v === 'string' && /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(v);
16
+ function runtimeFile(root, name) {
17
+ const file = path.join(runtimeDirectory(root), name);
18
+ try {
19
+ if (fs.lstatSync(file).isSymbolicLink())
20
+ throw Error('Symlink not supported for pending AC request.');
21
+ }
22
+ catch (error) {
23
+ if (error.code !== 'ENOENT')
24
+ throw error;
25
+ }
26
+ return file;
27
+ }
28
+ const pendingFile = (root) => runtimeFile(root, 'request.json');
29
+ function requireCompletedSetup(root) {
30
+ if (fs.existsSync(runtimeFile(root, 'setup.json')))
31
+ throw Error('AC coordination setup is pending; repeat ac coordinate with the original remote and --apply before allocating or synchronizing.');
32
+ }
33
+ function git(root, args, input) {
34
+ return execFileSync('git', args, { cwd: root, input, encoding: 'utf8', timeout: 10000, maxBuffer: 16 * 1024 * 1024, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_AUTHOR_NAME: 'Cliewen AC allocator', GIT_AUTHOR_EMAIL: 'allocator@example.invalid', GIT_COMMITTER_NAME: 'Cliewen AC allocator', GIT_COMMITTER_EMAIL: 'allocator@example.invalid' } }).trim();
35
+ }
36
+ function repository(root, remote) {
37
+ if (!validRemote(remote))
38
+ throw Error('Use a configured Git remote name for AC coordination.');
39
+ const top = fs.realpathSync.native(git(root, ['rev-parse', '--show-toplevel']));
40
+ const selected = fs.realpathSync.native(root);
41
+ // Windows Git can spell a root with different casing or an 8.3 alias.
42
+ if (path.relative(top, selected) !== '')
43
+ throw Error('Run AC coordination at the Git repository root.');
44
+ git(root, ['remote', 'get-url', '--push', '--all', remote]);
45
+ const fetch = git(root, ['remote', 'get-url', '--all', remote]), push = git(root, ['remote', 'get-url', '--push', '--all', remote]);
46
+ if (fetch.includes('\n') || push.includes('\n') || fetch !== push)
47
+ throw Error('AC coordination requires the same fetch and push URL.');
48
+ }
49
+ export function coordinationSettings(root) {
50
+ const file = local(root, settingsPath);
51
+ if (!fs.existsSync(file))
52
+ return;
53
+ const raw = JSON.parse(fs.readFileSync(file, 'utf8'));
54
+ if (raw?.version !== 1 || !['git', 'local'].includes(raw.mode))
55
+ throw Error('Invalid AC coordination settings; select local or git mode explicitly.');
56
+ if (raw.mode === 'local') {
57
+ if (Object.keys(raw).some(k => !['version', 'mode'].includes(k)))
58
+ throw Error('Local AC settings accept only version and mode.');
59
+ return;
60
+ }
61
+ if (!validRemote(raw.remote) || !uuid(raw.authority) || Object.keys(raw).some(k => !['version', 'mode', 'remote', 'authority'].includes(k)))
62
+ throw Error('Invalid Git AC coordination settings.');
63
+ return raw;
64
+ }
65
+ function readAuthority(root, remote, c) {
66
+ const line = git(root, ['ls-remote', '--refs', remote, authorityRef]);
67
+ if (!line)
68
+ return;
69
+ const tip = line.split(/\s+/)[0];
70
+ if (!/^[a-f0-9]{40,64}$/.test(tip))
71
+ throw Error('Invalid AC authority tip.');
72
+ git(root, ['fetch', '--no-tags', '--no-write-fetch-head', remote, tip]);
73
+ const raw = JSON.parse(git(root, ['show', `${tip}:claims.json`]));
74
+ if (raw?.version !== 1 || !uuid(raw.id) || !raw.requests || typeof raw.requests !== 'object' || Array.isArray(raw.requests))
75
+ throw Error('Invalid AC authority state.');
76
+ raw.registry = parseRegistry(raw.registry, { ...c, ac: { ...c.ac, capabilities: {} } });
77
+ const claims = new Set();
78
+ for (const [key, v] of Object.entries(raw.requests)) {
79
+ if (!uuid(key) || !v || typeof v.signature !== 'string')
80
+ throw Error('Invalid AC request record.');
81
+ const request = JSON.parse(v.signature), record = Object.hasOwn(raw.registry.capabilities, request.capability) ? raw.registry.capabilities[request.capability] : undefined;
82
+ if (!record || !['next', 'rename'].includes(request.kind))
83
+ throw Error('Invalid AC request capability or kind.');
84
+ if (request.kind === 'next') {
85
+ const match = typeof v.result === 'string' ? /^([A-Z][A-Z0-9]*)-(\d+)$/.exec(v.result) : null;
86
+ if (!match || ![record.prefix, ...record.previousPrefixes].includes(match[1]) || !Number.isSafeInteger(Number(match[2])) || Number(match[2]) < 1 || Number(match[2]) > record.highWater)
87
+ throw Error('Invalid AC reservation result.');
88
+ const claim = `${request.capability}:${Number(match[2])}`;
89
+ if (claims.has(claim))
90
+ throw Error('Duplicate AC reservation result.');
91
+ claims.add(claim);
92
+ }
93
+ else if (v.result !== null || ![record.prefix, ...record.previousPrefixes].includes(request.prefix))
94
+ throw Error('Invalid AC prefix reservation result.');
95
+ }
96
+ return { tip, value: raw };
97
+ }
98
+ function publish(root, remote, tip, value) {
99
+ const blob = git(root, ['hash-object', '-w', '--stdin'], json(value));
100
+ const tree = git(root, ['mktree'], `100644 blob ${blob}\tclaims.json\n`);
101
+ const commit = git(root, ['commit-tree', tree, ...(tip ? ['-p', tip] : []), '-m', 'Reserve acceptance identities']);
102
+ // Every update is constructed as a descendant; the exact lease also rejects deletion or a changed tip.
103
+ git(root, ['push', '--porcelain', `--force-with-lease=${authorityRef}:${tip ?? ''}`, remote, `${commit}:${authorityRef}`]);
104
+ }
105
+ function writeSetup(file, remote, authority, rejectedCreation = false) {
106
+ const temp = file + '.' + randomUUID() + '.tmp';
107
+ fs.writeFileSync(temp, json({ remote, authority, ...(rejectedCreation ? { rejectedCreation: true } : {}) }), { flag: 'wx' });
108
+ fs.renameSync(temp, file);
109
+ }
110
+ function rejectedCreation(error) {
111
+ // A transport failure is ambiguous. Only Git's explicit lease rejection proves this creation did not publish.
112
+ const output = String(error?.stdout ?? '');
113
+ return output.split(/\r?\n/).some(line => {
114
+ const [flag, ref, status] = line.split('\t');
115
+ return flag === '!' && ref?.endsWith(`:${authorityRef}`) && /^\[rejected\] \((stale info|already exists)\)$/.test(status ?? '');
116
+ });
117
+ }
118
+ function merge(root, c, remote, own) {
119
+ const r = structuredClone(remote);
120
+ for (const [prefix, n] of Object.entries(own.unassignedPrefixes))
121
+ r.unassignedPrefixes[prefix] = Math.max(r.unassignedPrefixes[prefix] ?? 0, n);
122
+ for (const [name, record] of Object.entries(own.capabilities)) {
123
+ const target = Object.hasOwn(r.capabilities, name) ? r.capabilities[name] : undefined;
124
+ if (target) {
125
+ if (target.prefix !== record.prefix && !target.previousPrefixes.includes(record.prefix))
126
+ throw Error(`Conflicting AC prefix authority for ${name}; synchronize and reconcile mappings.`);
127
+ if (record.previousPrefixes.some(p => p !== target.prefix && !target.previousPrefixes.includes(p)))
128
+ throw Error(`Conflicting AC prefix history for ${name}.`);
129
+ target.highWater = Math.max(target.highWater, record.highWater, maximum(root, target));
130
+ }
131
+ else
132
+ r.capabilities[name] = structuredClone(record);
133
+ }
134
+ for (const record of Object.values(r.capabilities)) {
135
+ for (const prefix of [record.prefix, ...record.previousPrefixes]) {
136
+ if (Object.hasOwn(r.unassignedPrefixes, prefix)) {
137
+ record.highWater = Math.max(record.highWater, r.unassignedPrefixes[prefix]);
138
+ delete r.unassignedPrefixes[prefix];
139
+ }
140
+ }
141
+ record.highWater = maximum(root, record);
142
+ }
143
+ return parseRegistry(r, { ...c, ac: { ...c.ac, capabilities: {} } });
144
+ }
145
+ function persist(root, r, settings) {
146
+ const doc = parseDocument(fs.readFileSync(local(root, '.cliewen-openspec/config.yaml'), 'utf8'));
147
+ if (doc.errors.length)
148
+ throw Error(doc.errors[0].message);
149
+ const c = config(root), expected = structuredClone(doc.toJS());
150
+ let changed = false;
151
+ for (const name of Object.keys(c.ac.capabilities))
152
+ if (Object.hasOwn(r.capabilities, name) && c.ac.capabilities[name] !== r.capabilities[name].prefix) {
153
+ doc.setIn(['ac', 'capabilities', name], r.capabilities[name].prefix);
154
+ expected.ac.capabilities[name] = r.capabilities[name].prefix;
155
+ changed = true;
156
+ }
157
+ if (!isDeepStrictEqual(doc.toJS(), expected))
158
+ throw Error('Prefix synchronization would change unrelated YAML values through shared aliases; reconcile those aliases first.');
159
+ transaction(root, { [registryPath]: json(r), ...(changed ? { '.cliewen-openspec/config.yaml': doc.toString() } : {}), ...(settings ? { [settingsPath]: json(settings) } : {}) });
160
+ }
161
+ export function coordinate(root, remote, apply = false) {
162
+ const action = () => {
163
+ repository(root, remote);
164
+ const c = config(root), own = validateRegistry(root, c), settings = coordinationSettings(root);
165
+ const setupFile = runtimeFile(root, 'setup.json');
166
+ const pending = fs.existsSync(setupFile) ? JSON.parse(fs.readFileSync(setupFile, 'utf8')) : undefined;
167
+ if (pending && (!uuid(pending.authority) || pending.remote !== remote))
168
+ throw Error('Pending AC setup names another remote or is invalid; reconcile it before changing authority.');
169
+ if (settings && settings.remote !== remote)
170
+ throw Error('AC authority is already selected; changing authorities requires explicit project migration.');
171
+ const found = readAuthority(root, remote, c);
172
+ if (pending && found && found.value.id !== pending.authority && !(pending.rejectedCreation === true && !settings))
173
+ throw Error('Pending AC setup authority was replaced; investigate before continuing.');
174
+ if (settings && (!found || found.value.id !== settings.authority))
175
+ throw Error('Selected AC authority is missing or replaced; no local fallback.');
176
+ const r = merge(root, c, found?.value.registry ?? { version: 2, capabilities: {}, unassignedPrefixes: {} }, own);
177
+ if (!apply)
178
+ return { mode: 'git', remote, ref: authorityRef, action: found ? 'join-and-seed' : 'create-and-seed', registry: r };
179
+ if (fs.existsSync(pendingFile(root)))
180
+ throw Error('A reservation is pending; run ac resume before setup.');
181
+ let value = found?.value ?? { version: 1, id: pending?.authority ?? randomUUID(), registry: r, requests: {} };
182
+ writeSetup(setupFile, remote, value.id);
183
+ value.registry = r;
184
+ try {
185
+ publish(root, remote, found?.tip, value);
186
+ }
187
+ catch (error) {
188
+ if (!found && !settings && rejectedCreation(error)) {
189
+ writeSetup(setupFile, remote, value.id, true);
190
+ throw Error(`Another setup won initial creation. Repeat ac coordinate ${remote} --apply to join its authority; allocation remains blocked until then.`);
191
+ }
192
+ throw error;
193
+ }
194
+ persist(root, r, { version: 1, mode: 'git', remote, authority: value.id });
195
+ fs.unlinkSync(setupFile);
196
+ return { mode: 'git', remote, ref: authorityRef, authority: value.id };
197
+ };
198
+ return apply ? withStateLock(root, () => { recover(root); return action(); }) : action();
199
+ }
200
+ export function syncIds(root) {
201
+ return withStateLock(root, () => {
202
+ requireCompletedSetup(root);
203
+ recover(root);
204
+ const settings = coordinationSettings(root);
205
+ if (!settings)
206
+ throw Error('AC sync requires Git coordination.');
207
+ repository(root, settings.remote);
208
+ const c = config(root), own = validateRegistry(root, c), found = readAuthority(root, settings.remote, c);
209
+ if (!found || found.value.id !== settings.authority)
210
+ throw Error('Selected AC authority is missing or replaced.');
211
+ const combined = merge(root, c, found.value.registry, own);
212
+ if (JSON.stringify(combined) !== JSON.stringify(found.value.registry))
213
+ throw Error('Local reservations exceed the authority; preview and apply ac coordinate to seed them first.');
214
+ persist(root, found.value.registry);
215
+ return { mode: 'git', remote: settings.remote };
216
+ });
217
+ }
218
+ export function reserve(root, kind, capability, prefix) {
219
+ requireCompletedSetup(root);
220
+ const settings = coordinationSettings(root);
221
+ if (!settings)
222
+ throw Error('Git coordination is not selected.');
223
+ repository(root, settings.remote);
224
+ const c = config(root), own = validateRegistry(root, c), file = pendingFile(root);
225
+ const request = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : { id: randomUUID(), kind, capability, ...(prefix ? { prefix } : {}) };
226
+ if (!request || !['next', 'rename'].includes(request.kind) || typeof request.capability !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(request.capability) || (request.kind === 'next' ? request.prefix !== undefined : typeof request.prefix !== 'string' || !/^[A-Z][A-Z0-9]*$/.test(request.prefix)))
227
+ throw Error('Invalid pending AC request; abandon it after checking the authority.');
228
+ if (!uuid(request.id) || request.kind !== kind || request.capability !== capability || request.prefix !== prefix)
229
+ throw Error('Another AC reservation is pending; run ac resume before requesting a different operation.');
230
+ const signature = JSON.stringify({ kind, capability, prefix: prefix ?? null });
231
+ let lastError;
232
+ for (let attempt = 0; attempt < 6; attempt++) {
233
+ const found = readAuthority(root, settings.remote, c);
234
+ if (!found || found.value.id !== settings.authority)
235
+ throw Error('Selected AC authority is missing or replaced; reservation remains pending.');
236
+ const value = found.value, previous = value.requests[request.id];
237
+ if (previous) {
238
+ if (previous.signature !== signature)
239
+ throw Error('AC request identity conflict.');
240
+ persist(root, value.registry);
241
+ fs.unlinkSync(file);
242
+ return previous.result;
243
+ }
244
+ const r = merge(root, c, value.registry, own);
245
+ if (!Object.hasOwn(c.ac.capabilities, capability))
246
+ throw Error(`Unknown capability: ${capability}`);
247
+ const record = r.capabilities[capability];
248
+ let result = null;
249
+ if (kind === 'next') {
250
+ record.highWater++;
251
+ if (!Number.isSafeInteger(record.highWater))
252
+ throw Error('AC sequence exhausted.');
253
+ result = `${record.prefix}-${String(record.highWater).padStart(c.ac.padding, '0')}`;
254
+ }
255
+ else {
256
+ if (!prefix || !/^[A-Z][A-Z0-9]*$/.test(prefix))
257
+ throw Error('Invalid AC prefix.');
258
+ if (record.prefix !== prefix) {
259
+ if (Object.hasOwn(r.unassignedPrefixes, prefix) || Object.values(r.capabilities).some(v => v.prefix === prefix || v.previousPrefixes.includes(prefix)))
260
+ throw Error(`AC prefix is already reserved: ${prefix}`);
261
+ if (maximum(root, { prefix, previousPrefixes: [], highWater: 0 }) > 0)
262
+ throw Error(`AC prefix already occurs in OpenSpec documents: ${prefix}`);
263
+ record.previousPrefixes.push(record.prefix);
264
+ record.prefix = prefix;
265
+ }
266
+ }
267
+ value.registry = r;
268
+ value.requests[request.id] = { signature, result };
269
+ if (!fs.existsSync(file)) {
270
+ const temp = file + '.' + randomUUID() + '.tmp';
271
+ fs.writeFileSync(temp, json(request), { flag: 'wx' });
272
+ fs.renameSync(temp, file);
273
+ }
274
+ try {
275
+ publish(root, settings.remote, found.tip, value);
276
+ }
277
+ catch (error) {
278
+ lastError = error;
279
+ continue;
280
+ }
281
+ // Re-read the remote even after an apparently successful push to reconcile the durable request.
282
+ }
283
+ const final = readAuthority(root, settings.remote, c);
284
+ if (final?.value.id === settings.authority && final.value.requests[request.id]?.signature === signature) {
285
+ persist(root, final.value.registry);
286
+ const result = final.value.requests[request.id].result;
287
+ fs.unlinkSync(file);
288
+ return result;
289
+ }
290
+ throw Error(`AC reservation could not be confirmed; no ID returned. Retry ac resume. ${lastError instanceof Error ? lastError.message : ''}`);
291
+ }
292
+ export function resumeIds(root) {
293
+ return withStateLock(root, () => { recover(root); const file = pendingFile(root); if (!fs.existsSync(file))
294
+ throw Error('No AC reservation is pending.'); const r = JSON.parse(fs.readFileSync(file, 'utf8')); return reserve(root, r.kind, r.capability, r.prefix); });
295
+ }
296
+ export function assertNoPendingLocal(root) {
297
+ requireCompletedSetup(root);
298
+ if (fs.existsSync(pendingFile(root)))
299
+ throw Error('A coordinated reservation is pending. Restore Git mode and run ac resume or ac abandon before local allocation.');
300
+ }
301
+ export function abandonRequest(root) {
302
+ return withStateLock(root, () => {
303
+ recover(root);
304
+ const settings = coordinationSettings(root);
305
+ if (!settings)
306
+ throw Error('Restore Git coordination before abandoning a pending request.');
307
+ const file = pendingFile(root);
308
+ if (!fs.existsSync(file))
309
+ throw Error('No AC reservation is pending.');
310
+ repository(root, settings.remote);
311
+ const c = config(root), found = readAuthority(root, settings.remote, c);
312
+ if (!found || found.value.id !== settings.authority)
313
+ throw Error('Cannot abandon while the selected authority is unavailable or replaced.');
314
+ persist(root, merge(root, c, found.value.registry, validateRegistry(root, c)));
315
+ fs.unlinkSync(file);
316
+ return 'Pending request abandoned; any published reservation remains permanently reserved.';
317
+ });
318
+ }
package/dist/ac.d.ts CHANGED
@@ -1,16 +1,17 @@
1
1
  import { type Config } from './core.js';
2
- type Sequence = {
2
+ export type Sequence = {
3
3
  prefix: string;
4
4
  previousPrefixes: string[];
5
5
  highWater: number;
6
6
  };
7
- type Registry = {
7
+ export type Registry = {
8
8
  version: 2;
9
9
  capabilities: Record<string, Sequence>;
10
10
  unassignedPrefixes: Record<string, number>;
11
11
  };
12
12
  export declare function validateRegistry(root: string, c: Config): Registry;
13
+ export declare function parseRegistry(raw: any, c: Config): Registry;
14
+ export declare function maximum(root: string, record: Sequence): number;
13
15
  export declare function nextId(root: string, capability: string): string;
14
16
  export declare function capabilityForPrefix(root: string, prefix: string): string;
15
17
  export declare function renamePrefix(root: string, capability: string, prefix: string): void;
16
- export {};
package/dist/ac.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { coordinationSettings, reserve, assertNoPendingLocal } from './ac-coordination.js';
2
+ import { withStateLock } from './state-lock.js';
1
3
  import fs from 'node:fs';
2
4
  import { parseDocument } from 'yaml';
3
5
  import { config, local, markdowns, recover, transaction } from './core.js';
@@ -11,6 +13,9 @@ const json = (o) => JSON.stringify(o, null, 2) + '\n';
11
13
  export function validateRegistry(root, c) {
12
14
  const dest = local(root, registryPath);
13
15
  const raw = fs.existsSync(dest) ? JSON.parse(read(dest)) : {};
16
+ return parseRegistry(raw, c);
17
+ }
18
+ export function parseRegistry(raw, c) {
14
19
  if (!raw || typeof raw !== 'object' || Array.isArray(raw))
15
20
  throw Error('Invalid AC registry');
16
21
  let r;
@@ -62,7 +67,7 @@ export function validateRegistry(root, c) {
62
67
  }
63
68
  return r;
64
69
  }
65
- function maximum(root, record) {
70
+ export function maximum(root, record) {
66
71
  let max = record.highWater;
67
72
  const prefixes = new Set([record.prefix, ...record.previousPrefixes]);
68
73
  for (const file of markdowns(local(root, 'openspec'))) {
@@ -76,8 +81,14 @@ function maximum(root, record) {
76
81
  return max;
77
82
  }
78
83
  export function nextId(root, capability) {
84
+ return withStateLock(root, () => allocate(root, capability));
85
+ }
86
+ function allocate(root, capability) {
79
87
  recover(root);
80
88
  const c = config(root), r = validateRegistry(root, c);
89
+ if (coordinationSettings(root))
90
+ return reserve(root, 'next', capability);
91
+ assertNoPendingLocal(root);
81
92
  if (!Object.hasOwn(c.ac.capabilities, capability))
82
93
  throw Error(`Unknown capability: ${capability}; register it in ac.capabilities first`);
83
94
  const record = r.capabilities[capability];
@@ -100,10 +111,18 @@ export function capabilityForPrefix(root, prefix) {
100
111
  return entry[0];
101
112
  }
102
113
  export function renamePrefix(root, capability, prefix) {
114
+ return withStateLock(root, () => rename(root, capability, prefix));
115
+ }
116
+ function rename(root, capability, prefix) {
103
117
  recover(root);
104
118
  if (!validPrefix(prefix))
105
119
  throw Error('Prefix must contain uppercase letters/digits and start with a letter');
106
120
  const c = config(root), r = validateRegistry(root, c);
121
+ if (coordinationSettings(root)) {
122
+ reserve(root, 'rename', capability, prefix);
123
+ return;
124
+ }
125
+ assertNoPendingLocal(root);
107
126
  if (!Object.hasOwn(c.ac.capabilities, capability))
108
127
  throw Error(`Unknown capability: ${capability}`);
109
128
  const record = r.capabilities[capability];
@@ -0,0 +1,19 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ export declare const ciLimits: {
3
+ requestMilliseconds: number;
4
+ totalMilliseconds: number;
5
+ responseBytes: number;
6
+ pages: number;
7
+ pageSize: number;
8
+ rulesets: number;
9
+ };
10
+ export type HostResponse = {
11
+ status: number;
12
+ data?: unknown;
13
+ next?: boolean;
14
+ problem?: string;
15
+ };
16
+ export type HostAccess = (endpoint: string) => HostResponse;
17
+ type Execute = (file: string, args: string[], options: Parameters<typeof execFileSync>[2]) => string;
18
+ export declare function githubAccess(execute?: Execute, now?: () => number): HostAccess;
19
+ export {};