@akjamie/agentic-sdlc 1.1.0 → 1.3.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 (40) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +264 -154
  3. package/assets/schema/risk-assessment.schema.json +225 -0
  4. package/assets/schema/templates/design.md +94 -31
  5. package/assets/skills/api-design/SKILL.md +204 -0
  6. package/assets/skills/asdlc-apply/SKILL.md +43 -18
  7. package/assets/skills/asdlc-impl-review/SKILL.md +153 -47
  8. package/assets/skills/asdlc-new/SKILL.md +42 -24
  9. package/assets/skills/asdlc-verify/SKILL.md +16 -6
  10. package/assets/skills/batch-grill-me/SKILL.md +11 -7
  11. package/assets/skills/frontend-design/SKILL.md +84 -0
  12. package/assets/skills/grilling/SKILL.md +43 -17
  13. package/package.json +2 -2
  14. package/src/assess/ai_judge.js +163 -0
  15. package/src/assess/decide.js +164 -0
  16. package/src/assess/governance.js +53 -0
  17. package/src/assess/index.js +183 -0
  18. package/src/assess/render.js +71 -0
  19. package/src/assess/rules/builtin.js +195 -0
  20. package/src/assess/schema.js +148 -0
  21. package/src/assess/store.js +138 -0
  22. package/src/assess/vectors/v1_intent.js +80 -0
  23. package/src/assess/vectors/v2_security.js +131 -0
  24. package/src/assess/vectors/v3_topology.js +107 -0
  25. package/src/cli.js +91 -89
  26. package/src/commands/apply.js +103 -36
  27. package/src/commands/assess.js +57 -0
  28. package/src/commands/doctor.js +1 -14
  29. package/src/commands/init.js +0 -9
  30. package/src/commands/new.js +97 -19
  31. package/src/commands/pr.js +27 -3
  32. package/src/commands/upgrade.js +1 -1
  33. package/src/commands/verify.js +109 -15
  34. package/src/lib/agents.js +5 -4
  35. package/src/lib/fs.js +26 -3
  36. package/src/lib/level.js +118 -0
  37. package/src/lib/paths.js +2 -1
  38. package/src/lib/prtype.js +17 -4
  39. package/src/lib/risk.js +50 -0
  40. package/src/lib/schema.js +4 -0
@@ -3,9 +3,9 @@ import { exists, readText, writeText } from '../lib/fs.js';
3
3
  import { changeDir } from '../lib/paths.js';
4
4
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
5
5
  import { lastCommitTouching, git } from '../lib/git.js';
6
- import { readYaml } from '../lib/yaml.js';
7
6
  import { fail } from '../lib/errors.js';
8
7
  import { log } from '../lib/log.js';
8
+ import { isSinglePrLevel, readEffectiveLevel } from '../lib/level.js';
9
9
 
10
10
  // Guard before implementing: the spec must be APPROVED on the target branch
11
11
  // (i.e. the Spec PR has been merged into targetBranch, locking proposal.md & specs/**).
@@ -23,7 +23,15 @@ export function applyGuard(changeId, opts = {}) {
23
23
  const sha = text.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
24
24
  const status = text.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
25
25
  const tb = text.match(/^\s*targetBranch:\s*['"]?([^\s'"]+)['"]?\s*$/m);
26
- meta = { specSha: sha ? sha[1] : null, status: status ? status[1] : null, targetBranch: tb ? tb[1] : null };
26
+ const apr = text.match(/^\s*autoPr:\s*['"]?([^\s'"]+)['"]?\s*$/m);
27
+ const lvl = text.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
28
+ meta = {
29
+ specSha: sha ? sha[1] : null,
30
+ status: status ? status[1] : null,
31
+ targetBranch: tb ? tb[1] : null,
32
+ autoPr: apr ? apr[1] : null,
33
+ level: lvl ? lvl[1].toUpperCase() : null,
34
+ };
27
35
  }
28
36
 
29
37
  const branch = opts.targetBranch
@@ -33,53 +41,102 @@ export function applyGuard(changeId, opts = {}) {
33
41
 
34
42
  const locked = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
35
43
 
36
- // 2. Multi-tenant path-isolated approval detection
37
- // Query ONLY commits touching this change's own directory on target branch
38
- const approvedSha = lastCommitTouching(repoRoot, branch, locked);
39
-
40
- if (!approvedSha) {
41
- fail(`'${slug}' is not approved yet (no Spec PR for this change merged into ${branch})`, {
42
- code: 'NOT_APPROVED',
43
- hint: `open a Spec PR via \`asdlc pr ${changeId} ${branch}\` and merge it before implementing`,
44
+ const levelInfo = readEffectiveLevel(repoRoot, slug);
45
+ if (levelInfo?.tampered) {
46
+ fail(`cannot apply '${slug}': declared level in .openspec.yaml (${levelInfo.declaredLevel}) is lower than recorded history (${levelInfo.maxHistoryLevel}). Manual level downgrading is strictly forbidden.`, {
47
+ code: 'LEVEL_TAMPERED',
48
+ hint: 'Revert unauthorized level edits in .openspec.yaml or raise a system rule fix.'
44
49
  });
45
50
  }
46
51
 
47
- // 3. Local working tree tamper check: locked paths must not have uncommitted edits
48
- const dirty = (git(['status', '--porcelain', '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
49
- if (dirty) {
50
- fail(`cannot apply '${slug}': locked spec paths have uncommitted local modifications:\n${dirty}`, {
51
- code: 'SPEC_DIRTY',
52
- hint: 'commit or stash your spec modifications before proceeding with implementation',
53
- });
54
- }
55
-
56
- // 4. Content-level cryptographic zero-diff invariant:
57
- // The local spec content MUST match the approved version on the target branch
58
- const diff = (git(['diff', approvedSha, '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
59
- if (diff) {
60
- fail(`'${slug}' spec differs from the approved version on ${branch} (${approvedSha.slice(0, 8)}):\n${diff.slice(0, 300)}`, {
61
- code: 'SPEC_DIFFERS_FROM_APPROVED',
62
- hint: `spec was modified after approval. Merge latest ${branch} or revert unauthorized spec changes.`,
63
- });
64
- }
52
+ const effectiveLevel = levelInfo?.effectiveLevel || meta.level || null;
53
+ const isSinglePr = isSinglePrLevel(effectiveLevel);
54
+ let approvedSha = null;
65
55
 
66
- // 5. Automatic state transition: PR Merge is the single source of truth for approval!
67
- // If the spec is physically merged on the target branch with 0 diff, automatically transition to ready_for_impl
68
- if (meta.status !== 'ready_for_impl' || meta.specSha !== approvedSha) {
69
- if (exists(metaPath)) {
56
+ if (isSinglePr) {
57
+ // For L0 / L1, Single PR mode allows direct local implementation.
58
+ // Transition to ready_for_impl automatically if drafting.
59
+ if (meta.status !== 'ready_for_impl' && exists(metaPath)) {
70
60
  let metaText = readText(metaPath);
71
61
  const upsertKey = (text, key, val) => {
72
62
  const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
73
63
  return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
74
64
  };
75
- metaText = upsertKey(metaText, 'specSha', approvedSha);
76
65
  metaText = upsertKey(metaText, 'status', 'ready_for_impl');
77
66
  writeText(metaPath, metaText);
78
67
  }
79
- log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
68
+ log.ok(`${slug}: governance level is ${effectiveLevel} (Single PR mode: direct local implementation permitted)`);
69
+ } else {
70
+ // L2 / L3 Two-phase Spec-first flow
71
+ // 2. Multi-tenant path-isolated approval detection
72
+ // Query ONLY commits touching this change's own directory on target branch
73
+ approvedSha = lastCommitTouching(repoRoot, branch, locked);
74
+
75
+ if (!approvedSha) {
76
+ fail(`'${slug}' is not approved yet (no Spec PR for this change merged into ${branch})`, {
77
+ code: 'NOT_APPROVED',
78
+ hint: `open a Spec PR via \`asdlc pr ${changeId} ${branch}\` and merge it before implementing`,
79
+ });
80
+ }
81
+
82
+ // 3. Local working tree tamper check: locked paths must not have uncommitted edits
83
+ const dirty = (git(['status', '--porcelain', '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
84
+ if (dirty) {
85
+ fail(`cannot apply '${slug}': locked spec paths have uncommitted local modifications:\n${dirty}`, {
86
+ code: 'SPEC_DIRTY',
87
+ hint: 'commit or stash your spec modifications before proceeding with implementation',
88
+ });
89
+ }
90
+
91
+ // 4. Content-level cryptographic zero-diff invariant:
92
+ // The local spec content MUST match the approved version on the target branch
93
+ const diff = (git(['diff', approvedSha, '--', ...locked], repoRoot, { allowFail: true }) ?? '').trim();
94
+ if (diff) {
95
+ fail(`'${slug}' spec differs from the approved version on ${branch} (${approvedSha.slice(0, 8)}):\n${diff.slice(0, 300)}`, {
96
+ code: 'SPEC_DIFFERS_FROM_APPROVED',
97
+ hint: `spec was modified after approval. Merge latest ${branch} or revert unauthorized spec changes.`,
98
+ });
99
+ }
100
+
101
+ // 5. Automatic state transition: PR Merge is the single source of truth for approval!
102
+ // If the spec is physically merged on the target branch with 0 diff, automatically transition to ready_for_impl
103
+ if (meta.status !== 'ready_for_impl' || meta.specSha !== approvedSha) {
104
+ if (exists(metaPath)) {
105
+ let metaText = readText(metaPath);
106
+ const upsertKey = (text, key, val) => {
107
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
108
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
109
+ };
110
+ metaText = upsertKey(metaText, 'specSha', approvedSha);
111
+ metaText = upsertKey(metaText, 'status', 'ready_for_impl');
112
+ writeText(metaPath, metaText);
113
+ }
114
+ log.ok(`${slug}: recognized PR approval on ${branch} (synced state to ready_for_impl @ ${approvedSha.slice(0, 8)})`);
115
+ }
80
116
  }
81
117
 
82
- // 6. Tasks checklist presence
118
+ // 6. Explicit Auto-PR Delegation Handling
119
+ if (opts.autoPr !== undefined && exists(metaPath)) {
120
+ let metaText = readText(metaPath);
121
+ const upsertKey = (text, key, val) => {
122
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
123
+ return re.test(text) ? text.replace(re, `${key}: ${val}`) : `${text.trimEnd()}\n${key}: ${val}\n`;
124
+ };
125
+ metaText = upsertKey(metaText, 'autoPr', opts.autoPr ? 'true' : 'false');
126
+ writeText(metaPath, metaText);
127
+ }
128
+
129
+ if (opts.targetBranch && exists(metaPath)) {
130
+ let metaText = readText(metaPath);
131
+ const upsertKey = (text, key, val) => {
132
+ const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
133
+ return re.test(text) ? text.replace(re, `${key}: "${val}"`) : `${text.trimEnd()}\n${key}: "${val}"\n`;
134
+ };
135
+ metaText = upsertKey(metaText, 'targetBranch', opts.targetBranch);
136
+ writeText(metaPath, metaText);
137
+ }
138
+
139
+ // 7. Tasks checklist presence
83
140
  const tasksPath = path.join(cdir, 'tasks.md');
84
141
  if (!exists(tasksPath)) {
85
142
  fail(`'${slug}' missing tasks.md`, {
@@ -88,7 +145,14 @@ export function applyGuard(changeId, opts = {}) {
88
145
  });
89
146
  }
90
147
 
91
- log.ok(`${slug} is APPROVED on ${branch} (specSha: ${approvedSha.slice(0, 8)}, state: ready_for_impl)`);
148
+ const isAutoPr = opts.autoPr === true || (opts.autoPr === undefined && meta.autoPr === 'true');
149
+ const shaDisplay = approvedSha ? ` (specSha: ${approvedSha.slice(0, 8)}, state: ready_for_impl)` : ` (state: ready_for_impl)`;
150
+ log.ok(`${slug} is READY FOR IMPLEMENTATION on ${branch}${shaDisplay}`);
151
+ if (isAutoPr) {
152
+ log.info(`Auto-PR delegation: ENABLED (agent is authorized to open Implementation PR once tasks & verify pass).`);
153
+ } else {
154
+ log.info(`Auto-PR delegation: DISABLED (local-only mode; run \`asdlc pr\` when ready to submit).`);
155
+ }
92
156
  log.info(`Ready for implementation. Follow task-level TDD loop in tasks.md.`);
93
157
  return 0;
94
158
  }
@@ -107,6 +171,9 @@ export function register(program) {
107
171
  .command('apply <changeId>')
108
172
  .description('guard before implementing: the spec must be approved on the protected branch')
109
173
  .option('--protected-branch <ref>', 'branch the approved spec must be merged into', 'origin/main')
174
+ .option('--target-branch <ref>', 'target branch to merge into')
175
+ .option('--auto-pr', 'explicitly delegate authority to automatically open Implementation PR after verification passes')
176
+ .option('--no-auto-pr', 'disable automatic Implementation PR creation (default)')
110
177
  .option('--repo-root <path>')
111
178
  .action((changeId, opts) => {
112
179
  process.exitCode = applyGuard(changeId, opts);
@@ -0,0 +1,57 @@
1
+ import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
2
+ import { git } from '../lib/git.js';
3
+ import { assess, renderCheckSummary, renderPRComment } from '../assess/index.js';
4
+ import { log } from '../lib/log.js';
5
+
6
+ export function runAssessCommand(changeId, opts = {}) {
7
+ const repoRoot = requireRepo(opts);
8
+ const slug = changeId ? toChangeSlug(changeId) : null;
9
+ const stage = opts.stage || 'new';
10
+
11
+ let changedFiles = [];
12
+ if (stage === 'impl') {
13
+ const base = opts.base || 'origin/main';
14
+ const head = opts.head || 'HEAD';
15
+ const diffFiles = git(['diff', '--name-only', `${base}...${head}`], repoRoot, { allowFail: true }) ?? '';
16
+ changedFiles = diffFiles.split(/\r?\n/).map((s) => s.trim()).filter(Boolean);
17
+ }
18
+
19
+ const result = assess({
20
+ stage,
21
+ changeId: slug,
22
+ requirement: opts.requirement || '',
23
+ changedFiles,
24
+ baseSha: opts.base || 'HEAD',
25
+ headSha: opts.head || null,
26
+ repoRoot,
27
+ persist: Boolean(slug)
28
+ });
29
+
30
+ if (opts.json) {
31
+ console.log(JSON.stringify(result, null, 2));
32
+ return result.verdict === 'ok' ? 0 : 1;
33
+ }
34
+
35
+ log.info(renderCheckSummary(result));
36
+ if (result.transition && result.transition.direction === 'up') {
37
+ log.warn(`[ESCALATED] Level increased from ${result.transition.from_level} to ${result.risk.level}`);
38
+ }
39
+ return result.verdict === 'ok' ? 0 : 1;
40
+ }
41
+
42
+ export function register(program) {
43
+ program
44
+ .command('assess [changeId]')
45
+ .description('evaluate change risk and governance requirements via unified assess engine')
46
+ .option('--stage <stage>', 'assessment stage: new | spec | impl', 'new')
47
+ .option('--requirement <text>', 'requirement description (for stage: new)')
48
+ .option('--base <ref>', 'base ref for diff (for stage: impl)', 'origin/main')
49
+ .option('--head <ref>', 'head ref for diff (for stage: impl)', 'HEAD')
50
+ .option('--json', 'output raw assessment JSON')
51
+ .action((changeId, opts) => {
52
+ const code = runAssessCommand(changeId, opts);
53
+ if (code !== 0 && !process.exitCode) {
54
+ process.exitCode = code;
55
+ }
56
+ });
57
+ }
@@ -52,9 +52,6 @@ export function doctor(opts = {}) {
52
52
  if (exists(cfgPath)) { try { cfgSchema = (readYaml(cfgPath) ?? {}).schema ?? null; } catch { /* ignore */ } }
53
53
  add('repo config schema', cfgSchema === 'agentic-repo-change' ? 'pass' : 'warn', cfgSchema ?? 'unset');
54
54
 
55
- const policy = exists(path.join(repoRoot, '.sdlc', 'policy.yaml'));
56
- add('.sdlc/policy.yaml', policy ? 'pass' : 'warn', policy ? '' : 'missing (run `asdlc init`)');
57
-
58
55
  let hooksPath = null;
59
56
  try { hooksPath = git(['config', '--get', 'core.hooksPath'], repoRoot, { allowFail: true }); } catch { /* ignore */ }
60
57
  add('.githooks', hooksPath === '.githooks' ? 'pass' : 'warn', hooksPath === '.githooks' ? 'core.hooksPath=.githooks' : `core.hooksPath=${hooksPath ?? 'unset'}`);
@@ -98,17 +95,7 @@ export function doctor(opts = {}) {
98
95
  } catch (e) { log.warn(`fix failed for .gitignore: ${e.message}`); }
99
96
  }
100
97
 
101
- // 3. .sdlc/policy.yaml
102
- if (!policy && exists(policyAssetFile)) {
103
- try {
104
- const pdir = path.join(repoRoot, '.sdlc');
105
- ensureDir(pdir);
106
- copyTree(policyAssetFile, path.join(pdir, 'policy.yaml'));
107
- log.ok('fixed: created .sdlc/policy.yaml from template');
108
- } catch (e) { log.warn(`fix failed for policy: ${e.message}`); }
109
- }
110
-
111
- // 4. .githooks
98
+ // 3. .githooks
112
99
  if (hooksPath !== '.githooks') {
113
100
  try {
114
101
  if (exists(githooksAssetDir)) {
@@ -94,15 +94,6 @@ export function initRepo(opts = {}) {
94
94
  }
95
95
  if (opts.hooks !== false) installHooks(repoRoot);
96
96
 
97
- // 3.5) Platform policy (v6 §7.3): committed, CODEOWNERS-protected. Default only.
98
- const policyDest = path.join(repoRoot, '.sdlc', 'policy.yaml');
99
- if (exists(policyDest) && !opts.force) {
100
- log.step('.sdlc/policy.yaml exists (use --force to reset)');
101
- } else {
102
- writeText(policyDest, readText(policyAssetFile));
103
- log.ok('wrote .sdlc/policy.yaml (platform-owned; protect with CODEOWNERS)');
104
- }
105
-
106
97
  // 3.6) Pre-provision remote governance labels if git remote & gh are available
107
98
  try {
108
99
  ensureRemoteLabels(repoRoot);
@@ -7,6 +7,8 @@ import { runOpenspec } from '../lib/openspec.js';
7
7
  import { runShell } from '../lib/exec.js';
8
8
  import { fail } from '../lib/errors.js';
9
9
  import { log } from '../lib/log.js';
10
+ import { Option } from 'commander';
11
+ import { inferInitialLevel, isSinglePrLevel } from '../lib/level.js';
10
12
 
11
13
  // STAGE 1 of the spec (v10: explore + propose are ONE step).
12
14
  // 1) scaffold the change through OpenSpec (derives canonical slug from requirement)
@@ -29,11 +31,28 @@ export function newChange(requirement, opts = {}) {
29
31
  log.ok(`created change '${slug}' (derived from: "${requirement}")`);
30
32
  }
31
33
 
32
- // Record requirement in change metadata (.openspec.yaml)
34
+ // Determine grill mode: 'none' (--no-grill), 'batch' (--batch-grill), or 'interactive' (default grill-me)
35
+ const grillMode = opts.grill === false ? 'none' : (opts.batchGrill ? 'batch' : 'interactive');
36
+
37
+ // Infer governance level (L0, L1, L2, L3) via unified assessment engine
38
+ const { level, changeType, workflowMode, reason: levelReason } = inferInitialLevel({
39
+ requirement,
40
+ explicitLevel: opts.level,
41
+ repoRoot,
42
+ changeId: slug
43
+ });
44
+
45
+ // Record requirement, grill mode, and governance level in change metadata (.openspec.yaml)
33
46
  const metaPath = path.join(cdir, '.openspec.yaml');
34
47
  if (exists(metaPath)) {
35
48
  const existing = readText(metaPath).trimEnd();
36
- writeText(metaPath, `${existing}\nrequirement: ${JSON.stringify(requirement)}\n`);
49
+ writeText(metaPath, `${existing}\nrequirement: ${JSON.stringify(requirement)}\ngrillMode: "${grillMode}"\nchangeType: "${changeType}"\nworkflowMode: "${workflowMode}"\nlevel: "${level}"\nlevelReason: ${JSON.stringify(levelReason)}\n`);
50
+ }
51
+
52
+ if (workflowMode === 'single-pr') {
53
+ log.ok(`assigned governance level: ${level} [Type: ${changeType}] (${levelReason}) - [Single PR mode: code & specs in one PR]`);
54
+ } else {
55
+ log.ok(`assigned governance level: ${level} [Type: ${changeType}] (${levelReason}) - [Spec-first mode: Spec PR required before implementation]`);
37
56
  }
38
57
 
39
58
  const g = ensureGraphify();
@@ -97,18 +116,20 @@ _(unavailable - graph query error)_
97
116
  }
98
117
  }
99
118
 
100
- // Seed the grilling interview (skill: grilling / batch-grill-me). The agent runs it
101
- // with the author in batch mode to resolve the decision frontier in 1-2 turns.
119
+ // Seed the grilling interview / clarification record.
102
120
  const clar = path.join(cdir, 'clarifications.md');
103
121
  if (!exists(clar)) {
104
- writeText(clar, `# Clarifications: ${slug}
122
+ let clarContent = '';
123
+ if (grillMode === 'batch') {
124
+ clarContent = `# Clarifications: ${slug}
105
125
 
106
126
  > Requirement: "${requirement}"
127
+ > Mode: batch-grill
107
128
  > Before writing proposal.md / specs, the agent MUST run a **batch-grill-me** interview
108
- > with the author (skill: \`grilling\`) and record the settled decisions here.
109
- > Use batch-grill-me for maximum efficiency: evaluate the design tree, present the ENTIRE
110
- > frontier in one structured batch (numbered Q1..Qn with concrete recommended defaults),
111
- > allowing the author to approve or selectively adjust decisions in 1-2 rounds.
129
+ > with the author (skill: \`batch-grill-me\`) and record the settled decisions here.
130
+ > Evaluate the design tree, present the ENTIRE active frontier in structured batches
131
+ > (numbered Q1..Qn with concrete recommended defaults and trade-offs), allowing the author
132
+ > to approve or adjust decisions.
112
133
  > Facts are the agent's job to look up; decisions are the author's to make.
113
134
 
114
135
  ## Requirement
@@ -116,15 +137,55 @@ _(unavailable - graph query error)_
116
137
 
117
138
  ## Settled decisions
118
139
  <!-- one entry per settled decision: decision -> answer, with the reason -->
119
- <!-- Consider key architectural dimensions: -->
120
- <!-- 1. Functional Scope & Seams (user journeys, error states, domain models) -->
121
- <!-- 2. Security & Threat Mitigation (auth, parameter validation, secrets, data privacy) -->
122
- <!-- 3. Operational NFRs & Performance Budgets (latency SLAs, cache TTL, rate limits) -->
123
140
 
124
141
  ## Open questions
125
142
  <!-- must be empty before the spec is written -->
126
- `);
127
- log.ok('seeded clarifications.md (run batch-grill-me interview)');
143
+ `;
144
+ } else if (grillMode === 'none') {
145
+ clarContent = `# Clarifications: ${slug}
146
+
147
+ > Requirement: "${requirement}"
148
+ > Mode: no-grill (self-settled)
149
+ > Interactive grilling was skipped via \`--no-grill\`.
150
+ > The agent MUST ground decisions in codebase facts, AST (\`explore.md\`), and existing patterns,
151
+ > and record all settled assumptions below BEFORE authoring proposal.md / specs.
152
+
153
+ ## Requirement
154
+ "${requirement}"
155
+
156
+ ## Settled decisions
157
+ <!-- record all context-inferred decisions and assumptions here -->
158
+
159
+ ## Open questions
160
+ <!-- (none) -->
161
+ `;
162
+ } else {
163
+ // Default: interactive (grill-me)
164
+ clarContent = `# Clarifications: ${slug}
165
+
166
+ > Requirement: "${requirement}"
167
+ > Mode: interactive (grill-me)
168
+ > Before writing proposal.md / specs, the agent runs a high-signal conversational **grill-me** interview
169
+ > with the author (skill: \`grilling\`) and records settled decisions here.
170
+ >
171
+ > **Anti-Fatigue Guardrails**:
172
+ > 1. Codebase-first: Look up facts in AST/code; NEVER ask what can be inspected.
173
+ > 2. Material forks only: Ask only about real architectural trade-offs; decide implementation details yourself.
174
+ > 3. Recommendation-led: Ask 1 focused question at a time with a concrete recommended default and rationale.
175
+ > 4. Early-exit: Stop questioning immediately when material forks are settled or the author says "proceed".
176
+
177
+ ## Requirement
178
+ "${requirement}"
179
+
180
+ ## Settled decisions
181
+ <!-- one entry per settled decision: decision -> answer, with the reason -->
182
+
183
+ ## Open questions
184
+ <!-- must be empty before the spec is written -->
185
+ `;
186
+ }
187
+ writeText(clar, clarContent);
188
+ log.ok(`seeded clarifications.md (${grillMode === 'batch' ? 'batch-grill mode' : (grillMode === 'none' ? 'no-grill mode' : 'conversational grill-me mode')})`);
128
189
  }
129
190
 
130
191
  // Technical design (design.md) scaffolding:
@@ -148,10 +209,24 @@ _(unavailable - graph query error)_
148
209
  log.info(' ▶ Ground yourself in `explore.md` and research codebase facts first.');
149
210
  log.info(' ▶ Perform external search for 3rd-party APIs, vendor SDKs, and UI design patterns (enabled by default).');
150
211
  log.info(' (If search fails or offline: emit \'[WARN] External search failed or offline: <reason>. Continuing with defined steps.\' and continue without blocking).');
151
- log.info(' ▶ Formulate decision frontier covering Functional scope, Security threat vectors, and Operational NFRs.');
152
- log.info(' ▶ Invoke `batch-grill-me` (or `grilling`) to present structured Batch 1 questions with recommended defaults.');
153
- log.info(' ▶ Record agreed decisions into `clarifications.md`.');
154
- log.info(' ▶ ONLY AFTER clarifications are settled: author `proposal.md`, `specs/**`, and `design.md` (if seeded/needed).');
212
+ if (grillMode === 'batch') {
213
+ log.info(' ▶ [MODE: BATCH-GRILL] Formulate decision frontier and invoke `batch-grill-me` to present structured batches with recommended defaults.');
214
+ log.info(' ▶ Record agreed decisions into `clarifications.md`.');
215
+ log.info(' ▶ ONLY AFTER clarifications are settled: author `proposal.md`, `specs/**`, and `design.md` (if seeded/needed).');
216
+ } else if (grillMode === 'none') {
217
+ log.info(' ▶ [MODE: NO-GRILL] Interactive grilling bypassed via `--no-grill`.');
218
+ log.info(' ▶ Ground decisions in code/AST facts, record settled assumptions into `clarifications.md`, and proceed to `proposal.md`, `specs/**`, and `design.md` (if seeded/needed).');
219
+ } else {
220
+ log.info(' ▶ [MODE: GRILL-ME] Formulate decision frontier and run conversational, recommendation-led grilling (1 material decision at a time).');
221
+ log.info(' (Anti-fatigue: look up code facts first; skip micro-trivia; halt questioning when author says proceed or forks hit zero).');
222
+ log.info(' ▶ Record agreed decisions into `clarifications.md`.');
223
+ log.info(' ▶ ONLY AFTER clarifications are settled: author `proposal.md`, `specs/**`, and `design.md` (if seeded/needed).');
224
+ }
225
+ if (shouldSeedDesign) {
226
+ log.info(' ▶ [ARCHITECTURE] Generate architecture diagram (embedded Mermaid flowchart / sequenceDiagram).');
227
+ log.info(' ▶ [API DESIGN] Follow `api-design` skill (RESTful nouns, Stripe-style / RFC 7807 errors, idempotency, cursor pagination).');
228
+ log.info(' ▶ [UI/UX DESIGN] Ground visual specs in `frontend-design` (Anthropic) & Vercel Web Interface Guidelines.');
229
+ }
155
230
  log.info(` ▶ Run \`asdlc lint ${slug}\`.`);
156
231
  return slug;
157
232
  }
@@ -164,6 +239,9 @@ export function register(program) {
164
239
  .option('--query <q>', 'graph query terms (default: extracted requirement terms)')
165
240
  .option('--design', 'explicitly generate technical design (design.md)')
166
241
  .option('--no-design', 'skip generating technical design (design.md)')
242
+ .option('--batch-grill', 'use batch-grill-me (present entire decision frontier in structured batches)')
243
+ .option('--no-grill', 'skip interactive grilling interview (self-settle decisions in clarifications.md)')
244
+ .addOption(new Option('--level <level>', 'internal governance level override (hidden)').hideHelp())
167
245
  .option('--repo-root <path>')
168
246
  .action((requirement, opts) => {
169
247
  newChange(requirement, opts);
@@ -8,6 +8,8 @@ import { runLint } from './lint.js';
8
8
  import { runVerify } from './verify.js';
9
9
  import { fail } from '../lib/errors.js';
10
10
  import { log } from '../lib/log.js';
11
+ import { assess, renderLabels, renderPRComment } from '../assess/index.js';
12
+ import { readEffectiveLevel } from '../lib/level.js';
11
13
 
12
14
  export const ASDLC_LABELS = {
13
15
  'asdlc:spec-review': {
@@ -88,6 +90,10 @@ export async function createPR(changeId, targetBranch, opts = {}) {
88
90
  .split(/\r?\n/).filter(Boolean);
89
91
  const hasSourceChanges = diffFiles.some((f) => !f.startsWith(`openspec/changes/${slug}/`));
90
92
 
93
+ const lvlMatch = metaText.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
94
+ const changeLevel = lvlMatch ? lvlMatch[1].toUpperCase() : null;
95
+ const isSinglePr = changeLevel === 'L0' || changeLevel === 'L1';
96
+
91
97
  let prType;
92
98
  if (opts.type) {
93
99
  prType = opts.type.toLowerCase();
@@ -96,6 +102,7 @@ export async function createPR(changeId, targetBranch, opts = {}) {
96
102
  changeStatus === 'ready_for_impl' ||
97
103
  Boolean(specSha) ||
98
104
  currentBranch.startsWith('impl/') ||
105
+ (isSinglePr && hasSourceChanges) ||
99
106
  (hasSourceChanges && (checkedCount > 0 || uncheckedCount === 0))
100
107
  ) {
101
108
  prType = 'impl';
@@ -122,6 +129,7 @@ export async function createPR(changeId, targetBranch, opts = {}) {
122
129
  repoRoot,
123
130
  base: targetBranch,
124
131
  protectedBranch: targetBranch,
132
+ openingPr: true,
125
133
  ...opts,
126
134
  });
127
135
  if (verifyExit !== 0) {
@@ -200,7 +208,23 @@ ${proposalText}
200
208
  `;
201
209
  }
202
210
 
203
- // 6. Multi-tier PR creation strategy:
211
+ // 6. Assessment Governance & PR Metadata
212
+ const assessment = assess({
213
+ stage: isSpec ? 'spec' : 'impl',
214
+ changeId: slug,
215
+ baseSha: targetBranch,
216
+ headSha: 'HEAD',
217
+ changedFiles: diffFiles,
218
+ repoRoot,
219
+ persist: false
220
+ });
221
+ const assessLabels = renderLabels(assessment);
222
+ const assessComment = renderPRComment(assessment);
223
+ const labelsToApply = Array.from(new Set([labelPrefix, secondaryLabel, ...assessLabels]));
224
+
225
+ body = `${body}\n\n---\n\n${assessComment}\n`;
226
+
227
+ // 7. Multi-tier PR creation strategy:
204
228
  // Tier 1: Platform CLI (gh / glab)
205
229
  // Tier 2: Direct REST API (GITHUB_TOKEN / GITLAB_TOKEN)
206
230
  // Tier 3: 1-click Web compare URL fallback
@@ -213,7 +237,7 @@ ${proposalText}
213
237
 
214
238
  // Pre-provision governance labels on remote before PR creation (so gh pr create doesn't reject unknown labels)
215
239
  if (remoteInfo?.isGitHub) {
216
- ensureRemoteLabels(repoRoot, [labelPrefix, secondaryLabel]);
240
+ ensureRemoteLabels(repoRoot, labelsToApply);
217
241
  }
218
242
 
219
243
  // Attempt Tier 1: CLI (gh)
@@ -224,7 +248,7 @@ ${proposalText}
224
248
  '--body', body,
225
249
  '--base', targetBranch,
226
250
  '--head', currentBranch,
227
- '--label', `${labelPrefix},${secondaryLabel}`,
251
+ '--label', labelsToApply.join(','),
228
252
  ], { cwd: repoRoot, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
229
253
  prCreated = true;
230
254
  prUrl = out.trim();
@@ -111,7 +111,7 @@ export function upgradeSchema() {
111
111
  log.warn(`schema asset directory missing at ${schemaAssetDir}`);
112
112
  return false;
113
113
  }
114
- const dest = installSchema();
114
+ const dest = installSchema({ force: true });
115
115
  log.ok(`refreshed schema v${builtinSchemaVersion()} -> ${dest}`);
116
116
  return true;
117
117
  } catch (err) {