@akjamie/agentic-sdlc 1.9.0 → 1.9.2

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.
package/README.md CHANGED
@@ -1,9 +1,10 @@
1
1
  # agentic-sdlc
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@akjamie/agentic-sdlc?color=6366f1&label=npm)](https://www.npmjs.com/package/@akjamie/agentic-sdlc)
4
+ [![version: v1.9.2](https://img.shields.io/badge/version-v1.9.2-6366f1.svg)](package.json)
4
5
  [![license: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-10b981.svg)](LICENSE)
5
6
  [![Node.js](https://img.shields.io/badge/node-%3E%3D20.19.0-38bdf8.svg)](https://nodejs.org/)
6
- [![tests](https://img.shields.io/badge/tests-168%20passing-10b981.svg)](#development--verification)
7
+ [![tests](https://img.shields.io/badge/tests-213%20passing-10b981.svg)](#development--verification)
7
8
  [![architecture](https://img.shields.io/badge/governance-L0--L3%20Adaptive%20Dual--Track-f59e0b.svg)](#adaptive-risk-tiered-governance-l0l3)
8
9
 
9
10
  > **The Intelligent Governance Engine for Autonomous AI Coding.**
@@ -212,7 +213,7 @@ asdlc doctor
212
213
  # 1. Start a routine change (automatically inferred as L1)
213
214
  asdlc new "add memory cache helper with TTL eviction"
214
215
 
215
- # 2. Directly implement using the task-level TDD loop (no Spec PR needed!)
216
+ # 2. Directly implement using the task-level TDD loop (no Spec PR or `asdlc approve` needed!)
216
217
  asdlc apply memory-cache-helper
217
218
 
218
219
  # 3. Verify locally against 12 quality gates
@@ -287,7 +288,7 @@ CLI (--mode) > Env (ASDLC_WORKFLOW_MODE) > Repo (.sdlc/policy.yaml) > Global (~/
287
288
  | [`asdlc-new`](assets/skills/asdlc-new/SKILL.md) | Scaffolds change, queries AST hubs, runs conversational anti-fatigue `grill-me`. |
288
289
  | [`asdlc-lint`](assets/skills/asdlc-lint/SKILL.md) | Enforces deterministic BDD GIVEN/WHEN/THEN and R5 scenario-to-AC coverage. |
289
290
  | [`asdlc-pr`](assets/skills/asdlc-pr/SKILL.md) | Smart PR dispatcher: automatically handles Spec PR vs. Implementation PR. |
290
- | [`asdlc-approve`](assets/skills/asdlc-approve/SKILL.md) | Stamps Git `specSha` lock upon Spec PR merge. |
291
+ | [`asdlc-approve`](assets/skills/asdlc-approve/SKILL.md) | Stamps Git `specSha` lock upon Spec PR merge (Track A Dual-PR; waived for Track B Single-PR). |
291
292
  | [`asdlc-apply`](assets/skills/asdlc-apply/SKILL.md) | Strict task-level TDD engine (`Red -> Green -> Refactor -> Evidence -> Converge`). |
292
293
  | [`asdlc-verify`](assets/skills/asdlc-verify/SKILL.md) | Pre-flight audit across 12 gates (test presence, evidence, tamper guard, schema). |
293
294
  | [`asdlc-spec-review`](assets/skills/asdlc-spec-review/SKILL.md) | Independent review agent: 6-dimensional spec review before human lead approval. |
@@ -349,7 +350,7 @@ asdlc init # Scaffold repository with OpenSpec, Graphify
349
350
  asdlc new "<intent>" # Scaffold change with AST explore + grill-me interview
350
351
  asdlc lint <ID> # Validate BDD scenarios, AC rules, and coverage (docs/spec-format.md)
351
352
  asdlc pr <ID> <target-branch> # Smart PR creator (auto-handles Spec PR vs Impl PR + smart staging)
352
- asdlc approve <ID> # Record approvedSha and transition to ready_for_impl
353
+ asdlc approve <ID> # Record approvedSha & ready_for_impl (Track A; idempotent no-op in Single-PR)
353
354
  asdlc apply <ID> # Guarded implementation launcher (checks approvedSha)
354
355
  asdlc test <ID> [--json] # Execute real test runners mapped to AC annotations
355
356
  asdlc verify <ID> # Audit diff against all 12 quality gates
@@ -370,7 +371,7 @@ git clone https://github.com/akjamie/agentic-sdlc.git
370
371
  cd agentic-sdlc
371
372
  npm install
372
373
 
373
- # Run complete test suite (168 tests passing, 100% pass rate)
374
+ # Run complete test suite (213 tests passing, 100% pass rate)
374
375
  npm test
375
376
 
376
377
  # Run end-to-end multi-language simulation tests
@@ -36,8 +36,8 @@ asdlc apply <CHANGE_ID> [--auto-pr] [--target-branch <ref>]
36
36
  - If `asdlc apply` succeeds: Proceed to Step 2.
37
37
 
38
38
  > [!NOTE]
39
- > **Governance Level & Single PR Flow (L0 / L1)**:
40
- > For changes evaluated as `level: L0` or `level: L1`, prior merging of a Spec PR to the protected branch is waived. `asdlc apply` immediately unblocks local TDD implementation, allowing source code and spec delta to be submitted together in a Single PR.
39
+ > **Governance Level & Single PR Flow (Track B: L0 / L1)**:
40
+ > For changes evaluated as `level: L0` or `level: L1` (under `supervised` or `auto` without `spec-first` override), separate Spec PR and `asdlc approve` are **waived**. `asdlc apply` immediately unblocks local TDD implementation, automatically transitions status to `ready_for_impl` in-place, and allows source code and spec delta to be submitted together in a Single PR. (In `supervised` mode, human Lead sign-off occurs at the single PR merge).
41
41
 
42
42
 
43
43
  ### Step 2: Read `tasks.md` and Ground Context
@@ -7,6 +7,11 @@ description: "Execute Stage 4 of Agentic SDLC: approve spec intent, lock specSha
7
7
 
8
8
  This skill executes **Stage 4 (Approve)** of the Agentic SDLC. It transitions a change from approved intent into the implementation stage (`READY_FOR_IMPL`), locking the spec to a path-limited approved commit SHA (`specSha`).
9
9
 
10
+ > [!IMPORTANT]
11
+ > **Two-Track Lifecycle Routing (Track A vs. Track B)**:
12
+ > - **Track A (Dual-PR / Spec-First — L2/L3 or forced `spec-first`)**: Separate Spec PR + merge + `asdlc approve <ID>` is **strictly required** before implementation (`apply`).
13
+ > - **Track B (Single-PR / Fast-Path — L0/L1 under supervised/auto)**: Standalone Spec PR and `asdlc approve` are **waived**. You may proceed directly to `asdlc apply <ID>` to start TDD. If `asdlc approve <ID>` is run in Single-PR mode, it idempotently marks `status: ready_for_impl` in-place without generating a fake `specSha`, without git tags, and **without modifying `review.md`** (final human sign-off happens on the combined PR).
14
+
10
15
  ---
11
16
 
12
17
  ## Core Concept: The Spec SHA Freeze Gate
@@ -28,6 +28,10 @@ Drawing from Anthropic's engineering practices for scaling AI code reviews, this
28
28
  > **Scope**: Reviews *implementation conformance and code quality* — spec adherence, test rigor, architecture, and production safety.
29
29
  > Requires `asdlc test <CHANGE_ID>` and `asdlc verify <CHANGE_ID>` to have passed before this review can issue an APPROVE verdict.
30
30
  > Does NOT review spec intent — that is `asdlc-spec-review`.
31
+ >
32
+ > **Output Routing Contract (PR vs. Local)**:
33
+ > - **PR Mode** (invoked with a PR URL, PR number, or via CI PR trigger): **Post the review comment directly to the PR** via `gh pr comment` — **NEVER pause to ask the user whether to post comments**.
34
+ > - **Local Mode** (invoked with `<CHANGE_ID>` only, no PR context): **Print the formatted review report directly** in your response; do NOT run `gh pr comment`.
31
35
 
32
36
  ---
33
37
 
@@ -214,9 +218,11 @@ Every finding must follow a structured schema with explicit defect attribution s
214
218
 
215
219
  ---
216
220
 
217
- ### Step 5: Post PR Comment
221
+ ### Step 5: Deliver Review (Post PR Comment or Print Locally)
218
222
 
219
- Compose the review markdown and post it as a PR comment using the GitHub API:
223
+ Compose the review using the markdown format below, then deliver it according to the invocation mode:
224
+
225
+ - **If reviewing a PR** (PR URL, PR number, or CI PR trigger): **Post the comment directly** without asking the user for confirmation:
220
226
 
221
227
  ```bash
222
228
  gh pr comment $PR_NUMBER --repo $REPO --body "$(cat <<'EOF'
@@ -225,6 +231,8 @@ EOF
225
231
  )"
226
232
  ```
227
233
 
234
+ - **If reviewing locally** (`<CHANGE_ID>` only, no PR): **Print the formatted review markdown directly** in your response and skip `gh pr comment` and Step 6.
235
+
228
236
  Format the comment body strictly as:
229
237
 
230
238
  ~~~markdown
@@ -53,7 +53,10 @@ If `pass` is false:
53
53
 
54
54
  ### Step 3: Lint Complete (Self-Review Passed)
55
55
  When `pass` is true (`0 blockers`):
56
- Report to the author that the spec is structurally valid, fully traceable, and passes all BDD/acceptance criteria checks:
56
+ Report to the author that the spec is structurally valid, fully traceable, and passes all BDD/acceptance criteria checks, then guide them based on the change's governance track (`asdlc status <CHANGE_ID>`):
57
57
 
58
- > "Spec lint passed with 0 blocking issues. The spec is ready for PR. When you are ready to submit it for review, use `asdlc pr <CHANGE_ID> <targetBranch>`."
58
+ - **Track A (Dual-PR — L2 / L3 or `spec-first`)**:
59
+ > "Spec lint passed with 0 blocking issues. Open the Spec PR with `asdlc pr <CHANGE_ID> [targetBranch]`."
60
+ - **Track B (Single-PR — L0 / L1 under `supervised` or `auto`)**:
61
+ > "Spec lint passed with 0 blocking issues. In Single-PR mode, no separate Spec PR or `asdlc approve` is needed — draft `tasks.md` and run `asdlc apply <CHANGE_ID>` to start TDD."
59
62
 
@@ -137,6 +137,7 @@ Once `## Open questions` in `clarifications.md` is empty, author the change docu
137
137
  - Independent AI review (`asdlc:spec-review`) is executed by an independent review agent (locally or via PR automation).
138
138
  - Formal approval is given by the human lead via PR merge or `asdlc approve <SLUG>`.
139
139
 
140
- ### Step 5: Transition to Lint
141
- Once artifacts are written, guide the developer:
142
- > "Artifacts drafted! Now run `/asdlc:lint <SLUG>` to verify BDD scenarios, technical design, and acceptance criteria before opening the spec PR."
140
+ ### Step 5: Transition to Implementation / Review (Two-Track Lifecycle)
141
+ Once artifacts are written, guide the developer based on the change's governance level (`asdlc status <SLUG>`):
142
+ - **Track A (L2 / L3 or `spec-first`)**: Run `/asdlc:lint <SLUG>` to verify BDD scenarios and open a Spec PR (`asdlc pr <SLUG>`). After merge, run `asdlc approve <SLUG>`.
143
+ - **Track B (L0 / L1 under supervised/auto)**: Draft `tasks.md` and proceed directly to `/asdlc:apply <SLUG>` to begin the TDD loop (standalone Spec PR and `asdlc approve` are waived; combined PR opened after verify).
@@ -12,20 +12,20 @@ This skill opens a **Spec PR** (Stage 3) or an **Implementation PR** (Stage 6.5)
12
12
  ## Command
13
13
 
14
14
  ```powershell
15
- asdlc pr <CHANGE_ID> <targetBranch>
15
+ asdlc pr <CHANGE_ID> [targetBranch]
16
16
  ```
17
17
 
18
- - `<targetBranch>`: Target branch to merge into (e.g. `main`, `develop`, `release/*`). Required.
19
- - Zero manual flags: `asdlc pr` automatically detects whether to open a Spec PR or an Implementation PR.
18
+ - `[targetBranch]`: Target branch to merge into (e.g. `main`, `master`, `develop`). Optional — defaults to `.openspec.yaml`'s `targetBranch` or the repository's default branch (`resolveDefaultBranch`).
19
+ - Zero manual flags: `asdlc pr` automatically detects whether to open a Spec PR (Track A) or an Implementation / Single PR (Track A/B).
20
20
 
21
21
  ---
22
22
 
23
- ## Dual-PR Lifecycle & Pre-flight Gates
23
+ ## Two-Track Lifecycle & Pre-flight Gates
24
24
 
25
- | PR Type | Phase & Moment | Pre-Flight Guard | Auto Labels | Review Automation Trigger |
25
+ | PR Type | Track & Moment | Pre-Flight Guard | Auto Labels | Review Automation Trigger |
26
26
  | :--- | :--- | :--- | :--- | :--- |
27
- | **Spec PR** | Stage 3 (After drafting proposal & specs) | **`asdlc lint <ID>`**<br>(0 blocking BDD/AC issues) | `asdlc:spec-review`<br>`spec` | Runs `asdlc lint` + routes to **Independent Spec AI Review** (`asdlc-spec-review`) |
28
- | **Impl PR** | Stage 6.5 (After TDD apply & tasks complete) | **`asdlc verify <ID>`**<br>(12 deterministic gates pass) | `asdlc:impl-review`<br>`impl` | Runs `asdlc verify` + routes to **Independent Impl AI Review** (`asdlc-impl-review`) |
27
+ | **Spec PR** | **Track A** Stage 3 (L2/L3/`spec-first` after drafting proposal & specs) | **`asdlc lint <ID>`**<br>(0 blocking BDD/AC issues) | `asdlc:spec-review`<br>`spec` | Runs `asdlc lint` + routes to **Independent Spec AI Review** (`asdlc-spec-review`) |
28
+ | **Impl / Single PR** | **Track A** Stage 6.5 or **Track B** (L0/L1 Single-PR after TDD & tasks complete) | **`asdlc verify <ID>`**<br>(12 deterministic gates pass) | `asdlc:impl-review`<br>`impl` | Runs `asdlc verify` + routes to **Independent Impl AI Review** (`asdlc-impl-review`) |
29
29
 
30
30
  ---
31
31
 
@@ -37,6 +37,7 @@ asdlc pr <CHANGE_ID> <targetBranch>
37
37
  - `.openspec.yaml` has `status: ready_for_impl` or a locked `specSha`.
38
38
  - Spec intent commit is already merged on `<targetBranch>`.
39
39
  - Branch name starts with `impl/`.
40
+ - Single-PR change (`L0`/`L1` under `supervised`/`auto`) with source code changes outside `openspec/changes/<slug>/`.
40
41
  - Source code changes exist outside `openspec/changes/<slug>/` and tasks in `tasks.md` are marked complete.
41
42
  - **Detected as Spec PR (`spec`) otherwise**:
42
43
  - Spec artifacts (`proposal.md`, `specs/**`) are in drafting/review stage before approval.
@@ -16,7 +16,10 @@ It applies the **Player ≠ Referee** principle: the reviewing agent MUST NOT be
16
16
  > **Scope**: Reviews *intent* — BDD quality, logical consistency, architectural soundness, AC testability.
17
17
  > Does NOT re-run `asdlc lint` (deterministic structural checks are already gated by `asdlc pr`).
18
18
  > Does NOT review implementation code — that is `asdlc-impl-review`.
19
- > Output can be posted as a PR comment or reported locally.
19
+ >
20
+ > **Output Routing Contract (PR vs. Local)**:
21
+ > - **PR Mode** (invoked with a PR URL, PR number, or via CI PR trigger): **Post the review comment directly to the PR** via `gh pr comment` — **NEVER pause to ask the user whether to post comments**.
22
+ > - **Local Mode** (invoked with `<CHANGE_ID>` only, no PR context): **Print the formatted review report directly** in your response; do NOT run `gh pr comment`.
20
23
 
21
24
  ---
22
25
 
@@ -121,9 +124,11 @@ Classify each finding:
121
124
 
122
125
  ---
123
126
 
124
- ### Step 5: Post PR Comment
127
+ ### Step 5: Deliver Review (Post PR Comment or Print Locally)
125
128
 
126
- Compose the review as markdown and post it as a PR comment using the GitHub API:
129
+ Compose the review using the markdown format below, then deliver it according to the invocation mode:
130
+
131
+ - **If reviewing a PR** (PR URL, PR number, or CI PR trigger): **Post the comment directly** without asking the user for confirmation:
127
132
 
128
133
  ```bash
129
134
  gh pr comment $PR_NUMBER --repo $REPO --body "$(cat <<'EOF'
@@ -132,6 +137,8 @@ EOF
132
137
  )"
133
138
  ```
134
139
 
140
+ - **If reviewing locally** (`<CHANGE_ID>` only, no PR): **Print the formatted review markdown directly** in your response and skip `gh pr comment` and Step 6.
141
+
135
142
  Format the comment body strictly as:
136
143
 
137
144
  ~~~markdown
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@akjamie/agentic-sdlc",
3
- "version": "1.9.0",
3
+ "version": "1.9.2",
4
4
  "description": "Enterprise Agentic SDLC governance CLI: a 7-stage spec-driven flow on top of OpenSpec + Graphify, enforced by CI.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -2,7 +2,7 @@ import path from 'node:path';
2
2
  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
- import { lastCommitTouching, git } from '../lib/git.js';
5
+ import { lastCommitTouching, git, resolveDefaultBranch } from '../lib/git.js';
6
6
  import { fail } from '../lib/errors.js';
7
7
  import { log } from '../lib/log.js';
8
8
  import { isSinglePrLevel, readEffectiveLevel } from '../lib/level.js';
@@ -94,6 +94,7 @@ export function applyGuard(changeId, opts = {}) {
94
94
  };
95
95
  metaText = upsertKey(metaText, 'status', 'ready_for_impl');
96
96
  writeText(metaPath, metaText);
97
+ log.ok(`${slug}: marked status=ready_for_impl (no separate Spec PR in Single-PR mode; human sign-off happens on the final PR)`);
97
98
  }
98
99
  log.ok(`${slug}: governance level is ${effectiveLevel} (Single PR mode: direct local implementation permitted)`);
99
100
  } else {
@@ -191,15 +192,6 @@ export function applyGuard(changeId, opts = {}) {
191
192
  return 0;
192
193
  }
193
194
 
194
- function resolveDefaultBranch(repoRoot) {
195
- // Check if origin/main, origin/master, main, or master exists
196
- for (const candidate of ['origin/main', 'origin/master', 'main', 'master']) {
197
- const existsRef = git(['rev-parse', '--verify', candidate], repoRoot, { allowFail: true });
198
- if (existsRef) return candidate;
199
- }
200
- return 'main';
201
- }
202
-
203
195
  export function register(program) {
204
196
  program
205
197
  .command('apply <changeId>')
@@ -3,11 +3,12 @@ import { execFileSync } from 'node:child_process';
3
3
  import { exists, readText, writeText } from '../lib/fs.js';
4
4
  import { changeDir } from '../lib/paths.js';
5
5
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
6
- import { headSha, git, isGitRepo, lastCommitTouching, changeOnRef, safeCommit } from '../lib/git.js';
6
+ import { headSha, git, isGitRepo, lastCommitTouching, changeOnRef, safeCommit, resolveDefaultBranch } from '../lib/git.js';
7
7
  import { loadPolicy } from '../lib/policy.js';
8
8
  import { classifyPR } from '../lib/prtype.js';
9
9
  import { fail } from '../lib/errors.js';
10
10
  import { log } from '../lib/log.js';
11
+ import { resolveTopology } from '../lib/level.js';
11
12
 
12
13
  function upsertKey(text, key, value) {
13
14
  const re = new RegExp(`^\\s*${key}:\\s*.*$`, 'm');
@@ -83,6 +84,53 @@ export function mergeChange(changeId, opts = {}) {
83
84
  return [];
84
85
  }
85
86
 
87
+ // Single-PR optimization (Stage 4 decoupling):
88
+ // When explicitly invoked for a Single-PR change, spec approval is co-located with the
89
+ // final implementation PR. We idempotently mark status: ready_for_impl without requiring
90
+ // a separate merged Spec PR, without stamping specSha or tagging, and without writing review.md.
91
+ if (changeId) {
92
+ const branch = opts.targetBranch ?? opts.protectedBranch ?? opts.branch ?? resolveDefaultBranch(repoRoot);
93
+ const topology = resolveTopology({ repoRoot, slug, baseRef: branch, cliMode: opts.mode });
94
+
95
+ if (topology.tampered) {
96
+ fail(`cannot approve '${slug}': ${topology.reason}. Manual level downgrading or history tampering is strictly forbidden.`, {
97
+ code: 'LEVEL_TAMPERED',
98
+ hint: 'Revert unauthorized level edits in .openspec.yaml or restore risk-history.jsonl.'
99
+ });
100
+ }
101
+
102
+ if (topology.isSinglePr) {
103
+ const meta = path.join(changeDir(repoRoot, slug), '.openspec.yaml');
104
+ if (!exists(meta)) fail(`${slug}: no .openspec.yaml`);
105
+
106
+ const preImplStatuses = [null, '', 'draft', 'spec_review'];
107
+ if (preImplStatuses.includes(topology.declaredStatus)) {
108
+ let text = readText(meta);
109
+ text = upsertKey(text, 'status', 'ready_for_impl');
110
+ writeText(meta, text);
111
+ log.ok('marked status=ready_for_impl in-place (no separate Spec PR required).');
112
+ } else {
113
+ log.info(`${slug}: status=${topology.declaredStatus} preserved (no status regression).`);
114
+ }
115
+
116
+ log.ok(`${slug}: Single-PR mode (${topology.effectiveLevel}) - spec approval is co-located with implementation PR.`);
117
+ log.info('final approval = human Approve on the single PR (NOT waived).');
118
+ log.info('note: final governance level is re-assessed by `asdlc apply` when implementation context is available.');
119
+ return [slug];
120
+ }
121
+
122
+ // Track A (Dual-PR / Spec-First / unlevelled):
123
+ // Require physical merge evidence on target branch before stamping approval.
124
+ const trackALocked = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
125
+ const mergedSha = lastCommitTouching(repoRoot, branch, trackALocked);
126
+ if (!mergedSha) {
127
+ fail(`cannot approve '${slug}': no commit touching ${trackALocked.join(' or ')} is merged into ${branch}. Spec PR must be approved and merged before running asdlc approve.`, {
128
+ code: 'SPEC_NOT_MERGED',
129
+ hint: `Open a Spec PR targeting ${branch}, merge it, then run: asdlc approve ${changeId}`
130
+ });
131
+ }
132
+ }
133
+
86
134
  const changedFiles = (git(['diff-tree', '--no-commit-id', '--name-only', '-r', 'HEAD^1', 'HEAD'], repoRoot, { allowFail: true }) ?? '')
87
135
  .split(/\r?\n/).filter(Boolean);
88
136
  // was the change already on main BEFORE this merge?
@@ -156,6 +204,9 @@ export function register(program) {
156
204
  .command('approve [changeId]')
157
205
  .description('record the approved spec after the spec PR merges (tags approved/<ID> + marks READY_FOR_IMPL)')
158
206
  .option('--sha <sha>', 'merge commit (default: HEAD)')
207
+ .option('--protected-branch <ref>', 'branch the approved spec must be merged into')
208
+ .option('--target-branch <ref>', 'target branch to check for spec merge')
209
+ .option('--mode <mode>', 'workflow mode override (supervised, spec-first, auto)')
159
210
  .option('--no-tag', 'skip the approved/<ID> git tag')
160
211
  .option('--no-commit', 'stamp without committing')
161
212
  .option('--repo-root <path>')
@@ -4,7 +4,7 @@ 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
6
  import { checkSchema, builtinSchemaVersion, localOverride, installSchema } from '../lib/schema.js';
7
- import { refreshAgents } from '../lib/agents.js';
7
+ import { refreshAgents, hasCurrentRouting } from '../lib/agents.js';
8
8
  import { readYaml } from '../lib/yaml.js';
9
9
  import { git } from '../lib/git.js';
10
10
  import { log, dim } from '../lib/log.js';
@@ -70,8 +70,10 @@ export function doctor(opts = {}) {
70
70
  } catch { /* ignore */ }
71
71
 
72
72
  const agents = path.join(repoRoot, 'AGENTS.md');
73
- hasRouting = exists(agents) && readText(agents).includes('<!-- asdlc:routing -->');
74
- add('AGENTS.md routing', hasRouting ? 'pass' : 'warn', hasRouting ? '' : 'missing (run `asdlc init`)');
73
+ const agentsText = exists(agents) ? readText(agents) : '';
74
+ hasRouting = hasCurrentRouting(agentsText);
75
+ add('AGENTS.md routing', hasRouting ? 'pass' : 'warn',
76
+ hasRouting ? '' : (agentsText.includes('<!-- asdlc:routing -->') ? 'outdated (run `asdlc doctor --fix`)' : 'missing (run `asdlc init`)'));
75
77
 
76
78
  const gstatus = graphStatus(repoRoot);
77
79
  add('knowledge graph', gstatus === 'fresh' ? 'pass' : 'warn', gstatus);
@@ -4,15 +4,14 @@ import { execFileSync } from 'node:child_process';
4
4
  import { exists, readText, writeText } from '../lib/fs.js';
5
5
  import { changeDir } from '../lib/paths.js';
6
6
  import { requireRepo, toChangeSlug } from '../lib/cliutil.js';
7
- import { git, isGitRepo, changeOnRef, lastCommitTouching, safeCommit } from '../lib/git.js';
7
+ import { git, isGitRepo, changeOnRef, lastCommitTouching, safeCommit, resolveDefaultBranch } from '../lib/git.js';
8
8
  import { loadPolicy, matchesAny } from '../lib/policy.js';
9
9
  import { runLint } from './lint.js';
10
10
  import { runVerify } from './verify.js';
11
11
  import { fail } from '../lib/errors.js';
12
12
  import { log } from '../lib/log.js';
13
13
  import { assess, renderLabels, renderPRComment } from '../assess/index.js';
14
- import { readEffectiveLevel } from '../lib/level.js';
15
- import { resolveWorkflowMode } from '../lib/config.js';
14
+ import { readEffectiveLevel, resolveTopology } from '../lib/level.js';
16
15
 
17
16
  const SAFE_ENV_TEMPLATE_RE = /(^|\/)\.env\.(example|sample|template|defaults|schema)$/i;
18
17
  const SENSITIVE_OR_DUMP_PATTERNS = [
@@ -129,13 +128,6 @@ export async function createPR(changeId, targetBranch, opts = {}) {
129
128
  const repoRoot = requireRepo(opts);
130
129
  if (!isGitRepo(repoRoot)) fail('not a git repository');
131
130
 
132
- if (!targetBranch) {
133
- fail('target branch is required (e.g. `asdlc pr <changeId> main` or `asdlc pr <changeId> develop`)', {
134
- code: 'MISSING_TARGET_BRANCH',
135
- hint: 'specify the base branch to merge into: asdlc pr <changeId> <targetBranch>',
136
- });
137
- }
138
-
139
131
  const slug = toChangeSlug(changeId);
140
132
  const cdir = changeDir(repoRoot, slug);
141
133
  if (!exists(cdir)) fail(`change '${slug}' not found`);
@@ -143,6 +135,11 @@ export async function createPR(changeId, targetBranch, opts = {}) {
143
135
  // Detect PR type 100% automatically (Spec PR vs Impl PR)
144
136
  const metaPath = path.join(cdir, '.openspec.yaml');
145
137
  const metaText = exists(metaPath) ? readText(metaPath) : '';
138
+ const tbMatch = metaText.match(/^\s*targetBranch:\s*['"]?([^\s'"]+)['"]?\s*$/m);
139
+ const metaTargetBranch = tbMatch ? tbMatch[1] : null;
140
+ if (!targetBranch) {
141
+ targetBranch = metaTargetBranch || resolveDefaultBranch(repoRoot).replace(/^origin\//, '');
142
+ }
146
143
  const statusMatch = metaText.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
147
144
  const changeStatus = statusMatch ? statusMatch[1].toLowerCase() : '';
148
145
  const shaMatch = metaText.match(/^\s*specSha:\s*['"]?([^\s'"]+)['"]?\s*$/m);
@@ -172,10 +169,9 @@ export async function createPR(changeId, targetBranch, opts = {}) {
172
169
  const allPotentialFiles = [...diffFilesPre, ...uncommittedFiles];
173
170
  const hasSourceChanges = allPotentialFiles.some((f) => !f.startsWith(`openspec/changes/${slug}/`));
174
171
 
175
- const lvlMatch = metaText.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
176
- const changeLevel = lvlMatch ? lvlMatch[1].toUpperCase() : null;
177
- const resolvedMode = resolveWorkflowMode({ cliMode: opts.mode, repoRoot, baseRef: targetBranch });
178
- const isSinglePr = (changeLevel === 'L0' || changeLevel === 'L1') && resolvedMode !== 'spec-first' && !metaText.match(/^\s*workflowMode:\s*['"]?spec-first['"]?/m);
172
+ const topology = resolveTopology({ repoRoot, slug, baseRef: targetBranch, cliMode: opts.mode });
173
+ const resolvedMode = topology.mode;
174
+ const isSinglePr = topology.isSinglePr;
179
175
 
180
176
  let prType;
181
177
  if (opts.type) {
@@ -598,7 +594,7 @@ export function parseRemoteUrl(url, opts = {}) {
598
594
 
599
595
  export function register(program) {
600
596
  program
601
- .command('pr <changeId> <targetBranch>')
597
+ .command('pr <changeId> [targetBranch]')
602
598
  .description('automatically open a Spec or Implementation PR: auto-detects stage, pre-flight checks, pushes branch, and attaches labels for CI AI review')
603
599
  .option('--mode <mode>', 'workflow mode: supervised (default) | spec-first | auto')
604
600
  .option('--repo-root <path>')
@@ -2,19 +2,18 @@ import path from 'node:path';
2
2
  import { exists, readText, walkFiles, listDir } from '../lib/fs.js';
3
3
  import { changeDir, openspecDir, CHANGES_DIR } from '../lib/paths.js';
4
4
  import { requireRepo, toChangeSlug, jsonOut } from '../lib/cliutil.js';
5
- import { lastCommitTouching } from '../lib/git.js';
5
+ import { lastCommitTouching, resolveDefaultBranch } from '../lib/git.js';
6
6
  import { verdictOf } from './lint.js';
7
7
  import { countUncheckedTasks } from './verify.js';
8
8
  import { log } from '../lib/log.js';
9
- import { isSinglePrLevel } from '../lib/level.js';
10
- import { resolveWorkflowMode } from '../lib/config.js';
9
+ import { resolveTopology } from '../lib/level.js';
11
10
 
12
11
  // "Where am I?" for a change - a read-only view of the 7 stages from the working
13
12
  // tree + git. Useful for humans and for an agent deciding the next command.
14
13
  export function statusChange(changeId, opts = {}) {
15
14
  const repoRoot = requireRepo(opts);
16
15
  const slug = toChangeSlug(changeId);
17
- const branch = opts.protectedBranch ?? 'origin/main';
16
+ const branch = opts.protectedBranch ?? resolveDefaultBranch(repoRoot);
18
17
  const cdir = changeDir(repoRoot, slug);
19
18
 
20
19
  if (!exists(cdir)) {
@@ -43,33 +42,44 @@ export function statusChange(changeId, opts = {}) {
43
42
 
44
43
  const metaPath = path.join(cdir, '.openspec.yaml');
45
44
  let metaText = exists(metaPath) ? readText(metaPath) : '';
46
- const levelMatch = metaText.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
47
- const level = levelMatch ? levelMatch[1].toUpperCase() : 'L1';
48
45
 
49
- const resolvedMode = resolveWorkflowMode({ cliMode: opts.mode, repoRoot, baseRef: branch });
50
- const isSinglePr = isSinglePrLevel(level) && resolvedMode !== 'spec-first' && !metaText.match(/^\s*workflowMode:\s*['"]?spec-first['"]?/m);
46
+ const topology = resolveTopology({ repoRoot, slug, baseRef: branch, cliMode: opts.mode });
47
+ const isSinglePr = topology.isSinglePr;
48
+ const level = topology.effectiveLevel || 'unlevelled';
49
+
50
+ const stage3Label = isSinglePr
51
+ ? '3 spec approval (co-located in single PR; human sign-off at merge)'
52
+ : `3 spec approved on ${branch}`;
51
53
 
52
54
  const stage = [
53
55
  ['1 explore (draft)', has('explore.md')],
54
56
  ['2 proposal.md', has('proposal.md')],
55
57
  ['2 spec delta', specFiles.length > 0],
56
- ['3 spec approved on ' + branch, isSinglePr ? true : Boolean(approvedSha)],
58
+ [stage3Label, isSinglePr ? '~' : Boolean(approvedSha)],
57
59
  ['4 tasks complete', unchecked === 0],
58
60
  ];
59
61
 
60
62
  let next;
61
63
  if (!has('explore.md') && !has('proposal.md')) next = `asdlc new ${changeId}`;
62
64
  else if (!has('proposal.md') || specFiles.length === 0) next = 'author proposal.md + specs/**';
63
- else if (!isSinglePr && !approvedSha) next = `run: asdlc lint ${changeId} && asdlc pr ${changeId} (after independent spec review & merge, run: asdlc approve ${changeId})`;
64
- else if (unchecked !== 0) next = `asdlc apply ${changeId}, then complete tasks in tasks.md`;
65
- else next = `asdlc verify ${changeId}`;
65
+ else if (isSinglePr) {
66
+ if (!has('tasks.md')) next = `author tasks.md, then run: asdlc apply ${changeId}`;
67
+ else if (unchecked !== 0) next = `asdlc apply ${changeId}, then complete tasks in tasks.md`;
68
+ else next = `asdlc verify ${changeId} && asdlc pr ${changeId} ${branch}`;
69
+ } else if (!approvedSha) {
70
+ next = `run: asdlc lint ${changeId} && asdlc pr ${changeId} (after independent spec review & merge, run: asdlc approve ${changeId})`;
71
+ } else if (unchecked !== 0) {
72
+ next = `asdlc apply ${changeId}, then complete tasks in tasks.md`;
73
+ } else {
74
+ next = `asdlc verify ${changeId}`;
75
+ }
66
76
 
67
77
  if (opts.json) {
68
- jsonOut({
78
+ const payload = {
69
79
  change: slug,
70
80
  exists: true,
71
81
  level,
72
- stage: stage.map(([name, ok]) => ({ name, ok })),
82
+ stage: stage.map(([name, ok]) => ({ name, ok: ok === '~' ? true : Boolean(ok) })),
73
83
  next,
74
84
  checks: {
75
85
  explore: has('explore.md'),
@@ -78,12 +88,20 @@ export function statusChange(changeId, opts = {}) {
78
88
  approvedSha,
79
89
  tasksComplete: unchecked === 0,
80
90
  }
81
- });
91
+ };
92
+ if (isSinglePr) {
93
+ payload.mode = 'single-pr';
94
+ payload.approvalTrack = 'colocated';
95
+ }
96
+ jsonOut(payload);
82
97
  return 0;
83
98
  }
84
99
 
85
100
  log.plain(`change: ${slug}`);
86
- for (const [name, ok] of stage) log.plain(` [${ok ? 'x' : ' '}] ${name}`);
101
+ for (const [name, ok] of stage) {
102
+ const mark = ok === '~' ? '~' : (ok ? 'x' : ' ');
103
+ log.plain(` [${mark}] ${name}`);
104
+ }
87
105
  log.plain('');
88
106
  log.plain(`next: ${next}`);
89
107
  return 0;
@@ -93,7 +111,7 @@ export function statusChange(changeId, opts = {}) {
93
111
  // Deliberately excludes completed/archived changes to keep output compact and scannable.
94
112
  export function statusPortfolio(opts = {}) {
95
113
  const repoRoot = requireRepo(opts);
96
- const branch = opts.protectedBranch ?? 'origin/main';
114
+ const branch = opts.protectedBranch ?? resolveDefaultBranch(repoRoot);
97
115
  const cdirRoot = path.join(openspecDir(repoRoot), CHANGES_DIR);
98
116
 
99
117
  if (!exists(cdirRoot)) {
@@ -122,8 +140,9 @@ export function statusPortfolio(opts = {}) {
122
140
  const specFiles = exists(path.join(cdir, 'specs'))
123
141
  ? walkFiles(path.join(cdir, 'specs')).filter((f) => f.endsWith('spec.md')) : [];
124
142
 
125
- const levelMatch = metaText.match(/^\s*level:\s*['"]?([^\s'"]+)['"]?\s*$/m);
126
- const level = levelMatch ? levelMatch[1].toUpperCase() : 'L1';
143
+ const topology = resolveTopology({ repoRoot, slug, baseRef: branch, cliMode: opts.mode });
144
+ const isSinglePr = topology.isSinglePr;
145
+ const level = topology.effectiveLevel || 'unlevelled';
127
146
 
128
147
  const reqMatch = metaText.match(/^\s*requirement:\s*([^\r\n]+)/m);
129
148
  let requirement = reqMatch ? reqMatch[1].trim() : null;
@@ -134,10 +153,7 @@ export function statusPortfolio(opts = {}) {
134
153
  const locked = [`openspec/changes/${slug}/proposal.md`, `openspec/changes/${slug}/specs`];
135
154
  const approvedSha = lastCommitTouching(repoRoot, branch, locked);
136
155
  const unchecked = has('tasks.md') ? countUncheckedTasks(readText(path.join(cdir, 'tasks.md'))) : null;
137
- const resolvedMode = resolveWorkflowMode({ cliMode: opts.mode, repoRoot, baseRef: branch });
138
- const isSinglePr = isSinglePrLevel(level) && resolvedMode !== 'spec-first' && !metaText.match(/^\s*workflowMode:\s*['"]?spec-first['"]?/m);
139
- const statusMatch = metaText.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
140
- const recordedStatus = statusMatch ? statusMatch[1].toLowerCase() : null;
156
+ const recordedStatus = topology.declaredStatus;
141
157
 
142
158
  let stage = '';
143
159
  let next = '';
@@ -149,7 +165,10 @@ export function statusPortfolio(opts = {}) {
149
165
  stage = 'Drafting Specs';
150
166
  next = `author proposal.md + specs/**`;
151
167
  } else if (isSinglePr) {
152
- if (unchecked === null) {
168
+ if (!has('tasks.md')) {
169
+ stage = 'Ready for Impl';
170
+ next = `author tasks.md, then run: asdlc apply ${slug}`;
171
+ } else if (unchecked === null) {
153
172
  stage = 'Ready for Impl';
154
173
  next = `asdlc apply ${slug}`;
155
174
  } else if (unchecked > 0) {
@@ -6,7 +6,7 @@ import { openspecDir, changeDir } from '../lib/paths.js';
6
6
  import { requireRepo, toChangeSlug, readLintConfig, jsonOut } from '../lib/cliutil.js';
7
7
  import { validateChange } from '../lib/openspec.js';
8
8
  import { runShell } from '../lib/exec.js';
9
- import { lastCommitTouching, changeOnRef, git } from '../lib/git.js';
9
+ import { lastCommitTouching, changeOnRef, git, resolveDefaultBranch } from '../lib/git.js';
10
10
  import { lintSpecText, countBlockers } from '../lib/speclint.js';
11
11
  import { checkSchema } from '../lib/schema.js';
12
12
  import { loadPolicy, isAdvisory, DEFAULT_POLICY, matchesAny } from '../lib/policy.js';
@@ -195,7 +195,6 @@ export function extractJson(text) {
195
195
  export function runVerify(changeId, opts = {}) {
196
196
  const results = [];
197
197
  const add = (name, status, detail) => results.push({ name, status, detail });
198
- const branch = opts.protectedBranch ?? 'origin/main';
199
198
 
200
199
  let repoRoot;
201
200
  try {
@@ -206,6 +205,8 @@ export function runVerify(changeId, opts = {}) {
206
205
  return finish(results, DEFAULT_POLICY);
207
206
  }
208
207
 
208
+ const branch = opts.protectedBranch ?? resolveDefaultBranch(repoRoot);
209
+
209
210
  const slug = toChangeSlug(changeId);
210
211
  const base = opts.base ?? branch;
211
212
  const head = opts.head ?? 'HEAD';
@@ -266,7 +267,7 @@ export function runVerify(changeId, opts = {}) {
266
267
  } else if (isSinglePr) {
267
268
  add('approved-spec', 'pass', `${changeLevel || 'single-pr'} single-PR mode (spec approval co-located in implementation PR)`);
268
269
  } else if (!approvedSha) {
269
- add('approved-spec', 'fail', `no commit on locked paths is merged into ${branch} (not approved)`);
270
+ add('approved-spec', 'fail', `no commit on locked paths is merged into ${branch} (not approved; ensure target branch is fetched, e.g. git fetch)`);
270
271
  } else if (specSha && specSha !== approvedSha) {
271
272
  add('approved-spec', 'fail', `declared specSha ${specSha.slice(0, 8)} != approved commit ${approvedSha.slice(0, 8)}`);
272
273
  } else {
@@ -285,7 +286,7 @@ export function runVerify(changeId, opts = {}) {
285
286
  add('flow-state', 'pass', `${changeLevel || 'single-pr'} single-PR mode (direct implementation)`);
286
287
  } else {
287
288
  add('flow-state', status === 'ready_for_impl' ? 'pass' : 'fail',
288
- status === 'ready_for_impl' ? 'READY_FOR_IMPL' : `status is ${status ?? 'unset'} (run: asdlc approve ${changeId})`);
289
+ status === 'ready_for_impl' ? 'READY_FOR_IMPL' : `status is ${status ?? 'unset'} (ensure target branch is fetched, then run: asdlc approve ${changeId})`);
289
290
  }
290
291
 
291
292
  const isCI = opts.ci !== undefined
package/src/lib/agents.js CHANGED
@@ -11,27 +11,26 @@ import { graphExists } from './graphify.js';
11
11
  export const ROUTING_MARKER = '<!-- asdlc:routing -->';
12
12
  export const STATUS_MARKER = '<!-- asdlc:system-status -->';
13
13
 
14
+ export function hasCurrentRouting(text = '') {
15
+ return String(text).includes(ROUTING_MARKER) && String(text).includes('Two-Track Execution Flow');
16
+ }
17
+
14
18
  const ROUTING_BLOCK = `${ROUTING_MARKER}
15
- ## Agentic SDLC — the 7 stages (one front door)
19
+ ## Agentic SDLC — Two-Track Execution Flow
20
+
21
+ Everything runs through \`asdlc\` - do NOT call \`openspec ...\` directly. Check current level and mode with \`asdlc status <ID>\`.
16
22
 
17
- Everything runs through \`asdlc\` - do NOT call \`openspec ...\` directly. There is no
18
- raw escape hatch: the wrappers ARE the guards (graph refresh, approval, checks).
23
+ ### 📌 Track A: High-Risk & Core Modules (L2/L3 or spec-first)
24
+ Dual-PR lifecycle with cryptographic intent lock:
25
+ 1. \`asdlc new "<intent>"\` (scaffold + explore + **grill-me interview embedded**, settle \`clarifications.md\`, then author proposal/specs) ->
26
+ 2. \`asdlc lint <ID>\` -> 3. \`asdlc pr <ID> <target>\` (Spec PR) -> 4. Human merge & \`asdlc approve <ID>\` ->
27
+ 5. \`asdlc apply <ID>\` (TDD loop) -> 6. \`asdlc verify <ID>\` -> 7. \`asdlc pr <ID> <target>\` (Impl PR) -> 8. \`asdlc archive <ID>\`.
19
28
 
20
- 1. **new** - \`asdlc new "<requirement>" [--batch-grill] [--no-grill]\`: scaffold the change (derives slug from intent) +
21
- refresh the knowledge graph + write \`explore.md\` + seed \`clarifications.md\`.
22
- ▶ **IMMEDIATE ACTION FOR AGENT**: DO NOT stop or ask permission. In the SAME interaction turn,
23
- ground yourself in \`explore.md\` and codebase facts. Run high-signal conversational **grill-me**
24
- (or **batch-grill-me** if \`--batch-grill\` was passed) with anti-fatigue guardrails (look facts up yourself,
25
- focus on material trade-offs, lead with recommendations, early-exit on agreement), and record settled decisions
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/**\`. (Independent AI Review is executed in an isolated agent session via \`asdlc-spec-review\` / \`asdlc-impl-review\` skills).
28
- 2. **grill** - (embedded in Stage 2) settle all design forks in \`clarifications.md\` BEFORE writing specs.
29
- 3. **lint** - \`asdlc lint <ID>\`: artifacts + BDD/acceptance criteria. Open Spec PR via \`asdlc pr <ID> <targetBranch>\`.
30
- 4. **approve** - human/TL approves (via PR merge, on PR, or in-place); \`asdlc approve <ID>\` records approved SHA + READY_FOR_IMPL.
31
- 5. **apply** - \`asdlc apply <ID>\` (guard: the spec must be approved), then
32
- \`/opsx-apply\` with task-level TDD + task-level converge.
33
- 6. **verify** - \`asdlc verify <ID>\`: approved SHA, artifacts, tasks complete, tests, AI.
34
- 7. **archive** - \`asdlc archive [<ID> | --merged]\`: post-merge compaction syncing specs to openspec/specs/ (updates AGENTS.md only on \`--agents\` or constitutional changes).
29
+ ### ⚡ Track B: Bounded & Routine Modules (L0/L1 under supervised/auto)
30
+ Fast-path Single-PR lifecycle (Spec & code in one PR, human confirms at merge):
31
+ 1. \`asdlc new "<intent>"\` (grill-me interview embedded) -> 2. Draft \`specs/\` & \`tasks.md\` ->
32
+ 3. \`asdlc apply <ID>\` (directly starts TDD loop; **separate Spec PR and \`asdlc approve\` are waived**) ->
33
+ 4. \`asdlc verify <ID>\` -> 5. \`asdlc pr <ID> <target>\` (Single PR; human Approve at merge is still required under supervised; auto per policy) -> 6. \`asdlc archive <ID>\`.
35
34
 
36
35
  Need orientation? \`asdlc status <ID>\` (where am I / next command) and \`asdlc doctor\`
37
36
  (environment health). A bad spec is never edited: close it and \`asdlc new\` again.`;
package/src/lib/git.js CHANGED
@@ -123,3 +123,11 @@ export function getBatchGitFiles(cwd = process.cwd(), ref = 'HEAD', filePaths =
123
123
  }
124
124
  return result;
125
125
  }
126
+
127
+ export function resolveDefaultBranch(repoRoot) {
128
+ for (const candidate of ['origin/main', 'origin/master', 'main', 'master']) {
129
+ const existsRef = git(['rev-parse', '--verify', candidate], repoRoot, { allowFail: true });
130
+ if (existsRef) return candidate;
131
+ }
132
+ return 'main';
133
+ }
package/src/lib/level.js CHANGED
@@ -2,10 +2,11 @@ import path from 'node:path';
2
2
  import { exists, readText } from './fs.js';
3
3
  import { changeDir } from './paths.js';
4
4
  import { toChangeSlug } from './cliutil.js';
5
- import { git } from './git.js';
5
+ import { git, resolveDefaultBranch } from './git.js';
6
6
  import { assess, loadMaxHistoryLevel, loadRiskHistory } from '../assess/index.js';
7
7
  import { deriveGovernance } from '../assess/governance.js';
8
8
  import { RISK_LEVELS, LEVEL_RANK } from '../assess/rules/builtin.js';
9
+ import { resolveWorkflowMode } from './config.js';
9
10
  import { fail } from './errors.js';
10
11
 
11
12
  export const LEVELS = RISK_LEVELS;
@@ -181,3 +182,61 @@ export function readEffectiveLevel(repoRoot, changeId, opts = {}) {
181
182
  };
182
183
  }
183
184
 
185
+ export function resolveTopology({ repoRoot, slug, baseRef, cliMode } = {}) {
186
+ const effectiveBaseRef = baseRef || (repoRoot ? resolveDefaultBranch(repoRoot) : 'origin/main');
187
+ const eff = readEffectiveLevel(repoRoot, slug, { baseRef: effectiveBaseRef });
188
+ const cdir = repoRoot && slug ? changeDir(repoRoot, slug) : null;
189
+ const metaPath = cdir ? path.join(cdir, '.openspec.yaml') : null;
190
+ let metaText = '';
191
+ let declaredWorkflowMode = null;
192
+ let declaredStatus = null;
193
+ if (metaPath && exists(metaPath)) {
194
+ metaText = readText(metaPath);
195
+ const mMode = metaText.match(/^\s*workflowMode:\s*['"]?([^\s'"]+)['"]?\s*$/m);
196
+ if (mMode) declaredWorkflowMode = mMode[1].toLowerCase();
197
+ const mStat = metaText.match(/^\s*status:\s*['"]?([^\s'"]+)['"]?\s*$/m);
198
+ if (mStat) declaredStatus = mStat[1].toLowerCase();
199
+ }
200
+
201
+ const effectiveLevel = eff?.effectiveLevel || eff?.declaredLevel || null;
202
+ const declaredLevel = eff?.declaredLevel || null;
203
+ const tampered = Boolean(eff?.tampered);
204
+ const mode = resolveWorkflowMode({ cliMode, repoRoot, baseRef: effectiveBaseRef });
205
+
206
+ let isSinglePr = false;
207
+ let reason = '';
208
+
209
+ if (tampered) {
210
+ isSinglePr = false;
211
+ reason = `governance level tampered (declared ${declaredLevel} < history ${eff?.maxHistoryLevel})`;
212
+ } else if (!effectiveLevel) {
213
+ isSinglePr = false;
214
+ reason = 'unlevelled change requires Dual-PR (Spec-First)';
215
+ } else if (mode === 'spec-first') {
216
+ isSinglePr = false;
217
+ reason = 'workflow mode is spec-first';
218
+ } else if (declaredWorkflowMode === 'spec-first') {
219
+ isSinglePr = false;
220
+ reason = 'change workflowMode is spec-first';
221
+ } else if (!isSinglePrLevel(effectiveLevel)) {
222
+ isSinglePr = false;
223
+ reason = `governance level ${effectiveLevel} requires Dual-PR (Spec-First)`;
224
+ } else {
225
+ isSinglePr = true;
226
+ reason = `Single-PR mode (${effectiveLevel})`;
227
+ }
228
+
229
+ return {
230
+ isSinglePr,
231
+ effectiveLevel,
232
+ declaredLevel,
233
+ tampered,
234
+ mode,
235
+ reason,
236
+ workflowMode: isSinglePr ? 'single-pr' : 'spec-first',
237
+ declaredStatus,
238
+ declaredWorkflowMode
239
+ };
240
+ }
241
+
242
+