@akjamie/agentic-sdlc 0.0.0-stage → 1.0.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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/assets/ci/Jenkinsfile +80 -0
  4. package/assets/ci/asdlc-ai-review.yml +65 -0
  5. package/assets/config/config.yaml +76 -0
  6. package/assets/githooks/post-merge +22 -0
  7. package/assets/githooks/pre-push +17 -0
  8. package/assets/policy/policy.yaml +46 -0
  9. package/assets/schema/schema.yaml +162 -0
  10. package/assets/schema/templates/design.md +16 -0
  11. package/assets/schema/templates/proposal.md +25 -0
  12. package/assets/schema/templates/review.md +24 -0
  13. package/assets/schema/templates/spec.md +37 -0
  14. package/assets/schema/templates/tasks.md +10 -0
  15. package/assets/skills/asdlc-apply/SKILL.md +128 -0
  16. package/assets/skills/asdlc-approve/SKILL.md +107 -0
  17. package/assets/skills/asdlc-archive/SKILL.md +48 -0
  18. package/assets/skills/asdlc-doctor/SKILL.md +82 -0
  19. package/assets/skills/asdlc-impl-review/SKILL.md +214 -0
  20. package/assets/skills/asdlc-init/SKILL.md +68 -0
  21. package/assets/skills/asdlc-lint/SKILL.md +56 -0
  22. package/assets/skills/asdlc-new/SKILL.md +74 -0
  23. package/assets/skills/asdlc-pr/SKILL.md +59 -0
  24. package/assets/skills/asdlc-review/SKILL.md +80 -0
  25. package/assets/skills/asdlc-spec-review/SKILL.md +194 -0
  26. package/assets/skills/asdlc-status/SKILL.md +49 -0
  27. package/assets/skills/asdlc-upgrade/SKILL.md +34 -0
  28. package/assets/skills/asdlc-verify/SKILL.md +55 -0
  29. package/assets/skills/batch-grill-me/SKILL.md +136 -0
  30. package/assets/skills/grilling/SKILL.md +136 -0
  31. package/bin/asdlc.js +6 -0
  32. package/package.json +43 -4
  33. package/src/cli.js +86 -0
  34. package/src/commands/apply.js +114 -0
  35. package/src/commands/approve.js +166 -0
  36. package/src/commands/archive.js +115 -0
  37. package/src/commands/doctor.js +163 -0
  38. package/src/commands/init.js +201 -0
  39. package/src/commands/lint.js +103 -0
  40. package/src/commands/new.js +142 -0
  41. package/src/commands/pr.js +495 -0
  42. package/src/commands/skills.js +184 -0
  43. package/src/commands/status.js +65 -0
  44. package/src/commands/update.js +103 -0
  45. package/src/commands/upgrade.js +175 -0
  46. package/src/commands/verify.js +229 -0
  47. package/src/index.js +3 -0
  48. package/src/lib/agents.js +73 -0
  49. package/src/lib/cliutil.js +99 -0
  50. package/src/lib/errors.js +18 -0
  51. package/src/lib/exec.js +19 -0
  52. package/src/lib/fs.js +83 -0
  53. package/src/lib/git.js +76 -0
  54. package/src/lib/graphify.js +106 -0
  55. package/src/lib/log.js +15 -0
  56. package/src/lib/openspec.js +91 -0
  57. package/src/lib/paths.js +43 -0
  58. package/src/lib/policy.js +54 -0
  59. package/src/lib/prtype.js +41 -0
  60. package/src/lib/schema.js +86 -0
  61. package/src/lib/speclint.js +168 -0
  62. package/src/lib/tdd.js +71 -0
  63. package/src/lib/yaml.js +18 -0
package/src/cli.js ADDED
@@ -0,0 +1,86 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { Command } from 'commander';
3
+ import { register as registerInit } from './commands/init.js';
4
+ import { register as registerNew } from './commands/new.js';
5
+ import { register as registerLint } from './commands/lint.js';
6
+ import { register as registerPr } from './commands/pr.js';
7
+ import { register as registerApprove } from './commands/approve.js';
8
+ import { register as registerApply } from './commands/apply.js';
9
+ import { register as registerVerify } from './commands/verify.js';
10
+ import { register as registerArchive } from './commands/archive.js';
11
+ import { register as registerStatus } from './commands/status.js';
12
+ import { register as registerDoctor } from './commands/doctor.js';
13
+ import { register as registerUpgrade } from './commands/upgrade.js';
14
+ import { register as registerUpdate } from './commands/update.js';
15
+ import { register as registerSkills } from './commands/skills.js';
16
+ import { AsdlcError } from './lib/errors.js';
17
+ import { log } from './lib/log.js';
18
+
19
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
20
+
21
+ export function buildCli() {
22
+ const program = new Command();
23
+ program
24
+ .name('asdlc')
25
+ .description('Agentic SDLC - an OpenSpec + Graphify flow behind one command.')
26
+ .version(pkg.version);
27
+
28
+ // The 7 stages, in order.
29
+ registerInit(program); // 1. set up the repo
30
+ registerNew(program); // 2. start a spec (scaffold + graph refresh + explore.md)
31
+ registerLint(program); // 3. check the spec
32
+ registerPr(program); // 3.5 open the Spec PR automatically
33
+ registerApprove(program); // 4. record approval (after the spec PR merges or in-place)
34
+ registerApply(program); // 5. start implementing
35
+ registerVerify(program); // 6. check the implementation
36
+ registerArchive(program); // 7. finish (sync living specs to openspec/specs/)
37
+
38
+ // Navigation + health + maintenance (not stages).
39
+ registerStatus(program); // where am I / what's next
40
+ registerDoctor(program); // environment + setup health
41
+ registerUpdate(program); // update repo state: skills, AST graph (KB) & AGENTS.md
42
+ registerUpgrade(program); // upgrade toolchain (asdlc, openspec, graphify, schema)
43
+ registerSkills(program); // manage & install bundled agent skills (repo or global CI)
44
+
45
+ program.addHelpText('after', `
46
+ The flow:
47
+ asdlc init set up the repo (installs OpenSpec + Graphify, wires CI)
48
+ asdlc new "<requirement>" start a spec: scaffold + refresh graph + explore.md + grilling
49
+ asdlc lint <ID> check the spec (artifacts + BDD + acceptance criteria)
50
+ asdlc pr <ID> <targetBranch> open the Spec PR (pushes branch + auto-creates PR via CLI or API)
51
+ asdlc approve <ID> record approval (on PR / merge / in-place) + mark READY_FOR_IMPL
52
+ asdlc apply <ID> guard, then /opsx-apply (task-level TDD loop)
53
+ asdlc verify <ID> check the implementation (artifacts, tasks, tests, AI)
54
+ asdlc archive <ID> finish: archive change + sync living specs to openspec/specs/
55
+
56
+ Navigation, health & maintenance:
57
+ asdlc status <ID> where a change is in the 7 stages + the next command
58
+ asdlc doctor environment + repo setup health
59
+ asdlc update update repo state: skills, AST knowledge graph (KB) & AGENTS.md
60
+ asdlc upgrade [--global] upgrade asdlc CLI, openspec, graphify & managed schema
61
+ asdlc skills list list all available bundled agent skills
62
+ asdlc skills install --global install skills globally for CI/headless agents (opencode, pi, dsh)
63
+
64
+ A bad spec is not edited: close it and run \`asdlc new\` again.`);
65
+ return program;
66
+ }
67
+
68
+ export async function run(argv = process.argv) {
69
+ const program = buildCli();
70
+ program.exitOverride();
71
+ try {
72
+ await program.parseAsync(argv);
73
+ return process.exitCode ?? 0;
74
+ } catch (err) {
75
+ if (err?.code?.startsWith('commander.')) return err.exitCode ?? 0;
76
+ if (err instanceof AsdlcError) {
77
+ log.error(err.message);
78
+ if (err.hint) log.info(` hint: ${err.hint}`);
79
+ if (err.detail) log.info(` ${err.detail}`);
80
+ return err.exitCode;
81
+ }
82
+ log.error(err?.message ?? String(err));
83
+ if (process.env.ASDLC_DEBUG) log.error(err?.stack ?? '');
84
+ return 1;
85
+ }
86
+ }
@@ -0,0 +1,114 @@
1
+ import path from 'node:path';
2
+ import { exists, readText, writeText } from '../lib/fs.js';
3
+ import { changeDir } from '../lib/paths.js';
4
+ import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
5
+ import { lastCommitTouching, git } from '../lib/git.js';
6
+ import { readYaml } from '../lib/yaml.js';
7
+ import { fail } from '../lib/errors.js';
8
+ import { log } from '../lib/log.js';
9
+
10
+ // Guard before implementing: the spec must be APPROVED on the target branch
11
+ // (i.e. the Spec PR has been merged into targetBranch, locking proposal.md & specs/**).
12
+ export function applyGuard(changeId, opts = {}) {
13
+ const repoRoot = requireRepo(opts);
14
+ const slug = toChangeSlug(changeId);
15
+ const cdir = changeDir(repoRoot, slug);
16
+ if (!exists(cdir)) fail(`change '${slug}' not found`);
17
+
18
+ // 1. Resolve target branch dynamically: CLI option -> .openspec.yaml -> git tracking -> main/master
19
+ const metaPath = path.join(cdir, '.openspec.yaml');
20
+ let meta = {};
21
+ if (exists(metaPath)) {
22
+ const text = readText(metaPath);
23
+ const sha = text.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
24
+ const status = text.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
25
+ const tb = text.match(/^\s*targetBranch:\s*['"]?([^\s'"]+)['"]?\s*$/m);
26
+ meta = { specSha: sha ? sha[1] : null, status: status ? status[1] : null, targetBranch: tb ? tb[1] : null };
27
+ }
28
+
29
+ const branch = opts.targetBranch
30
+ ?? opts.protectedBranch
31
+ ?? meta.targetBranch
32
+ ?? resolveDefaultBranch(repoRoot);
33
+
34
+ const locked = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
35
+
36
+ // 2. Multi-tenant path-isolated approval detection
37
+ // Query ONLY commits touching this change's own directory on target branch
38
+ const approvedSha = lastCommitTouching(repoRoot, branch, locked);
39
+
40
+ if (!approvedSha) {
41
+ fail(`'${slug}' is not approved yet (no Spec PR for this change merged into ${branch})`, {
42
+ code: 'NOT_APPROVED',
43
+ hint: `open a Spec PR via \`asdlc pr ${changeId} ${branch}\` and merge it before implementing`,
44
+ });
45
+ }
46
+
47
+ // 3. Local working tree tamper check: locked paths must not have uncommitted edits
48
+ const dirty = (git(['status', '--porcelain', '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
49
+ if (dirty) {
50
+ fail(`cannot apply '${slug}': locked spec paths have uncommitted local modifications:\n${dirty}`, {
51
+ code: 'SPEC_DIRTY',
52
+ hint: 'commit or stash your spec modifications before proceeding with implementation',
53
+ });
54
+ }
55
+
56
+ // 4. Content-level cryptographic zero-diff invariant:
57
+ // The local spec content MUST match the approved version on the target branch
58
+ const diff = (git(['diff', approvedSha, '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
59
+ if (diff) {
60
+ fail(`'${slug}' spec differs from the approved version on ${branch} (${approvedSha.slice(0, 8)}):\n${diff.slice(0, 300)}`, {
61
+ code: 'SPEC_DIFFERS_FROM_APPROVED',
62
+ hint: `spec was modified after approval. Merge latest ${branch} or revert unauthorized spec changes.`,
63
+ });
64
+ }
65
+
66
+ // 5. Automatic state transition: PR Merge is the single source of truth for approval!
67
+ // If the spec is physically merged on the target branch with 0 diff, automatically transition to ready_for_impl
68
+ if (meta.status !== 'ready_for_impl' || meta.specSha !== approvedSha) {
69
+ if (exists(metaPath)) {
70
+ let metaText = readText(metaPath);
71
+ const upsertKey = (text, key, val) => {
72
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
73
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
74
+ };
75
+ metaText = upsertKey(metaText, 'specSha', approvedSha);
76
+ metaText = upsertKey(metaText, 'status', 'ready_for_impl');
77
+ writeText(metaPath, metaText);
78
+ }
79
+ log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
80
+ }
81
+
82
+ // 6. Tasks checklist presence
83
+ const tasksPath = path.join(cdir, 'tasks.md');
84
+ if (!exists(tasksPath)) {
85
+ fail(`'${slug}' missing tasks.md`, {
86
+ code: 'TASKS_MISSING',
87
+ hint: 'author tasks.md with TDD verification tasks before running apply',
88
+ });
89
+ }
90
+
91
+ log.ok(`${slug} is APPROVED on ${branch} (specSha: ${approvedSha.slice(0, 8)}, state: ready_for_impl)`);
92
+ log.info(`Ready for implementation. Follow task-level TDD loop in tasks.md.`);
93
+ return 0;
94
+ }
95
+
96
+ function resolveDefaultBranch(repoRoot) {
97
+ // Check if origin/main, origin/master, main, or master exists
98
+ for (const candidate of ['origin/main', 'origin/master', 'main', 'master']) {
99
+ const existsRef = git(['rev-parse', '--verify', candidate], repoRoot, { allowFail: true });
100
+ if (existsRef) return candidate;
101
+ }
102
+ return 'main';
103
+ }
104
+
105
+ export function register(program) {
106
+ program
107
+ .command('apply <changeId>')
108
+ .description('guard before implementing: the spec must be approved on the protected branch')
109
+ .option('--protected-branch <ref>', 'branch the approved spec must be merged into', 'origin/main')
110
+ .option('--repo-root <path>')
111
+ .action((changeId, opts) => {
112
+ process.exitCode = applyGuard(changeId, opts);
113
+ });
114
+ }
@@ -0,0 +1,166 @@
1
+ import path from 'node:path';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { exists, readText, writeText } from '../lib/fs.js';
4
+ import { changeDir } from '../lib/paths.js';
5
+ import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
6
+ import { headSha, git, isGitRepo, lastCommitTouching, changeOnRef } from '../lib/git.js';
7
+ import { loadPolicy } from '../lib/policy.js';
8
+ import { classifyPR } from '../lib/prtype.js';
9
+ import { fail } from '../lib/errors.js';
10
+ import { log } from '../lib/log.js';
11
+
12
+ function upsertKey(text, key, value) {
13
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
14
+ const line = `${key}: ${value}`;
15
+ if (re.test(text)) return text.replace(re, line);
16
+ return `${text.trimEnd()}\n${line}\n`;
17
+ }
18
+
19
+ function ensureApprovedReview(repoRoot, slug, approvedSha, mergeSha) {
20
+ const cdir = changeDir(repoRoot, slug);
21
+ const reviewPath = path.join(cdir, 'review.md');
22
+ const now = new Date().toISOString();
23
+
24
+ if (exists(reviewPath)) {
25
+ let content = readText(reviewPath);
26
+ if (/##\s*Verdict[^\n]*/i.test(content)) {
27
+ content = content.replace(/##\s*Verdict[^\n]*\n+\s*[A-Za-z_]+/i, '## Verdict\nAPPROVE');
28
+ } else {
29
+ content = `${content.trimEnd()}\n\n## Verdict\nAPPROVE\n`;
30
+ }
31
+ const record = `\n\n## Approval Record\n- status: READY_FOR_IMPL\n- specSha: ${approvedSha}\n- mergeCommit: ${mergeSha}\n- approvedAt: ${now}\n`;
32
+ if (/##\s*Approval Record/i.test(content)) {
33
+ content = content.replace(/##\s*Approval Record[\s\S]*$/i, record.trimStart());
34
+ } else {
35
+ content = `${content.trimEnd()}${record}`;
36
+ }
37
+ writeText(reviewPath, content);
38
+ } else {
39
+ const content = `# Review: ${slug}
40
+
41
+ ## Summary
42
+ Human PR review and merge completed on protected branch.
43
+ Spec approval confirmed and locked via merge commit \`${mergeSha.slice(0, 8)}\`.
44
+
45
+ ## Dimensions Evaluation
46
+ - Completeness: PASS
47
+ - Ambiguity: PASS
48
+ - Cross-repo consistency: PASS
49
+ - Contract impact: PASS
50
+ - Testability: PASS
51
+ - Security: PASS
52
+
53
+ ## Blocking Findings
54
+ (none)
55
+
56
+ ## Verdict
57
+ APPROVE
58
+
59
+ ## Approval Record
60
+ - status: READY_FOR_IMPL
61
+ - specSha: ${approvedSha}
62
+ - mergeCommit: ${mergeSha}
63
+ - approvedAt: ${now}
64
+ `;
65
+ writeText(reviewPath, content);
66
+ }
67
+ }
68
+
69
+ // DISCRIMINATOR (v6 7.1): PR type is decided by PATHS ONLY. A merge is an
70
+ // APPROVAL only when it is a spec merge (new change dir, no source); impl/archive/
71
+ // fast/normal merges are ignored so the flow stays distinguishable.
72
+ export function mergeChange(changeId, opts = {}) {
73
+ const repoRoot = requireRepo(opts);
74
+ if (!isGitRepo(repoRoot)) fail('not a git repository; cannot derive merge evidence');
75
+
76
+ const policy = loadPolicy(repoRoot);
77
+ const sha = opts.sha ?? headSha(repoRoot);
78
+ if (!sha) fail('cannot resolve the merge commit (HEAD)');
79
+
80
+ const slug = changeId ? toChangeSlug(changeId) : detectSlugFromHead(repoRoot);
81
+ if (!slug) {
82
+ log.warn('no openspec/changes/* touched by this merge; treating as a normal PR (no approval)');
83
+ return [];
84
+ }
85
+
86
+ const changedFiles = (git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD^1', 'HEAD'], repoRoot, { allowFail: true }) ?? '')
87
+ .split(/\r?\n/).filter(Boolean);
88
+ // was the change already on main BEFORE this merge?
89
+ const changeOnMain = changeOnRef(repoRoot, 'HEAD^1', slug);
90
+ const pr = classifyPR({ changedFiles, changeOnMain, policy, emergency: opts.emergency });
91
+ // If auto-detected without an explicit changeId (e.g. post-merge hook),
92
+ // strictly verify that this merge commit was a spec-only merge.
93
+ if (!changeId && pr.type !== 'spec') {
94
+ log.info(`${slug}: not a spec merge (type=${pr.type}) -> no approval stamp`);
95
+ return [];
96
+ }
97
+
98
+ // The approved commit is PATH-LIMITED (v6 4): last commit on HEAD touching the
99
+ // locked paths. review.md / tasks.md commits never move it.
100
+ const lockedPaths = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
101
+ const approvedSha = lastCommitTouching(repoRoot, 'HEAD', lockedPaths) ?? sha;
102
+
103
+ const meta = path.join(changeDir(repoRoot, slug), '.openspec.yaml');
104
+ if (!exists(meta)) fail(`${slug}: no .openspec.yaml`);
105
+
106
+ let text = readText(meta);
107
+ text = upsertKey(text, 'specSha', approvedSha);
108
+ text = upsertKey(text, 'status', 'ready_for_impl');
109
+ writeText(meta, text);
110
+ log.ok(`${slug}: APPROVED specSha=${approvedSha.slice(0, 8)} status=ready_for_impl`);
111
+
112
+ // Auto-generate / stamp review.md with human approval and approvedSha
113
+ ensureApprovedReview(repoRoot, slug, approvedSha, sha);
114
+ log.ok(`${slug}: stamped review.md (verdict=APPROVE, specSha=${approvedSha.slice(0, 8)})`);
115
+
116
+ // The "approved" tag on the spec: an immutable, machine-readable record.
117
+ if (opts.tag !== false) {
118
+ try {
119
+ execFileSync('git', ['tag', '-f', `approved/${slug.toUpperCase()}`, approvedSha], { cwd: repoRoot, stdio: 'ignore' });
120
+ log.ok(`tagged approved/${slug.toUpperCase()} @ ${approvedSha.slice(0, 8)}`);
121
+ } catch (err) {
122
+ log.warn(`tag not created: ${err.message}`);
123
+ }
124
+ }
125
+
126
+ if (opts.commit !== false) {
127
+ try {
128
+ execFileSync('git', ['add', `openspec/changes/${slug}/.openspec.yaml`, `openspec/changes/${slug}/review.md`], { cwd: repoRoot, stdio: 'ignore' });
129
+ execFileSync('git', ['-c', 'user.name=asdlc-bot', '-c', 'user.email=asdlc-bot@example.invalid',
130
+ 'commit', '-m', `chore(approve): spec approved @ ${approvedSha.slice(0, 8)} (${slug})`], { cwd: repoRoot, stdio: 'ignore' });
131
+ log.ok('committed approval stamp');
132
+ } catch {
133
+ log.warn('nothing to commit (already stamped)');
134
+ }
135
+ }
136
+
137
+ log.info('');
138
+ log.info('Next (automatic chain):');
139
+ log.info(' - generate tasks: /opsx-continue (its own step, after approval)');
140
+ log.info(' - implement: /opsx-apply -> implementation PR');
141
+ log.info(' - verify: asdlc verify <ID>');
142
+ return [slug];
143
+ }
144
+
145
+ function detectSlugFromHead(repoRoot) {
146
+ const out = git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD^1', 'HEAD'], repoRoot, { allowFail: true });
147
+ if (!out) return null;
148
+ for (const line of out.split(/\r?\n/)) {
149
+ const m = line.match(/^openspec\/changes\/([^/]+)\//);
150
+ if (m && m[1] !== 'archive') return m[1];
151
+ }
152
+ return null;
153
+ }
154
+
155
+ export function register(program) {
156
+ program
157
+ .command('approve [changeId]')
158
+ .description('record the approved spec after the spec PR merges (tags approved/<ID> + marks READY_FOR_IMPL)')
159
+ .option('--sha <sha>', 'merge commit (default: HEAD)')
160
+ .option('--no-tag', 'skip the approved/<ID> git tag')
161
+ .option('--no-commit', 'stamp without committing')
162
+ .option('--repo-root <path>')
163
+ .action((changeId, opts) => {
164
+ mergeChange(changeId, opts);
165
+ });
166
+ }
@@ -0,0 +1,115 @@
1
+ import path from 'node:path';
2
+ import { exists, readText, writeText, listDir } from '../lib/fs.js';
3
+ import { changeDir } from '../lib/paths.js';
4
+ import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
5
+ import { runOpenspec } from '../lib/openspec.js';
6
+ import { refreshAgents } from '../lib/agents.js';
7
+ import { git } from '../lib/git.js';
8
+ import { fail } from '../lib/errors.js';
9
+ import { log } from '../lib/log.js';
10
+
11
+ function syncReadme(repoRoot, slug, proposalText) {
12
+ const readmePath = path.join(repoRoot, 'README.md');
13
+ if (!exists(readmePath)) return;
14
+ let text = readText(readmePath);
15
+ if (text.includes(`\`${slug}\``)) return;
16
+
17
+ let summary = 'Implemented capability.';
18
+ const m = proposalText.match(/##\s*Why\s*\n+([^\n\r]+)/i);
19
+ if (m && m[1]) {
20
+ const raw = m[1].replace(/<!--[\s\S]*?-->/g, '').trim();
21
+ if (raw) summary = raw;
22
+ }
23
+
24
+ const entry = `- **\`${slug}\`**: ${summary}`;
25
+ if (text.includes('## Living Specifications')) {
26
+ text = text.replace('## Living Specifications', `## Living Specifications\n\n${entry}`);
27
+ } else {
28
+ text = `${text.trimEnd()}\n\n## Living Specifications\n\n${entry}\n`;
29
+ }
30
+ writeText(readmePath, text);
31
+ log.ok(`updated README.md with archived capability (${slug})`);
32
+ }
33
+
34
+ export const CONSTITUTIONAL_PATHS = [
35
+ 'AGENTS.md',
36
+ '.sdlc/policy.yaml',
37
+ 'openspec/config.yaml',
38
+ '.githooks',
39
+ ];
40
+
41
+ export function isConstitutionalChange(repoRoot, opts = {}) {
42
+ if (opts.constitutional === true || opts.agents === true) return true;
43
+
44
+ // 2. Working tree status (unstaged/staged governance changes)
45
+ const statusOut = git(['status', '--porcelain'], repoRoot, { allowFail: true }) ?? '';
46
+ const statusFiles = statusOut
47
+ .split(/\r?\n/)
48
+ .map((l) => l.slice(3).trim())
49
+ .filter(Boolean);
50
+
51
+ // 3. Precise commit check: check HEAD commit (the merge commit being archived)
52
+ const commitFilesOut = git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD'], repoRoot, { allowFail: true }) ?? '';
53
+ const commitFiles = commitFilesOut
54
+ .split(/\r?\n/)
55
+ .map((s) => s.trim())
56
+ .filter(Boolean);
57
+
58
+ const allTouched = new Set([...statusFiles, ...commitFiles]);
59
+
60
+ for (const rawFile of allTouched) {
61
+ const file = rawFile.replace(/\\/g, '/');
62
+ for (const cp of CONSTITUTIONAL_PATHS) {
63
+ if (file === cp || file.startsWith(`${cp}/`)) {
64
+ return true;
65
+ }
66
+ }
67
+ }
68
+
69
+ return false;
70
+ }
71
+
72
+ // Stage 7: Archive. Moves change to archive, syncs delta specs into
73
+ // openspec/specs/, updates README.md, and updates AGENTS.md ONLY if constitutional.
74
+ export function archiveChange(changeId, opts = {}) {
75
+ const repoRoot = requireRepo(opts);
76
+ const slug = toChangeSlug(changeId);
77
+ const cdir = changeDir(repoRoot, slug);
78
+ if (!exists(cdir)) fail(`change '${slug}' not found`);
79
+
80
+ const proposalFile = path.join(cdir, 'proposal.md');
81
+ const proposalText = exists(proposalFile) ? readText(proposalFile) : '';
82
+
83
+ if (opts.openspec !== false) {
84
+ const res = runOpenspec(['archive', slug, '--yes'], repoRoot);
85
+ if (res.status === 0) log.ok(`archived ${slug}: synced living specs -> openspec/specs/`);
86
+ else log.warn(`openspec archive returned ${res.status} (archive manually if needed)`);
87
+ }
88
+
89
+ syncReadme(repoRoot, slug, proposalText);
90
+
91
+ // Constitutional change check: normal spec changes sync to openspec/specs/ and README.
92
+ // AGENTS.md is updated ONLY if constitutional governance files were touched.
93
+ const shouldUpdateAgents = opts.agents === true || (opts.agents !== false && isConstitutionalChange(repoRoot, opts));
94
+ if (shouldUpdateAgents) {
95
+ refreshAgents(repoRoot, { systemStatus: false });
96
+ log.ok(`updated AGENTS.md (constitutional change detected on governance paths)`);
97
+ }
98
+
99
+ log.ok(`archive complete for ${slug}`);
100
+ return 0;
101
+ }
102
+
103
+ export function register(program) {
104
+ program
105
+ .command('archive <changeId>')
106
+ .description('finish: archive change + sync living specs to openspec/specs/ + update README (and AGENTS.md if constitutional)')
107
+ .option('--repo-root <path>')
108
+ .option('--agents', 'force refresh AGENTS.md')
109
+ .option('--no-agents', 'skip updating AGENTS.md')
110
+ .option('--no-openspec', 'skip the openspec archive step')
111
+ .action((changeId, opts) => {
112
+ process.exitCode = archiveChange(changeId, opts);
113
+ });
114
+ }
115
+
@@ -0,0 +1,163 @@
1
+ import path from 'node:path';
2
+ import { exists, readText, writeText, copyTree, ensureDir } from '../lib/fs.js';
3
+ import { openspecDir, resolveRepoRoot, policyAssetFile, githooksAssetDir } from '../lib/paths.js';
4
+ import { openspecVersion, OPENSPEC_PINNED, findOpenspec } from '../lib/openspec.js';
5
+ import { graphifyAvailable, graphStatus, GITIGNORE_LINE, ensureGraphify } from '../lib/graphify.js';
6
+ import { readInstalledVersion, builtinSchemaVersion, localOverride, installSchema } from '../lib/schema.js';
7
+ import { refreshAgents } from '../lib/agents.js';
8
+ import { readYaml } from '../lib/yaml.js';
9
+ import { git } from '../lib/git.js';
10
+ import { log, dim } from '../lib/log.js';
11
+
12
+ // Environment + setup health. Exit non-zero only on a critical failure
13
+ // (no OpenSpec project, or the managed schema is not installed / is overridden).
14
+ export function doctor(opts = {}) {
15
+ const isGlobal = Boolean(opts.global);
16
+ const repoRoot = opts.global ? null : resolveRepoRoot(opts);
17
+ const hasProject = repoRoot ? exists(openspecDir(repoRoot)) : false;
18
+ const isRepo = repoRoot ? exists(path.join(repoRoot, '.git')) : false;
19
+
20
+ const rows = [];
21
+ const add = (name, status, detail) => rows.push({ name, status, detail });
22
+
23
+ // 1) Environment & Toolchain checks (run in all modes)
24
+ const nodeOk = /^v?\d+\./.test(process.version) && compare(process.versions.node, '20.19.0') >= 0;
25
+ add('node >= 20.19', nodeOk ? 'pass' : 'fail', process.version);
26
+
27
+ const checkCwd = repoRoot || process.cwd();
28
+ const osV = openNav(checkCwd);
29
+ add('OpenSpec CLI', findOpenspec(checkCwd) ? (osV === OPENSPEC_PINNED ? 'pass' : 'warn') : 'fail',
30
+ osV ? `${osV}${osV === OPENSPEC_PINNED ? '' : ` (pinned ${OPENSPEC_PINNED})`}` : 'not found (run `npm install -g @fission-ai/openspec`)');
31
+
32
+ add('Graphify', graphifyAvailable() ? 'pass' : 'warn', graphifyAvailable() ? 'installed' : 'not found (install via uv tool install graphifyy or pip)');
33
+
34
+ const schemaV = readInstalledVersion();
35
+ add('managed schema', schemaV ? 'pass' : 'fail', schemaV ? `v${schemaV} (bundled v${builtinSchemaVersion()})` : 'not installed (run `asdlc init` or `asdlc upgrade`)');
36
+
37
+ // If in global mode or not in a repository workspace, check global skills and skip repo-specific checks
38
+ if (isGlobal || (!isRepo && !hasProject)) {
39
+ const globalSkills = path.join(process.env.HOME || process.env.USERPROFILE || '', '.agents', 'skills');
40
+ const hasGlobalSkills = exists(globalSkills);
41
+ add('global skills (~/.agents)', hasGlobalSkills ? 'pass' : 'warn', hasGlobalSkills ? 'installed' : 'run `asdlc skills install --global`');
42
+ } else {
43
+ // 2) Repository Workspace Checks (only when inside an actual repo)
44
+ add('OpenSpec project', hasProject ? 'pass' : 'fail', hasProject ? openspecDir(repoRoot) : 'run `asdlc init`');
45
+
46
+ const override = localOverride(repoRoot);
47
+ add('schema override', override.tracked ? 'fail' : 'pass',
48
+ override.tracked ? `${override.path} COMMITTED (forbidden)` : 'none');
49
+
50
+ const cfgPath = path.join(openspecDir(repoRoot), 'config.yaml');
51
+ let cfgSchema = null;
52
+ if (exists(cfgPath)) { try { cfgSchema = (readYaml(cfgPath) ?? {}).schema ?? null; } catch { /* ignore */ } }
53
+ add('repo config schema', cfgSchema === 'agentic-repo-change' ? 'pass' : 'warn', cfgSchema ?? 'unset');
54
+
55
+ const policy = exists(path.join(repoRoot, '.sdlc', 'policy.yaml'));
56
+ add('.sdlc/policy.yaml', policy ? 'pass' : 'warn', policy ? '' : 'missing (run `asdlc init`)');
57
+
58
+ let hooksPath = null;
59
+ try { hooksPath = git(['config', '--get', 'core.hooksPath'], repoRoot, { allowFail: true }); } catch { /* ignore */ }
60
+ add('.githooks', hooksPath === '.githooks' ? 'pass' : 'warn', hooksPath === '.githooks' ? 'core.hooksPath=.githooks' : `core.hooksPath=${hooksPath ?? 'unset'}`);
61
+
62
+ const agents = path.join(repoRoot, 'AGENTS.md');
63
+ const hasRouting = exists(agents) && readText(agents).includes('<!-- asdlc:routing -->');
64
+ add('AGENTS.md routing', hasRouting ? 'pass' : 'warn', hasRouting ? '' : 'missing (run `asdlc init`)');
65
+
66
+ const gstatus = graphStatus(repoRoot);
67
+ add('knowledge graph', gstatus === 'fresh' ? 'pass' : 'warn', gstatus);
68
+
69
+ const gi = path.join(repoRoot, '.gitignore');
70
+ const ignored = exists(gi) && readText(gi).split(/\r?\n/).some((l) => l.trim() === GITIGNORE_LINE);
71
+ add('graphify-out ignored', ignored ? 'pass' : 'warn', ignored ? '' : `add ${GITIGNORE_LINE} to .gitignore`);
72
+ }
73
+
74
+ let failed = 0;
75
+ log.info('');
76
+ for (const r of rows) {
77
+ const badge = { pass: 'PASS', warn: 'WARN', fail: 'FAIL' }[r.status];
78
+ if (r.status === 'fail') failed += 1;
79
+ log.plain(` [${badge}] ${r.name}`);
80
+ if (r.detail) log.plain(` ${dim(r.detail)}`);
81
+ }
82
+ log.info('');
83
+
84
+ if (opts.fix) {
85
+ log.step('attempting automated remediation (--fix)...');
86
+
87
+ // 1. Managed schema
88
+ if (!schemaV) {
89
+ try { installSchema(); log.ok('fixed: installed managed schema'); } catch (e) { log.warn(`fix failed for schema: ${e.message}`); }
90
+ }
91
+
92
+ // 2. .gitignore graphify-out
93
+ if (!ignored) {
94
+ try {
95
+ const text = exists(gi) ? readText(gi) : '';
96
+ writeText(gi, `${text.trimEnd()}\n${GITIGNORE_LINE}\n`);
97
+ log.ok('fixed: added graphify-out/ to .gitignore');
98
+ } catch (e) { log.warn(`fix failed for .gitignore: ${e.message}`); }
99
+ }
100
+
101
+ // 3. .sdlc/policy.yaml
102
+ if (!policy && exists(policyAssetFile)) {
103
+ try {
104
+ const pdir = path.join(repoRoot, '.sdlc');
105
+ ensureDir(pdir);
106
+ copyTree(policyAssetFile, path.join(pdir, 'policy.yaml'));
107
+ log.ok('fixed: created .sdlc/policy.yaml from template');
108
+ } catch (e) { log.warn(`fix failed for policy: ${e.message}`); }
109
+ }
110
+
111
+ // 4. .githooks
112
+ if (hooksPath !== '.githooks') {
113
+ try {
114
+ if (exists(githooksAssetDir)) {
115
+ copyTree(githooksAssetDir, path.join(repoRoot, '.githooks'));
116
+ }
117
+ git(['config', 'core.hooksPath', '.githooks'], repoRoot);
118
+ log.ok('fixed: configured git core.hooksPath -> .githooks');
119
+ } catch (e) { log.warn(`fix failed for githooks: ${e.message}`); }
120
+ }
121
+
122
+ // 5. AGENTS.md routing
123
+ if (!hasRouting) {
124
+ try {
125
+ refreshAgents(repoRoot);
126
+ log.ok('fixed: refreshed AGENTS.md routing');
127
+ } catch (e) { log.warn(`fix failed for AGENTS.md: ${e.message}`); }
128
+ }
129
+
130
+ // 6. Graphify install
131
+ if (!graphifyAvailable()) {
132
+ try {
133
+ const g = ensureGraphify();
134
+ if (g.installed) log.ok('fixed: installed graphify CLI');
135
+ } catch (e) { log.warn(`fix failed for graphify: ${e.message}`); }
136
+ }
137
+ log.info('');
138
+ }
139
+
140
+ log.plain(failed ? `doctor: ${failed} critical issue(s)` : 'doctor: ok');
141
+ return failed ? 1 : 0;
142
+ }
143
+
144
+ function compare(a, b) {
145
+ const pa = String(a).split('.').map(Number);
146
+ const pb = String(b).split('.').map(Number);
147
+ for (let i = 0; i < 3; i += 1) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) - (pb[i] || 0);
148
+ return 0;
149
+ }
150
+
151
+ function openNav(repoRoot) { return openspecVersion(repoRoot); }
152
+
153
+ export function register(program) {
154
+ program
155
+ .command('doctor')
156
+ .description('check the environment + repo setup health (with optional --fix)')
157
+ .option('-g, --global', 'check global toolchain and agent skills only (for CI/headless environments)')
158
+ .option('--fix', 'automatically remediate fixable environment and configuration drift')
159
+ .option('--repo-root <path>')
160
+ .action((opts) => {
161
+ process.exitCode = doctor(opts);
162
+ });
163
+ }