@akjamie/agentic-sdlc 1.8.0 → 1.9.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.
@@ -0,0 +1,145 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { readYaml, stringifyYaml } from './yaml.js';
5
+ import { loadPolicy } from './policy.js';
6
+ import { fail } from './errors.js';
7
+
8
+ export const GLOBAL_CONFIG_DIR = path.join(os.homedir(), '.asdlc');
9
+ export const GLOBAL_CONFIG_FILE = path.join(GLOBAL_CONFIG_DIR, 'config.yaml');
10
+
11
+ export const VALID_WORKFLOW_MODES = ['supervised', 'spec-first', 'auto'];
12
+ export const DEFAULT_WORKFLOW_MODE = 'supervised';
13
+
14
+ export const MODE_RANK = {
15
+ auto: 1,
16
+ supervised: 2,
17
+ 'spec-first': 3
18
+ };
19
+
20
+ /**
21
+ * Loads machine-level global config from ~/.asdlc/config.yaml.
22
+ * Returns empty object if file does not exist or fails to parse.
23
+ */
24
+ export function loadGlobalConfig(configPath = GLOBAL_CONFIG_FILE) {
25
+ try {
26
+ if (fs.existsSync(configPath)) {
27
+ const parsed = readYaml(configPath);
28
+ return parsed && typeof parsed === 'object' ? parsed : {};
29
+ }
30
+ } catch {
31
+ // Ignore read errors, fall back to empty config
32
+ }
33
+ return {};
34
+ }
35
+
36
+ /**
37
+ * Writes machine-level global config to ~/.asdlc/config.yaml with 0600 permissions.
38
+ */
39
+ export function saveGlobalConfig(config, configPath = GLOBAL_CONFIG_FILE) {
40
+ const dir = path.dirname(configPath);
41
+ if (!fs.existsSync(dir)) {
42
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
43
+ }
44
+ const text = stringifyYaml(config);
45
+ fs.writeFileSync(configPath, text, { encoding: 'utf8', mode: 0o600 });
46
+ try {
47
+ fs.chmodSync(configPath, 0o600);
48
+ } catch {
49
+ // Best-effort chmod on Windows platforms
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Validates whether a mode string is valid.
55
+ * Fails closed if 'single-pr' (internal topology, not configurable mode) or unknown string.
56
+ */
57
+ export function validateWorkflowMode(mode) {
58
+ if (!mode) return DEFAULT_WORKFLOW_MODE;
59
+ const norm = String(mode).toLowerCase().trim();
60
+ if (norm === 'single-pr') {
61
+ fail("Configured mode cannot be 'single-pr'. Valid modes are: 'supervised', 'spec-first', 'auto'. Single-PR is an internal topology granted to L0/L1 changes.", {
62
+ code: 'INVALID_WORKFLOW_MODE',
63
+ hint: "Use 'supervised' (default), 'spec-first', or 'auto'."
64
+ });
65
+ }
66
+ if (!VALID_WORKFLOW_MODES.includes(norm)) {
67
+ fail(`Invalid workflow mode '${mode}'. Allowed modes: supervised, spec-first, auto`, {
68
+ code: 'INVALID_WORKFLOW_MODE',
69
+ hint: "Choose one of 'supervised', 'spec-first', 'auto'."
70
+ });
71
+ }
72
+ return norm;
73
+ }
74
+
75
+ /**
76
+ * Resolves the effective workflow mode across the 5-tier precedence chain:
77
+ * CLI (--mode) > Env (ASDLC_WORKFLOW_MODE) > Repo (.sdlc/policy.yaml) > Global (~/.asdlc/config.yaml) > Default ('supervised')
78
+ *
79
+ * Enforces monotonic policy tightening against repo floor:
80
+ * If repo policy specifies a workflow_mode floor (e.g. 'supervised' or 'spec-first'),
81
+ * any higher-tier setting cannot downgrade security below that floor (fails with ILLEGAL_MODE_DOWNGRADE).
82
+ */
83
+ export function resolveWorkflowMode({
84
+ cliMode = null,
85
+ envMode = null,
86
+ repoPolicy = null,
87
+ repoRoot = null,
88
+ globalConfig = null,
89
+ baseRef = null,
90
+ customGlobalPath = null
91
+ } = {}) {
92
+ // 1. Resolve Repo Floor
93
+ let repoMode = repoPolicy?.workflow_mode ?? null;
94
+ if (!repoMode && repoRoot) {
95
+ try {
96
+ const pol = loadPolicy(repoRoot, { baseRef });
97
+ if (pol?.workflow_mode) {
98
+ repoMode = pol.workflow_mode;
99
+ }
100
+ } catch {
101
+ // ignore
102
+ }
103
+ }
104
+ const repoFloor = repoMode ? validateWorkflowMode(repoMode) : null;
105
+
106
+ // 2. Resolve requested mode by precedence:
107
+ // CLI > Env > Repo > Global > Default
108
+ let requestedMode = null;
109
+ let source = null;
110
+
111
+ if (cliMode) {
112
+ requestedMode = validateWorkflowMode(cliMode);
113
+ source = 'CLI';
114
+ } else if (envMode || process.env.ASDLC_WORKFLOW_MODE) {
115
+ requestedMode = validateWorkflowMode(envMode || process.env.ASDLC_WORKFLOW_MODE);
116
+ source = 'Env';
117
+ } else if (repoFloor) {
118
+ requestedMode = repoFloor;
119
+ source = 'Repo';
120
+ } else {
121
+ const globalCfg = globalConfig || loadGlobalConfig(customGlobalPath || GLOBAL_CONFIG_FILE);
122
+ if (globalCfg?.workflow_mode) {
123
+ requestedMode = validateWorkflowMode(globalCfg.workflow_mode);
124
+ source = 'Global';
125
+ } else {
126
+ requestedMode = DEFAULT_WORKFLOW_MODE;
127
+ source = 'Default';
128
+ }
129
+ }
130
+
131
+ // 3. Enforce monotonic policy tightening against Repo Floor:
132
+ // spec-first (3) > supervised (2) > auto (1)
133
+ if (repoFloor && source !== 'Repo') {
134
+ const requestedRank = MODE_RANK[requestedMode] ?? 0;
135
+ const floorRank = MODE_RANK[repoFloor] ?? 0;
136
+ if (requestedRank < floorRank) {
137
+ fail(`cannot downgrade workflow mode to '${requestedMode}': repository policy enforces '${repoFloor}' as minimum security floor`, {
138
+ code: 'ILLEGAL_MODE_DOWNGRADE',
139
+ hint: `Repository policy (.sdlc/policy.yaml) sets a minimum floor of '${repoFloor}'. You may tighten it to stricter modes, but cannot relax it.`
140
+ });
141
+ }
142
+ }
143
+
144
+ return requestedMode;
145
+ }
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,14 +2,16 @@ 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
+ import { deriveGovernance } from '../assess/governance.js';
7
8
  import { RISK_LEVELS, LEVEL_RANK } from '../assess/rules/builtin.js';
9
+ import { resolveWorkflowMode } from './config.js';
8
10
  import { fail } from './errors.js';
9
11
 
10
12
  export const LEVELS = RISK_LEVELS;
11
13
 
12
- export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, changeId, agentContext = null } = {}) {
14
+ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, changeId, agentContext = null, mode = 'supervised' } = {}) {
13
15
  // Always run assessment to establish immutable baseline in history
14
16
  const result = assess({
15
17
  stage: 'new',
@@ -17,6 +19,7 @@ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, c
17
19
  requirement,
18
20
  agentContext,
19
21
  repoRoot,
22
+ mode,
20
23
  persist: Boolean(repoRoot && changeId)
21
24
  });
22
25
 
@@ -35,6 +38,8 @@ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, c
35
38
  reason = result.reason_codes[0];
36
39
  }
37
40
 
41
+ let finalGovernance = result.governance;
42
+
38
43
  if (explicitLevel) {
39
44
  const norm = String(explicitLevel).toUpperCase();
40
45
  if (LEVELS[norm]) {
@@ -48,16 +53,22 @@ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, c
48
53
  }
49
54
  finalLevel = norm;
50
55
  reason = `explicitly specified via --level ${norm}`;
56
+ finalGovernance = deriveGovernance({
57
+ level: finalLevel,
58
+ confidence: result.risk.confidence,
59
+ mandatory_human_review: result.vectors?.v1_intent?.mandatory_human_review || result.vectors?.v2_security?.mandatory_human_review || result.vectors?.v3_topology?.mandatory_human_review,
60
+ mode
61
+ });
51
62
  }
52
63
  }
53
64
 
54
- const isSpecFirst = finalLevel === 'L2' || finalLevel === 'L3';
55
65
  return {
56
66
  level: finalLevel,
57
67
  changeType: result.change_type,
58
68
  reason,
59
- workflowMode: isSpecFirst ? 'spec-first' : 'single-pr',
60
- implementationReview: isSpecFirst ? 'ai+human' : 'ai',
69
+ workflowMode: finalGovernance.workflow_mode,
70
+ implementationReview: finalGovernance.implementation_review,
71
+ autoApproval: finalGovernance.auto_approval,
61
72
  assessment: result
62
73
  };
63
74
  }
@@ -171,3 +182,61 @@ export function readEffectiveLevel(repoRoot, changeId, opts = {}) {
171
182
  };
172
183
  }
173
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
+
package/src/lib/risk.js CHANGED
@@ -6,7 +6,7 @@ export { RISK_LEVELS, LEVEL_RANK };
6
6
  /**
7
7
  * Backward-compatible adapter for legacy callers/tests, delegating to unified assess engine.
8
8
  */
9
- export function assessRisk({ requirement = '', changedFiles = [], currentLevel = null, repoRoot = null, agentContext = null } = {}) {
9
+ export function assessRisk({ requirement = '', changedFiles = [], currentLevel = null, repoRoot = null, agentContext = null, mode = null } = {}) {
10
10
  const result = assess({
11
11
  stage: changedFiles.length > 0 ? 'impl' : 'new',
12
12
  requirement,
@@ -15,6 +15,7 @@ export function assessRisk({ requirement = '', changedFiles = [], currentLevel =
15
15
  baseline: currentLevel ? { risk: { level: currentLevel } } : null,
16
16
  repoRoot,
17
17
  agentContext,
18
+ mode,
18
19
  persist: false
19
20
  });
20
21