@akjamie/agentic-sdlc 1.5.0 → 1.6.1

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 (40) hide show
  1. package/README.md +42 -18
  2. package/assets/config/config.yaml +1 -1
  3. package/assets/policy/policy.yaml +6 -0
  4. package/assets/schema/schema.yaml +168 -168
  5. package/assets/skills/asdlc-approve/SKILL.md +1 -1
  6. package/assets/skills/asdlc-archive/SKILL.md +17 -13
  7. package/assets/skills/asdlc-doctor/SKILL.md +8 -8
  8. package/assets/skills/asdlc-impl-review/SKILL.md +2 -14
  9. package/assets/skills/asdlc-init/SKILL.md +11 -18
  10. package/assets/skills/asdlc-pr/SKILL.md +13 -8
  11. package/assets/skills/asdlc-review/SKILL.md +7 -7
  12. package/assets/skills/asdlc-spec-review/SKILL.md +2 -14
  13. package/package.json +2 -1
  14. package/src/assess/ai_judge.js +36 -3
  15. package/src/assess/rules/builtin.js +2 -2
  16. package/src/assess/vectors/v2_security.js +24 -1
  17. package/src/assess/vectors/v3_topology.js +29 -11
  18. package/src/commands/apply.js +1 -1
  19. package/src/commands/approve.js +2 -3
  20. package/src/commands/archive.js +116 -64
  21. package/src/commands/doctor.js +24 -21
  22. package/src/commands/init.js +24 -50
  23. package/src/commands/pr.js +106 -25
  24. package/src/commands/test.js +90 -21
  25. package/src/commands/update.js +1 -11
  26. package/src/commands/upgrade.js +47 -25
  27. package/src/commands/verify.js +94 -14
  28. package/src/lib/agents.js +2 -2
  29. package/src/lib/cliutil.js +57 -7
  30. package/src/lib/git.js +10 -4
  31. package/src/lib/graphify.js +22 -11
  32. package/src/lib/level.js +63 -9
  33. package/src/lib/openspec.js +61 -31
  34. package/src/lib/paths.js +0 -2
  35. package/src/lib/policy.js +4 -0
  36. package/src/lib/schema.js +32 -11
  37. package/src/lib/tdd.js +29 -9
  38. package/assets/ci/asdlc-ai-review.yml +0 -65
  39. package/assets/githooks/post-merge +0 -22
  40. package/assets/githooks/pre-push +0 -17
@@ -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,17 +32,18 @@ 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
 
44
- // If in global mode or not in a repository workspace, check global skills and skip repo-specific checks
45
- if (isGlobal || (!isRepo && !hasProject)) {
45
+ // If in global mode or not in an actual git repository workspace, check global skills and skip repo-specific checks
46
+ if (isGlobal || !isRepo) {
46
47
  const globalSkills = path.join(process.env.HOME || process.env.USERPROFILE || '', '.agents', 'skills');
47
48
  const hasGlobalSkills = exists(globalSkills);
48
49
  add('global skills (~/.agents)', hasGlobalSkills ? 'pass' : 'warn', hasGlobalSkills ? 'installed' : 'run `asdlc skills install --global`');
@@ -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
@@ -1,10 +1,9 @@
1
1
  import path from 'node:path';
2
- import { exists, ensureDir, copyTree, readText, writeText, listDir } from '../lib/fs.js';
3
- import { openspecDir, configAssetFile, ciAssetDir, githooksAssetDir, schemaAssetDir, policyAssetFile, skillsAssetDir, SCHEMA_NAME } from '../lib/paths.js';
2
+ import { exists, ensureDir, copyTree, readText, writeText } from '../lib/fs.js';
3
+ import { openspecDir, configAssetFile, schemaAssetDir, SCHEMA_NAME } from '../lib/paths.js';
4
4
  import { installSchema, builtinSchemaVersion, localOverride } from '../lib/schema.js';
5
5
  import { log } from '../lib/log.js';
6
6
  import { runOpenspec, openspecVersion, ensureOpenspec } from '../lib/openspec.js';
7
- import { git } from '../lib/git.js';
8
7
  import { ensureGraphify, buildGraph, ensureGitignore } from '../lib/graphify.js';
9
8
  import { refreshAgents } from '../lib/agents.js';
10
9
  import { ensureRemoteLabels } from './pr.js';
@@ -16,16 +15,14 @@ export function initRepo(opts = {}) {
16
15
  const repoRoot = path.resolve(opts.repoRoot ?? process.cwd());
17
16
  const osDir = openspecDir(repoRoot);
18
17
 
19
- // 1) Ensure the OpenSpec ENGINE is installed (pinned devDependency), then
20
- // REUSE it for setup: init the project + wire agent tooling. Re-running
21
- // is idempotent and never resets our governance config.
18
+ // 1) Resolve bundled OpenSpec engine (zero package.json / node_modules pollution in target repo),
19
+ // then initialize OpenSpec project structure & wire agent tooling idempotently.
22
20
  const osInstall = opts.openspec === false
23
21
  ? { installed: openspecVersion(repoRoot) != null, action: 'skipped' }
24
22
  : ensureOpenspec(repoRoot);
25
23
  if (!osInstall.installed) {
26
- log.warn('openspec CLI unavailable and could not be installed (need npm)');
24
+ log.warn('openspec CLI unavailable');
27
25
  } else {
28
- if (osInstall.action === 'npm-install') log.ok(`installed openspec@${'1.13.2'} (devDependency)`);
29
26
  const tools = opts.tools ?? (detectTools(repoRoot).join(',') || 'none');
30
27
  const res = runOpenspec(['init', '--tools', tools, '--no-animation'], repoRoot);
31
28
  if (res.status === 0) log.ok(`openspec init --tools ${tools}`);
@@ -34,20 +31,22 @@ export function initRepo(opts = {}) {
34
31
  ensureDir(path.join(osDir, 'changes'));
35
32
  ensureDir(path.join(osDir, 'specs'));
36
33
 
37
- // 1.5) BU-managed OpenSpec schema: install ONCE per machine (central), never
38
- // copied into the repo. This IS the OpenSpec customization layer - the
39
- // enterprise change flow (proposal -> specs -> review -> tasks).
34
+ // 1.5) Managed OpenSpec schema: bundled statelessly with asdlc and optionally cached in user data dir.
40
35
  const override = localOverride(repoRoot);
41
36
  if (override.tracked) {
42
37
  log.warn(`committed local schema copy found: ${override.path}`);
43
- log.warn('the BU standard forbids per-repo schema overrides; remove it (the schema is installed centrally by `asdlc init`)');
38
+ log.warn('per-repo committed schema overrides are disallowed; remove it to use the bundled schema');
39
+ }
40
+ try {
41
+ const schemaDest = installSchema();
42
+ log.ok(`synced managed schema v${builtinSchemaVersion()} -> ${path.relative(repoRoot, schemaDest) || schemaDest}`);
43
+ } catch {
44
+ log.info(`using stateless bundled schema v${builtinSchemaVersion()}`);
44
45
  }
45
- const schemaDest = installSchema();
46
- log.ok(`installed managed schema v${builtinSchemaVersion()} -> ${path.relative(repoRoot, schemaDest) || schemaDest}`);
47
46
  if (opts.vendor) {
48
47
  const vendored = path.join(osDir, 'schemas', SCHEMA_NAME);
49
48
  copyTree(schemaAssetDir, vendored);
50
- log.ok(`vendored schema -> openspec/schemas/${SCHEMA_NAME} (CI-only; do not commit)`);
49
+ log.ok(`vendored schema -> openspec/schemas/${SCHEMA_NAME} (do not commit)`);
51
50
  }
52
51
 
53
52
  // 2) Governance overlay: schema name + context + rules + lint + verify policy.
@@ -65,26 +64,17 @@ export function initRepo(opts = {}) {
65
64
  log.ok('wrote governance config (openspec/config.yaml)');
66
65
  }
67
66
 
68
- // 3) CI + git hooks (governance glue, not OpenSpec's job).
69
- if (opts.ci === 'jenkins') {
70
- const dest = path.join(repoRoot, 'Jenkinsfile');
71
- if (exists(dest) && !opts.force) log.step('Jenkinsfile exists (use --force)');
72
- else { writeText(dest, readText(path.join(ciAssetDir, 'Jenkinsfile'))); log.ok('wrote Jenkinsfile'); }
73
- }
74
- if (opts.hooks !== false) installHooks(repoRoot);
75
-
76
- // 3.6) Pre-provision remote governance labels if git remote & gh are available
67
+ // 3) Pre-provision remote governance labels if git remote & gh are available
77
68
  try {
78
69
  ensureRemoteLabels(repoRoot);
79
70
  } catch { /* ignore */ }
80
71
 
81
- // 4) graphify (BU standard): a code-derived navigation graph for spec drafting.
82
- // Deterministic code-only AST (no LLM key), bound to HEAD, derived cache.
72
+ // 4) graphify: deterministic code-only AST navigation & topology graph (no LLM key), bound to HEAD.
83
73
  if (opts.graph !== false) {
84
74
  const g = ensureGraphify();
85
75
  if (!g.installed) {
86
- log.warn('graphify not installed and could not be installed');
87
- log.info(' install it (uv tool install graphifyy, or pip install graphifyy via your internal mirror)');
76
+ log.warn('graphify not installed and could not be auto-installed');
77
+ log.info(' install via internal mirror: pip install -i <mirror-url> graphifyy (or uv tool install graphifyy)');
88
78
  } else {
89
79
  if (g.action !== 'present') log.ok(`installed graphify (${g.action})`);
90
80
  const b = buildGraph(repoRoot);
@@ -94,15 +84,13 @@ export function initRepo(opts = {}) {
94
84
  }
95
85
  }
96
86
 
97
- // 4.5) Bundled Agent Skills & Slash Commands: install out-of-the-box skills and
98
- // slash command parity into detected agent tools (.claude, .opencode, .pi, .agents, .github, etc.)
87
+ // 4.5) Bundled Agent Skills & Slash Commands
99
88
  const explicitTools = opts.tools ? opts.tools.split(',').map((s) => s.trim().toLowerCase()) : [];
100
89
  const allTools = [...new Set([...detectTools(repoRoot), ...explicitTools])];
101
90
  installSkills(repoRoot, allTools);
102
91
  installCommands(repoRoot, allTools);
103
92
 
104
- // 5) AGENTS.md: the routing layer the agentic IDE reads (workflow + system
105
- // status derived from the graph). Written after the graph so status has nodes.
93
+ // 5) AGENTS.md: the routing layer the agentic IDE reads
106
94
  refreshAgents(repoRoot);
107
95
  log.ok('refreshed AGENTS.md (asdlc workflow + system status)');
108
96
 
@@ -110,33 +98,19 @@ export function initRepo(opts = {}) {
110
98
  log.info('Next:');
111
99
  log.info(' 1. start a spec: asdlc new "<requirement>"');
112
100
  log.info(' 2. check the spec: asdlc lint <CHANGE-ID>');
113
- log.info(' 3. after the spec PR merges: asdlc approve <CHANGE-ID>');
114
- log.info(' 4. implementation PR: asdlc verify <CHANGE-ID> --repo <name>');
101
+ log.info(' 3. open Spec PR: asdlc pr <CHANGE-ID> <targetBranch>');
102
+ log.info(' 4. verify & Impl PR: asdlc verify <CHANGE-ID>');
115
103
  return repoRoot;
116
104
  }
117
105
 
118
- export function installHooks(repoRoot) {
119
- if (!exists(githooksAssetDir)) return;
120
- const dest = path.join(repoRoot, '.githooks');
121
- copyTree(githooksAssetDir, dest);
122
- try {
123
- git(['config', 'core.hooksPath', '.githooks'], repoRoot);
124
- log.ok('installed .githooks (pre-push, post-merge) + core.hooksPath');
125
- } catch {
126
- log.warn('could not set core.hooksPath (not a git repo?)');
127
- }
128
- }
129
-
130
106
  export function register(program) {
131
107
  program
132
108
  .command('init')
133
- .description('set up a repo: reuse `openspec init` + governance overlay + CI/hooks')
109
+ .description('set up a repo: OpenSpec project + governance overlay + Graphify AST + agent skills')
134
110
  .option('--repo-root <path>', 'repository root (default: cwd)')
135
111
  .option('--tools <list>', 'OpenSpec agent tools (default: auto-detect)')
136
- .option('--ci <name>', 'scaffold a CI pipeline (supported: jenkins)')
137
- .option('--no-hooks', 'skip installing .githooks')
138
112
  .option('--no-graph', 'skip graphify install/build')
139
113
  .option('--no-openspec', 'skip the openspec CLI step')
140
- .option('--force', 'overwrite existing config / Jenkinsfile')
114
+ .option('--force', 'overwrite existing governance config')
141
115
  .action((opts) => initRepo(opts));
142
116
  }
@@ -1,9 +1,11 @@
1
+ import fs from 'node:fs';
1
2
  import path from 'node:path';
2
3
  import { execFileSync } from 'node:child_process';
3
4
  import { exists, readText, writeText } from '../lib/fs.js';
4
5
  import { changeDir } from '../lib/paths.js';
5
6
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
6
- import { git, isGitRepo, changeOnRef, lastCommitTouching } from '../lib/git.js';
7
+ import { git, isGitRepo, changeOnRef, lastCommitTouching, safeCommit } from '../lib/git.js';
8
+ import { loadPolicy, matchesAny } from '../lib/policy.js';
7
9
  import { runLint } from './lint.js';
8
10
  import { runVerify } from './verify.js';
9
11
  import { fail } from '../lib/errors.js';
@@ -11,6 +13,77 @@ import { log } from '../lib/log.js';
11
13
  import { assess, renderLabels, renderPRComment } from '../assess/index.js';
12
14
  import { readEffectiveLevel } from '../lib/level.js';
13
15
 
16
+ const SAFE_ENV_TEMPLATE_RE = /(^|\/)\.env\.(example|sample|template|defaults|schema)$/i;
17
+ const SENSITIVE_OR_DUMP_PATTERNS = [
18
+ { re: /(^|\/)\.env(\..+)?$/i, reason: 'dotenv file' },
19
+ { re: /\.(pem|key|p12|pfx|jks|keystore)$/i, reason: 'cryptographic key/certificate' },
20
+ { re: /(^|\/)id_(rsa|ed25519|ecdsa|dsa)(\.pub)?$/i, reason: 'SSH key' },
21
+ { re: /(^|\/)(credentials|service-account[^/]*)\.(json|ya?ml)$/i, reason: 'credentials file' },
22
+ { re: /(^|\/)\.?secrets?(\.(json|ya?ml|env|txt|toml))?$/i, reason: 'secrets file' },
23
+ { re: /\.(hprof|dmp|core|heapdump)$/i, reason: 'crash/memory dump' },
24
+ { re: /(^|\/)core\.\d+$/i, reason: 'core dump' },
25
+ { re: /\.log(\.\d+)?$/i, reason: 'log artifact' },
26
+ ];
27
+
28
+ /**
29
+ * Smart controlled staging for Implementation PRs:
30
+ * Stages modified/deleted tracked files and legitimate untracked source/assets,
31
+ * while skipping untracked secrets, crash dumps, logs, and oversized blobs (> 50MB default)
32
+ * with a warning so unattended automation never halts or leaks credentials.
33
+ */
34
+ export function stageImplementationChanges(repoRoot, opts = {}) {
35
+ const policy = opts.policy ?? loadPolicy(repoRoot);
36
+ const maxMb = Number(opts.maxFileSizeMb ?? policy?.staging?.max_file_size_mb ?? 50);
37
+ const maxBytes = maxMb * 1024 * 1024;
38
+ const extraIgnoreGlobs = Array.isArray(policy?.staging?.ignore_patterns) ? policy.staging.ignore_patterns : [];
39
+
40
+ // 1. Stage all tracked file modifications & deletions
41
+ git(['add', '-u'], repoRoot, { allowFail: true });
42
+
43
+ // 2. Inspect untracked files respecting .gitignore
44
+ const untrackedOut = git(['ls-files', '--others', '--exclude-standard'], repoRoot, { allowFail: true }) ?? '';
45
+ const untracked = untrackedOut.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
46
+
47
+ const staged = [];
48
+ const skipped = [];
49
+
50
+ for (const rel of untracked) {
51
+ const norm = rel.replace(/\\/g, '/');
52
+
53
+ if (extraIgnoreGlobs.length > 0 && matchesAny(norm, extraIgnoreGlobs)) {
54
+ const reason = 'matched policy.staging.ignore_patterns';
55
+ skipped.push({ file: norm, reason });
56
+ log.warn(`[WARN] Skipped untracked sensitive/artifact file: ${norm} (${reason})`);
57
+ continue;
58
+ }
59
+
60
+ if (!SAFE_ENV_TEMPLATE_RE.test(norm)) {
61
+ const matchedRule = SENSITIVE_OR_DUMP_PATTERNS.find((r) => r.re.test(norm));
62
+ if (matchedRule) {
63
+ skipped.push({ file: norm, reason: matchedRule.reason });
64
+ log.warn(`[WARN] Skipped untracked sensitive/artifact file: ${norm} (${matchedRule.reason})`);
65
+ continue;
66
+ }
67
+ }
68
+
69
+ try {
70
+ const stat = fs.statSync(path.join(repoRoot, rel));
71
+ if (stat.isFile() && stat.size > maxBytes) {
72
+ const sizeMb = (stat.size / (1024 * 1024)).toFixed(1);
73
+ const reason = `size ${sizeMb}MB exceeds ${maxMb}MB limit`;
74
+ skipped.push({ file: norm, reason });
75
+ log.warn(`[WARN] Skipped untracked sensitive/artifact file: ${norm} (${reason})`);
76
+ continue;
77
+ }
78
+ } catch { /* ignore stat race */ }
79
+
80
+ git(['add', '--', rel], repoRoot, { allowFail: true });
81
+ staged.push(norm);
82
+ }
83
+
84
+ return { staged, skipped };
85
+ }
86
+
14
87
  export const ASDLC_LABELS = {
15
88
  'asdlc:spec-review': {
16
89
  color: '1d76db',
@@ -85,10 +158,14 @@ export async function createPR(changeId, targetBranch, opts = {}) {
85
158
  || changeOnRef(repoRoot, `origin/${targetBranch}`, slug)
86
159
  || Boolean(lastCommitTouching(repoRoot, targetBranch, [`openspec/changes/${slug}/proposal.md`]));
87
160
 
88
- // Check git diff or status for source code changes outside openspec/changes/<slug>
89
- const diffFiles = (git(['diff', '--name-only', `${targetBranch}...HEAD`], repoRoot, { allowFail: true }) ?? '')
161
+ // Inspect both committed diff and uncommitted working-tree changes to correctly detect source modifications
162
+ const diffFilesPre = (git(['diff', '--name-only', `${targetBranch}...HEAD`], repoRoot, { allowFail: true }) ?? '')
163
+ .split(/\r?\n/).filter(Boolean);
164
+ const statusLines = (git(['status', '--porcelain', '-uall'], repoRoot, { allowFail: true }) ?? '')
90
165
  .split(/\r?\n/).filter(Boolean);
91
- const hasSourceChanges = diffFiles.some((f) => !f.startsWith(`openspec/changes/${slug}/`));
166
+ const uncommittedFiles = statusLines.map((l) => l.replace(/^\s*\S+\s+/, '').trim()).filter(Boolean);
167
+ const allPotentialFiles = [...diffFilesPre, ...uncommittedFiles];
168
+ const hasSourceChanges = allPotentialFiles.some((f) => !f.startsWith(`openspec/changes/${slug}/`));
92
169
 
93
170
  const lvlMatch = metaText.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
94
171
  const changeLevel = lvlMatch ? lvlMatch[1].toUpperCase() : null;
@@ -115,7 +192,30 @@ export async function createPR(changeId, targetBranch, opts = {}) {
115
192
  const secondaryLabel = isSpec ? 'spec' : 'impl';
116
193
  const prTypeName = isSpec ? 'Spec PR' : 'Implementation PR';
117
194
 
118
- // 1. Pre-flight self-check
195
+ // 1. Stage & commit any unstaged changes BEFORE running pre-flight gates,
196
+ // ensuring runVerify and runLint evaluate the true, complete state being pushed.
197
+ try {
198
+ if (isSpec) {
199
+ git(['add', `openspec/changes/${slug}`], repoRoot);
200
+ const status = git(['status', '--porcelain', `openspec/changes/${slug}`], repoRoot);
201
+ if (status) {
202
+ safeCommit(repoRoot, `spec(${slug}): specify feature intent`);
203
+ log.ok('committed latest spec changes');
204
+ }
205
+ } else {
206
+ stageImplementationChanges(repoRoot);
207
+ const diffCached = git(['diff', '--cached', '--name-only'], repoRoot, { allowFail: true });
208
+ if (diffCached && diffCached.trim()) {
209
+ safeCommit(repoRoot, `impl(${slug}): implement verified changes`);
210
+ log.ok('committed latest implementation changes');
211
+ }
212
+ }
213
+ } catch { /* ignore */ }
214
+
215
+ const diffFiles = (git(['diff', '--name-only', `${targetBranch}...HEAD`], repoRoot, { allowFail: true }) ?? '')
216
+ .split(/\r?\n/).filter(Boolean);
217
+
218
+ // 2. Pre-flight self-check (evaluates committed HEAD vs targetBranch)
119
219
  if (isSpec) {
120
220
  log.step(`running spec lint pre-flight for ${slug}...`);
121
221
  const lintExit = runLint(slug, { repoRoot, json: true });
@@ -138,7 +238,7 @@ export async function createPR(changeId, targetBranch, opts = {}) {
138
238
  log.ok('implementation verify passed (all 12 gates passed)');
139
239
  }
140
240
 
141
- // 2. Extract Title and Description from proposal.md
241
+ // 3. Extract Title and Description from proposal.md
142
242
  const proposalPath = path.join(cdir, 'proposal.md');
143
243
  if (!exists(proposalPath)) fail(`proposal.md missing for ${slug}`);
144
244
  const proposalText = readText(proposalPath);
@@ -150,25 +250,6 @@ export async function createPR(changeId, targetBranch, opts = {}) {
150
250
  if (raw) title = `${isSpec ? 'spec' : 'impl'}(${slug}): ${raw}`;
151
251
  }
152
252
 
153
- // 3. Stage & commit any unstaged changes
154
- try {
155
- if (isSpec) {
156
- git(['add', `openspec/changes/${slug}`], repoRoot);
157
- const status = git(['status', '--porcelain', `openspec/changes/${slug}`], repoRoot);
158
- if (status) {
159
- execFileSync('git', ['commit', '-m', `spec(${slug}): specify feature intent`], { cwd: repoRoot, stdio: 'ignore' });
160
- log.ok('committed latest spec changes');
161
- }
162
- } else {
163
- git(['add', '-A'], repoRoot);
164
- const status = git(['status', '--porcelain'], repoRoot);
165
- if (status) {
166
- execFileSync('git', ['commit', '-m', `impl(${slug}): implement verified changes`], { cwd: repoRoot, stdio: 'ignore' });
167
- log.ok('committed latest implementation changes');
168
- }
169
- }
170
- } catch { /* ignore */ }
171
-
172
253
  // 4. Push to remote
173
254
  log.step(`pushing branch '${currentBranch}' to origin...`);
174
255
  try {