@akjamie/agentic-sdlc 1.7.0 → 1.9.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.
@@ -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
@@ -81,3 +81,45 @@ export function lastCommitTouching(cwd, ref, paths = []) {
81
81
  export function changeOnRef(cwd, ref, slug) {
82
82
  return Boolean(git(['log', '-1', '--format=%H', ref, '--', `openspec/changes/${slug}/proposal.md`], cwd, { allowFail: true }));
83
83
  }
84
+
85
+ /**
86
+ * Batch-reads file contents from a git ref in a single subprocess using `git cat-file --batch`.
87
+ * Returns a Map of filePath -> content string (or null if file does not exist on ref).
88
+ */
89
+ export function getBatchGitFiles(cwd = process.cwd(), ref = 'HEAD', filePaths = []) {
90
+ const result = new Map();
91
+ if (!ref || !Array.isArray(filePaths) || filePaths.length === 0 || !isGitRepo(cwd)) return result;
92
+ try {
93
+ const input = filePaths.map((f) => `${ref}:${f.replace(/\\/g, '/')}\n`).join('');
94
+ const raw = execFileSync('git', ['-c', 'core.quotepath=off', 'cat-file', '--batch'], {
95
+ cwd,
96
+ input: Buffer.from(input, 'utf8'),
97
+ maxBuffer: 50 * 1024 * 1024,
98
+ stdio: ['pipe', 'pipe', 'ignore']
99
+ });
100
+
101
+ let offset = 0;
102
+ for (const f of filePaths) {
103
+ const headerEnd = raw.indexOf(0x0a, offset);
104
+ if (headerEnd === -1) break;
105
+ const header = raw.subarray(offset, headerEnd).toString('utf8');
106
+ offset = headerEnd + 1;
107
+
108
+ if (header.endsWith('missing')) {
109
+ result.set(f, null);
110
+ continue;
111
+ }
112
+
113
+ const parts = header.split(' ');
114
+ if (parts.length >= 3 && parts[1] === 'blob') {
115
+ const size = parseInt(parts[2], 10);
116
+ const contentBuf = raw.subarray(offset, offset + size);
117
+ result.set(f, contentBuf.toString('utf8'));
118
+ offset += size + 1;
119
+ }
120
+ }
121
+ } catch {
122
+ // If batch cat-file fails, return empty map
123
+ }
124
+ return result;
125
+ }
package/src/lib/level.js CHANGED
@@ -4,18 +4,21 @@ import { changeDir } from './paths.js';
4
4
  import { toChangeSlug } from './cliutil.js';
5
5
  import { git } 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';
8
9
  import { fail } from './errors.js';
9
10
 
10
11
  export const LEVELS = RISK_LEVELS;
11
12
 
12
- export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, changeId } = {}) {
13
+ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, changeId, agentContext = null, mode = 'supervised' } = {}) {
13
14
  // Always run assessment to establish immutable baseline in history
14
15
  const result = assess({
15
16
  stage: 'new',
16
17
  changeId: changeId || 'provisional',
17
18
  requirement,
19
+ agentContext,
18
20
  repoRoot,
21
+ mode,
19
22
  persist: Boolean(repoRoot && changeId)
20
23
  });
21
24
 
@@ -34,6 +37,8 @@ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, c
34
37
  reason = result.reason_codes[0];
35
38
  }
36
39
 
40
+ let finalGovernance = result.governance;
41
+
37
42
  if (explicitLevel) {
38
43
  const norm = String(explicitLevel).toUpperCase();
39
44
  if (LEVELS[norm]) {
@@ -47,16 +52,22 @@ export function inferInitialLevel({ requirement = '', explicitLevel, repoRoot, c
47
52
  }
48
53
  finalLevel = norm;
49
54
  reason = `explicitly specified via --level ${norm}`;
55
+ finalGovernance = deriveGovernance({
56
+ level: finalLevel,
57
+ confidence: result.risk.confidence,
58
+ mandatory_human_review: result.vectors?.v1_intent?.mandatory_human_review || result.vectors?.v2_security?.mandatory_human_review || result.vectors?.v3_topology?.mandatory_human_review,
59
+ mode
60
+ });
50
61
  }
51
62
  }
52
63
 
53
- const isSpecFirst = finalLevel === 'L2' || finalLevel === 'L3';
54
64
  return {
55
65
  level: finalLevel,
56
66
  changeType: result.change_type,
57
67
  reason,
58
- workflowMode: isSpecFirst ? 'spec-first' : 'single-pr',
59
- implementationReview: isSpecFirst ? 'ai+human' : 'ai',
68
+ workflowMode: finalGovernance.workflow_mode,
69
+ implementationReview: finalGovernance.implementation_review,
70
+ autoApproval: finalGovernance.auto_approval,
60
71
  assessment: result
61
72
  };
62
73
  }
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 } = {}) {
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,
@@ -14,6 +14,8 @@ export function assessRisk({ requirement = '', changedFiles = [], currentLevel =
14
14
  previous: currentLevel ? { risk: { level: currentLevel } } : null,
15
15
  baseline: currentLevel ? { risk: { level: currentLevel } } : null,
16
16
  repoRoot,
17
+ agentContext,
18
+ mode,
17
19
  persist: false
18
20
  });
19
21