@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
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  import { exists, readText, writeText, walkFiles } from '../lib/fs.js';
3
3
  import { readYaml } from '../lib/yaml.js';
4
4
  import { openspecDir, changeDir } from '../lib/paths.js';
5
- import { requireRepo, toChangeSlug, readLintConfig } from '../lib/cliutil.js';
5
+ import { requireRepo, toChangeSlug, readLintConfig, jsonOut } from '../lib/cliutil.js';
6
6
  import { validateChange } from '../lib/openspec.js';
7
7
  import { runShell } from '../lib/exec.js';
8
8
  import { lastCommitTouching, changeOnRef, git } from '../lib/git.js';
@@ -11,8 +11,9 @@ import { checkSchema } from '../lib/schema.js';
11
11
  import { loadPolicy, isAdvisory, DEFAULT_POLICY, matchesAny } from '../lib/policy.js';
12
12
  import { classifyPR } from '../lib/prtype.js';
13
13
  import { isSinglePrLevel, requiresHumanReview, readChangeLevel, readEffectiveLevel } from '../lib/level.js';
14
- import { assess, renderCheckSummary, loadInitialAssessment } from '../assess/index.js';
14
+ import { assess, renderCheckSummary, loadRiskHistory } from '../assess/index.js';
15
15
  import { checkTestPresence, checkTaskEvidence } from '../lib/tdd.js';
16
+ import { runTests, parseSpecAcceptanceCriteria } from './test.js';
16
17
  import { log, dim } from '../lib/log.js';
17
18
 
18
19
  // THE implementation check (v10: gate absorbed verify). Deterministic checks
@@ -22,15 +23,27 @@ import { log, dim } from '../lib/log.js';
22
23
  function meta(repoRoot, changeId) {
23
24
  const p = path.join(changeDir(repoRoot, toChangeSlug(changeId)), '.openspec.yaml');
24
25
  if (!exists(p)) return {};
25
- const text = readText(p);
26
- const sha = text.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
27
- const status = text.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
28
- const lvl = text.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
29
- return {
30
- specSha: sha ? sha[1] : null,
31
- status: status ? status[1] : null,
32
- level: lvl ? lvl[1].toUpperCase() : null,
33
- };
26
+ try {
27
+ const data = readYaml(p) ?? {};
28
+ return {
29
+ specSha: data.specSha ? String(data.specSha) : null,
30
+ status: data.status ? String(data.status) : null,
31
+ level: data.level ? String(data.level).toUpperCase() : null,
32
+ escalatedInImpl: data.escalatedInImpl === true || String(data.escalatedInImpl).toLowerCase() === 'true',
33
+ };
34
+ } catch {
35
+ const text = readText(p);
36
+ const sha = text.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
37
+ const status = text.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
38
+ const lvl = text.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
39
+ const esc = text.match(/^\s*escalatedInImpl:\s*['"]?([^\s'"]+)['"]?\s*$/m);
40
+ return {
41
+ specSha: sha ? sha[1] : null,
42
+ status: status ? status[1] : null,
43
+ level: lvl ? lvl[1].toUpperCase() : null,
44
+ escalatedInImpl: esc ? esc[1].toLowerCase() === 'true' : false,
45
+ };
46
+ }
34
47
  }
35
48
 
36
49
  function readYamlConfig(repoRoot) {
@@ -49,13 +62,27 @@ function readExternalChecks(repoRoot) {
49
62
  return ext.filter((e) => e && typeof e.command === 'string').map((e) => ({ name: e.name ?? e.command, command: e.command }));
50
63
  }
51
64
 
52
- function finish(results, policy) {
65
+ function finish(results, policy, opts = {}) {
53
66
  let failed = 0;
54
- log.info('');
55
- for (const r of results) {
67
+ const processed = results.map((r) => {
56
68
  const status = r.status === 'fail' && isAdvisory(policy, r.name) ? 'warn' : r.status;
57
- const badge = { pass: 'PASS', fail: 'FAIL', warn: 'WARN', skip: 'SKIP' }[status];
58
69
  if (status === 'fail') failed += 1;
70
+ return { ...r, status };
71
+ });
72
+
73
+ if (opts.json) {
74
+ jsonOut({
75
+ verdict: failed === 0 ? 'PASS' : 'FAIL',
76
+ pass: failed === 0,
77
+ failed,
78
+ results: processed,
79
+ });
80
+ return failed ? 1 : 0;
81
+ }
82
+
83
+ log.info('');
84
+ for (const r of processed) {
85
+ const badge = { pass: 'PASS', fail: 'FAIL', warn: 'WARN', skip: 'SKIP' }[r.status];
59
86
  log.plain(` [${badge}] ${r.name}`);
60
87
  if (r.detail) log.plain(` ${dim(r.detail)}`);
61
88
  }
@@ -80,7 +107,43 @@ function intent(cdir) {
80
107
  return parts.join('\n\n');
81
108
  }
82
109
 
83
- function buildPrompt(changeId, intentText, diff, base) {
110
+ export const DEFAULT_MAX_DIFF_CHARS = 32000;
111
+
112
+ export function buildVerifierDiffPayload(diff, { maxChars = DEFAULT_MAX_DIFF_CHARS } = {}) {
113
+ const raw = String(diff || '');
114
+ if (!raw) return '(empty diff)';
115
+ if (raw.length <= maxChars) return raw;
116
+
117
+ // Split unified diff by file and preserve file manifest + bounded per-file hunks
118
+ const sections = raw.split(/(?=^diff --git )/m).filter(Boolean);
119
+ const fileManifest = sections.map((sec) => {
120
+ const header = sec.match(/^diff --git a\/(.+?) b\/(.+?)$/m);
121
+ const file = header ? header[2] : 'unknown';
122
+ const adds = (sec.match(/^\+(?!\+\+)/gm) || []).length;
123
+ const dels = (sec.match(/^-(?!--)/gm) || []).length;
124
+ return ` - ${file} (+${adds} / -${dels})`;
125
+ });
126
+
127
+ const manifestBlock = `Changed files (${sections.length}):\n${fileManifest.join('\n')}\n\n`;
128
+ const notice = `\n\n[DIFF TRUNCATED: total ${raw.length} chars exceeded ${maxChars}-char stdin budget. Run the \`asdlc-impl-review\` skill in an independent agent session for multi-file deep review.]`;
129
+ const remainingBudget = Math.max(256, maxChars - manifestBlock.length - notice.length);
130
+ const perFileBudget = Math.max(160, Math.floor(remainingBudget / Math.max(1, sections.length)));
131
+
132
+ const excerpts = [];
133
+ let used = 0;
134
+ for (const sec of sections) {
135
+ if (used >= remainingBudget) break;
136
+ const allowance = Math.min(perFileBudget, remainingBudget - used);
137
+ const slice = sec.length > allowance ? `${sec.slice(0, allowance)}\n... (hunk truncated)` : sec;
138
+ excerpts.push(slice);
139
+ used += slice.length + 2;
140
+ }
141
+
142
+ return `${manifestBlock}${excerpts.join('\n\n')}${notice}`;
143
+ }
144
+
145
+ function buildPrompt(changeId, intentText, diff, base, opts = {}) {
146
+ const boundedDiff = buildVerifierDiffPayload(diff, { maxChars: opts.maxDiffChars ?? DEFAULT_MAX_DIFF_CHARS });
84
147
  return `You are an INDEPENDENT VERIFIER for change ${changeId}. You did NOT author it.
85
148
  Verify the IMPLEMENTATION satisfies the APPROVED INTENT. Be skeptical.
86
149
  - Decide PASS/FAIL for every requirement / acceptance criterion and every task.
@@ -91,7 +154,7 @@ Output ONLY strict JSON: {"verdict":"PASS|FAIL","summary":"...","requirements":[
91
154
  ${intentText}
92
155
 
93
156
  ===== IMPLEMENTATION DIFF (base ${base}) =====
94
- ${diff || '(empty diff)'}
157
+ ${boundedDiff}
95
158
  `;
96
159
  }
97
160
 
@@ -124,24 +187,36 @@ export function runVerify(changeId, opts = {}) {
124
187
  const cdir = changeDir(repoRoot, slug);
125
188
  if (!exists(cdir)) {
126
189
  add('change', 'fail', `change '${slug}' not found`);
127
- return finish(results, policy);
190
+ return finish(results, policy, opts);
128
191
  }
129
192
  add('change', 'pass', slug);
130
- const effLevel = readEffectiveLevel(repoRoot, changeId);
193
+ const effLevel = readEffectiveLevel(repoRoot, changeId, { baseRef: base });
131
194
  if (effLevel?.tampered) {
132
195
  add('level-integrity', 'fail', `tampered: declared ${effLevel.declaredLevel} < recorded history ${effLevel.maxHistoryLevel}`);
133
196
  } else {
134
197
  add('level-integrity', 'pass', `conforms to recorded history (${effLevel?.effectiveLevel || 'L1'})`);
135
198
  }
136
- const { specSha, status } = meta(repoRoot, changeId);
137
- const changeLevel = effLevel?.effectiveLevel || meta(repoRoot, changeId).level || null;
199
+ const metaInfo = meta(repoRoot, changeId);
200
+ const { specSha, status } = metaInfo;
201
+ const changeLevel = effLevel?.effectiveLevel || metaInfo.level || null;
138
202
 
139
203
  const changedFiles = (git(['diff', '--name-only', `${base}...${head}`], repoRoot, { allowFail: true }) ?? '')
140
204
  .split(/\r?\n/).filter(Boolean);
141
205
  const changeOnMain = changeOnRef(repoRoot, branch, slug);
142
- const initialAss = loadInitialAssessment(repoRoot, slug);
143
- const wasInitialSinglePr = initialAss && isSinglePrLevel(initialAss.risk?.level);
144
- const isSinglePr = Boolean(wasInitialSinglePr || isSinglePrLevel(changeLevel));
206
+
207
+ // Single-PR privilege applies ONLY if the change is currently L0/L1 OR legitimately entered
208
+ // implementation as L0/L1 and escalated strictly during `impl` (NOT during `new`/`spec`).
209
+ let history = [];
210
+ try { history = loadRiskHistory(repoRoot, slug); } catch { /* handled by readEffectiveLevel */ }
211
+ const preImplRecords = history.filter((r) => r.stage === 'new' || r.stage === 'spec');
212
+ const escalatedOnlyInImpl = Boolean(
213
+ metaInfo.escalatedInImpl ||
214
+ (history.length > 0 &&
215
+ preImplRecords.length > 0 &&
216
+ preImplRecords.every((r) => isSinglePrLevel(r.risk?.level)) &&
217
+ history.some((r) => r.stage === 'impl' && !isSinglePrLevel(r.risk?.level)))
218
+ );
219
+ const isSinglePr = Boolean(isSinglePrLevel(changeLevel) || escalatedOnlyInImpl);
145
220
 
146
221
  const pr = classifyPR({ changedFiles, changeOnMain, policy, emergency: opts.emergency, level: changeLevel, repoRoot, singlePr: isSinglePr });
147
222
  add('pr-type', pr.type === 'invalid' ? 'fail' : 'pass', `type=${pr.type} (${pr.reason})`);
@@ -157,7 +232,7 @@ export function runVerify(changeId, opts = {}) {
157
232
  const approvedSha = lastCommitTouching(repoRoot, branch, lockedPaths);
158
233
  if (effLevel?.tampered) {
159
234
  add('approved-spec', 'fail', 'governance level tampered: declared level is lower than history');
160
- } else if (isSinglePrLevel(changeLevel) || wasInitialSinglePr) {
235
+ } else if (isSinglePr) {
161
236
  add('approved-spec', 'pass', `${changeLevel || 'single-pr'} single-PR mode (spec approval co-located in implementation PR)`);
162
237
  } else if (!approvedSha) {
163
238
  add('approved-spec', 'fail', `no commit on locked paths is merged into ${branch} (not approved)`);
@@ -169,13 +244,13 @@ export function runVerify(changeId, opts = {}) {
169
244
 
170
245
  // Lightweight tamper guard: in a two-phase implementation PR, locked spec files MUST NOT be modified
171
246
  const lockedModified = changedFiles.filter((f) => matchesAny(f, policy?.locked_paths ?? DEFAULT_POLICY.locked_paths));
172
- if (!isSinglePrLevel(changeLevel) && !wasInitialSinglePr && pr.type === 'impl' && lockedModified.length > 0) {
247
+ if (!isSinglePr && pr.type === 'impl' && lockedModified.length > 0) {
173
248
  add('spec-tamper', 'fail', `${lockedModified.length} locked spec file(s) modified in implementation PR (${lockedModified.join(', ')})`);
174
249
  } else {
175
250
  add('spec-tamper', 'pass', 'locked spec paths unmodified');
176
251
  }
177
252
 
178
- if (isSinglePrLevel(changeLevel) || wasInitialSinglePr) {
253
+ if (isSinglePr) {
179
254
  add('flow-state', 'pass', `${changeLevel || 'single-pr'} single-PR mode (direct implementation)`);
180
255
  } else {
181
256
  add('flow-state', status === 'ready_for_impl' ? 'pass' : 'fail',
@@ -184,7 +259,7 @@ export function runVerify(changeId, opts = {}) {
184
259
 
185
260
  const isCI = opts.ci !== undefined
186
261
  ? Boolean(opts.ci)
187
- : (opts.openingPr ? false : Boolean(process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI || process.env.JENKINS_URL));
262
+ : (opts.openingPr ? false : Boolean(process.env.CI || process.env.GITHUB_ACTIONS || process.env.GITLAB_CI));
188
263
 
189
264
  const assessment = assess({
190
265
  stage: 'impl',
@@ -197,9 +272,12 @@ export function runVerify(changeId, opts = {}) {
197
272
  });
198
273
 
199
274
  const effectiveLevel = assessment.risk.level;
200
- const isEscalated = assessment.verdict === 'escalated' || (effLevel?.declaredLevel && effLevel.declaredLevel !== effectiveLevel && effectiveLevel !== 'L1');
275
+ const isEscalatedInImpl = Boolean(
276
+ (assessment.reason_codes || []).includes('ESCALATED_IN_IMPL') ||
277
+ (isSinglePr && !isSinglePrLevel(effectiveLevel))
278
+ );
201
279
 
202
- if (isEscalated) {
280
+ if (isEscalatedInImpl) {
203
281
  // Synchronize .openspec.yaml on in-place escalation (local runs only, avoid dirtying tree in CI)
204
282
  const metaPath = path.join(cdir, '.openspec.yaml');
205
283
  if (!isCI && !opts.openingPr && exists(metaPath)) {
@@ -276,7 +354,10 @@ export function runVerify(changeId, opts = {}) {
276
354
  else add('openspec-validate', 'fail', `${res.stdout}${res.stderr}`.trim().slice(0, 600));
277
355
  }
278
356
 
279
- const schema = checkSchema(repoRoot, { expectedVersion: readYamlConfig(repoRoot)?.schemaVersion ?? null });
357
+ const schema = checkSchema(repoRoot, {
358
+ expectedVersion: readYamlConfig(repoRoot)?.schemaVersion ?? null,
359
+ stateless: true,
360
+ });
280
361
  add('schema-managed', schema.ok ? 'pass' : 'fail',
281
362
  schema.ok ? `managed schema v${schema.installed}` : `${schema.reason}${schema.hint ? ` (${schema.hint})` : ''}`);
282
363
 
@@ -284,11 +365,28 @@ export function runVerify(changeId, opts = {}) {
284
365
  const SECRET = /TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|PRIVATE_?KEY|CREDENTIAL/i;
285
366
  const cleanEnv = Object.fromEntries(Object.entries(process.env).filter(([k]) => !SECRET.test(k)));
286
367
  const env = { ...cleanEnv, ASDLC_CHANGE_ID: changeId, ASDLC_REPO: opts.repo ?? '', ASDLC_SPEC_SHA: specSha ?? '' };
287
- for (const check of readExternalChecks(repoRoot)) {
368
+ const extChecks = readExternalChecks(repoRoot);
369
+ for (const check of extChecks) {
288
370
  const res = runShell(check.command, repoRoot, { env });
289
371
  if (res.status === 0) add(check.name, 'pass', '');
290
372
  else add(check.name, 'fail', `${res.stdout}${res.stderr}`.trim().slice(0, 600) || `exit ${res.status}`);
291
373
  }
374
+
375
+ // Default mapped acceptance-test execution when specs declare AC test mappings
376
+ if (extChecks.length === 0 && specFiles.length > 0 && blockers === 0) {
377
+ const hasMappedAcs = specFiles.some((f) =>
378
+ parseSpecAcceptanceCriteria(readText(path.join(cdir, 'specs', f))).some((ac) => ac.testPath)
379
+ );
380
+ if (hasMappedAcs) {
381
+ try {
382
+ const testExit = runTests(slug, { repoRoot, silent: true });
383
+ add('acceptance-tests', testExit === 0 ? 'pass' : 'fail',
384
+ testExit === 0 ? 'all spec-mapped acceptance tests passed' : 'one or more spec-mapped acceptance tests failed');
385
+ } catch (err) {
386
+ add('acceptance-tests', 'fail', err.message);
387
+ }
388
+ }
389
+ }
292
390
  }
293
391
 
294
392
  const vcfg = readYamlConfig(repoRoot).verify ?? {};
@@ -298,13 +396,17 @@ export function runVerify(changeId, opts = {}) {
298
396
  add('AI verification', required2 ? 'fail' : 'skip', required2 ? 'no verifier configured (set ASDLC_VERIFY_COMMAND)' : 'no verifier configured');
299
397
  } else {
300
398
  const diff = git(['diff', `${base}...${head}`], repoRoot, { allowFail: true }) ?? '';
301
- const res = runShell(command, repoRoot, { input: buildPrompt(changeId, intent(cdir), diff, base), timeout: 900000 });
399
+ const maxDiffChars = opts.maxDiffChars ?? vcfg.maxDiffChars ?? DEFAULT_MAX_DIFF_CHARS;
400
+ const res = runShell(command, repoRoot, {
401
+ input: buildPrompt(changeId, intent(cdir), diff, base, { maxDiffChars }),
402
+ timeout: 900000,
403
+ });
302
404
  const report = extractJson(res.stdout) ?? { verdict: 'FAIL', summary: 'verifier produced no parseable JSON' };
303
405
  const ok = String(report.verdict).toUpperCase() === 'PASS' && res.status === 0;
304
406
  add('AI verification', ok ? 'pass' : 'fail', String(report.summary ?? '').slice(0, 300));
305
407
  }
306
408
 
307
- return finish(results, policy);
409
+ return finish(results, policy, opts);
308
410
  }
309
411
 
310
412
  export function register(program) {
@@ -312,11 +414,16 @@ export function register(program) {
312
414
  .command('verify <changeId>')
313
415
  .description('check the implementation: artifacts + approved SHA + tasks complete + lint + validate + AI verification')
314
416
  .option('--repo <name>', 'repository name')
417
+ .option('--repo-root <dir>', 'repository root path')
315
418
  .option('--protected-branch <ref>', 'branch the approved spec must be merged into', 'origin/main')
316
419
  .option('--base <ref>', 'base ref for the PR diff (default: protected branch)')
317
420
  .option('--head <ref>', 'head ref (default: HEAD)')
421
+ .option('--approved', 'flag indicating human lead approval is verified on PR / platform')
422
+ .option('--emergency', 'emergency mode bypassing standard branch checks')
423
+ .option('--required', 'require AI verification gate to pass')
318
424
  .option('--skip-openspec', 'skip openspec validation')
319
425
  .option('--skip-external', 'skip external checks from config')
426
+ .option('--json', 'print output in structured JSON')
320
427
  .action((changeId, opts) => {
321
428
  process.exitCode = runVerify(changeId, opts);
322
429
  });
package/src/lib/agents.js CHANGED
@@ -24,14 +24,14 @@ raw escape hatch: the wrappers ARE the guards (graph refresh, approval, checks).
24
24
  (or **batch-grill-me** if \`--batch-grill\` was passed) with anti-fatigue guardrails (look facts up yourself,
25
25
  focus on material trade-offs, lead with recommendations, early-exit on agreement), and record settled decisions
26
26
  in \`clarifications.md\`. (If \`--no-grill\` was passed, self-settle context-inferred assumptions).
27
- ▶ **CRITICAL**: ONLY AFTER \`clarifications.md\` is settled may you author **proposal.md -> specs/**\`. (AI Review is handled on PR by CI).
27
+ ▶ **CRITICAL**: ONLY AFTER \`clarifications.md\` is settled may you author **proposal.md -> specs/**\`. (Independent AI Review is executed in an isolated agent session via \`asdlc-spec-review\` / \`asdlc-impl-review\` skills).
28
28
  2. **grill** - (embedded in Stage 2) settle all design forks in \`clarifications.md\` BEFORE writing specs.
29
29
  3. **lint** - \`asdlc lint <ID>\`: artifacts + BDD/acceptance criteria. Open Spec PR via \`asdlc pr <ID> <targetBranch>\`.
30
30
  4. **approve** - human/TL approves (via PR merge, on PR, or in-place); \`asdlc approve <ID>\` records approved SHA + READY_FOR_IMPL.
31
31
  5. **apply** - \`asdlc apply <ID>\` (guard: the spec must be approved), then
32
32
  \`/opsx-apply\` with task-level TDD + task-level converge.
33
33
  6. **verify** - \`asdlc verify <ID>\`: approved SHA, artifacts, tasks complete, tests, AI.
34
- 7. **archive** - \`asdlc archive <ID>\`: sync specs to openspec/specs/ + update README.md (updates AGENTS.md only for constitutional changes).
34
+ 7. **archive** - \`asdlc archive [<ID> | --merged]\`: post-merge compaction syncing specs to openspec/specs/ (updates AGENTS.md only on \`--agents\` or constitutional changes).
35
35
 
36
36
  Need orientation? \`asdlc status <ID>\` (where am I / next command) and \`asdlc doctor\`
37
37
  (environment health). A bad spec is never edited: close it and \`asdlc new\` again.`;
@@ -11,16 +11,64 @@ export function toChangeSlug(changeId) {
11
11
  .replace(/^-+|-+$/g, '');
12
12
  }
13
13
 
14
+ // Bilingual domain lexicon bridging Chinese engineering requirements to canonical English
15
+ // codebase symbols and readable change slugs (enabling Graphify AST queries on CJK inputs).
16
+ const CJK_DOMAIN_LEXICON = [
17
+ [/重构/, 'refactor'],
18
+ [/修复|排障|缺陷/, 'fix'],
19
+ [/清结算|清算/, 'clearing-settlement'],
20
+ [/支付|打款|收单/, 'payment'],
21
+ [/结算/, 'settlement'],
22
+ [/退款/, 'refund'],
23
+ [/账务|账本|记账|对账/, 'ledger'],
24
+ [/计费|账单/, 'billing'],
25
+ [/钱包|资金/, 'wallet'],
26
+ [/删表|删除.*表|清空.*表|清理历史|物理删除/, 'purge-table'],
27
+ [/鉴权|认证|登录态|单点登录/, 'auth'],
28
+ [/权限|越权|角色/, 'rbac'],
29
+ [/密钥|私钥|令牌|加密|脱敏/, 'secret-crypto'],
30
+ [/接口|出入参|协议/, 'api'],
31
+ [/路由|网关|控制器/, 'router'],
32
+ [/数据库|数据表|表结构|迁移|索引/, 'schema-db'],
33
+ [/订单/, 'order'],
34
+ [/缓存/, 'cache'],
35
+ [/队列|消息/, 'queue'],
36
+ [/配置/, 'config'],
37
+ [/单元测试|集成测试|测试用例/, 'test'],
38
+ [/文档|注释/, 'docs'],
39
+ [/微信/, 'wechat'],
40
+ [/回调|通知/, 'callback'],
41
+ [/状态机/, 'state-machine'],
42
+ [/错别字/, 'typo'],
43
+ ];
44
+
45
+ function extractCjkMappedTokens(text) {
46
+ const raw = String(text ?? '');
47
+ if (!/[\u4e00-\u9fff]/.test(raw)) return [];
48
+ const tokens = [];
49
+ for (const [pattern, mapped] of CJK_DOMAIN_LEXICON) {
50
+ if (pattern.test(raw)) {
51
+ for (const part of mapped.split('-')) {
52
+ if (!tokens.includes(part)) tokens.push(part);
53
+ }
54
+ }
55
+ }
56
+ return tokens;
57
+ }
58
+
14
59
  export function extractRequirementTerms(text) {
15
- const s = String(text ?? '')
60
+ const raw = String(text ?? '');
61
+ const s = raw
16
62
  .replace(/\b[A-Za-z]{2,10}-\d+\b[:\s-]*/g, '')
17
63
  .toLowerCase()
18
64
  .replace(/\b(i\s+want\s+to\s+build|i\s+want\s+to\s+add|i\s+want\s+to|we\s+need\s+to|please\s+add|build|create|add|implement)\b/gi, '')
19
65
  .replace(/\b(a|an|the|of|for|with|in|on|to|and|by)\b/gi, '')
20
66
  .replace(/[^a-z0-9\s]/g, ' ')
21
67
  .trim();
22
- const words = s.split(/\s+/).filter(Boolean);
23
- return words.slice(0, 5).join(' ');
68
+ const asciiWords = s.split(/\s+/).filter(Boolean);
69
+ const cjkWords = extractCjkMappedTokens(raw).filter((w) => !['refactor', 'fix'].includes(w));
70
+ const merged = [...new Set([...asciiWords, ...cjkWords])];
71
+ return merged.slice(0, 6).join(' ');
24
72
  }
25
73
 
26
74
  export function deriveChangeSlug(input, opts = {}) {
@@ -47,11 +95,13 @@ export function deriveChangeSlug(input, opts = {}) {
47
95
 
48
96
  if (!cleaned) cleaned = text.toLowerCase();
49
97
 
50
- const words = cleaned
98
+ const asciiWords = cleaned
51
99
  .replace(/[^a-z0-9\s-]/g, ' ')
52
100
  .split(/\s+/)
53
- .filter(Boolean)
54
- .slice(0, 4);
101
+ .filter(Boolean);
102
+
103
+ const cjkTokens = extractCjkMappedTokens(text);
104
+ const words = [...new Set([...cjkTokens, ...asciiWords])].slice(0, 5);
55
105
 
56
106
  const keywords = words.join('-');
57
107
  if (ticket && keywords) return `${ticket}-${keywords}`.slice(0, 40).replace(/-+$/, '');
@@ -60,7 +110,7 @@ export function deriveChangeSlug(input, opts = {}) {
60
110
  const fallback = toChangeSlug(text).slice(0, 40);
61
111
  if (fallback) return fallback;
62
112
 
63
- // Non-ASCII fallback (e.g. pure Chinese input): generate deterministic slug from content hash
113
+ // Non-ASCII fallback when no domain terms matched: generate deterministic slug from content hash
64
114
  const hash = Math.abs(text.split('').reduce((acc, c) => ((acc << 5) - acc) + c.charCodeAt(0), 0)).toString(36);
65
115
  return `change-${hash || Date.now().toString(36)}`;
66
116
  }
package/src/lib/git.js CHANGED
@@ -23,12 +23,18 @@ export function currentBranch(cwd) {
23
23
  return git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd, { allowFail: true });
24
24
  }
25
25
 
26
+ export function safeCommit(cwd, message) {
27
+ const userName = git(['config', 'user.name'], cwd, { allowFail: true });
28
+ const userEmail = git(['config', 'user.email'], cwd, { allowFail: true });
29
+ const authorArgs = [];
30
+ if (!userName) authorArgs.push('-c', 'user.name=asdlc-bot');
31
+ if (!userEmail) authorArgs.push('-c', 'user.email=asdlc-bot@example.invalid');
32
+ return git([...authorArgs, 'commit', '-m', message], cwd);
33
+ }
34
+
26
35
  export function commitAll(cwd, message) {
27
36
  git(['add', '-A'], cwd);
28
- git(
29
- ['-c', 'user.name=asdlc-bot', '-c', 'user.email=asdlc-bot@example.invalid', 'commit', '-m', message],
30
- cwd,
31
- );
37
+ safeCommit(cwd, message);
32
38
  return headSha(cwd);
33
39
  }
34
40
 
@@ -3,9 +3,9 @@ import path from 'node:path';
3
3
  import { exists, readText, writeText } from './fs.js';
4
4
  import { headSha } from './git.js';
5
5
 
6
- // graphify is a BU-standard authoring aid: it builds a code-derived knowledge
7
- // graph (deterministic AST, no LLM key) that the drafting agent queries for a
8
- // map of the codebase before writing a spec. It is NOT a gate.
6
+ // graphify builds a deterministic code-derived AST knowledge graph (no LLM key)
7
+ // used both to ground explore.md before spec authoring and to compute cross-file
8
+ // fan-in / blast-radius centrality in v3_topology risk assessment.
9
9
  //
10
10
  // The graph is a DERIVED CACHE bound to the current HEAD (graphify-out/), never
11
11
  // committed; refreshed when HEAD moves.
@@ -14,29 +14,40 @@ const GRAPH_REL = 'graphify-out/graph.json';
14
14
  const REF_REL = 'graphify-out/.asdlc_ref';
15
15
  export const GITIGNORE_LINE = 'graphify-out/';
16
16
 
17
- function which(name) {
17
+ function which(name, env = process.env) {
18
18
  const finder = process.platform === 'win32' ? 'where' : 'which';
19
- const r = spawnSync(finder, [name], { encoding: 'utf8' });
19
+ const r = spawnSync(finder, [name], { encoding: 'utf8', env });
20
20
  if (r.status !== 0) return null;
21
21
  return r.stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean)[0] ?? null;
22
22
  }
23
23
 
24
- export function graphifyAvailable() {
25
- return Boolean(which('graphify'));
24
+ export function graphifyAvailable(env = process.env) {
25
+ return Boolean(which('graphify', env));
26
26
  }
27
27
 
28
- // Default-install per the BU standard (uv preferred, else pip). Never throws.
29
- export function ensureGraphify({ autoInstall = true } = {}) {
30
- if (graphifyAvailable()) return { installed: true, action: 'present' };
28
+ // Default-install per the BU standard (uv preferred, else pip), honoring internal mirror
29
+ // env vars (PIP_INDEX_URL, UV_INDEX_URL, ASDLC_PIP_INDEX_URL) and offline air-gapped guards. Never throws.
30
+ export function ensureGraphify({ autoInstall = true, env = process.env } = {}) {
31
+ if (graphifyAvailable(env)) return { installed: true, action: 'present' };
31
32
  if (!autoInstall) return { installed: false, action: 'missing' };
32
- const viaUv = Boolean(which('uv'));
33
- const cmd = viaUv ? ['uv', 'tool', 'install', '--upgrade', 'graphifyy'] : ['pip', 'install', 'graphifyy'];
33
+ if (env.ASDLC_OFFLINE === '1' || env.ASDLC_OFFLINE === 'true') {
34
+ return { installed: false, action: 'offline-skipped' };
35
+ }
36
+
37
+ const mirrorUrl = env.ASDLC_PIP_INDEX_URL || env.PIP_INDEX_URL || env.UV_INDEX_URL || null;
38
+ const viaUv = Boolean(which('uv', env));
39
+ const viaPip = Boolean(which('pip', env));
40
+ if (!viaUv && !viaPip) return { installed: false, action: 'missing-installer' };
41
+
42
+ const cmd = viaUv
43
+ ? ['uv', 'tool', 'install', '--upgrade', ...(mirrorUrl ? ['--index-url', mirrorUrl] : []), 'graphifyy']
44
+ : ['pip', 'install', ...(mirrorUrl ? ['--index-url', mirrorUrl] : []), 'graphifyy'];
34
45
  try {
35
- execFileSync(cmd[0], cmd.slice(1), { encoding: 'utf8', stdio: 'pipe' });
46
+ execFileSync(cmd[0], cmd.slice(1), { encoding: 'utf8', stdio: 'pipe', env, timeout: 45000 });
36
47
  } catch {
37
48
  /* fall through to the availability check */
38
49
  }
39
- return { installed: graphifyAvailable(), action: viaUv ? 'uv-install' : 'pip-install' };
50
+ return { installed: graphifyAvailable(env), action: viaUv ? 'uv-install' : 'pip-install' };
40
51
  }
41
52
 
42
53
  function run(args, cwd) {
@@ -56,6 +67,70 @@ export function readRef(repoRoot) {
56
67
  return exists(p) ? readText(p).trim() : null;
57
68
  }
58
69
 
70
+ /**
71
+ * Loads the Graphify knowledge graph JSON.
72
+ * Returns null if missing or invalid.
73
+ */
74
+ export function loadGraphData(repoRoot) {
75
+ if (!repoRoot) return null;
76
+ const p = path.join(repoRoot, GRAPH_REL);
77
+ if (!exists(p)) return null;
78
+ try {
79
+ return JSON.parse(readText(p));
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ function isNonProdCaller(filePath = '') {
86
+ const norm = String(filePath).replace(/\\/g, '/');
87
+ return (
88
+ /(^|\/)(tests?|__tests__|testing|docs?)\//i.test(norm) ||
89
+ /\.(test|spec)\.[a-z0-9]+$/i.test(norm) ||
90
+ /_test\.go$/i.test(norm) ||
91
+ /(^|\/)test_[^/]+\.py$/i.test(norm) ||
92
+ /_test\.py$/i.test(norm) ||
93
+ /\.(md|txt)$/i.test(norm)
94
+ );
95
+ }
96
+
97
+ /**
98
+ * Calculates cross-file fan-in (inbound dependency count) from Graphify AST.
99
+ * Excludes test/doc callers so test suites do not artificially inflate hub centrality.
100
+ */
101
+ export function getGraphTopologyMetrics(repoRoot) {
102
+ const graph = loadGraphData(repoRoot);
103
+ if (!graph || !Array.isArray(graph.nodes) || !Array.isArray(graph.links)) {
104
+ return { available: false, fileInDegree: {}, topHubs: [] };
105
+ }
106
+
107
+ const nodeToFile = {};
108
+ const fileInDegree = {};
109
+
110
+ for (const n of graph.nodes) {
111
+ if (n.source_file) {
112
+ nodeToFile[n.id] = String(n.source_file).replace(/\\/g, '/');
113
+ }
114
+ }
115
+
116
+ for (const link of graph.links) {
117
+ const targetFile = nodeToFile[link.target];
118
+ const sourceFile = nodeToFile[link.source];
119
+ if (targetFile && sourceFile && targetFile !== sourceFile && !isNonProdCaller(sourceFile)) {
120
+ fileInDegree[targetFile] = (fileInDegree[targetFile] || 0) + 1;
121
+ }
122
+ }
123
+
124
+ const sortedFiles = Object.entries(fileInDegree)
125
+ .sort((a, b) => b[1] - a[1]);
126
+
127
+ return {
128
+ available: true,
129
+ fileInDegree,
130
+ topHubs: sortedFiles.slice(0, 15)
131
+ };
132
+ }
133
+
59
134
  export function writeRef(repoRoot) {
60
135
  const sha = headSha(repoRoot);
61
136
  if (sha) writeText(path.join(repoRoot, REF_REL), sha);