bastion-gate 0.0.0-stage → 0.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.
@@ -0,0 +1,305 @@
1
+ import { spawn } from 'node:child_process';
2
+ import * as fs from 'node:fs';
3
+ import * as path from 'node:path';
4
+ import { readConfigFromDisk, readPlanFromDisk, } from '../config.js';
5
+ import { execGit, getDirtyFiles, getRepoRoot, resolveRef } from '../git.js';
6
+ import { buildExecutionWaves } from '../orchestrator/dag.js';
7
+ import { createNodeWorktree, mergeNodeBranch, removeNodeWorktree, } from '../orchestrator/worktree.js';
8
+ import { runTestCommandAsync } from '../runner.js';
9
+ import { runGateAsync } from './gate.js';
10
+ const BLOCKED_COMMIT_PATTERN = /(?:^|\/)(?:\.env(?:\..+)?|\.DS_Store|Thumbs\.db)$|^\.bastion\//;
11
+ function readRunState(repoRoot) {
12
+ const p = path.join(repoRoot, '.bastion', 'run-state.json');
13
+ if (!fs.existsSync(p))
14
+ return null;
15
+ try {
16
+ return JSON.parse(fs.readFileSync(p, 'utf8'));
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ function writeRunState(repoRoot, state) {
23
+ const p = path.join(repoRoot, '.bastion', 'run-state.json');
24
+ fs.mkdirSync(path.dirname(p), { recursive: true });
25
+ fs.writeFileSync(p, JSON.stringify(state, null, 2) + '\n', 'utf8');
26
+ }
27
+ function stageSafeWorktreeFiles(worktreeDir, nodeId) {
28
+ const dirty = getDirtyFiles(worktreeDir);
29
+ if (dirty.length === 0)
30
+ return true;
31
+ const allowed = [];
32
+ const skipped = [];
33
+ for (const rel of dirty) {
34
+ if (BLOCKED_COMMIT_PATTERN.test(rel)) {
35
+ skipped.push(rel);
36
+ }
37
+ else {
38
+ allowed.push(rel);
39
+ }
40
+ }
41
+ if (skipped.length > 0) {
42
+ console.warn(`[${nodeId}] Skipping untracked/sensitive files: ${skipped.join(', ')}`);
43
+ }
44
+ if (allowed.length === 0)
45
+ return true;
46
+ console.log(`[${nodeId}] Staging ${allowed.length} file(s): ${allowed.join(', ')}`);
47
+ const addRes = execGit(['add', '--', ...allowed], worktreeDir);
48
+ if (!addRes.ok) {
49
+ console.error(`[${nodeId}] git add failed: ${addRes.stderr}`);
50
+ return false;
51
+ }
52
+ const commitRes = execGit(['-c', 'user.name=bastion', '-c', 'user.email=bastion@local', 'commit', '-m', `feat(${nodeId}): apply verified changes`], worktreeDir);
53
+ if (!commitRes.ok) {
54
+ console.error(`[${nodeId}] git commit failed: ${commitRes.stderr}`);
55
+ return false;
56
+ }
57
+ return true;
58
+ }
59
+ function runAgentAsync(commandTemplate, node, worktreeDir, attempt, feedback, logFile, promptFile, timeoutMs) {
60
+ return new Promise((resolve) => {
61
+ const fullPrompt = feedback
62
+ ? `${node.prompt}\n\n[Bastion Gate Feedback - Fix Required]\n${feedback}`
63
+ : node.prompt;
64
+ fs.mkdirSync(path.dirname(promptFile), { recursive: true });
65
+ fs.writeFileSync(promptFile, fullPrompt, 'utf8');
66
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
67
+ const logStream = fs.createWriteStream(logFile, { flags: 'w' });
68
+ const escapedSingleLine = fullPrompt.replace(/[\r\n]+/g, ' ').replace(/"/g, '\\"');
69
+ const cmd = commandTemplate
70
+ .replace(/\{promptFile\}/g, promptFile)
71
+ .replace(/\{prompt\}/g, escapedSingleLine)
72
+ .replace(/\{nodeId\}/g, node.id)
73
+ .replace(/\{worktree\}/g, worktreeDir);
74
+ const env = {
75
+ ...process.env,
76
+ BASTION_NODE_ID: node.id,
77
+ BASTION_NODE_TITLE: node.title,
78
+ BASTION_PROMPT: fullPrompt,
79
+ BASTION_PROMPT_FILE: promptFile,
80
+ BASTION_WORKTREE: worktreeDir,
81
+ BASTION_ATTEMPT: String(attempt),
82
+ BASTION_FEEDBACK: feedback,
83
+ };
84
+ delete env.NODE_TEST_CONTEXT;
85
+ const child = spawn(cmd, {
86
+ cwd: worktreeDir,
87
+ env,
88
+ shell: true,
89
+ stdio: ['ignore', 'pipe', 'pipe'],
90
+ });
91
+ let output = '';
92
+ let lineBuf = '';
93
+ let timedOut = false;
94
+ const timer = timeoutMs > 0
95
+ ? setTimeout(() => {
96
+ timedOut = true;
97
+ logStream.write(`\n[bastion] Agent timed out after ${timeoutMs}ms.\n`);
98
+ child.kill();
99
+ }, timeoutMs)
100
+ : null;
101
+ const onChunk = (chunk) => {
102
+ const text = String(chunk);
103
+ output += text;
104
+ logStream.write(text);
105
+ lineBuf += text;
106
+ const lines = lineBuf.split(/\r?\n/);
107
+ lineBuf = lines.pop() ?? '';
108
+ for (const line of lines) {
109
+ if (line.trim())
110
+ console.log(` [${node.id}] ${line}`);
111
+ }
112
+ };
113
+ child.stdout?.on('data', onChunk);
114
+ child.stderr?.on('data', onChunk);
115
+ child.on('close', (code) => {
116
+ if (timer)
117
+ clearTimeout(timer);
118
+ if (lineBuf.trim())
119
+ console.log(` [${node.id}] ${lineBuf}`);
120
+ logStream.end();
121
+ resolve({ exitCode: timedOut ? 124 : (code ?? 1), output, timedOut });
122
+ });
123
+ });
124
+ }
125
+ async function runWithConcurrency(items, limit, worker) {
126
+ const results = new Array(items.length);
127
+ let nextIdx = 0;
128
+ async function next() {
129
+ while (nextIdx < items.length) {
130
+ const idx = nextIdx++;
131
+ results[idx] = await worker(items[idx]);
132
+ }
133
+ }
134
+ const workers = Array.from({ length: Math.min(limit, items.length) }, () => next());
135
+ await Promise.all(workers);
136
+ return results;
137
+ }
138
+ export async function runSwarm(opts) {
139
+ const repoRoot = getRepoRoot(opts.cwd);
140
+ if (!repoRoot) {
141
+ console.error('[bastion] Error: not inside a git repository.');
142
+ return 1;
143
+ }
144
+ const config = readConfigFromDisk(repoRoot);
145
+ const plan = readPlanFromDisk(repoRoot);
146
+ const waves = buildExecutionWaves(plan.nodes);
147
+ const blockedTier3 = plan.nodes.filter((n) => n.tier === 3 && !n.approved);
148
+ if (blockedTier3.length > 0) {
149
+ console.error('[bastion] RUN BLOCKED: tier-3 node(s) require human approval ("approved": true):');
150
+ for (const n of blockedTier3)
151
+ console.error(` - ${n.id}: ${n.title}`);
152
+ return 1;
153
+ }
154
+ const agentCmd = opts.agentCommand ?? config.agentCommand;
155
+ if (!agentCmd) {
156
+ console.error('[bastion] Error: no agentCommand configured. Pass --agent "<cmd>" or set "agentCommand" in .bastion/config.json.');
157
+ return 1;
158
+ }
159
+ const baseRef = opts.baseRef ?? config.baseBranch;
160
+ if (!resolveRef(baseRef, repoRoot)) {
161
+ console.error(`[bastion] Error: cannot resolve baseline ref "${baseRef}".`);
162
+ return 1;
163
+ }
164
+ const dirty = getDirtyFiles(repoRoot);
165
+ if (dirty.length > 0) {
166
+ console.error('[bastion] Error: working tree is not clean. Commit or stash changes before `bastion run`.');
167
+ return 1;
168
+ }
169
+ const setupCmd = opts.setupCommand ?? config.setupCommand;
170
+ const concurrency = opts.concurrency ?? config.concurrency ?? 2;
171
+ const maxRetries = opts.maxRetries ?? config.maxRetries ?? 2;
172
+ const verifyRuns = opts.verifyRuns ?? config.verifyRuns ?? 1;
173
+ const timeoutMs = (opts.timeoutMinutes ?? config.timeoutMinutes ?? 20) * 60_000;
174
+ let integrationBranch;
175
+ const completedSet = new Set();
176
+ if (opts.resume) {
177
+ const prev = readRunState(repoRoot);
178
+ if (!prev) {
179
+ console.error('[bastion] Error: no .bastion/run-state.json found to resume from.');
180
+ return 1;
181
+ }
182
+ integrationBranch = prev.integrationBranch;
183
+ for (const id of prev.completedNodes)
184
+ completedSet.add(id);
185
+ const checkoutRes = execGit(['checkout', integrationBranch], repoRoot);
186
+ if (!checkoutRes.ok) {
187
+ console.error(`[bastion] Error checking out ${integrationBranch}: ${checkoutRes.stderr}`);
188
+ return 1;
189
+ }
190
+ console.log(`[bastion] Resuming "${integrationBranch}" (${completedSet.size} node(s) already completed).`);
191
+ }
192
+ else {
193
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
194
+ integrationBranch = `bastion/run-${stamp}`;
195
+ const checkoutRes = execGit(['checkout', '-b', integrationBranch], repoRoot);
196
+ if (!checkoutRes.ok) {
197
+ console.error(`[bastion] Error creating integration branch ${integrationBranch}: ${checkoutRes.stderr}`);
198
+ return 1;
199
+ }
200
+ writeRunState(repoRoot, { integrationBranch, baseRef, completedNodes: [] });
201
+ }
202
+ const logsDir = path.join(repoRoot, '.bastion', 'logs');
203
+ const pidFile = path.join(repoRoot, '.bastion', 'run.pid');
204
+ fs.mkdirSync(path.dirname(pidFile), { recursive: true });
205
+ fs.writeFileSync(pidFile, String(process.pid), 'utf8');
206
+ try {
207
+ console.log(`[bastion] Integration branch: ${integrationBranch}`);
208
+ console.log(`[bastion] Starting parallel swarm (${plan.nodes.length} nodes, ${waves.length} waves, concurrency=${concurrency}, maxRetries=${maxRetries})`);
209
+ for (let w = 0; w < waves.length; w++) {
210
+ const pendingNodes = waves[w].filter((n) => !completedSet.has(n.id));
211
+ if (pendingNodes.length === 0) {
212
+ console.log(`\n=== Wave ${w + 1}/${waves.length}: all nodes already completed, skipping ===`);
213
+ continue;
214
+ }
215
+ console.log(`\n=== Wave ${w + 1}/${waves.length}: [${pendingNodes.map((n) => n.id).join(', ')}] ===`);
216
+ const currentHead = resolveRef('HEAD', repoRoot);
217
+ const handles = pendingNodes.map((node) => createNodeWorktree(repoRoot, currentHead, node.id));
218
+ try {
219
+ const outcomes = await runWithConcurrency(pendingNodes.map((node, i) => ({ node, handle: handles[i] })), concurrency, async ({ node, handle }) => {
220
+ if (setupCmd) {
221
+ console.log(`[${node.id}] Running setupCommand: ${setupCmd}`);
222
+ const setupRes = await runTestCommandAsync(setupCmd, handle.dir, timeoutMs);
223
+ if (setupRes.exitCode !== 0) {
224
+ console.error(`[${node.id}] SETUP FAILED (exit ${setupRes.exitCode}):\n${setupRes.stderr || setupRes.stdout}`);
225
+ return { ok: false, node, handle };
226
+ }
227
+ }
228
+ let feedback = '';
229
+ for (let attempt = 1; attempt <= maxRetries + 1; attempt++) {
230
+ const logFile = path.join(logsDir, `${node.id}-attempt-${attempt}.log`);
231
+ const promptFile = path.join(logsDir, `${node.id}-prompt.txt`);
232
+ console.log(`[${node.id}] Attempt ${attempt}/${maxRetries + 1} in ${handle.branch} (log: .bastion/logs/${node.id}-attempt-${attempt}.log)`);
233
+ const agentRes = await runAgentAsync(agentCmd, node, handle.dir, attempt, feedback, logFile, promptFile, timeoutMs);
234
+ if (agentRes.exitCode !== 0) {
235
+ feedback = agentRes.timedOut
236
+ ? `Agent timed out after ${Math.round(timeoutMs / 60_000)}m.`
237
+ : `Agent command exited with ${agentRes.exitCode}.\n${agentRes.output.slice(-800)}`;
238
+ console.error(`[${node.id}] Agent exited ${agentRes.exitCode}, retrying...`);
239
+ continue;
240
+ }
241
+ // Check if the agent filed a test_defect dispute instead of trying to cheat
242
+ const disputeFile = path.join(handle.dir, '.bastion', 'disputes', `${node.id}.md`);
243
+ if (fs.existsSync(disputeFile)) {
244
+ const reason = fs.readFileSync(disputeFile, 'utf8').trim();
245
+ console.error(`[${node.id}] DISPUTE FILED (.bastion/disputes/${node.id}.md) — pausing node for human review:\n${reason}`);
246
+ return { ok: false, node, handle };
247
+ }
248
+ const gateRes = await runGateAsync({
249
+ cwd: handle.dir,
250
+ baseRef,
251
+ testCommandOverride: node.testCommand,
252
+ });
253
+ if (gateRes.exitCode === 0) {
254
+ if (!stageSafeWorktreeFiles(handle.dir, node.id)) {
255
+ return { ok: false, node, handle };
256
+ }
257
+ console.log(`[${node.id}] GATE PASS on attempt ${attempt}.`);
258
+ return { ok: true, node, handle };
259
+ }
260
+ feedback = gateRes.feedback;
261
+ console.error(`[${node.id}] Gate failed on attempt ${attempt}, feeding back error to agent...`);
262
+ }
263
+ return { ok: false, node, handle };
264
+ });
265
+ const failed = outcomes.filter((o) => !o.ok);
266
+ if (failed.length > 0) {
267
+ console.error(`\n[bastion] Wave ${w + 1} failed: ${failed.map((f) => f.node.id).join(', ')}`);
268
+ console.error(`[bastion] Inspect logs under .bastion/logs/. Fix and resume with: bastion run --resume`);
269
+ return 1;
270
+ }
271
+ for (const { node, handle } of outcomes) {
272
+ console.log(`[bastion] Merging ${handle.branch} -> ${integrationBranch}...`);
273
+ mergeNodeBranch(repoRoot, handle, node.title);
274
+ completedSet.add(node.id);
275
+ writeRunState(repoRoot, {
276
+ integrationBranch,
277
+ baseRef,
278
+ completedNodes: [...completedSet],
279
+ });
280
+ }
281
+ }
282
+ finally {
283
+ for (const handle of handles) {
284
+ removeNodeWorktree(repoRoot, handle);
285
+ }
286
+ }
287
+ }
288
+ console.log(`\n[bastion] All waves merged into ${integrationBranch}! Running final verification (${verifyRuns}x)...`);
289
+ for (let i = 1; i <= verifyRuns; i++) {
290
+ const res = await runTestCommandAsync(config.testCommand, repoRoot, timeoutMs);
291
+ if (res.exitCode !== 0) {
292
+ console.error(`[bastion] Final verification ${i}/${verifyRuns} FAILED (exit ${res.exitCode}).`);
293
+ return 1;
294
+ }
295
+ console.log(`[bastion] Final verification ${i}/${verifyRuns} PASS (${res.durationMs}ms).`);
296
+ }
297
+ console.log(`\n[bastion] SWARM COMPLETE on branch "${integrationBranch}".`);
298
+ console.log(` Review and merge when ready: git checkout ${baseRef} && git merge --no-ff ${integrationBranch}`);
299
+ return 0;
300
+ }
301
+ finally {
302
+ if (fs.existsSync(pidFile))
303
+ fs.unlinkSync(pidFile);
304
+ }
305
+ }
package/dist/config.js ADDED
@@ -0,0 +1,130 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { readFileAtRef, toPosixPath } from './git.js';
4
+ export const BASTION_DIR = '.bastion';
5
+ export const CONFIG_REL_PATH = '.bastion/config.json';
6
+ export const LOCK_REL_PATH = '.bastion/lock.json';
7
+ export const PLAN_REL_PATH = '.bastion/plan.json';
8
+ export const DEFAULT_EXTRA_LOCKED_PATHS = [
9
+ 'package.json',
10
+ 'package-lock.json',
11
+ 'pnpm-lock.yaml',
12
+ 'yarn.lock',
13
+ 'pyproject.toml',
14
+ 'pytest.ini',
15
+ 'setup.cfg',
16
+ 'tox.ini',
17
+ 'vitest.config.*',
18
+ 'jest.config.*',
19
+ 'tsconfig.json',
20
+ '**/conftest.py',
21
+ '**/fixtures/**',
22
+ '**/__snapshots__/**',
23
+ ];
24
+ export function createDefaultConfig(overrides) {
25
+ return {
26
+ version: 1,
27
+ testCommand: overrides?.testCommand ?? 'npm test',
28
+ baseBranch: overrides?.baseBranch ?? 'main',
29
+ lockedGlobs: overrides?.lockedGlobs ?? ['tests/**', 'test/**', '**/*.test.*', '**/*.spec.*', '**/*_test.*', '**/test_*.*'],
30
+ extraLockedPaths: overrides?.extraLockedPaths ?? DEFAULT_EXTRA_LOCKED_PATHS,
31
+ };
32
+ }
33
+ export function readConfigFromDisk(repoRoot) {
34
+ const fullPath = path.join(repoRoot, CONFIG_REL_PATH);
35
+ if (!fs.existsSync(fullPath)) {
36
+ throw new Error(`Missing ${CONFIG_REL_PATH}. Run "bastion init" first.`);
37
+ }
38
+ return parseConfigJson(fs.readFileSync(fullPath, 'utf8'), CONFIG_REL_PATH);
39
+ }
40
+ export function readConfigFromRef(ref, repoRoot) {
41
+ const raw = readFileAtRef(ref, CONFIG_REL_PATH, repoRoot);
42
+ if (raw === null) {
43
+ throw new Error(`Missing ${CONFIG_REL_PATH} on baseline ref "${ref}". Commit it to the baseline branch first.`);
44
+ }
45
+ return parseConfigJson(raw, `${ref}:${CONFIG_REL_PATH}`);
46
+ }
47
+ export function readLockFromDisk(repoRoot) {
48
+ const fullPath = path.join(repoRoot, LOCK_REL_PATH);
49
+ if (!fs.existsSync(fullPath)) {
50
+ throw new Error(`Missing ${LOCK_REL_PATH}. Run "bastion lock" first.`);
51
+ }
52
+ return parseLockJson(fs.readFileSync(fullPath, 'utf8'), LOCK_REL_PATH);
53
+ }
54
+ export function readLockFromRef(ref, repoRoot) {
55
+ const raw = readFileAtRef(ref, LOCK_REL_PATH, repoRoot);
56
+ if (raw === null) {
57
+ throw new Error(`Missing ${LOCK_REL_PATH} on baseline ref "${ref}". Commit the lock file on the baseline branch first.`);
58
+ }
59
+ return parseLockJson(raw, `${ref}:${LOCK_REL_PATH}`);
60
+ }
61
+ export function writeConfigToDisk(repoRoot, config) {
62
+ const dir = path.join(repoRoot, BASTION_DIR);
63
+ fs.mkdirSync(dir, { recursive: true });
64
+ fs.writeFileSync(path.join(repoRoot, CONFIG_REL_PATH), JSON.stringify(config, null, 2) + '\n', 'utf8');
65
+ }
66
+ export function writeLockToDisk(repoRoot, lock) {
67
+ const dir = path.join(repoRoot, BASTION_DIR);
68
+ fs.mkdirSync(dir, { recursive: true });
69
+ fs.writeFileSync(path.join(repoRoot, LOCK_REL_PATH), JSON.stringify(lock, null, 2) + '\n', 'utf8');
70
+ }
71
+ function stripBom(raw) {
72
+ return raw.replace(/^\uFEFF/, '');
73
+ }
74
+ function parseConfigJson(raw, label) {
75
+ const parsed = JSON.parse(stripBom(raw));
76
+ if (!parsed || typeof parsed.testCommand !== 'string' || !parsed.testCommand.trim()) {
77
+ throw new Error(`Invalid ${label}: "testCommand" must be a non-empty string.`);
78
+ }
79
+ return {
80
+ version: 1,
81
+ testCommand: parsed.testCommand.trim(),
82
+ baseBranch: typeof parsed.baseBranch === 'string' && parsed.baseBranch.trim() ? parsed.baseBranch.trim() : 'main',
83
+ lockedGlobs: Array.isArray(parsed.lockedGlobs) ? parsed.lockedGlobs.map(toPosixPath) : [],
84
+ extraLockedPaths: Array.isArray(parsed.extraLockedPaths) ? parsed.extraLockedPaths.map(toPosixPath) : [],
85
+ ...(typeof parsed.setupCommand === 'string' && parsed.setupCommand.trim()
86
+ ? { setupCommand: parsed.setupCommand.trim() }
87
+ : {}),
88
+ ...(typeof parsed.agentCommand === 'string' && parsed.agentCommand.trim()
89
+ ? { agentCommand: parsed.agentCommand.trim() }
90
+ : {}),
91
+ ...(Array.isArray(parsed.mutateExclude)
92
+ ? { mutateExclude: parsed.mutateExclude.map(toPosixPath) }
93
+ : {}),
94
+ ...(typeof parsed.concurrency === 'number' && parsed.concurrency > 0
95
+ ? { concurrency: Math.floor(parsed.concurrency) }
96
+ : {}),
97
+ ...(typeof parsed.maxRetries === 'number' && parsed.maxRetries >= 0
98
+ ? { maxRetries: Math.floor(parsed.maxRetries) }
99
+ : {}),
100
+ ...(typeof parsed.verifyRuns === 'number' && parsed.verifyRuns > 0
101
+ ? { verifyRuns: Math.floor(parsed.verifyRuns) }
102
+ : {}),
103
+ ...(typeof parsed.timeoutMinutes === 'number' && parsed.timeoutMinutes > 0
104
+ ? { timeoutMinutes: parsed.timeoutMinutes }
105
+ : {}),
106
+ };
107
+ }
108
+ export function readPlanFromDisk(repoRoot) {
109
+ const fullPath = path.join(repoRoot, PLAN_REL_PATH);
110
+ if (!fs.existsSync(fullPath)) {
111
+ throw new Error(`Missing ${PLAN_REL_PATH}. Run "bastion plan --init" first.`);
112
+ }
113
+ const parsed = JSON.parse(stripBom(fs.readFileSync(fullPath, 'utf8')));
114
+ if (!parsed || !Array.isArray(parsed.nodes) || parsed.nodes.length === 0) {
115
+ throw new Error(`Invalid ${PLAN_REL_PATH}: "nodes" must be a non-empty array.`);
116
+ }
117
+ return { version: 1, nodes: parsed.nodes };
118
+ }
119
+ export function writePlanToDisk(repoRoot, plan) {
120
+ const dir = path.join(repoRoot, BASTION_DIR);
121
+ fs.mkdirSync(dir, { recursive: true });
122
+ fs.writeFileSync(path.join(repoRoot, PLAN_REL_PATH), JSON.stringify(plan, null, 2) + '\n', 'utf8');
123
+ }
124
+ function parseLockJson(raw, label) {
125
+ const parsed = JSON.parse(stripBom(raw));
126
+ if (!parsed || typeof parsed.baseCommit !== 'string' || !Array.isArray(parsed.lockedFiles)) {
127
+ throw new Error(`Invalid ${label}: missing baseCommit or lockedFiles.`);
128
+ }
129
+ return parsed;
130
+ }
package/dist/git.js ADDED
@@ -0,0 +1,75 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import * as path from 'node:path';
3
+ /** Run a git command safely without shell interpolation. */
4
+ export function execGit(args, cwd) {
5
+ const res = spawnSync('git', args, {
6
+ cwd,
7
+ encoding: 'utf8',
8
+ stdio: ['ignore', 'pipe', 'pipe'],
9
+ });
10
+ return {
11
+ ok: res.status === 0,
12
+ stdout: (res.stdout ?? '').trimEnd(),
13
+ stderr: (res.stderr ?? '').trimEnd(),
14
+ status: res.status ?? 1,
15
+ };
16
+ }
17
+ /** Normalize a relative path to forward slashes for cross-platform git comparisons. */
18
+ export function toPosixPath(p) {
19
+ return p.replace(/\\/g, '/').replace(/^\.\//, '');
20
+ }
21
+ /** Return the git repository root directory, or null if not inside a git repo. */
22
+ export function getRepoRoot(cwd) {
23
+ const res = execGit(['rev-parse', '--show-toplevel'], cwd);
24
+ if (!res.ok || !res.stdout)
25
+ return null;
26
+ return path.resolve(res.stdout.trim());
27
+ }
28
+ /** Resolve any git ref (HEAD, branch, commit SHA) to a full 40-char SHA. */
29
+ export function resolveRef(ref, cwd) {
30
+ const res = execGit(['rev-parse', '--verify', `${ref}^{commit}`], cwd);
31
+ return res.ok ? res.stdout.trim() : null;
32
+ }
33
+ /** Read a file's UTF-8 content from a specific git ref without touching the working tree. */
34
+ export function readFileAtRef(ref, relPath, cwd) {
35
+ const posix = toPosixPath(relPath);
36
+ const res = execGit(['show', `${ref}:${posix}`], cwd);
37
+ return res.ok ? res.stdout : null;
38
+ }
39
+ /** List files changed between two git refs (excluding pure renames confusion via --no-renames). */
40
+ export function getChangedFilesBetween(baseRef, targetRef, cwd) {
41
+ const res = execGit(['diff', '--name-only', '--no-renames', `${baseRef}..${targetRef}`], cwd);
42
+ if (!res.ok)
43
+ throw new Error(`git diff failed: ${res.stderr}`);
44
+ return res.stdout
45
+ .split(/\r?\n/)
46
+ .map((s) => s.trim())
47
+ .filter(Boolean)
48
+ .map(toPosixPath);
49
+ }
50
+ /** List uncommitted (staged, unstaged, and untracked) files in the working tree. */
51
+ export function getDirtyFiles(cwd) {
52
+ const res = execGit(['status', '--porcelain', '-uall'], cwd);
53
+ if (!res.ok)
54
+ throw new Error(`git status failed: ${res.stderr}`);
55
+ const files = [];
56
+ for (const line of res.stdout.split(/\r?\n/)) {
57
+ if (!line.trim())
58
+ continue;
59
+ // Format: XY <path> (or XY old -> new)
60
+ const rawPath = line.slice(3).trim();
61
+ const finalPath = rawPath.includes(' -> ') ? rawPath.split(' -> ').pop() : rawPath;
62
+ // Strip surrounding quotes if git quoted non-ASCII or spaces
63
+ const unquoted = finalPath.startsWith('"') && finalPath.endsWith('"')
64
+ ? finalPath.slice(1, -1)
65
+ : finalPath;
66
+ files.push(toPosixPath(unquoted));
67
+ }
68
+ return files;
69
+ }
70
+ /** Check if a file is tracked at a given ref. */
71
+ export function fileExistsAtRef(ref, relPath, cwd) {
72
+ const posix = toPosixPath(relPath);
73
+ const res = execGit(['cat-file', '-e', `${ref}:${posix}`], cwd);
74
+ return res.ok;
75
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Group plan nodes into dependency waves using topological sorting.
3
+ * Throws if there are duplicate IDs, missing dependencies, or cycles.
4
+ */
5
+ export function buildExecutionWaves(nodes) {
6
+ const byId = new Map();
7
+ for (const node of nodes) {
8
+ if (!node.id || !node.id.trim()) {
9
+ throw new Error('Plan node is missing a non-empty "id".');
10
+ }
11
+ if (byId.has(node.id)) {
12
+ throw new Error(`Duplicate plan node id: "${node.id}".`);
13
+ }
14
+ byId.set(node.id, node);
15
+ }
16
+ // Validate dependencies exist
17
+ const inDegree = new Map();
18
+ const dependents = new Map();
19
+ for (const node of nodes) {
20
+ const deps = node.dependsOn ?? [];
21
+ inDegree.set(node.id, deps.length);
22
+ for (const dep of deps) {
23
+ if (!byId.has(dep)) {
24
+ throw new Error(`Node "${node.id}" depends on unknown node "${dep}".`);
25
+ }
26
+ const list = dependents.get(dep) ?? [];
27
+ list.push(node.id);
28
+ dependents.set(dep, list);
29
+ }
30
+ }
31
+ const waves = [];
32
+ let ready = nodes.filter((n) => (inDegree.get(n.id) ?? 0) === 0);
33
+ let visited = 0;
34
+ while (ready.length > 0) {
35
+ waves.push(ready);
36
+ visited += ready.length;
37
+ const nextReady = [];
38
+ for (const node of ready) {
39
+ for (const childId of dependents.get(node.id) ?? []) {
40
+ const nextDeg = (inDegree.get(childId) ?? 0) - 1;
41
+ inDegree.set(childId, nextDeg);
42
+ if (nextDeg === 0) {
43
+ nextReady.push(byId.get(childId));
44
+ }
45
+ }
46
+ }
47
+ ready = nextReady;
48
+ }
49
+ if (visited !== nodes.length) {
50
+ throw new Error('Cycle detected in plan dependencies.');
51
+ }
52
+ return waves;
53
+ }
@@ -0,0 +1,36 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { execGit } from '../git.js';
4
+ /** Create an isolated git worktree and branch for a parallel agent node. */
5
+ export function createNodeWorktree(repoRoot, baseRef, nodeId) {
6
+ const safeId = nodeId.replace(/[^a-zA-Z0-9_-]/g, '-');
7
+ const branch = `bastion/${safeId}`;
8
+ const dir = path.join(repoRoot, '.bastion', 'worktrees', safeId);
9
+ // Clean up stale worktree or branch if left over from an aborted run
10
+ removeNodeWorktree(repoRoot, { nodeId, branch, dir });
11
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
12
+ const res = execGit(['worktree', 'add', '-b', branch, dir, baseRef], repoRoot);
13
+ if (!res.ok) {
14
+ throw new Error(`Failed to create worktree for "${nodeId}": ${res.stderr}`);
15
+ }
16
+ return { nodeId, branch, dir };
17
+ }
18
+ /** Remove a node's temporary git worktree and branch. */
19
+ export function removeNodeWorktree(repoRoot, handle) {
20
+ if (fs.existsSync(handle.dir)) {
21
+ execGit(['worktree', 'remove', '--force', handle.dir], repoRoot);
22
+ if (fs.existsSync(handle.dir)) {
23
+ fs.rmSync(handle.dir, { recursive: true, force: true });
24
+ }
25
+ }
26
+ execGit(['worktree', 'prune'], repoRoot);
27
+ execGit(['branch', '-D', handle.branch], repoRoot);
28
+ }
29
+ /** Merge a verified node branch into the current integration branch with --no-ff. */
30
+ export function mergeNodeBranch(repoRoot, handle, title) {
31
+ const res = execGit(['merge', '--no-ff', handle.branch, '-m', `bastion(${handle.nodeId}): ${title}`], repoRoot);
32
+ if (!res.ok) {
33
+ execGit(['merge', '--abort'], repoRoot);
34
+ throw new Error(`Merge conflict integrating "${handle.nodeId}" (${handle.branch}): ${res.stderr}`);
35
+ }
36
+ }