@akjamie/agentic-sdlc 1.4.0 → 1.6.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 (51) hide show
  1. package/README.md +57 -29
  2. package/assets/commands/asdlc-approve.md +2 -2
  3. package/assets/config/config.yaml +1 -1
  4. package/assets/policy/policy.yaml +6 -0
  5. package/assets/schema/risk-assessment.schema.json +2 -1
  6. package/assets/schema/schema.yaml +168 -168
  7. package/assets/skills/asdlc-apply/SKILL.md +1 -1
  8. package/assets/skills/asdlc-approve/SKILL.md +2 -2
  9. package/assets/skills/asdlc-archive/SKILL.md +17 -13
  10. package/assets/skills/asdlc-doctor/SKILL.md +8 -8
  11. package/assets/skills/asdlc-impl-review/SKILL.md +15 -25
  12. package/assets/skills/asdlc-init/SKILL.md +11 -18
  13. package/assets/skills/asdlc-new/SKILL.md +5 -2
  14. package/assets/skills/asdlc-pr/SKILL.md +13 -8
  15. package/assets/skills/asdlc-review/SKILL.md +7 -7
  16. package/assets/skills/asdlc-spec-review/SKILL.md +10 -20
  17. package/package.json +2 -1
  18. package/src/assess/ai_judge.js +106 -36
  19. package/src/assess/decide.js +8 -6
  20. package/src/assess/index.js +13 -3
  21. package/src/assess/rules/builtin.js +7 -2
  22. package/src/assess/schema.js +6 -1
  23. package/src/assess/vectors/v1_intent.js +53 -8
  24. package/src/assess/vectors/v2_security.js +24 -1
  25. package/src/assess/vectors/v3_topology.js +125 -13
  26. package/src/commands/apply.js +33 -4
  27. package/src/commands/approve.js +2 -3
  28. package/src/commands/archive.js +116 -64
  29. package/src/commands/doctor.js +22 -19
  30. package/src/commands/init.js +24 -50
  31. package/src/commands/lint.js +32 -2
  32. package/src/commands/new.js +23 -22
  33. package/src/commands/pr.js +106 -25
  34. package/src/commands/status.js +1 -1
  35. package/src/commands/test.js +101 -5
  36. package/src/commands/update.js +1 -11
  37. package/src/commands/verify.js +141 -34
  38. package/src/lib/agents.js +2 -2
  39. package/src/lib/cliutil.js +57 -7
  40. package/src/lib/git.js +10 -4
  41. package/src/lib/graphify.js +89 -14
  42. package/src/lib/level.js +63 -9
  43. package/src/lib/openspec.js +61 -31
  44. package/src/lib/paths.js +0 -2
  45. package/src/lib/policy.js +4 -0
  46. package/src/lib/schema.js +32 -11
  47. package/src/lib/speclint.js +5 -3
  48. package/src/lib/tdd.js +35 -11
  49. package/assets/ci/asdlc-ai-review.yml +0 -65
  50. package/assets/githooks/post-merge +0 -22
  51. package/assets/githooks/pre-push +0 -17
@@ -1,8 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { HARD_RULES, isTestOrDocFile } from '../rules/builtin.js';
3
+ import { HARD_RULES, isTestOrDocFile, isChangeMetadataFile } from '../rules/builtin.js';
4
+ import { getGraphTopologyMetrics } from '../../lib/graphify.js';
4
5
 
5
- export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRoot = null } = {}) {
6
+ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRoot = null, changeId = null } = {}) {
6
7
  const req = String(requirement || '').toLowerCase();
7
8
  const evidence = [];
8
9
  const unresolved = [];
@@ -72,29 +73,140 @@ export function evaluateV3Topology({ requirement = '', changedFiles = [], repoRo
72
73
  }
73
74
  }
74
75
 
75
- // 2. Check Requirement Semantics for Architecture / Schema / Infra
76
+ // 2. Graphify AST Knowledge Graph Centrality & God Nodes Check
77
+ // Escalates to L2 if changed files touch architectural hubs with high cross-file fan-in
78
+ if (repoRoot) {
79
+ try {
80
+ const topoMetrics = getGraphTopologyMetrics(repoRoot);
81
+ if (topoMetrics.available && topoMetrics.fileInDegree) {
82
+ // High centrality threshold: >= 20 cross-file inbound dependencies
83
+ // Exclude purely peripheral utility loggers or formats
84
+ const GOD_NODE_THRESHOLD = 20;
85
+ const hitHubs = [];
86
+
87
+ const substantiveFiles = changedFiles.filter((f) => !isChangeMetadataFile(f));
88
+
89
+ // Check 1: Physical changed files
90
+ for (const f of substantiveFiles) {
91
+ if (isTestOrDocFile(f)) continue;
92
+ const norm = f.replace(/\\/g, '/');
93
+ if (/(^|\/)(log|logger|logging|cliutil)\.[a-z0-9]+$/i.test(norm)) continue; // ignore pure logger / cli wrappers
94
+ const inDegree = topoMetrics.fileInDegree[norm] || 0;
95
+ if (inDegree >= GOD_NODE_THRESHOLD) {
96
+ hitHubs.push({ file: norm, inDegree });
97
+ }
98
+ }
99
+
100
+ // Check 2: Pre-implementation stages (no substantive changedFiles yet) — ground in explore.md query
101
+ // IMPORTANT:
102
+ // a) Only inspect the ## Query: section (never the global ## Architectural hubs header).
103
+ // b) When Graphify outputs a BFS depth=2 traversal with `Start: [...]`, restrict matches to
104
+ // 0-hop Start nodes so 2-hop neighbor hubs (e.g. leaf -> caller -> fs.js) do not trigger false positives.
105
+ if (substantiveFiles.length === 0 && hitHubs.length === 0 && changeId) {
106
+ try {
107
+ const expPath = path.join(repoRoot, 'openspec', 'changes', changeId, 'explore.md');
108
+ if (fs.existsSync(expPath)) {
109
+ const expContent = fs.readFileSync(expPath, 'utf8');
110
+ const queryMatch = expContent.match(/##\s*Query:[^\n]*\n([\s\S]*?)(?:\n##\s|$)/i);
111
+ const queryContent = queryMatch ? queryMatch[1] : '';
112
+ if (queryContent && !queryContent.includes('_(no matches)_') && !queryContent.includes('_(unavailable')) {
113
+ const startHeaderMatch = queryContent.match(/\bStart:\s*\[([^\]]*)\]/);
114
+ let directHitFiles = null;
115
+ let startLabels = null;
116
+
117
+ if (startHeaderMatch) {
118
+ startLabels = new Set();
119
+ const rawList = startHeaderMatch[1];
120
+ for (const m of rawList.matchAll(/['"]([^'"]+)['"]/g)) {
121
+ startLabels.add(m[1].trim());
122
+ }
123
+ directHitFiles = new Set();
124
+ for (const m of queryContent.matchAll(/^NODE\s+(.+?)\s+\[src=([^\s\]]+)/gm)) {
125
+ const nodeLabel = m[1].trim();
126
+ const nodeSrc = m[2].replace(/\\/g, '/');
127
+ if (startLabels.has(nodeLabel) && !isTestOrDocFile(nodeSrc)) {
128
+ directHitFiles.add(nodeSrc);
129
+ }
130
+ }
131
+ }
132
+
133
+ for (const [hubFile, inDeg] of (topoMetrics.topHubs || [])) {
134
+ if (inDeg >= GOD_NODE_THRESHOLD && !/(^|\/)(log|logger|logging|cliutil)\.[a-z0-9]+$/i.test(hubFile)) {
135
+ const baseName = path.basename(hubFile);
136
+ const matched = directHitFiles !== null
137
+ ? (directHitFiles.has(hubFile) || startLabels.has(hubFile) || startLabels.has(baseName))
138
+ : (queryContent.includes(hubFile) || queryContent.includes(baseName));
139
+ if (matched) {
140
+ hitHubs.push({ file: hubFile, inDegree: inDeg });
141
+ }
142
+ }
143
+ }
144
+ }
145
+ }
146
+ } catch { /* ignore explore read */ }
147
+ }
148
+
149
+ if (hitHubs.length > 0) {
150
+ no_signal = false;
151
+ if (level === 'L1') {
152
+ level = 'L2';
153
+ }
154
+ const hubDesc = hitHubs.slice(0, 3).map((h) => `${h.file} (${h.inDegree} inbound refs)`).join(', ');
155
+ evidence.push({
156
+ id: 'V3_GRAPHIFY_GOD_NODE',
157
+ kind: 'topology_centrality',
158
+ signal: 'hard',
159
+ summary: `Touches Graphify AST architectural hub: ${hubDesc}`,
160
+ source: hitHubs[0].file
161
+ });
162
+ }
163
+ }
164
+ } catch {
165
+ /* ignore graph metrics reading failure */
166
+ }
167
+ }
168
+
169
+ // 3. Check Requirement Semantics for Architecture / Schema / Infra (English + Chinese)
76
170
  const topoKeywords = [
77
171
  'api', 'endpoint', 'openapi', 'swagger', 'grpc', 'protobuf', 'graphql', 'webhook',
78
172
  'fastapi', 'springboot', 'spring boot', 'controller', 'rest api', 'router',
79
173
  'database', 'migration', 'schema', 'db table', 'database table', 'sql table', 'ddl', 'model', 'docker', 'k8s', 'helm'
80
174
  ];
81
175
 
176
+ const cjkTopoKeywords = [
177
+ '接口', '路由', '协议', '网关', '控制器', '出入参', '字段变更',
178
+ '数据库', '数据表', '表结构', '数据库迁移', '索引变更', '容器编排'
179
+ ];
180
+
181
+ let matchedTopoKw = null;
82
182
  for (const kw of topoKeywords) {
83
183
  const re = new RegExp(`\\b${kw.replace(/-/g, '[-\\s]')}\\b`, 'i');
84
184
  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
- });
185
+ matchedTopoKw = kw;
95
186
  break;
96
187
  }
97
188
  }
189
+ if (!matchedTopoKw) {
190
+ for (const cjkKw of cjkTopoKeywords) {
191
+ if (req.includes(cjkKw)) {
192
+ matchedTopoKw = cjkKw;
193
+ break;
194
+ }
195
+ }
196
+ }
197
+
198
+ if (matchedTopoKw) {
199
+ no_signal = false;
200
+ if (level === 'L1') {
201
+ level = 'L2';
202
+ }
203
+ evidence.push({
204
+ id: 'V3_TOPOLOGY_KEYWORD',
205
+ kind: 'task_statement',
206
+ signal: 'soft',
207
+ summary: `Requirement touches cross-boundary architectural keyword: '${matchedTopoKw}'`
208
+ });
209
+ }
98
210
 
99
211
  return {
100
212
  level,
@@ -6,6 +6,7 @@ import { lastCommitTouching, git } from '../lib/git.js';
6
6
  import { fail } from '../lib/errors.js';
7
7
  import { log } from '../lib/log.js';
8
8
  import { isSinglePrLevel, readEffectiveLevel } from '../lib/level.js';
9
+ import { assess } from '../assess/index.js';
9
10
 
10
11
  // Guard before implementing: the spec must be APPROVED on the target branch
11
12
  // (i.e. the Spec PR has been merged into targetBranch, locking proposal.md & specs/**).
@@ -15,7 +16,6 @@ export function applyGuard(changeId, opts = {}) {
15
16
  const cdir = changeDir(repoRoot, slug);
16
17
  if (!exists(cdir)) fail(`change '${slug}' not found`);
17
18
 
18
- // 1. Resolve target branch dynamically: CLI option -> .openspec.yaml -> git tracking -> main/master
19
19
  const metaPath = path.join(cdir, '.openspec.yaml');
20
20
  let meta = {};
21
21
  if (exists(metaPath)) {
@@ -41,7 +41,7 @@ export function applyGuard(changeId, opts = {}) {
41
41
 
42
42
  const locked = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
43
43
 
44
- const levelInfo = readEffectiveLevel(repoRoot, slug);
44
+ const levelInfo = readEffectiveLevel(repoRoot, slug, { baseRef: branch });
45
45
  if (levelInfo?.tampered) {
46
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
47
  code: 'LEVEL_TAMPERED',
@@ -49,7 +49,32 @@ export function applyGuard(changeId, opts = {}) {
49
49
  });
50
50
  }
51
51
 
52
- const effectiveLevel = levelInfo?.effectiveLevel || meta.level || null;
52
+ let effectiveLevel = levelInfo?.effectiveLevel || meta.level || null;
53
+ const agentAssessPath = path.join(cdir, '.agent-assess.json');
54
+ if (meta.level && (exists(agentAssessPath) || levelInfo?.maxHistoryLevel)) {
55
+ const assessment = assess({
56
+ stage: 'spec',
57
+ changeId: slug,
58
+ repoRoot,
59
+ persist: true
60
+ });
61
+ const assessedLevel = assessment.risk.level;
62
+ const rank = { L0: 0, L1: 1, L2: 2, L3: 3 };
63
+ if ((rank[assessedLevel] ?? 0) > (rank[effectiveLevel] ?? 0)) {
64
+ effectiveLevel = assessedLevel;
65
+ if (exists(metaPath)) {
66
+ let metaText = readText(metaPath);
67
+ const upsertKey = (text, key, val) => {
68
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
69
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
70
+ };
71
+ metaText = upsertKey(metaText, 'level', effectiveLevel);
72
+ metaText = upsertKey(metaText, 'workflowMode', assessment.governance.workflow_mode);
73
+ writeText(metaPath, metaText);
74
+ }
75
+ }
76
+ }
77
+
53
78
  const isSinglePr = isSinglePrLevel(effectiveLevel);
54
79
  let approvedSha = null;
55
80
 
@@ -88,7 +113,7 @@ export function applyGuard(changeId, opts = {}) {
88
113
  });
89
114
  }
90
115
 
91
- // 4. Content-level cryptographic zero-diff invariant:
116
+ // 4. Content-level Git-anchored zero-diff invariant:
92
117
  // The local spec content MUST match the approved version on the target branch
93
118
  const diff = (git(['diff', approvedSha, '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
94
119
  if (diff) {
@@ -109,6 +134,10 @@ export function applyGuard(changeId, opts = {}) {
109
134
  };
110
135
  metaText = upsertKey(metaText, 'specSha', approvedSha);
111
136
  metaText = upsertKey(metaText, 'status', 'ready_for_impl');
137
+ if (effectiveLevel && effectiveLevel !== meta.level) {
138
+ metaText = upsertKey(metaText, 'level', effectiveLevel);
139
+ metaText = upsertKey(metaText, 'workflowMode', 'spec-first');
140
+ }
112
141
  writeText(metaPath, metaText);
113
142
  }
114
143
  log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
@@ -3,7 +3,7 @@ import { execFileSync } from 'node:child_process';
3
3
  import { exists, readText, writeText } from '../lib/fs.js';
4
4
  import { changeDir } from '../lib/paths.js';
5
5
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
6
- import { headSha, git, isGitRepo, lastCommitTouching, changeOnRef } from '../lib/git.js';
6
+ import { headSha, git, isGitRepo, lastCommitTouching, changeOnRef, safeCommit } from '../lib/git.js';
7
7
  import { loadPolicy } from '../lib/policy.js';
8
8
  import { classifyPR } from '../lib/prtype.js';
9
9
  import { fail } from '../lib/errors.js';
@@ -126,8 +126,7 @@ export function mergeChange(changeId, opts = {}) {
126
126
  if (opts.commit !== false) {
127
127
  try {
128
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' });
129
+ safeCommit(repoRoot, `chore(approve): spec approved @ ${approvedSha.slice(0, 8)} (${slug})`);
131
130
  log.ok('committed approval stamp');
132
131
  } catch {
133
132
  log.warn('nothing to commit (already stamped)');
@@ -1,6 +1,7 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
- import { exists, readText, writeText, listDir } from '../lib/fs.js';
3
- import { changeDir } from '../lib/paths.js';
3
+ import { exists, readText, ensureDir, copyTree, removeDir, listDir, walkFiles } from '../lib/fs.js';
4
+ import { changeDir, openspecDir } from '../lib/paths.js';
4
5
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
5
6
  import { runOpenspec } from '../lib/openspec.js';
6
7
  import { refreshAgents } from '../lib/agents.js';
@@ -9,47 +10,21 @@ import { git } from '../lib/git.js';
9
10
  import { fail } from '../lib/errors.js';
10
11
  import { log } from '../lib/log.js';
11
12
 
12
- function syncReadme(repoRoot, slug, proposalText) {
13
- const readmePath = path.join(repoRoot, 'README.md');
14
- if (!exists(readmePath)) return;
15
- let text = readText(readmePath);
16
- if (text.includes(`\`${slug}\``)) return;
17
-
18
- let summary = 'Implemented capability.';
19
- const m = proposalText.match(/##\s*Why\s*\n+([^\n\r]+)/i);
20
- if (m && m[1]) {
21
- const raw = m[1].replace(/<!--[\s\S]*?-->/g, '').trim();
22
- if (raw) summary = raw;
23
- }
24
-
25
- const entry = `- **\`${slug}\`**: ${summary}`;
26
- if (text.includes('## Living Specifications')) {
27
- text = text.replace('## Living Specifications', `## Living Specifications\n\n${entry}`);
28
- } else {
29
- text = `${text.trimEnd()}\n\n## Living Specifications\n\n${entry}\n`;
30
- }
31
- writeText(readmePath, text);
32
- log.ok(`updated README.md with archived capability (${slug})`);
33
- }
34
-
35
13
  export const CONSTITUTIONAL_PATHS = [
36
14
  'AGENTS.md',
37
15
  '.sdlc/policy.yaml',
38
16
  'openspec/config.yaml',
39
- '.githooks',
40
17
  ];
41
18
 
42
19
  export function isConstitutionalChange(repoRoot, opts = {}) {
43
20
  if (opts.constitutional === true || opts.agents === true) return true;
44
21
 
45
- // 2. Working tree status (unstaged/staged governance changes)
46
- const statusOut = git(['status', '--porcelain'], repoRoot, { allowFail: true }) ?? '';
22
+ const statusOut = git(['status', '--porcelain', '-uall'], repoRoot, { allowFail: true }) ?? '';
47
23
  const statusFiles = statusOut
48
24
  .split(/\r?\n/)
49
- .map((l) => l.slice(3).trim())
25
+ .map((l) => l.replace(/^\s*\S+\s+/, '').trim())
50
26
  .filter(Boolean);
51
27
 
52
- // 3. Precise commit check: check HEAD commit (the merge commit being archived)
53
28
  const commitFilesOut = git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD'], repoRoot, { allowFail: true }) ?? '';
54
29
  const commitFiles = commitFilesOut
55
30
  .split(/\r?\n/)
@@ -70,26 +45,51 @@ export function isConstitutionalChange(repoRoot, opts = {}) {
70
45
  return false;
71
46
  }
72
47
 
73
- // Stage 7: Archive. Moves change to archive, syncs delta specs into
74
- // openspec/specs/, updates README.md, and updates AGENTS.md ONLY if constitutional.
48
+ function compactChangeFallback(repoRoot, slug) {
49
+ const cdir = changeDir(repoRoot, slug);
50
+ if (!exists(cdir)) return;
51
+
52
+ const specsSrc = path.join(cdir, 'specs');
53
+ if (exists(specsSrc)) {
54
+ const specRelFiles = walkFiles(specsSrc).filter((f) => f.endsWith('spec.md'));
55
+ for (const rel of specRelFiles) {
56
+ const srcFile = path.join(specsSrc, rel);
57
+ const destFile = path.join(openspecDir(repoRoot), 'specs', rel);
58
+ ensureDir(path.dirname(destFile));
59
+ fs.copyFileSync(srcFile, destFile);
60
+ }
61
+ }
62
+
63
+ const stamp = new Date().toISOString().slice(0, 10);
64
+ const archiveDest = path.join(openspecDir(repoRoot), 'changes', 'archive', `${stamp}-${slug}`);
65
+ ensureDir(path.dirname(archiveDest));
66
+ copyTree(cdir, archiveDest);
67
+ removeDir(cdir);
68
+ }
69
+
70
+ // Stage 7: Post-Merge Archive.
71
+ // Compacts openspec/changes/<slug> -> openspec/changes/archive/ and syncs living specs
72
+ // into openspec/specs/ WITHOUT polluting root README.md or routine AGENTS.md (zero merge-conflict hotspots).
75
73
  export function archiveChange(changeId, opts = {}) {
76
74
  const repoRoot = requireRepo(opts);
77
75
  const slug = toChangeSlug(changeId);
78
76
  const cdir = changeDir(repoRoot, slug);
79
77
  if (!exists(cdir)) fail(`change '${slug}' not found`);
80
78
 
81
- const proposalFile = path.join(cdir, 'proposal.md');
82
- const proposalText = exists(proposalFile) ? readText(proposalFile) : '';
83
-
84
79
  if (opts.openspec !== false) {
85
80
  const res = runOpenspec(['archive', slug, '--yes'], repoRoot);
86
- if (res.status === 0) log.ok(`archived ${slug}: synced living specs -> openspec/specs/`);
87
- else log.warn(`openspec archive returned ${res.status} (archive manually if needed)`);
81
+ if (res.status === 0) {
82
+ log.ok(`archived ${slug}: synced living specs -> openspec/specs/`);
83
+ } else {
84
+ compactChangeFallback(repoRoot, slug);
85
+ log.ok(`archived ${slug} via native compaction -> openspec/specs/`);
86
+ }
87
+ } else {
88
+ compactChangeFallback(repoRoot, slug);
89
+ log.ok(`archived ${slug}: synced living specs -> openspec/specs/`);
88
90
  }
89
91
 
90
- syncReadme(repoRoot, slug, proposalText);
91
-
92
- // Refresh AST knowledge graph if Graphify is available
92
+ // Refresh derived AST knowledge graph cache if Graphify is available (gitignored, no merge conflicts)
93
93
  if (opts.graph !== false) {
94
94
  try {
95
95
  const g = ensureFreshGraph(repoRoot);
@@ -101,43 +101,95 @@ export function archiveChange(changeId, opts = {}) {
101
101
  }
102
102
  }
103
103
 
104
- // AGENTS.md update:
105
- // - If AGENTS.md does not exist, create and initialize it.
106
- // - If AGENTS.md exists, refresh the system status (knowledge graph god nodes)
107
- // and routing block so the agentic IDE stays grounded in current architecture.
108
- // - If constitutional change or explicit --agents, log governance refresh.
109
- // - If --no-agents was explicitly passed, skip updating AGENTS.md.
110
- const agentsPath = path.join(repoRoot, 'AGENTS.md');
111
- const agentsMissing = !exists(agentsPath);
112
- const constitutional = isConstitutionalChange(repoRoot, opts);
113
- const shouldUpdateAgents = opts.agents !== false;
114
-
104
+ // Conflict-free root governance rule:
105
+ // Routine feature archives NEVER rewrite root README.md or AGENTS.md.
106
+ // AGENTS.md is updated ONLY when explicitly requested via --agents or when constitutional paths changed.
107
+ const shouldUpdateAgents = opts.agents === true || (opts.agents !== false && isConstitutionalChange(repoRoot, opts));
115
108
  if (shouldUpdateAgents) {
116
109
  refreshAgents(repoRoot, { systemStatus: true });
117
- if (agentsMissing) {
118
- log.ok('created AGENTS.md (was missing) and initialized system status');
119
- } else if (constitutional) {
120
- log.ok('updated AGENTS.md (constitutional change detected on governance paths)');
121
- } else {
122
- log.ok('refreshed AGENTS.md system status (knowledge graph hubs)');
123
- }
110
+ log.ok('updated AGENTS.md (explicit --agents or constitutional governance change)');
124
111
  }
125
112
 
126
113
  log.ok(`archive complete for ${slug}`);
127
114
  return 0;
128
115
  }
129
116
 
117
+ export function isChangeMergedAndComplete(repoRoot, slug, targetRef = 'HEAD') {
118
+ // First ensure targetRef has tracked files for this change
119
+ const trackedOnTarget = git(['ls-tree', '-r', '--name-only', targetRef, `openspec/changes/${slug}`], repoRoot, { allowFail: true }) ?? '';
120
+ if (!trackedOnTarget.trim()) return false;
121
+
122
+ // A change is only completed if implementation tasks were generated, completed, and checked off on targetRef.
123
+ // We read tasks.md directly from targetRef (via git show) to isolate against local working-tree leakage
124
+ // (e.g. running archive --merged while checked out on a dirty or unmerged feature branch).
125
+ const tasksGitPath = `${targetRef}:openspec/changes/${slug}/tasks.md`;
126
+ const tasksTextOnTarget = git(['show', tasksGitPath], repoRoot, { allowFail: true });
127
+ if (!tasksTextOnTarget) return false;
128
+
129
+ const checked = (tasksTextOnTarget.match(/^\s*-\s+\[x\]/gim) ?? []).length;
130
+ const unchecked = (tasksTextOnTarget.match(/^\s*-\s+\[\s\]/gm) ?? []).length;
131
+ return checked > 0 && unchecked === 0;
132
+ }
133
+
134
+ /**
135
+ * Post-merge batch compaction (`asdlc archive --merged`):
136
+ * Archives all completed changes already merged on targetRef in a single L0 maintenance pass,
137
+ * eliminating per-feature 3rd PR overhead.
138
+ */
139
+ export function archiveMergedChanges(opts = {}) {
140
+ const repoRoot = requireRepo(opts);
141
+ const changesRoot = path.join(openspecDir(repoRoot), 'changes');
142
+ if (!exists(changesRoot)) {
143
+ log.info('No openspec/changes directory found.');
144
+ return 0;
145
+ }
146
+
147
+ const targetRef = opts.targetBranch ?? 'HEAD';
148
+ const entries = fs.readdirSync(changesRoot, { withFileTypes: true });
149
+ const candidates = entries
150
+ .filter((ent) => ent.isDirectory() && ent.name !== 'archive' && !ent.name.startsWith('.'))
151
+ .map((ent) => ent.name);
152
+
153
+ const mergedSlugs = candidates.filter((slug) => isChangeMergedAndComplete(repoRoot, slug, targetRef));
154
+ if (mergedSlugs.length === 0) {
155
+ log.info('No completed merged changes pending archive.');
156
+ return 0;
157
+ }
158
+
159
+ for (const slug of mergedSlugs) {
160
+ archiveChange(slug, { ...opts, graph: false, agents: false });
161
+ }
162
+
163
+ if (opts.graph !== false) {
164
+ try { ensureFreshGraph(repoRoot); } catch { /* ignore */ }
165
+ }
166
+ if (opts.agents === true) {
167
+ refreshAgents(repoRoot, { systemStatus: true });
168
+ }
169
+
170
+ log.ok(`batch archived ${mergedSlugs.length} merged change(s): ${mergedSlugs.join(', ')}`);
171
+ return 0;
172
+ }
173
+
130
174
  export function register(program) {
131
175
  program
132
- .command('archive <changeId>')
133
- .description('finish: archive change + sync living specs to openspec/specs/ + update README & AGENTS.md')
176
+ .command('archive [changeId]')
177
+ .description('post-merge compaction: archive completed change(s) and sync living specs to openspec/specs/')
178
+ .option('--merged', 'batch-archive all completed changes merged on target branch')
179
+ .option('--target-branch <ref>', 'target branch ref to check for --merged (default: HEAD)')
134
180
  .option('--repo-root <path>')
135
- .option('--agents', 'force refresh AGENTS.md')
136
- .option('--no-agents', 'skip updating AGENTS.md')
181
+ .option('--agents', 'explicitly refresh AGENTS.md')
182
+ .option('--no-agents', 'skip updating AGENTS.md (default for non-constitutional changes)')
137
183
  .option('--no-graph', 'skip rebuilding knowledge graph')
138
- .option('--no-openspec', 'skip the openspec archive step')
184
+ .option('--no-openspec', 'use native compaction without invoking openspec archive')
139
185
  .action((changeId, opts) => {
186
+ if (opts.merged) {
187
+ process.exitCode = archiveMergedChanges(opts);
188
+ return;
189
+ }
190
+ if (!changeId) {
191
+ fail('specify <changeId> or pass --merged to batch-archive merged changes');
192
+ }
140
193
  process.exitCode = archiveChange(changeId, opts);
141
194
  });
142
195
  }
143
-
@@ -1,9 +1,9 @@
1
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';
2
+ import { exists, readText, writeText } from '../lib/fs.js';
3
+ import { openspecDir, resolveRepoRoot } from '../lib/paths.js';
4
4
  import { openspecVersion, OPENSPEC_PINNED, findOpenspec } from '../lib/openspec.js';
5
5
  import { graphifyAvailable, graphStatus, GITIGNORE_LINE, ensureGraphify } from '../lib/graphify.js';
6
- import { readInstalledVersion, builtinSchemaVersion, localOverride, installSchema } from '../lib/schema.js';
6
+ import { checkSchema, builtinSchemaVersion, localOverride, installSchema } from '../lib/schema.js';
7
7
  import { refreshAgents } from '../lib/agents.js';
8
8
  import { readYaml } from '../lib/yaml.js';
9
9
  import { git } from '../lib/git.js';
@@ -32,12 +32,13 @@ export function doctor(opts = {}) {
32
32
 
33
33
  add('Graphify', graphifyAvailable() ? 'pass' : 'warn', graphifyAvailable() ? 'installed' : 'not found (install via uv tool install graphifyy or pip)');
34
34
 
35
- const schemaV = readInstalledVersion();
36
- add('managed schema', schemaV ? 'pass' : 'fail', schemaV ? `v${schemaV} (bundled v${builtinSchemaVersion()})` : 'not installed (run `asdlc init` or `asdlc upgrade`)');
35
+ const schemaCheck = checkSchema(repoRoot || process.cwd(), { stateless: true });
36
+ add('managed schema', schemaCheck.ok ? 'pass' : 'fail',
37
+ schemaCheck.ok ? `v${schemaCheck.installed || builtinSchemaVersion()} (stateless bundled)` : schemaCheck.reason);
37
38
 
38
39
  let gi = null;
39
40
  let ignored = false;
40
- let hooksPath = null;
41
+ let staleHooksPath = false;
41
42
  let hasRouting = false;
42
43
  let detectedTools = [];
43
44
 
@@ -59,8 +60,13 @@ export function doctor(opts = {}) {
59
60
  if (exists(cfgPath)) { try { cfgSchema = (readYaml(cfgPath) ?? {}).schema ?? null; } catch { /* ignore */ } }
60
61
  add('repo config schema', cfgSchema === 'agentic-repo-change' ? 'pass' : 'warn', cfgSchema ?? 'unset');
61
62
 
62
- try { hooksPath = git(['config', '--get', 'core.hooksPath'], repoRoot, { allowFail: true }); } catch { /* ignore */ }
63
- add('.githooks', hooksPath === '.githooks' ? 'pass' : 'warn', hooksPath === '.githooks' ? 'core.hooksPath=.githooks' : `core.hooksPath=${hooksPath ?? 'unset'}`);
63
+ try {
64
+ const hooksPath = (git(['config', '--get', 'core.hooksPath'], repoRoot, { allowFail: true }) ?? '').trim();
65
+ if (hooksPath === '.githooks' && !exists(path.join(repoRoot, '.githooks'))) {
66
+ staleHooksPath = true;
67
+ add('git hooks hygiene', 'warn', 'stale core.hooksPath=.githooks (run `asdlc doctor --fix` to unset)');
68
+ }
69
+ } catch { /* ignore */ }
64
70
 
65
71
  const agents = path.join(repoRoot, 'AGENTS.md');
66
72
  hasRouting = exists(agents) && readText(agents).includes('<!-- asdlc:routing -->');
@@ -101,12 +107,12 @@ export function doctor(opts = {}) {
101
107
  log.step('attempting automated remediation (--fix)...');
102
108
 
103
109
  // 1. Managed schema
104
- if (!schemaV) {
105
- try { installSchema(); log.ok('fixed: installed managed schema'); } catch (e) { log.warn(`fix failed for schema: ${e.message}`); }
110
+ if (!schemaCheck.ok) {
111
+ try { installSchema(); log.ok('fixed: synced managed schema'); } catch (e) { log.warn(`fix failed for schema: ${e.message}`); }
106
112
  }
107
113
 
108
114
  // 2. .gitignore graphify-out
109
- if (!ignored) {
115
+ if (gi && !ignored) {
110
116
  try {
111
117
  const text = exists(gi) ? readText(gi) : '';
112
118
  writeText(gi, `${text.trimEnd()}\n${GITIGNORE_LINE}\n`);
@@ -114,15 +120,12 @@ export function doctor(opts = {}) {
114
120
  } catch (e) { log.warn(`fix failed for .gitignore: ${e.message}`); }
115
121
  }
116
122
 
117
- // 3. .githooks
118
- if (hooksPath !== '.githooks') {
123
+ // 3. Clean up stale .githooks config if present
124
+ if (staleHooksPath && repoRoot) {
119
125
  try {
120
- if (exists(githooksAssetDir)) {
121
- copyTree(githooksAssetDir, path.join(repoRoot, '.githooks'));
122
- }
123
- git(['config', 'core.hooksPath', '.githooks'], repoRoot);
124
- log.ok('fixed: configured git core.hooksPath -> .githooks');
125
- } catch (e) { log.warn(`fix failed for githooks: ${e.message}`); }
126
+ git(['config', '--unset', 'core.hooksPath'], repoRoot, { allowFail: true });
127
+ log.ok('fixed: removed stale core.hooksPath=.githooks');
128
+ } catch (e) { log.warn(`fix failed for core.hooksPath: ${e.message}`); }
126
129
  }
127
130
 
128
131
  // 5. AGENTS.md routing