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
@@ -0,0 +1,70 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { accessSync, constants, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ export const ciLimits = { requestMilliseconds: 10000, totalMilliseconds: 60000, responseBytes: 1048576, pages: 10, pageSize: 100, rulesets: 32 };
5
+ function githubExecutable() {
6
+ const windows = process.platform === 'win32';
7
+ for (const entry of (process.env.PATH ?? '').split(path.delimiter)) {
8
+ const directory = windows ? entry.replace(/^"|"$/g, '') : entry;
9
+ // An absolute executable avoids the implicit current-directory search on Windows.
10
+ if (!path.isAbsolute(directory))
11
+ continue;
12
+ const candidate = path.resolve(directory, windows ? 'gh.exe' : 'gh');
13
+ try {
14
+ if (!statSync(candidate).isFile())
15
+ continue;
16
+ if (!windows)
17
+ accessSync(candidate, constants.X_OK);
18
+ return candidate;
19
+ }
20
+ catch { /* Continue to the next PATH entry. */ }
21
+ }
22
+ }
23
+ // Only fixed GET requests reach gh. Error bodies and stderr can contain secrets.
24
+ export function githubAccess(execute, now = () => performance.now()) {
25
+ const end = now() + ciLimits.totalMilliseconds;
26
+ const executable = execute ? 'gh' : githubExecutable();
27
+ const run = execute ?? ((file, args, options) => String(execFileSync(file, args, options)));
28
+ return endpoint => {
29
+ const remaining = end - now();
30
+ if (remaining <= 0)
31
+ return { status: 0, problem: 'inspection-deadline' };
32
+ if (!executable)
33
+ return { status: 0, problem: 'github-cli-unavailable' };
34
+ let output = '';
35
+ try {
36
+ output = run(executable, ['api', '--hostname', 'github.com', '--method', 'GET', '--include', '-H', 'Accept: application/vnd.github+json', '-H', 'X-GitHub-Api-Version: 2022-11-28', endpoint], {
37
+ encoding: 'utf8', timeout: Math.max(1, Math.floor(Math.min(remaining, ciLimits.requestMilliseconds))), killSignal: 'SIGKILL',
38
+ maxBuffer: ciLimits.responseBytes, stdio: ['ignore', 'pipe', 'pipe'],
39
+ env: { ...process.env, GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1', GH_NO_EXTENSION_UPDATE_NOTIFIER: '1', GH_DEBUG: '', PAGER: 'cat', GH_PAGER: 'cat' }
40
+ });
41
+ }
42
+ catch (error) {
43
+ const e = error;
44
+ if (e.code === 'ENOENT')
45
+ return { status: 0, problem: 'github-cli-unavailable' };
46
+ if (e.code === 'ENOBUFS')
47
+ return { status: 0, problem: 'response-limit' };
48
+ if (e.code === 'ETIMEDOUT' || e.signal)
49
+ return { status: 0, problem: 'request-deadline' };
50
+ output = String(e.stdout ?? '');
51
+ const status = /^HTTP\/\S+ (\d{3})/m.exec(output)?.[1];
52
+ return { status: Number(status ?? 0), problem: status ? `http-${status}` : 'host-access-unavailable' };
53
+ }
54
+ if (now() > end)
55
+ return { status: 0, problem: 'inspection-deadline' };
56
+ if (Buffer.byteLength(output) > ciLimits.responseBytes)
57
+ return { status: 0, problem: 'response-limit' };
58
+ const split = /\r?\n\r?\n/.exec(output);
59
+ const status = Number(/^HTTP\/\S+ (\d{3})/m.exec(output)?.[1] ?? 0);
60
+ if (!split || status !== 200)
61
+ return { status, problem: status ? `http-${status}` : 'malformed-response' };
62
+ const headers = output.slice(0, split.index);
63
+ try {
64
+ return { status, data: JSON.parse(output.slice(split.index + split[0].length)), next: /^link:.*\brel="?next"?/im.test(headers) };
65
+ }
66
+ catch {
67
+ return { status, problem: 'malformed-response' };
68
+ }
69
+ };
70
+ }
@@ -0,0 +1,48 @@
1
+ import { type ExpectedCheck } from './ci-settings.js';
2
+ import { ciLimits, type HostAccess } from './ci-github.js';
3
+ type Check = {
4
+ context: string;
5
+ appId: number | null;
6
+ };
7
+ type Bypass = {
8
+ status: 'possible' | 'none-observed' | 'unknown';
9
+ reason: string;
10
+ };
11
+ type Source = {
12
+ id: string;
13
+ kind: 'classic' | 'effective-rules' | 'ruleset';
14
+ status: 'available' | 'absent' | 'unknown';
15
+ checks: Check[];
16
+ bypass: Bypass;
17
+ problem?: string;
18
+ };
19
+ type CheckResult = ExpectedCheck & {
20
+ status: 'observed' | 'missing' | 'unknown';
21
+ sources: string[];
22
+ };
23
+ export type CIReport = {
24
+ version: 1;
25
+ inspectedAt: string;
26
+ mode: 'off' | 'advisory';
27
+ status: 'off' | 'not-configured' | 'observed' | 'missing' | 'unknown';
28
+ exitCode: 0;
29
+ target: {
30
+ host: 'github.com';
31
+ repository: string | null;
32
+ branch: string | null;
33
+ };
34
+ checks: CheckResult[];
35
+ sources: Source[];
36
+ coverage: {
37
+ complete: boolean;
38
+ limits: typeof ciLimits;
39
+ notes: string[];
40
+ };
41
+ findings: {
42
+ code: string;
43
+ message: string;
44
+ }[];
45
+ };
46
+ export declare function inspectCI(root: string, suppliedAccess?: HostAccess): CIReport;
47
+ export declare function ciSummary(report: CIReport): string;
48
+ export {};
@@ -0,0 +1,246 @@
1
+ import { config } from './core.js';
2
+ import { ciBranch, ciText } from './ci-settings.js';
3
+ import { githubAccess, ciLimits } from './ci-github.js';
4
+ import { requirements, meetsMinimum } from './release.js';
5
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
6
+ const unknownBypass = () => ({ status: 'unknown', reason: 'Bypass information is unavailable; no actor-specific conclusion is made.' });
7
+ const source = (id, kind) => ({ id, kind, status: 'unknown', checks: [], bypass: unknownBypass() });
8
+ const positiveID = (v) => Number.isSafeInteger(v) && v > 0;
9
+ function checks(raw, binding) {
10
+ if (!Array.isArray(raw))
11
+ return;
12
+ const result = [];
13
+ for (const item of raw) {
14
+ if (!object(item) || !ciText(item.context))
15
+ return;
16
+ const id = item[binding];
17
+ if (id !== undefined && id !== null && id !== -1 && !positiveID(id))
18
+ return;
19
+ result.push({ context: item.context, appId: positiveID(id) ? id : null });
20
+ }
21
+ return result;
22
+ }
23
+ function ruleChecks(rule) {
24
+ return object(rule.parameters) ? checks(rule.parameters.required_status_checks, 'integration_id') : undefined;
25
+ }
26
+ function rulesetChecksAgree(current, previouslyObserved) {
27
+ if (!Array.isArray(current))
28
+ return false;
29
+ const identity = (check) => JSON.stringify([check.context, check.appId]);
30
+ const expected = new Set(previouslyObserved.map(identity));
31
+ const seen = new Set();
32
+ for (const rule of current) {
33
+ if (!object(rule) || !ciText(rule.type))
34
+ return false;
35
+ if (rule.type !== 'required_status_checks')
36
+ continue;
37
+ const list = ruleChecks(rule);
38
+ if (!list)
39
+ return false;
40
+ for (const check of list)
41
+ seen.add(identity(check));
42
+ }
43
+ return expected.size === seen.size && [...expected].every(check => seen.has(check));
44
+ }
45
+ function branchReportsClassicProtection(protection) {
46
+ if (!object(protection))
47
+ return false;
48
+ if (protection.enabled === true)
49
+ return true;
50
+ const required = protection.required_status_checks;
51
+ if (!object(required))
52
+ return false;
53
+ return (Array.isArray(required.checks) && required.checks.length > 0)
54
+ || (Array.isArray(required.contexts) && required.contexts.length > 0)
55
+ || ['everyone', 'non_admins'].includes(required.enforcement_level);
56
+ }
57
+ function classicProtection(response) {
58
+ const s = source('classic', 'classic');
59
+ if (response.problem || response.status !== 200 || !object(response.data)) {
60
+ s.problem = response.problem ?? 'classic-unavailable';
61
+ return s;
62
+ }
63
+ const raw = response.data, required = raw.required_status_checks;
64
+ if (required === null || required === undefined)
65
+ s.status = 'available';
66
+ else if (object(required)) {
67
+ const bound = required.checks === undefined ? [] : checks(required.checks, 'app_id');
68
+ const contexts = required.contexts;
69
+ if (!bound || (contexts !== undefined && (!Array.isArray(contexts) || !contexts.every(ciText))) || (required.checks === undefined && contexts === undefined)) {
70
+ s.problem = 'malformed-classic-checks';
71
+ return s;
72
+ }
73
+ s.checks = [...bound, ...(contexts ?? []).filter((c) => !bound.some(b => b.context === c)).map((context) => ({ context, appId: null }))];
74
+ s.status = 'available';
75
+ }
76
+ else {
77
+ s.problem = 'malformed-classic-protection';
78
+ return s;
79
+ }
80
+ if (object(raw.enforce_admins) && typeof raw.enforce_admins.enabled === 'boolean')
81
+ s.bypass = raw.enforce_admins.enabled
82
+ ? { status: 'none-observed', reason: 'Classic protection reports administrator enforcement; actor permissions were not resolved.' }
83
+ : { status: 'possible', reason: 'Classic protection exempts administrators; no actual bypass event was inspected.' };
84
+ return s;
85
+ }
86
+ // Known non-check rules do not prevent a status-check conclusion. New policy types
87
+ // stay incomplete until their effect on the supported contract is understood.
88
+ const otherRules = new Set(['creation', 'update', 'deletion', 'required_linear_history', 'merge_queue', 'required_deployments', 'required_signatures', 'pull_request', 'non_fast_forward', 'commit_message_pattern', 'commit_author_email_pattern', 'committer_email_pattern', 'branch_name_pattern', 'tag_name_pattern', 'file_path_restriction', 'file_extension_restriction', 'max_file_path_length', 'max_file_size', 'code_scanning', 'code_quality', 'copilot_code_review']);
89
+ export function inspectCI(root, suppliedAccess) {
90
+ if (!meetsMinimum(process.versions.node, requirements.node))
91
+ throw Error(`Node ${process.versions.node} is unsupported; requires Node ${requirements.node}+. Install a compatible Node runtime and rerun ci inspect.`);
92
+ const settings = config(root).ciInspection;
93
+ const report = { version: 1, inspectedAt: new Date().toISOString(), mode: settings.mode, status: 'unknown', exitCode: 0,
94
+ target: { host: 'github.com', repository: settings.repository, branch: settings.branch }, checks: settings.requiredChecks.map(c => ({ ...c, status: 'unknown', sources: [] })), sources: [],
95
+ coverage: { complete: false, limits: { ...ciLimits }, notes: ['This is a non-atomic policy snapshot, not current CI results, test quality or integration authorization.', 'Coverage is limited to GitHub.com status-check requirements; actor-specific permissions are not resolved.'] }, findings: [] };
96
+ const finding = (code, message) => report.findings.push({ code, message });
97
+ if (settings.mode === 'off') {
98
+ report.status = 'off';
99
+ return report;
100
+ }
101
+ if (!settings.repository || !settings.requiredChecks.length) {
102
+ report.status = 'not-configured';
103
+ finding('ci-not-configured', 'Select ciInspection.repository and a nonempty requiredChecks list before host access.');
104
+ return report;
105
+ }
106
+ const access = suppliedAccess ?? githubAccess();
107
+ const repo = `repos/${settings.repository.split('/').map(encodeURIComponent).join('/')}`;
108
+ const metadata = access(repo);
109
+ if (metadata.problem || metadata.status !== 200 || !object(metadata.data) || !ciText(metadata.data.full_name) || metadata.data.full_name.toLowerCase() !== settings.repository.toLowerCase()) {
110
+ finding('ci-target-unknown', `Repository identity could not be confirmed (${metadata.problem ?? 'invalid-repository-response'}).`);
111
+ return report;
112
+ }
113
+ const branch = settings.branch ?? metadata.data.default_branch;
114
+ if (!ciBranch(branch)) {
115
+ finding('ci-target-unknown', 'A valid target branch could not be resolved.');
116
+ return report;
117
+ }
118
+ report.target.branch = branch;
119
+ const branchPath = `${repo}/branches/${encodeURIComponent(branch)}`, branchResponse = access(branchPath);
120
+ if (branchResponse.problem || branchResponse.status !== 200 || !object(branchResponse.data) || branchResponse.data.name !== branch || typeof branchResponse.data.protected !== 'boolean') {
121
+ finding('ci-target-unknown', `The selected branch could not be confirmed (${branchResponse.problem ?? 'invalid-branch-response'}).`);
122
+ return report;
123
+ }
124
+ const classicResponse = access(`${branchPath}/protection`), classic = classicProtection(classicResponse);
125
+ const effective = source('effective-rules', 'effective-rules');
126
+ // This source records collection coverage. Individual rulesets retain their own exceptions.
127
+ effective.bypass = { status: 'unknown', reason: 'See individual ruleset sources for bypass visibility.' };
128
+ report.sources.push(classic, effective);
129
+ const ruleSources = new Map();
130
+ let rulesComplete = false, ruleCount = 0;
131
+ for (let page = 1; page <= ciLimits.pages; page++) {
132
+ const response = access(`${repo}/rules/branches/${encodeURIComponent(branch)}?per_page=${ciLimits.pageSize}&page=${page}`);
133
+ if (response.problem || response.status !== 200 || !Array.isArray(response.data) || response.data.length > ciLimits.pageSize) {
134
+ effective.problem = response.problem ?? 'malformed-rules';
135
+ break;
136
+ }
137
+ ruleCount += response.data.length;
138
+ for (const rule of response.data) {
139
+ if (!object(rule) || !ciText(rule.type)) {
140
+ effective.problem = 'malformed-rule';
141
+ continue;
142
+ }
143
+ if (rule.type !== 'required_status_checks') {
144
+ if (!otherRules.has(rule.type))
145
+ effective.problem = 'unsupported-policy-type';
146
+ continue;
147
+ }
148
+ const list = ruleChecks(rule);
149
+ if (!list || !positiveID(rule.ruleset_id) || !ciText(rule.ruleset_source) || !['Repository', 'Organization', 'Enterprise'].includes(rule.ruleset_source_type)) {
150
+ effective.problem = 'malformed-check-rule';
151
+ continue;
152
+ }
153
+ const key = `ruleset:${rule.ruleset_source_type}:${rule.ruleset_source}:${rule.ruleset_id}`;
154
+ let item = ruleSources.get(key);
155
+ if (!item) {
156
+ if (ruleSources.size >= ciLimits.rulesets) {
157
+ effective.problem = 'ruleset-limit';
158
+ continue;
159
+ }
160
+ item = { s: source(key, 'ruleset'), id: rule.ruleset_id, origin: rule.ruleset_source, originType: rule.ruleset_source_type };
161
+ item.s.status = 'available';
162
+ ruleSources.set(key, item);
163
+ report.sources.push(item.s);
164
+ }
165
+ item.s.checks.push(...list);
166
+ }
167
+ if (response.next !== true && response.data.length < ciLimits.pageSize) {
168
+ rulesComplete = true;
169
+ break;
170
+ }
171
+ if (page === ciLimits.pages)
172
+ effective.problem = 'pagination-limit';
173
+ }
174
+ effective.status = rulesComplete && !effective.problem ? 'available' : 'unknown';
175
+ const noProtection = branchResponse.data.protected === false;
176
+ if (noProtection && ruleCount > 0) {
177
+ effective.status = 'unknown';
178
+ effective.problem = 'contradictory-protection';
179
+ for (const item of ruleSources.values())
180
+ item.s.checks = [];
181
+ }
182
+ if (noProtection && classicResponse.status === 200) {
183
+ classic.status = 'unknown';
184
+ classic.checks = [];
185
+ classic.problem = 'contradictory-protection';
186
+ }
187
+ if (noProtection && classicResponse.status === 404) {
188
+ if (branchReportsClassicProtection(branchResponse.data.protection))
189
+ classic.problem = 'contradictory-protection';
190
+ else if (effective.status === 'available' && ruleCount === 0) {
191
+ classic.status = 'absent';
192
+ delete classic.problem;
193
+ }
194
+ }
195
+ for (const { s, id, origin, originType } of ruleSources.values()) {
196
+ const response = access(`${repo}/rulesets/${id}?includes_parents=true`), raw = response.data;
197
+ if (response.problem || response.status !== 200) {
198
+ s.problem = response.problem ?? 'ruleset-detail-unavailable';
199
+ continue;
200
+ }
201
+ if (!object(raw) || raw.id !== id || raw.source !== origin || raw.enforcement !== 'active'
202
+ || (raw.source_type !== undefined && raw.source_type !== originType)
203
+ || (raw.target !== undefined && raw.target !== 'branch')) {
204
+ s.status = 'unknown';
205
+ s.checks = [];
206
+ s.problem = 'contradictory-ruleset';
207
+ continue;
208
+ }
209
+ if (raw.rules !== undefined && !rulesetChecksAgree(raw.rules, s.checks)) {
210
+ s.status = 'unknown';
211
+ s.checks = [];
212
+ s.problem = 'contradictory-ruleset-checks';
213
+ continue;
214
+ }
215
+ if (raw.bypass_actors === undefined)
216
+ continue;
217
+ if (!Array.isArray(raw.bypass_actors) || raw.bypass_actors.some((a) => !object(a) || !ciText(a.actor_type) || (a.bypass_mode !== undefined && !['always', 'pull_request', 'exempt'].includes(a.bypass_mode)))) {
218
+ s.problem = 'malformed-bypass';
219
+ continue;
220
+ }
221
+ s.bypass = raw.bypass_actors.length
222
+ ? { status: 'possible', reason: 'The ruleset exposes bypass actors; their membership and combined policy permissions were not resolved.' }
223
+ : { status: 'none-observed', reason: 'The ruleset exposes an empty bypass list; actor-specific permissions were not resolved.' };
224
+ }
225
+ report.coverage.complete = report.sources.every(s => s.status !== 'unknown');
226
+ for (const s of report.sources) {
227
+ if (s.status === 'unknown' || s.problem)
228
+ finding('ci-source-incomplete', `${s.id}: ${s.problem ?? 'source-unavailable'}.`);
229
+ if (s.kind !== 'effective-rules' && s.status !== 'absent' && s.bypass.status !== 'none-observed')
230
+ finding('ci-bypass-visibility', `${s.id}: ${s.bypass.reason}`);
231
+ }
232
+ for (const expected of report.checks) {
233
+ expected.sources = report.sources.filter(s => s.checks.some(c => c.context === expected.context && (expected.appId === undefined || c.appId === expected.appId))).map(s => s.id);
234
+ expected.status = expected.sources.length ? 'observed' : report.coverage.complete ? 'missing' : 'unknown';
235
+ if (expected.status !== 'observed')
236
+ finding(`ci-check-${expected.status}`, `${expected.context}${expected.appId ? ` (app ${expected.appId})` : ''}: ${expected.status}; exact name and any selected app binding must match an active requirement.`);
237
+ }
238
+ report.status = report.checks.some(c => c.status === 'unknown') ? 'unknown' : report.checks.some(c => c.status === 'missing') ? 'missing' : 'observed';
239
+ return report;
240
+ }
241
+ export function ciSummary(report) {
242
+ return [`CI requirements: ${report.status} (${report.mode}; exit 0 does not establish enforcement).`,
243
+ `${report.target.host}/${report.target.repository ?? '(repository not selected)'}; branch ${report.target.branch ?? '(default unresolved)'}; inspected ${report.inspectedAt}.`,
244
+ ...report.checks.map(c => `${c.context}${c.appId ? ` (app ${c.appId})` : ''}: ${c.status}${c.sources.length ? ` [${c.sources.join(', ')}]` : ''}`),
245
+ ...report.sources.map(s => `${s.id}: ${s.status}; bypass ${s.bypass.status}; requirements ${s.checks.length ? s.checks.map(c => `${c.context} (app ${c.appId ?? 'unbound'})`).join(', ') : 'none observed'}.`), ...report.findings.map(f => `${f.code}: ${f.message}`), ...report.coverage.notes].join('\n');
246
+ }
@@ -0,0 +1,15 @@
1
+ export type ExpectedCheck = {
2
+ context: string;
3
+ appId?: number;
4
+ };
5
+ export type CISettings = {
6
+ mode: 'off' | 'advisory';
7
+ host: 'github';
8
+ repository: string | null;
9
+ branch: string | null;
10
+ requiredChecks: ExpectedCheck[];
11
+ };
12
+ export declare function ciDefaults(): CISettings;
13
+ export declare const ciText: (value: unknown) => value is string;
14
+ export declare const ciBranch: (value: unknown) => value is string;
15
+ export declare function ciSettings(raw: unknown): CISettings;
@@ -0,0 +1,50 @@
1
+ export function ciDefaults() {
2
+ return { mode: 'advisory', host: 'github', repository: null, branch: null, requiredChecks: [] };
3
+ }
4
+ function mapping(value, allowed, name) {
5
+ if (!value || typeof value !== 'object' || Array.isArray(value))
6
+ throw Error(`${name} must be a mapping`);
7
+ for (const key of Object.keys(value))
8
+ if (!allowed.includes(key))
9
+ throw Error(`Unknown ${name} key: ${key}`);
10
+ }
11
+ export const ciText = (value) => typeof value === 'string' && !!value && value === value.trim() && !/[\x00-\x1f\x7f]/.test(value);
12
+ export const ciBranch = (value) => ciText(value) && value !== '@' && !/[\\ ~^:?*\[]/.test(value) && !value.includes('@{') && !value.includes('..') && !value.includes('//') && !value.startsWith('-') && !value.endsWith('.') && value.split('/').every(part => !!part && !part.startsWith('.') && !part.endsWith('.lock'));
13
+ export function ciSettings(raw) {
14
+ const result = ciDefaults();
15
+ if (raw === undefined)
16
+ return result;
17
+ mapping(raw, ['mode', 'host', 'repository', 'branch', 'requiredChecks'], 'ciInspection');
18
+ if (raw.mode !== undefined) {
19
+ if (raw.mode !== 'off' && raw.mode !== 'advisory')
20
+ throw Error('ciInspection.mode must be off or advisory');
21
+ result.mode = raw.mode;
22
+ }
23
+ if (raw.host !== undefined && raw.host !== 'github')
24
+ throw Error('ciInspection.host supports github (GitHub.com) only');
25
+ if (raw.repository !== undefined && raw.repository !== null) {
26
+ if (!ciText(raw.repository) || !/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\/[A-Za-z0-9_.-]+$/.test(raw.repository) || ['.', '..'].includes(raw.repository.split('/')[1]))
27
+ throw Error('ciInspection.repository must be an explicit GitHub.com owner/name');
28
+ result.repository = raw.repository;
29
+ }
30
+ if (raw.branch !== undefined && raw.branch !== null) {
31
+ if (!ciBranch(raw.branch))
32
+ throw Error('ciInspection.branch must be a valid branch name or null for the default branch');
33
+ result.branch = raw.branch;
34
+ }
35
+ if (raw.requiredChecks !== undefined) {
36
+ if (!Array.isArray(raw.requiredChecks))
37
+ throw Error('ciInspection.requiredChecks must be an array');
38
+ const seen = new Set();
39
+ result.requiredChecks = raw.requiredChecks.map(value => {
40
+ mapping(value, ['context', 'appId'], 'ciInspection.requiredChecks entry');
41
+ if (!ciText(value.context) || seen.has(value.context))
42
+ throw Error('ciInspection.requiredChecks contexts must be nonempty, trimmed and unique');
43
+ seen.add(value.context);
44
+ if (value.appId !== undefined && (!Number.isSafeInteger(value.appId) || value.appId < 1))
45
+ throw Error('ciInspection.requiredChecks appId must be a positive integer');
46
+ return { context: value.context, ...(value.appId === undefined ? {} : { appId: value.appId }) };
47
+ });
48
+ }
49
+ return result;
50
+ }
package/dist/cli.js CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
+ import { coordinate, syncIds, resumeIds, abandonRequest } from './ac-coordination.js';
2
3
  import path from 'node:path';
3
- import { check, lifecycle, uninstall, nextId, renamePrefix, capabilityForPrefix, recover, version } from './core.js';
4
+ import { applyProfile, check, lifecycle, uninstall, nextId, renamePrefix, capabilityForPrefix, recover, version } from './core.js';
5
+ import { selectSetupProfile } from './setup-profile.js';
4
6
  const args = process.argv.slice(2);
5
7
  const wantsJson = args.includes('--json');
6
8
  function option(name) { const i = args.indexOf(name); if (i < 0)
@@ -14,7 +16,22 @@ try {
14
16
  const change = option('--change');
15
17
  const capability = option('--capability');
16
18
  const replacement = option('--default-schema');
19
+ const apply = flag('--apply');
20
+ const profile = option('--profile');
21
+ const concurrent = flag('--concurrent');
22
+ const sharedReview = flag('--shared-review');
23
+ const enableReview = flag('--enable-review');
17
24
  const command = args.shift();
25
+ if (apply && command !== 'profile' && (command !== 'ac' || args[0] !== 'coordinate'))
26
+ throw Error('--apply is supported only by profile and ac coordinate');
27
+ if (profile !== undefined && command !== 'init')
28
+ throw Error('--profile is supported only by init');
29
+ if ((concurrent || sharedReview || enableReview) && command !== 'init' && command !== 'profile')
30
+ throw Error('Setup options are supported only by init and profile');
31
+ if ((concurrent || sharedReview || enableReview) && command === 'init' && profile === undefined)
32
+ throw Error('Use setup options with --profile solo or --profile team');
33
+ if (enableReview && (!sharedReview || (command === 'profile' && !apply)))
34
+ throw Error('--enable-review requires --shared-review and an applying command');
18
35
  if (dry && !['init', 'update', 'uninstall'].includes(command ?? ''))
19
36
  throw Error('--dry-run is supported only by init, update, and uninstall');
20
37
  if (replacement !== undefined && command !== 'uninstall')
@@ -27,13 +44,44 @@ try {
27
44
  throw Error('--fail-on-pending is supported only by check');
28
45
  if (change && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(change))
29
46
  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') {
47
+ if (json && !['init', 'profile', 'update', 'uninstall', 'check', 'docs', 'ci'].includes(command ?? ''))
48
+ throw Error('--json is supported only by init, profile, update, uninstall, check, docs check, and ci inspect');
49
+ if (capability && command !== 'check' && (command !== 'ac' || args[0] !== 'next'))
50
+ throw Error('--capability is supported only by check and ac next');
51
+ if (command === 'ci') {
52
+ if (args.length !== 1 || args[0] !== 'inspect')
53
+ throw Error('Use ci inspect [--json] [--root PATH]');
54
+ const { inspectCI, ciSummary } = await import('./ci-inspection.js');
55
+ const result = inspectCI(root);
56
+ console.log(json ? JSON.stringify(result, null, 2) : ciSummary(result));
57
+ process.exitCode = result.exitCode;
58
+ }
59
+ else if (command === 'docs') {
60
+ if (args.length !== 1 || args[0] !== 'check')
61
+ throw Error('Use docs check [--json] [--root PATH]');
62
+ const { checkDocumentation } = await import('./documentation.js');
63
+ const result = await checkDocumentation(root);
64
+ console.log(json ? JSON.stringify(result, null, 2) : [
65
+ `Documentation: ${result.scope.readFiles} files read; exit policy ${result.ok ? 'passed' : 'blocked'}.`,
66
+ ...Object.entries(result.categories).map(([category, value]) => `${category}: ${value.status} (${value.mode}; ${value.checked} checked)`),
67
+ ...result.findings.map(f => `${f.severity.toUpperCase()} ${f.code} ${f.path}${f.line ? ':' + f.line : ''}: ${f.message}`),
68
+ `Non-local references skipped: ${result.scope.nonLocalReferences}. Mermaid checks syntax only; factual correctness and visual rendering are not assessed.`
69
+ ].join('\n'));
70
+ process.exitCode = result.exitCode;
71
+ }
72
+ else if (command === 'ac') {
35
73
  const action = args.shift();
36
- if (action === 'next') {
74
+ if (action === 'coordinate' && args.length === 1)
75
+ console.log(JSON.stringify(coordinate(root, args[0], apply), null, 2));
76
+ else if (action === 'sync' && !args.length)
77
+ console.log(JSON.stringify(syncIds(root), null, 2));
78
+ else if (action === 'abandon' && !args.length)
79
+ console.log(abandonRequest(root));
80
+ else if (action === 'resume' && !args.length) {
81
+ const result = resumeIds(root);
82
+ console.log(result ?? 'Prefix reservation recovered');
83
+ }
84
+ else if (action === 'next') {
37
85
  if (capability ? args.length !== 0 : args.length !== 1)
38
86
  throw Error('Use ac next --capability NAME (or ac next PREFIX for a registered active prefix)');
39
87
  console.log(nextId(root, capability ?? capabilityForPrefix(root, args[0])));
@@ -43,14 +91,27 @@ try {
43
91
  console.log(`Prefix updated for ${args[0]}: ${args[1]}`);
44
92
  }
45
93
  else
46
- throw Error('Use ac next --capability NAME or ac rename-prefix CAPABILITY PREFIX');
94
+ throw Error('Use ac next --capability NAME, ac rename-prefix CAPABILITY PREFIX, ac coordinate REMOTE [--apply], ac sync, ac resume, or ac abandon');
95
+ }
96
+ else if (command === 'profile') {
97
+ if (args.length !== 1)
98
+ throw Error('Use profile solo|team [--apply]');
99
+ const interactive = apply && !json && Boolean(process.stdin.isTTY && process.stdout.isTTY);
100
+ const result = await selectSetupProfile(root, args[0], { interactive, concurrent, sharedReview, enableReview, existingOnly: true });
101
+ if (!result)
102
+ throw Error('Choose a solo or team profile');
103
+ const writes = apply ? applyProfile(root, result.selection) : [];
104
+ console.log(JSON.stringify({ dryRun: !apply, ...result.summary, writes }, null, 2));
47
105
  }
48
106
  else if (args.length)
49
107
  throw Error(`Unexpected arguments: ${args.join(' ')}`);
50
108
  else if (command === '--version')
51
109
  console.log(version);
52
- else if (command === 'init')
53
- console.log(JSON.stringify({ dryRun: dry, ...lifecycle(root, 'init', dry, makeDefault) }, null, 2));
110
+ else if (command === 'init') {
111
+ const interactive = !dry && !json && Boolean(process.stdin.isTTY && process.stdout.isTTY);
112
+ const result = await selectSetupProfile(root, profile, { interactive, concurrent, sharedReview, enableReview });
113
+ console.log(JSON.stringify({ dryRun: dry, ...lifecycle(root, 'init', dry, makeDefault, result?.selection), setupProfile: result?.summary }, null, 2));
114
+ }
54
115
  else if (command === 'update')
55
116
  console.log(JSON.stringify({ dryRun: dry, ...lifecycle(root, 'update', dry) }, null, 2));
56
117
  else if (command === 'uninstall')
@@ -61,13 +122,13 @@ try {
61
122
  console.log('Recovery complete');
62
123
  }
63
124
  else if (command === 'check') {
64
- const findings = check(root, change, failPending);
125
+ const findings = check(root, change, failPending, capability);
65
126
  const ok = !findings.some(f => f.severity === 'error');
66
127
  console.log(json ? JSON.stringify({ ok, findings }, null, 2) : findings.map(f => `${f.severity.toUpperCase()} ${f.code}: ${f.message}`).join('\n'));
67
128
  process.exitCode = ok ? 0 : 1;
68
129
  }
69
130
  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.');
131
+ console.log('cliewen-openspec\ninit [--default] [--dry-run] [--profile solo|team]\nprofile solo|team [--concurrent] [--shared-review] [--apply [--enable-review]] [--json]\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\nac coordinate REMOTE [--apply] (preview by default)\nac sync\nac resume\nac abandon\ndocs check [--json]\nci inspect [--json]\ncheck [--change NAME | --capability NAME] [--json] [--fail-on-pending]\nrecover\nAll commands accept --root PATH.');
71
132
  else
72
133
  throw Error(`Unknown command: ${command}`);
73
134
  }
package/dist/core.d.ts CHANGED
@@ -1,8 +1,22 @@
1
+ import { type DocumentationSettings } from './documentation-settings.js';
2
+ import { type CISettings } from './ci-settings.js';
1
3
  import { type QualitySettings } from './quality.js';
2
4
  export { nextId, renamePrefix, capabilityForPrefix } from './ac.js';
3
5
  import { type Compatibility } from './compatibility.js';
4
6
  export { version } from './release.js';
5
7
  export type Config = {
8
+ ciInspection: CISettings;
9
+ documentationChecks: DocumentationSettings;
10
+ contextSelection: {
11
+ mode: 'off' | 'guided';
12
+ roots: string[];
13
+ exclude: string[];
14
+ maxFiles: number;
15
+ };
16
+ readiness: {
17
+ enabled: boolean;
18
+ threshold: number;
19
+ };
6
20
  docsRoot: string;
7
21
  learnings: {
8
22
  enabled: boolean;
@@ -50,18 +64,33 @@ export type LifecycleResult = {
50
64
  compatibility: Compatibility;
51
65
  recoveredTransaction: boolean;
52
66
  };
53
- export declare function lifecycle(root: string, operation: 'init' | 'update', dryRun?: boolean, makeDefault?: boolean): LifecycleResult;
67
+ export type SetupProfile = 'solo' | 'team';
68
+ export declare function setupProfile(value: string): SetupProfile;
69
+ export declare function profileSnapshot(root: string, existingOnly?: boolean): {
70
+ settings: string | undefined;
71
+ stored: string | undefined;
72
+ current: SetupProfile | undefined;
73
+ review: boolean;
74
+ coordinated: boolean;
75
+ };
76
+ type ProfileSelection = {
77
+ profile: SetupProfile;
78
+ enableReview: boolean;
79
+ basis: ReturnType<typeof profileSnapshot>;
80
+ };
81
+ export declare function applyProfile(root: string, selection: ProfileSelection): string[];
82
+ export declare function lifecycle(root: string, operation: 'init' | 'update', dryRun?: boolean, makeDefault?: boolean, profile?: ProfileSelection): LifecycleResult;
54
83
  export declare function init(root: string, dryRun: boolean, makeDefault: boolean): string[];
55
84
  export declare function update(root: string, dryRun?: boolean): {
56
85
  writes: string[];
57
86
  deletes: string[];
58
87
  };
59
88
  export declare function markdowns(dir: string): string[];
60
- export declare function scenarios(root: string, change?: string): {
89
+ export declare function scenarios(root: string, change?: string, capability?: string): {
61
90
  id: string;
62
91
  title: string;
63
92
  file: string;
64
93
  testTypes: string[];
65
94
  }[];
66
95
  export declare function git(root: string, args: string[]): string;
67
- export declare function check(root: string, change?: string, failPending?: boolean): Finding[];
96
+ export declare function check(root: string, change?: string, failPending?: boolean, capability?: string): Finding[];