@akjamie/agentic-sdlc 1.2.0 → 1.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 (48) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +239 -302
  3. package/assets/commands/asdlc-apply.md +24 -0
  4. package/assets/commands/asdlc-approve.md +21 -0
  5. package/assets/commands/asdlc-archive.md +21 -0
  6. package/assets/commands/asdlc-doctor.md +24 -0
  7. package/assets/commands/asdlc-lint.md +30 -0
  8. package/assets/commands/asdlc-new.md +29 -0
  9. package/assets/commands/asdlc-pr.md +25 -0
  10. package/assets/commands/asdlc-status.md +23 -0
  11. package/assets/commands/asdlc-test.md +20 -0
  12. package/assets/commands/asdlc-verify.md +29 -0
  13. package/assets/schema/risk-assessment.schema.json +225 -0
  14. package/assets/skills/asdlc-apply/SKILL.md +43 -18
  15. package/assets/skills/asdlc-new/SKILL.md +15 -1
  16. package/assets/skills/asdlc-verify/SKILL.md +16 -6
  17. package/package.json +2 -2
  18. package/src/assess/ai_judge.js +163 -0
  19. package/src/assess/decide.js +164 -0
  20. package/src/assess/governance.js +53 -0
  21. package/src/assess/index.js +183 -0
  22. package/src/assess/render.js +71 -0
  23. package/src/assess/rules/builtin.js +195 -0
  24. package/src/assess/schema.js +148 -0
  25. package/src/assess/store.js +138 -0
  26. package/src/assess/vectors/v1_intent.js +80 -0
  27. package/src/assess/vectors/v2_security.js +131 -0
  28. package/src/assess/vectors/v3_topology.js +107 -0
  29. package/src/cli.js +91 -89
  30. package/src/commands/apply.js +103 -36
  31. package/src/commands/assess.js +57 -0
  32. package/src/commands/doctor.js +33 -18
  33. package/src/commands/init.js +5 -64
  34. package/src/commands/lint.js +9 -2
  35. package/src/commands/new.js +19 -2
  36. package/src/commands/pr.js +27 -3
  37. package/src/commands/skills.js +7 -19
  38. package/src/commands/status.js +169 -8
  39. package/src/commands/update.js +4 -3
  40. package/src/commands/upgrade.js +1 -1
  41. package/src/commands/verify.js +109 -15
  42. package/src/lib/fs.js +26 -3
  43. package/src/lib/level.js +118 -0
  44. package/src/lib/paths.js +3 -1
  45. package/src/lib/prtype.js +17 -4
  46. package/src/lib/risk.js +50 -0
  47. package/src/lib/schema.js +4 -0
  48. package/src/lib/tools.js +313 -0
@@ -0,0 +1,107 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { HARD_RULES, isTestOrDocFile } from '../rules/builtin.js';
4
+
5
+ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRoot = null } = {}) {
6
+ const req = String(requirement || '').toLowerCase();
7
+ const evidence = [];
8
+ const unresolved = [];
9
+ let level = 'L1';
10
+ let confidence = 'high';
11
+ let mandatory_human_review = false;
12
+ let no_signal = true;
13
+
14
+ // 1. Check Hard Rules for Topology / Contracts / Infra
15
+ const topoRules = HARD_RULES.filter((r) =>
16
+ ['HARD_API_CONTRACT', 'HARD_DB_MIGRATION', 'HARD_SUPPLY_CHAIN'].includes(r.id)
17
+ );
18
+
19
+ const API_CONTENT_PATTERNS = [
20
+ /@(RestController|Controller|RequestMapping|GetMapping|PostMapping|PutMapping|DeleteMapping|PatchMapping)\b/,
21
+ /@(app|router)\.(get|post|put|delete|patch)\b/,
22
+ /\b(APIRouter|gin\.Default|router\.HandleFunc)\b/
23
+ ];
24
+
25
+ for (const rule of topoRules) {
26
+ const hits = changedFiles.filter((f) => {
27
+ if (isTestOrDocFile(f)) return false;
28
+ const norm = f.replace(/\\/g, '/');
29
+ if (rule.patterns.some((p) => p.test(norm))) return true;
30
+
31
+ // Content-based heuristic for API handlers in source files
32
+ if (rule.id === 'HARD_API_CONTRACT' && repoRoot && /\.(java|kt|py|go|ts|js)$/i.test(norm)) {
33
+ try {
34
+ const fullPath = path.isAbsolute(f) ? f : path.join(repoRoot, f);
35
+ if (fs.existsSync(fullPath)) {
36
+ const content = fs.readFileSync(fullPath, 'utf8');
37
+ if (API_CONTENT_PATTERNS.some((p) => p.test(content))) return true;
38
+ }
39
+ } catch { /* ignore read failure */ }
40
+ }
41
+ return false;
42
+ });
43
+
44
+ if (hits.length > 0) {
45
+ level = 'L2';
46
+ no_signal = false;
47
+ evidence.push({
48
+ id: `V3_${rule.id}`,
49
+ kind: 'rule_hit',
50
+ rule_id: rule.id,
51
+ signal: 'hard',
52
+ summary: `${rule.summary} (${hits.slice(0, 3).join(', ')})`,
53
+ source: hits[0]
54
+ });
55
+ }
56
+ }
57
+
58
+ // Check CI Tooling Rule
59
+ const ciRule = HARD_RULES.find((r) => r.id === 'HARD_CI_TOOLING');
60
+ if (ciRule) {
61
+ const ciHits = changedFiles.filter((f) => ciRule.patterns.some((p) => p.test(f.replace(/\\/g, '/'))));
62
+ if (ciHits.length > 0) {
63
+ no_signal = false;
64
+ evidence.push({
65
+ id: 'V3_HARD_CI_TOOLING',
66
+ kind: 'rule_hit',
67
+ rule_id: ciRule.id,
68
+ signal: 'hard',
69
+ summary: `${ciRule.summary} (${ciHits.slice(0, 3).join(', ')})`,
70
+ source: ciHits[0]
71
+ });
72
+ }
73
+ }
74
+
75
+ // 2. Check Requirement Semantics for Architecture / Schema / Infra
76
+ const topoKeywords = [
77
+ 'api', 'endpoint', 'openapi', 'swagger', 'grpc', 'protobuf', 'graphql', 'webhook',
78
+ 'fastapi', 'springboot', 'spring boot', 'controller', 'rest api', 'router',
79
+ 'database', 'migration', 'schema', 'db table', 'database table', 'sql table', 'ddl', 'model', 'docker', 'k8s', 'helm'
80
+ ];
81
+
82
+ for (const kw of topoKeywords) {
83
+ const re = new RegExp(`\\b${kw.replace(/-/g, '[-\\s]')}\\b`, 'i');
84
+ if (re.test(req)) {
85
+ no_signal = false;
86
+ if (level === 'L1') {
87
+ level = 'L2';
88
+ }
89
+ evidence.push({
90
+ id: 'V3_TOPOLOGY_KEYWORD',
91
+ kind: 'task_statement',
92
+ signal: 'soft',
93
+ summary: `Requirement touches cross-boundary architectural keyword: '${kw}'`
94
+ });
95
+ break;
96
+ }
97
+ }
98
+
99
+ return {
100
+ level,
101
+ confidence,
102
+ evidence,
103
+ unresolved,
104
+ mandatory_human_review,
105
+ no_signal
106
+ };
107
+ }
package/src/cli.js CHANGED
@@ -1,89 +1,91 @@
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 registerTest } from './commands/test.js';
10
- import { register as registerVerify } from './commands/verify.js';
11
- import { register as registerArchive } from './commands/archive.js';
12
- import { register as registerStatus } from './commands/status.js';
13
- import { register as registerDoctor } from './commands/doctor.js';
14
- import { register as registerUpgrade } from './commands/upgrade.js';
15
- import { register as registerUpdate } from './commands/update.js';
16
- import { register as registerSkills } from './commands/skills.js';
17
- import { AsdlcError } from './lib/errors.js';
18
- import { log } from './lib/log.js';
19
-
20
- const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
21
-
22
- export function buildCli() {
23
- const program = new Command();
24
- program
25
- .name('asdlc')
26
- .description('Agentic SDLC - an OpenSpec + Graphify flow behind one command.')
27
- .version(pkg.version);
28
-
29
- // The 7 stages, in order.
30
- registerInit(program); // 1. set up the repo
31
- registerNew(program); // 2. start a spec (scaffold + graph refresh + explore.md)
32
- registerLint(program); // 3. check the spec
33
- registerPr(program); // 3.5 open the Spec PR automatically
34
- registerApprove(program); // 4. record approval (after the spec PR merges or in-place)
35
- registerApply(program); // 5. start implementing
36
- registerTest(program); // 5.5 run acceptance tests mapped from change specs (TDD & CI gate)
37
- registerVerify(program); // 6. check the implementation
38
- registerArchive(program); // 7. finish (sync living specs to openspec/specs/)
39
-
40
- // Navigation + health + maintenance (not stages).
41
- registerStatus(program); // where am I / what's next
42
- registerDoctor(program); // environment + setup health
43
- registerUpdate(program); // update repo state: skills, AST graph (KB) & AGENTS.md
44
- registerUpgrade(program); // upgrade toolchain (asdlc, openspec, graphify, schema)
45
- registerSkills(program); // manage & install bundled agent skills (repo or global CI)
46
-
47
- program.addHelpText('after', `
48
- The flow:
49
- asdlc init set up the repo (installs OpenSpec + Graphify, wires CI)
50
- asdlc new "<requirement>" start a spec: scaffold + refresh graph + explore.md + grilling
51
- asdlc lint <ID> check the spec (artifacts + BDD + acceptance criteria)
52
- asdlc pr <ID> <targetBranch> open the Spec PR (pushes branch + auto-creates PR via CLI or API)
53
- asdlc approve <ID> record approval (on PR / merge / in-place) + mark READY_FOR_IMPL
54
- asdlc apply <ID> guard, then /opsx-apply (task-level TDD loop)
55
- asdlc test <ID> run acceptance tests mapped from change specs (TDD & CI gate)
56
- asdlc verify <ID> check the implementation (artifacts, tasks, tests, AI)
57
- asdlc archive <ID> finish: archive change + sync living specs to openspec/specs/
58
-
59
- Navigation, health & maintenance:
60
- asdlc status <ID> where a change is in the 7 stages + the next command
61
- asdlc doctor environment + repo setup health
62
- asdlc update update repo state: skills, AST knowledge graph (KB) & AGENTS.md
63
- asdlc upgrade [--global] upgrade asdlc CLI, openspec, graphify & managed schema
64
- asdlc skills list list all available bundled agent skills
65
- asdlc skills install --global install skills globally for CI/headless agents (opencode, pi, dsh)
66
-
67
- A bad spec is not edited: close it and run \`asdlc new\` again.`);
68
- return program;
69
- }
70
-
71
- export async function run(argv = process.argv) {
72
- const program = buildCli();
73
- program.exitOverride();
74
- try {
75
- await program.parseAsync(argv);
76
- return process.exitCode ?? 0;
77
- } catch (err) {
78
- if (err?.code?.startsWith('commander.')) return err.exitCode ?? 0;
79
- if (err instanceof AsdlcError) {
80
- log.error(err.message);
81
- if (err.hint) log.info(` hint: ${err.hint}`);
82
- if (err.detail) log.info(` ${err.detail}`);
83
- return err.exitCode;
84
- }
85
- log.error(err?.message ?? String(err));
86
- if (process.env.ASDLC_DEBUG) log.error(err?.stack ?? '');
87
- return 1;
88
- }
89
- }
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 registerTest } from './commands/test.js';
10
+ import { register as registerVerify } from './commands/verify.js';
11
+ import { register as registerArchive } from './commands/archive.js';
12
+ import { register as registerStatus } from './commands/status.js';
13
+ import { register as registerDoctor } from './commands/doctor.js';
14
+ import { register as registerUpgrade } from './commands/upgrade.js';
15
+ import { register as registerUpdate } from './commands/update.js';
16
+ import { register as registerSkills } from './commands/skills.js';
17
+ import { register as registerAssess } from './commands/assess.js';
18
+ import { AsdlcError } from './lib/errors.js';
19
+ import { log } from './lib/log.js';
20
+
21
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
22
+
23
+ export function buildCli() {
24
+ const program = new Command();
25
+ program
26
+ .name('asdlc')
27
+ .description('Agentic SDLC - an OpenSpec + Graphify flow behind one command.')
28
+ .version(pkg.version);
29
+
30
+ // The 7 stages, in order.
31
+ registerInit(program); // 1. set up the repo
32
+ registerNew(program); // 2. start a spec (scaffold + graph refresh + explore.md)
33
+ registerLint(program); // 3. check the spec
34
+ registerPr(program); // 3.5 open the Spec PR automatically
35
+ registerApprove(program); // 4. record approval (after the spec PR merges or in-place)
36
+ registerApply(program); // 5. start implementing
37
+ registerTest(program); // 5.5 run acceptance tests mapped from change specs (TDD & CI gate)
38
+ registerVerify(program); // 6. check the implementation
39
+ registerArchive(program); // 7. finish (sync living specs to openspec/specs/)
40
+
41
+ // Navigation + health + maintenance (not stages).
42
+ registerStatus(program); // where am I / what's next
43
+ registerDoctor(program); // environment + setup health
44
+ registerUpdate(program); // update repo state: skills, AST graph (KB) & AGENTS.md
45
+ registerUpgrade(program); // upgrade toolchain (asdlc, openspec, graphify, schema)
46
+ registerSkills(program); // manage & install bundled agent skills (repo or global CI)
47
+ registerAssess(program); // evaluate risk & governance requirements (CI & local tool)
48
+
49
+ program.addHelpText('after', `
50
+ The flow:
51
+ asdlc init set up the repo (installs OpenSpec + Graphify, wires CI)
52
+ asdlc new "<requirement>" start a spec: scaffold + refresh graph + explore.md + grilling
53
+ asdlc lint <ID> check the spec (artifacts + BDD + acceptance criteria)
54
+ asdlc pr <ID> <targetBranch> open the Spec PR (pushes branch + auto-creates PR via CLI or API)
55
+ asdlc approve <ID> record approval (on PR / merge / in-place) + mark READY_FOR_IMPL
56
+ asdlc apply <ID> guard, then /opsx-apply (task-level TDD loop)
57
+ asdlc test <ID> run acceptance tests mapped from change specs (TDD & CI gate)
58
+ asdlc verify <ID> check the implementation (artifacts, tasks, tests, AI)
59
+ asdlc archive <ID> finish: archive change + sync living specs to openspec/specs/
60
+
61
+ Navigation, health & maintenance:
62
+ asdlc status [ID] where a change is in the 7 stages (or portfolio overview if omitted)
63
+ asdlc doctor environment + repo setup health
64
+ asdlc update update repo state: skills, AST knowledge graph (KB) & AGENTS.md
65
+ asdlc upgrade [--global] upgrade asdlc CLI, openspec, graphify & managed schema
66
+ asdlc skills list list all available bundled agent skills
67
+ asdlc skills install --global install skills globally for CI/headless agents (opencode, pi, dsh)
68
+
69
+ A bad spec is not edited: close it and run \`asdlc new\` again.`);
70
+ return program;
71
+ }
72
+
73
+ export async function run(argv = process.argv) {
74
+ const program = buildCli();
75
+ program.exitOverride();
76
+ try {
77
+ await program.parseAsync(argv);
78
+ return process.exitCode ?? 0;
79
+ } catch (err) {
80
+ if (err?.code?.startsWith('commander.')) return err.exitCode ?? 0;
81
+ if (err instanceof AsdlcError) {
82
+ log.error(err.message);
83
+ if (err.hint) log.info(` hint: ${err.hint}`);
84
+ if (err.detail) log.info(` ${err.detail}`);
85
+ return err.exitCode;
86
+ }
87
+ log.error(err?.message ?? String(err));
88
+ if (process.env.ASDLC_DEBUG) log.error(err?.stack ?? '');
89
+ return 1;
90
+ }
91
+ }
@@ -3,9 +3,9 @@ import { exists, readText, writeText } from '../lib/fs.js';
3
3
  import { changeDir } from '../lib/paths.js';
4
4
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
5
5
  import { lastCommitTouching, git } from '../lib/git.js';
6
- import { readYaml } from '../lib/yaml.js';
7
6
  import { fail } from '../lib/errors.js';
8
7
  import { log } from '../lib/log.js';
8
+ import { isSinglePrLevel, readEffectiveLevel } from '../lib/level.js';
9
9
 
10
10
  // Guard before implementing: the spec must be APPROVED on the target branch
11
11
  // (i.e. the Spec PR has been merged into targetBranch, locking proposal.md & specs/**).
@@ -23,7 +23,15 @@ export function applyGuard(changeId, opts = {}) {
23
23
  const sha = text.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
24
24
  const status = text.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
25
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 };
26
+ const apr = text.match(/^\s*autoPr:\s*['"]?([^\s'"]+)['"]?\s*$/m);
27
+ const lvl = text.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
28
+ meta = {
29
+ specSha: sha ? sha[1] : null,
30
+ status: status ? status[1] : null,
31
+ targetBranch: tb ? tb[1] : null,
32
+ autoPr: apr ? apr[1] : null,
33
+ level: lvl ? lvl[1].toUpperCase() : null,
34
+ };
27
35
  }
28
36
 
29
37
  const branch = opts.targetBranch
@@ -33,53 +41,102 @@ export function applyGuard(changeId, opts = {}) {
33
41
 
34
42
  const locked = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
35
43
 
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
+ const levelInfo = readEffectiveLevel(repoRoot, slug);
45
+ if (levelInfo?.tampered) {
46
+ fail(`cannot apply '${slug}': declared level in .openspec.yaml (${levelInfo.declaredLevel}) is lower than recorded history (${levelInfo.maxHistoryLevel}). Manual level downgrading is strictly forbidden.`, {
47
+ code: 'LEVEL_TAMPERED',
48
+ hint: 'Revert unauthorized level edits in .openspec.yaml or raise a system rule fix.'
44
49
  });
45
50
  }
46
51
 
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
- }
52
+ const effectiveLevel = levelInfo?.effectiveLevel || meta.level || null;
53
+ const isSinglePr = isSinglePrLevel(effectiveLevel);
54
+ let approvedSha = null;
65
55
 
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)) {
56
+ if (isSinglePr) {
57
+ // For L0 / L1, Single PR mode allows direct local implementation.
58
+ // Transition to ready_for_impl automatically if drafting.
59
+ if (meta.status !== 'ready_for_impl' && exists(metaPath)) {
70
60
  let metaText = readText(metaPath);
71
61
  const upsertKey = (text, key, val) => {
72
62
  const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
73
63
  return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
74
64
  };
75
- metaText = upsertKey(metaText, 'specSha', approvedSha);
76
65
  metaText = upsertKey(metaText, 'status', 'ready_for_impl');
77
66
  writeText(metaPath, metaText);
78
67
  }
79
- log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
68
+ log.ok(`${slug}: governance level is ${effectiveLevel} (Single PR mode: direct local implementation permitted)`);
69
+ } else {
70
+ // L2 / L3 Two-phase Spec-first flow
71
+ // 2. Multi-tenant path-isolated approval detection
72
+ // Query ONLY commits touching this change's own directory on target branch
73
+ approvedSha = lastCommitTouching(repoRoot, branch, locked);
74
+
75
+ if (!approvedSha) {
76
+ fail(`'${slug}' is not approved yet (no Spec PR for this change merged into ${branch})`, {
77
+ code: 'NOT_APPROVED',
78
+ hint: `open a Spec PR via \`asdlc pr ${changeId} ${branch}\` and merge it before implementing`,
79
+ });
80
+ }
81
+
82
+ // 3. Local working tree tamper check: locked paths must not have uncommitted edits
83
+ const dirty = (git(['status', '--porcelain', '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
84
+ if (dirty) {
85
+ fail(`cannot apply '${slug}': locked spec paths have uncommitted local modifications:\n${dirty}`, {
86
+ code: 'SPEC_DIRTY',
87
+ hint: 'commit or stash your spec modifications before proceeding with implementation',
88
+ });
89
+ }
90
+
91
+ // 4. Content-level cryptographic zero-diff invariant:
92
+ // The local spec content MUST match the approved version on the target branch
93
+ const diff = (git(['diff', approvedSha, '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
94
+ if (diff) {
95
+ fail(`'${slug}' spec differs from the approved version on ${branch} (${approvedSha.slice(0, 8)}):\n${diff.slice(0, 300)}`, {
96
+ code: 'SPEC_DIFFERS_FROM_APPROVED',
97
+ hint: `spec was modified after approval. Merge latest ${branch} or revert unauthorized spec changes.`,
98
+ });
99
+ }
100
+
101
+ // 5. Automatic state transition: PR Merge is the single source of truth for approval!
102
+ // If the spec is physically merged on the target branch with 0 diff, automatically transition to ready_for_impl
103
+ if (meta.status !== 'ready_for_impl' || meta.specSha !== approvedSha) {
104
+ if (exists(metaPath)) {
105
+ let metaText = readText(metaPath);
106
+ const upsertKey = (text, key, val) => {
107
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
108
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
109
+ };
110
+ metaText = upsertKey(metaText, 'specSha', approvedSha);
111
+ metaText = upsertKey(metaText, 'status', 'ready_for_impl');
112
+ writeText(metaPath, metaText);
113
+ }
114
+ log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
115
+ }
80
116
  }
81
117
 
82
- // 6. Tasks checklist presence
118
+ // 6. Explicit Auto-PR Delegation Handling
119
+ if (opts.autoPr !== undefined && exists(metaPath)) {
120
+ let metaText = readText(metaPath);
121
+ const upsertKey = (text, key, val) => {
122
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
123
+ return re.test(text) ? text.replace(re, `${key}: ${val}`) : `${text.trimEnd()}\n${key}: ${val}\n`;
124
+ };
125
+ metaText = upsertKey(metaText, 'autoPr', opts.autoPr ? 'true' : 'false');
126
+ writeText(metaPath, metaText);
127
+ }
128
+
129
+ if (opts.targetBranch && exists(metaPath)) {
130
+ let metaText = readText(metaPath);
131
+ const upsertKey = (text, key, val) => {
132
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
133
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
134
+ };
135
+ metaText = upsertKey(metaText, 'targetBranch', opts.targetBranch);
136
+ writeText(metaPath, metaText);
137
+ }
138
+
139
+ // 7. Tasks checklist presence
83
140
  const tasksPath = path.join(cdir, 'tasks.md');
84
141
  if (!exists(tasksPath)) {
85
142
  fail(`'${slug}' missing tasks.md`, {
@@ -88,7 +145,14 @@ export function applyGuard(changeId, opts = {}) {
88
145
  });
89
146
  }
90
147
 
91
- log.ok(`${slug} is APPROVED on ${branch} (specSha: ${approvedSha.slice(0, 8)}, state: ready_for_impl)`);
148
+ const isAutoPr = opts.autoPr === true || (opts.autoPr === undefined && meta.autoPr === 'true');
149
+ const shaDisplay = approvedSha ? ` (specSha: ${approvedSha.slice(0, 8)}, state: ready_for_impl)` : ` (state: ready_for_impl)`;
150
+ log.ok(`${slug} is READY FOR IMPLEMENTATION on ${branch}${shaDisplay}`);
151
+ if (isAutoPr) {
152
+ log.info(`Auto-PR delegation: ENABLED (agent is authorized to open Implementation PR once tasks & verify pass).`);
153
+ } else {
154
+ log.info(`Auto-PR delegation: DISABLED (local-only mode; run \`asdlc pr\` when ready to submit).`);
155
+ }
92
156
  log.info(`Ready for implementation. Follow task-level TDD loop in tasks.md.`);
93
157
  return 0;
94
158
  }
@@ -107,6 +171,9 @@ export function register(program) {
107
171
  .command('apply <changeId>')
108
172
  .description('guard before implementing: the spec must be approved on the protected branch')
109
173
  .option('--protected-branch <ref>', 'branch the approved spec must be merged into', 'origin/main')
174
+ .option('--target-branch <ref>', 'target branch to merge into')
175
+ .option('--auto-pr', 'explicitly delegate authority to automatically open Implementation PR after verification passes')
176
+ .option('--no-auto-pr', 'disable automatic Implementation PR creation (default)')
110
177
  .option('--repo-root <path>')
111
178
  .action((changeId, opts) => {
112
179
  process.exitCode = applyGuard(changeId, opts);
@@ -0,0 +1,57 @@
1
+ import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
2
+ import { git } from '../lib/git.js';
3
+ import { assess, renderCheckSummary, renderPRComment } from '../assess/index.js';
4
+ import { log } from '../lib/log.js';
5
+
6
+ export function runAssessCommand(changeId, opts = {}) {
7
+ const repoRoot = requireRepo(opts);
8
+ const slug = changeId ? toChangeSlug(changeId) : null;
9
+ const stage = opts.stage || 'new';
10
+
11
+ let changedFiles = [];
12
+ if (stage === 'impl') {
13
+ const base = opts.base || 'origin/main';
14
+ const head = opts.head || 'HEAD';
15
+ const diffFiles = git(['diff', '--name-only', `${base}...${head}`], repoRoot, { allowFail: true }) ?? '';
16
+ changedFiles = diffFiles.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
17
+ }
18
+
19
+ const result = assess({
20
+ stage,
21
+ changeId: slug,
22
+ requirement: opts.requirement || '',
23
+ changedFiles,
24
+ baseSha: opts.base || 'HEAD',
25
+ headSha: opts.head || null,
26
+ repoRoot,
27
+ persist: Boolean(slug)
28
+ });
29
+
30
+ if (opts.json) {
31
+ console.log(JSON.stringify(result, null, 2));
32
+ return result.verdict === 'ok' ? 0 : 1;
33
+ }
34
+
35
+ log.info(renderCheckSummary(result));
36
+ if (result.transition && result.transition.direction === 'up') {
37
+ log.warn(`[ESCALATED] Level increased from ${result.transition.from_level} to ${result.risk.level}`);
38
+ }
39
+ return result.verdict === 'ok' ? 0 : 1;
40
+ }
41
+
42
+ export function register(program) {
43
+ program
44
+ .command('assess [changeId]')
45
+ .description('evaluate change risk and governance requirements via unified assess engine')
46
+ .option('--stage <stage>', 'assessment stage: new | spec | impl', 'new')
47
+ .option('--requirement <text>', 'requirement description (for stage: new)')
48
+ .option('--base <ref>', 'base ref for diff (for stage: impl)', 'origin/main')
49
+ .option('--head <ref>', 'head ref for diff (for stage: impl)', 'HEAD')
50
+ .option('--json', 'output raw assessment JSON')
51
+ .action((changeId, opts) => {
52
+ const code = runAssessCommand(changeId, opts);
53
+ if (code !== 0 && !process.exitCode) {
54
+ process.exitCode = code;
55
+ }
56
+ });
57
+ }
@@ -8,6 +8,7 @@ import { refreshAgents } from '../lib/agents.js';
8
8
  import { readYaml } from '../lib/yaml.js';
9
9
  import { git } from '../lib/git.js';
10
10
  import { log, dim } from '../lib/log.js';
11
+ import { detectTools, checkToolHealth, installSkills, installCommands } from '../lib/tools.js';
11
12
 
12
13
  // Environment + setup health. Exit non-zero only on a critical failure
13
14
  // (no OpenSpec project, or the managed schema is not installed / is overridden).
@@ -34,6 +35,12 @@ export function doctor(opts = {}) {
34
35
  const schemaV = readInstalledVersion();
35
36
  add('managed schema', schemaV ? 'pass' : 'fail', schemaV ? `v${schemaV} (bundled v${builtinSchemaVersion()})` : 'not installed (run `asdlc init` or `asdlc upgrade`)');
36
37
 
38
+ let gi = null;
39
+ let ignored = false;
40
+ let hooksPath = null;
41
+ let hasRouting = false;
42
+ let detectedTools = [];
43
+
37
44
  // If in global mode or not in a repository workspace, check global skills and skip repo-specific checks
38
45
  if (isGlobal || (!isRepo && !hasProject)) {
39
46
  const globalSkills = path.join(process.env.HOME || process.env.USERPROFILE || '', '.agents', 'skills');
@@ -52,23 +59,32 @@ export function doctor(opts = {}) {
52
59
  if (exists(cfgPath)) { try { cfgSchema = (readYaml(cfgPath) ?? {}).schema ?? null; } catch { /* ignore */ } }
53
60
  add('repo config schema', cfgSchema === 'agentic-repo-change' ? 'pass' : 'warn', cfgSchema ?? 'unset');
54
61
 
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
62
  try { hooksPath = git(['config', '--get', 'core.hooksPath'], repoRoot, { allowFail: true }); } catch { /* ignore */ }
60
63
  add('.githooks', hooksPath === '.githooks' ? 'pass' : 'warn', hooksPath === '.githooks' ? 'core.hooksPath=.githooks' : `core.hooksPath=${hooksPath ?? 'unset'}`);
61
64
 
62
65
  const agents = path.join(repoRoot, 'AGENTS.md');
63
- const hasRouting = exists(agents) && readText(agents).includes('<!-- asdlc:routing -->');
66
+ hasRouting = exists(agents) && readText(agents).includes('<!-- asdlc:routing -->');
64
67
  add('AGENTS.md routing', hasRouting ? 'pass' : 'warn', hasRouting ? '' : 'missing (run `asdlc init`)');
65
68
 
66
69
  const gstatus = graphStatus(repoRoot);
67
70
  add('knowledge graph', gstatus === 'fresh' ? 'pass' : 'warn', gstatus);
68
71
 
69
- const gi = path.join(repoRoot, '.gitignore');
70
- const ignored = exists(gi) && readText(gi).split(/\r?\n/).some((l) => l.trim() === GITIGNORE_LINE);
72
+ gi = path.join(repoRoot, '.gitignore');
73
+ ignored = exists(gi) && readText(gi).split(/\r?\n/).some((l) => l.trim() === GITIGNORE_LINE);
71
74
  add('graphify-out ignored', ignored ? 'pass' : 'warn', ignored ? '' : `add ${GITIGNORE_LINE} to .gitignore`);
75
+
76
+ // 3) Agent Tools & Slash-Command Parity Checks
77
+ detectedTools = detectTools(repoRoot);
78
+ if (detectedTools.length === 0) {
79
+ add('agent tools', 'pass', 'none detected (.agents used as default)');
80
+ } else {
81
+ for (const toolId of detectedTools) {
82
+ const health = checkToolHealth(repoRoot, toolId);
83
+ if (health) {
84
+ add(`tool: ${health.name}`, health.status, health.detail);
85
+ }
86
+ }
87
+ }
72
88
  }
73
89
 
74
90
  let failed = 0;
@@ -98,17 +114,7 @@ export function doctor(opts = {}) {
98
114
  } catch (e) { log.warn(`fix failed for .gitignore: ${e.message}`); }
99
115
  }
100
116
 
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
117
+ // 3. .githooks
112
118
  if (hooksPath !== '.githooks') {
113
119
  try {
114
120
  if (exists(githooksAssetDir)) {
@@ -134,6 +140,15 @@ export function doctor(opts = {}) {
134
140
  if (g.installed) log.ok('fixed: installed graphify CLI');
135
141
  } catch (e) { log.warn(`fix failed for graphify: ${e.message}`); }
136
142
  }
143
+
144
+ // 7. Tool skills & slash commands remediation
145
+ if (detectedTools && detectedTools.length > 0) {
146
+ try {
147
+ installSkills(repoRoot, detectedTools);
148
+ installCommands(repoRoot, detectedTools);
149
+ log.ok('fixed: synchronized skills and commands for detected tools');
150
+ } catch (e) { log.warn(`fix failed for tool parity: ${e.message}`); }
151
+ }
137
152
  log.info('');
138
153
  }
139
154