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.
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/action.yml +10 -0
- package/dist/action.js +11 -0
- package/dist/cli.js +184 -0
- package/dist/commands/audit.js +63 -0
- package/dist/commands/clean.js +143 -0
- package/dist/commands/gate.js +108 -0
- package/dist/commands/init.js +143 -0
- package/dist/commands/lock.js +146 -0
- package/dist/commands/mutate.js +154 -0
- package/dist/commands/plan.js +163 -0
- package/dist/commands/run.js +305 -0
- package/dist/config.js +130 -0
- package/dist/git.js +75 -0
- package/dist/orchestrator/dag.js +53 -0
- package/dist/orchestrator/worktree.js +36 -0
- package/dist/runner.js +136 -0
- package/dist/test-names.js +36 -0
- package/dist/version.js +25 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bastion Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Bastion (`bastion-gate`)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Red-first test gate & multi-agent parallel orchestrator for AI coding agents.**
|
|
4
|
+
|
|
5
|
+
> Like a fortress (*Bastion*): the outer wall locks your failing acceptance tests *before* coding starts and verifies every branch against the **baseline branch's** config in CI; inside the walls, multiple AI agents can work in parallel in isolated git worktrees by dependency waves.
|
|
6
|
+
|
|
7
|
+
- **Works with any AI CLI or model**: plug in Claude Code, Codex, Gemini CLI, or any script via `agentCommand` — no vendor lock-in, no multi-model requirement
|
|
8
|
+
- **Hard Test Gate (`init` + `lock` + `gate` + `mutate`)**: red-first & anti-fake-red locking (rejects syntax/import-error fake reds), `.bastion/acceptance.md` checklist display, baseline-ref config enforcement, lightweight mutation spot-checks, and `audit` for local-only repos
|
|
9
|
+
- **Parallel Swarm Engine (`plan` + `run`, advanced)**: DAG wave scheduling, isolated `git worktree` sandboxes, `setupCommand` per worktree, concurrency throttling, automatic gate-feedback retry loops, `.bastion/disputes/<nodeId>.md` human-review pause channel, and N-pass post-merge verification
|
|
10
|
+
- **Scope & Target Audience**: Built for engineers and leads who can review a plain-language acceptance list. Bastion guarantees your agent didn't move the goalposts — not that the goalposts were placed in the right spot. (Tip: use a separate session/model to write tests vs. implementation.)
|
|
11
|
+
- **Prerequisites**: **Node.js >= 18** and **Git >= 2.5** (for worktrees). Zero runtime dependencies. Built with Claude & Antigravity, and dogfooded by Bastion itself.
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## Quick Start (Test Gate)
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
# 1. Initialize .bastion/config.json, .gitignore, AGENTS.md, SKILL.md, and GitHub Action
|
|
19
|
+
npx bastion-gate init
|
|
20
|
+
|
|
21
|
+
# 2. Write failing acceptance tests, commit them + .bastion/config.json to your base branch
|
|
22
|
+
git add . && git commit -m "test: add failing acceptance tests"
|
|
23
|
+
|
|
24
|
+
# 3. Verify tests are RED on baseline and lock them (+ print plain-language test names)
|
|
25
|
+
npx bastion-gate lock
|
|
26
|
+
git add .bastion/lock.json && git commit -m "chore: lock baseline tests"
|
|
27
|
+
|
|
28
|
+
# 4. On any feature branch or CI PR, verify locked scope & run baseline testCommand
|
|
29
|
+
npx bastion-gate gate
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Multi-Agent Parallel Swarm (`plan` + `run`)
|
|
33
|
+
|
|
34
|
+
> **Cost & Isolation Note**: `bastion run` invokes your `agentCommand` up to `nodes * (maxRetries + 1)` times and runs `verifyRuns` full test passes at the end. It always merges into a dedicated `bastion/run-<timestamp>` integration branch so partial failures never pollute `main`. If your test suite binds fixed ports or a shared DB, start with `--concurrency 1` (each worker receives `BASTION_NODE_ID`).
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
# 1. Generate a draft .bastion/plan.json from your locked test files (then commit it!)
|
|
38
|
+
npx bastion-gate plan --init
|
|
39
|
+
npx bastion-gate plan
|
|
40
|
+
git add .bastion/plan.json && git commit -m "chore: add execution plan"
|
|
41
|
+
|
|
42
|
+
# 2. Run parallel worktree workers (use {promptFile} or $BASTION_PROMPT for cross-platform safety)
|
|
43
|
+
npx bastion-gate run --setup "npm ci" --agent "claude -p < {promptFile}" --concurrency 2 --verify-runs 3
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Supported Agent Examples (`--agent`)
|
|
47
|
+
|
|
48
|
+
| Agent CLI | Recommended `--agent` command |
|
|
49
|
+
|---|---|
|
|
50
|
+
| **Claude Code** | `claude -p --permission-mode acceptEdits --allowedTools "Bash(node --test:*)" < {promptFile}` *(or use your test runner prefix, e.g. `Bash(pytest:*)`)* |
|
|
51
|
+
| **Codex CLI** | `codex exec - < {promptFile}` |
|
|
52
|
+
| **Node / Custom Script** | `node scripts/my-agent.mjs` (reads `BASTION_PROMPT` or `BASTION_PROMPT_FILE`) |
|
|
53
|
+
|
|
54
|
+
> **Security & Shell Note**: Running agents non-interactively with `--dangerously-skip-permissions` grants full shell/file execution inside the worktree — run it in a container, VM, or disposable environment. Avoid embedding `{prompt}` directly in shell strings; prefer `< {promptFile}` or `BASTION_PROMPT_FILE`.
|
|
55
|
+
|
|
56
|
+
### `.bastion/plan.json` Schema
|
|
57
|
+
|
|
58
|
+
```json
|
|
59
|
+
{
|
|
60
|
+
"version": 1,
|
|
61
|
+
"nodes": [
|
|
62
|
+
{
|
|
63
|
+
"id": "auth",
|
|
64
|
+
"title": "Implement auth module",
|
|
65
|
+
"prompt": "Implement src/auth to pass tests/auth.test.ts.",
|
|
66
|
+
"testCommand": "npx vitest run tests/auth.test.ts",
|
|
67
|
+
"dependsOn": [],
|
|
68
|
+
"tier": 1
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"id": "billing-deploy",
|
|
72
|
+
"title": "High-risk billing migration",
|
|
73
|
+
"dependsOn": ["auth"],
|
|
74
|
+
"tier": 3,
|
|
75
|
+
"approved": true
|
|
76
|
+
}
|
|
77
|
+
]
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
- `id`, `title`, `prompt`: node identifier, summary, and instructions passed to the agent.
|
|
82
|
+
- `testCommand` *(optional)*: node-scoped test command checked during `gate` inside that node's worktree; omit to run the global `testCommand`.
|
|
83
|
+
- `dependsOn` *(optional)*: node IDs that must pass & merge in earlier waves.
|
|
84
|
+
- `tier` *(optional, `1 | 2 | 3`)*: `1` = auto-run & verify, `2` = reversible design choice, `3` = irreversible/high-risk (blocked by `plan`/`run` unless `"approved": true`).
|
|
85
|
+
|
|
86
|
+
## Commands
|
|
87
|
+
|
|
88
|
+
- `bastion init [--test-cmd "<cmd>"] [--base <branch>] [--force]`
|
|
89
|
+
Auto-detects `pytest`, `go test ./...`, `cargo test`, `flutter test`, or `npm test` and current git branch; updates `.gitignore`, creates `.bastion/config.json`, `AGENTS.md`, `.agents/skills/bastion-gate/SKILL.md`, and `.github/workflows/bastion.yml`.
|
|
90
|
+
- `bastion lock [--base <ref>] [--amend --reason "<why>"] [--allow-dirty] [files...]`
|
|
91
|
+
Runs `testCommand` on baseline, rejects green tests, locks git-tracked test files + configs/fixtures (`conftest.py`, `package.json`, `vitest.config.*`, etc.), and prints a plain-language list of locked test names.
|
|
92
|
+
- `bastion gate [--base <ref>]`
|
|
93
|
+
Reads `.bastion/config.json` and `.bastion/lock.json` from the baseline ref, verifies zero modifications to locked files, and executes `testCommand` directly.
|
|
94
|
+
- `bastion plan [--init] [--force]`
|
|
95
|
+
Drafts `.bastion/plan.json` from locked test files or validates wave dependencies & tier-3 approvals.
|
|
96
|
+
- `bastion run [--base <ref>] [--agent "<cmd>"] [--setup "<cmd>"] [--concurrency <n>] [--max-retries <n>] [--verify-runs <n>] [--timeout <min>] [--resume]`
|
|
97
|
+
Spawns parallel worktree workers on a `bastion/run-*` integration branch, enforces `gate` with failure-output feedback retries, skips sensitive files like `.env`, supports `--resume` after wave failures, and verifies N times after merge.
|
|
98
|
+
- `bastion mutate [--max <n>] [files...]`
|
|
99
|
+
Lightweight mutation spot-check: runs inside an isolated temporary worktree (leaving your source untouched), skips auxiliary directories (`scripts/`, `examples/`, `demo/`, etc., configurable via `mutateExclude`), samples evenly across files, and reports killed vs. survived mutants.
|
|
100
|
+
- `bastion audit [--limit <n>]`
|
|
101
|
+
Audits recent merge commits in local-only repositories to catch any locked-scope bypasses.
|
|
102
|
+
- `bastion clean [--yes] [--runs]`
|
|
103
|
+
Dry-run by default: previews leftover worktrees and temporary `bastion/<node>` branches. Pass `--yes` to delete them (preserves `bastion/run-*` integration branches unless `--runs` is also passed for already-merged runs).
|
|
104
|
+
|
|
105
|
+
## Troubleshooting
|
|
106
|
+
|
|
107
|
+
- **Where are worker logs?** Check `.bastion/logs/<nodeId>-attempt-<n>.log`.
|
|
108
|
+
- **Leftover worktrees after a crash?** Run `git worktree prune` and `rm -rf .bastion/worktrees` (or `Remove-Item -Recurse -Force .bastion/worktrees` on Windows).
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
MIT
|
package/action.yml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
name: 'Bastion Gate'
|
|
2
|
+
description: 'Verify locked tests/configs were not altered and run the baseline test command. (Requires actions/checkout with fetch-depth: 0)'
|
|
3
|
+
inputs:
|
|
4
|
+
base:
|
|
5
|
+
description: 'Baseline git ref to verify against (defaults to origin/${{ github.base_ref }} or config.baseBranch)'
|
|
6
|
+
required: false
|
|
7
|
+
default: ''
|
|
8
|
+
runs:
|
|
9
|
+
using: 'node20'
|
|
10
|
+
main: 'dist/action.js'
|
package/dist/action.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { runGate } from './commands/gate.js';
|
|
2
|
+
function main() {
|
|
3
|
+
const inputBase = process.env.INPUT_BASE?.trim();
|
|
4
|
+
const githubBase = process.env.GITHUB_BASE_REF?.trim();
|
|
5
|
+
const baseRef = inputBase || (githubBase ? `origin/${githubBase}` : undefined);
|
|
6
|
+
return runGate({
|
|
7
|
+
cwd: process.cwd(),
|
|
8
|
+
baseRef,
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
process.exitCode = main();
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { runAudit } from './commands/audit.js';
|
|
4
|
+
import { runClean } from './commands/clean.js';
|
|
5
|
+
import { runGate } from './commands/gate.js';
|
|
6
|
+
import { runInit } from './commands/init.js';
|
|
7
|
+
import { runLock } from './commands/lock.js';
|
|
8
|
+
import { runMutate } from './commands/mutate.js';
|
|
9
|
+
import { runPlan } from './commands/plan.js';
|
|
10
|
+
import { runSwarm } from './commands/run.js';
|
|
11
|
+
import { BASTION_VERSION } from './version.js';
|
|
12
|
+
const HELP = `bastion (bastion-gate) v${BASTION_VERSION}
|
|
13
|
+
Multi-agent parallel development & hard-gate CLI for AI coding agents.
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
bastion init [--test-cmd "<cmd>"] [--base <branch>] [--force]
|
|
17
|
+
bastion lock [--base <ref>] [--amend --reason "<why>"] [--allow-dirty] [files...]
|
|
18
|
+
bastion gate [--base <ref>]
|
|
19
|
+
bastion plan [--init] [--force]
|
|
20
|
+
bastion run [--base <ref>] [--agent "<cmd>"] [--setup "<cmd>"] [--concurrency <n>] [--max-retries <n>] [--verify-runs <n>] [--timeout <min>] [--resume]
|
|
21
|
+
bastion mutate [--max <n>] [files...]
|
|
22
|
+
bastion audit [--limit <n>]
|
|
23
|
+
bastion clean [--yes] [--runs]
|
|
24
|
+
bastion --help
|
|
25
|
+
`;
|
|
26
|
+
async function main() {
|
|
27
|
+
const argv = process.argv.slice(2);
|
|
28
|
+
const subcommand = argv[0];
|
|
29
|
+
if (!subcommand || subcommand === '--help' || subcommand === '-h') {
|
|
30
|
+
console.log(HELP);
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
const rest = argv.slice(1);
|
|
34
|
+
const cwd = process.cwd();
|
|
35
|
+
try {
|
|
36
|
+
switch (subcommand) {
|
|
37
|
+
case 'init': {
|
|
38
|
+
const { values } = parseArgs({
|
|
39
|
+
args: rest,
|
|
40
|
+
options: {
|
|
41
|
+
'test-cmd': { type: 'string' },
|
|
42
|
+
base: { type: 'string' },
|
|
43
|
+
force: { type: 'boolean', default: false },
|
|
44
|
+
},
|
|
45
|
+
allowPositionals: false,
|
|
46
|
+
});
|
|
47
|
+
return runInit({
|
|
48
|
+
cwd,
|
|
49
|
+
testCommand: values['test-cmd'],
|
|
50
|
+
baseBranch: values.base,
|
|
51
|
+
force: values.force,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
case 'lock': {
|
|
55
|
+
const { values, positionals } = parseArgs({
|
|
56
|
+
args: rest,
|
|
57
|
+
options: {
|
|
58
|
+
base: { type: 'string' },
|
|
59
|
+
amend: { type: 'boolean', default: false },
|
|
60
|
+
reason: { type: 'string' },
|
|
61
|
+
'allow-dirty': { type: 'boolean', default: false },
|
|
62
|
+
},
|
|
63
|
+
allowPositionals: true,
|
|
64
|
+
});
|
|
65
|
+
return runLock({
|
|
66
|
+
cwd,
|
|
67
|
+
baseRef: values.base,
|
|
68
|
+
extraFiles: positionals,
|
|
69
|
+
amend: values.amend,
|
|
70
|
+
reason: values.reason,
|
|
71
|
+
allowDirty: values['allow-dirty'],
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
case 'gate': {
|
|
75
|
+
const { values } = parseArgs({
|
|
76
|
+
args: rest,
|
|
77
|
+
options: {
|
|
78
|
+
base: { type: 'string' },
|
|
79
|
+
},
|
|
80
|
+
allowPositionals: false,
|
|
81
|
+
});
|
|
82
|
+
return runGate({
|
|
83
|
+
cwd,
|
|
84
|
+
baseRef: values.base,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
case 'plan': {
|
|
88
|
+
const { values } = parseArgs({
|
|
89
|
+
args: rest,
|
|
90
|
+
options: {
|
|
91
|
+
init: { type: 'boolean', default: false },
|
|
92
|
+
force: { type: 'boolean', default: false },
|
|
93
|
+
},
|
|
94
|
+
allowPositionals: false,
|
|
95
|
+
});
|
|
96
|
+
return runPlan({
|
|
97
|
+
cwd,
|
|
98
|
+
init: values.init,
|
|
99
|
+
force: values.force,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
case 'run': {
|
|
103
|
+
const { values } = parseArgs({
|
|
104
|
+
args: rest,
|
|
105
|
+
options: {
|
|
106
|
+
base: { type: 'string' },
|
|
107
|
+
agent: { type: 'string' },
|
|
108
|
+
setup: { type: 'string' },
|
|
109
|
+
concurrency: { type: 'string' },
|
|
110
|
+
'max-retries': { type: 'string' },
|
|
111
|
+
'verify-runs': { type: 'string' },
|
|
112
|
+
timeout: { type: 'string' },
|
|
113
|
+
resume: { type: 'boolean', default: false },
|
|
114
|
+
},
|
|
115
|
+
allowPositionals: false,
|
|
116
|
+
});
|
|
117
|
+
return await runSwarm({
|
|
118
|
+
cwd,
|
|
119
|
+
baseRef: values.base,
|
|
120
|
+
agentCommand: values.agent,
|
|
121
|
+
setupCommand: values.setup,
|
|
122
|
+
concurrency: values.concurrency ? Number(values.concurrency) : undefined,
|
|
123
|
+
maxRetries: values['max-retries'] ? Number(values['max-retries']) : undefined,
|
|
124
|
+
verifyRuns: values['verify-runs'] ? Number(values['verify-runs']) : undefined,
|
|
125
|
+
timeoutMinutes: values.timeout ? Number(values.timeout) : undefined,
|
|
126
|
+
resume: values.resume,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
case 'mutate': {
|
|
130
|
+
const { values, positionals } = parseArgs({
|
|
131
|
+
args: rest,
|
|
132
|
+
options: {
|
|
133
|
+
max: { type: 'string' },
|
|
134
|
+
},
|
|
135
|
+
allowPositionals: true,
|
|
136
|
+
});
|
|
137
|
+
return runMutate({
|
|
138
|
+
cwd,
|
|
139
|
+
files: positionals,
|
|
140
|
+
maxMutations: values.max ? Number(values.max) : undefined,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
case 'audit': {
|
|
144
|
+
const { values } = parseArgs({
|
|
145
|
+
args: rest,
|
|
146
|
+
options: {
|
|
147
|
+
limit: { type: 'string' },
|
|
148
|
+
},
|
|
149
|
+
allowPositionals: false,
|
|
150
|
+
});
|
|
151
|
+
return runAudit({
|
|
152
|
+
cwd,
|
|
153
|
+
limit: values.limit ? Number(values.limit) : undefined,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
case 'clean': {
|
|
157
|
+
const { values } = parseArgs({
|
|
158
|
+
args: rest,
|
|
159
|
+
options: {
|
|
160
|
+
yes: { type: 'boolean', default: false },
|
|
161
|
+
runs: { type: 'boolean', default: false },
|
|
162
|
+
},
|
|
163
|
+
allowPositionals: false,
|
|
164
|
+
});
|
|
165
|
+
return runClean({
|
|
166
|
+
cwd,
|
|
167
|
+
yes: values.yes,
|
|
168
|
+
runs: values.runs,
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
default:
|
|
172
|
+
console.error(`[bastion] Unknown command: ${subcommand}\n`);
|
|
173
|
+
console.error(HELP);
|
|
174
|
+
return 1;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
catch (err) {
|
|
178
|
+
console.error(`[bastion] ${err instanceof Error ? err.message : String(err)}`);
|
|
179
|
+
return 1;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
main().then((code) => {
|
|
183
|
+
process.exitCode = code;
|
|
184
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { CONFIG_REL_PATH, LOCK_REL_PATH, readConfigFromRef, readLockFromRef, } from '../config.js';
|
|
2
|
+
import { execGit, getChangedFilesBetween, getRepoRoot } from '../git.js';
|
|
3
|
+
import { matchesAnyGlob } from '../runner.js';
|
|
4
|
+
/**
|
|
5
|
+
* Post-hoc audit for local-only repos without CI branch protection:
|
|
6
|
+
* inspects recent merge commits (or linear commits) to verify no commit modified
|
|
7
|
+
* locked test/config files without an authorized lock amendment.
|
|
8
|
+
*/
|
|
9
|
+
export function runAudit(opts) {
|
|
10
|
+
const repoRoot = getRepoRoot(opts.cwd);
|
|
11
|
+
if (!repoRoot) {
|
|
12
|
+
console.error('[bastion] Error: not inside a git repository.');
|
|
13
|
+
return 1;
|
|
14
|
+
}
|
|
15
|
+
const maxCount = String(opts.limit ?? 20);
|
|
16
|
+
const mergesRes = execGit(['log', '--merges', '--format=%H %s', '-n', maxCount], repoRoot);
|
|
17
|
+
const commits = mergesRes.ok && mergesRes.stdout.trim()
|
|
18
|
+
? mergesRes.stdout.split(/\r?\n/).filter(Boolean)
|
|
19
|
+
: [];
|
|
20
|
+
if (commits.length === 0) {
|
|
21
|
+
console.log('[bastion] No merge commits found to audit.');
|
|
22
|
+
return 0;
|
|
23
|
+
}
|
|
24
|
+
let failures = 0;
|
|
25
|
+
for (const line of commits) {
|
|
26
|
+
const spaceIdx = line.indexOf(' ');
|
|
27
|
+
const sha = spaceIdx === -1 ? line : line.slice(0, spaceIdx);
|
|
28
|
+
const subject = spaceIdx === -1 ? '' : line.slice(spaceIdx + 1);
|
|
29
|
+
const parentRef = `${sha}^1`;
|
|
30
|
+
let baseConfig;
|
|
31
|
+
let baseLock;
|
|
32
|
+
try {
|
|
33
|
+
baseConfig = readConfigFromRef(parentRef, repoRoot);
|
|
34
|
+
baseLock = readLockFromRef(parentRef, repoRoot);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
// Bastion was not initialized on this merge's parent; skip
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const lockedSet = new Set(baseLock.lockedFiles.map((f) => f.path));
|
|
41
|
+
const patterns = [...baseConfig.lockedGlobs, ...baseConfig.extraLockedPaths];
|
|
42
|
+
const changed = getChangedFilesBetween(parentRef, sha, repoRoot);
|
|
43
|
+
const touched = changed.filter((rel) => rel === CONFIG_REL_PATH ||
|
|
44
|
+
rel === LOCK_REL_PATH ||
|
|
45
|
+
lockedSet.has(rel) ||
|
|
46
|
+
matchesAnyGlob(rel, patterns));
|
|
47
|
+
if (touched.length > 0) {
|
|
48
|
+
failures++;
|
|
49
|
+
console.error(`[FAIL] ${sha.slice(0, 8)} (${subject}) modified locked files:`);
|
|
50
|
+
for (const f of touched)
|
|
51
|
+
console.error(` - ${f}`);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
console.log(`[PASS] ${sha.slice(0, 8)} (${subject})`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (failures > 0) {
|
|
58
|
+
console.error(`\n[bastion] Audit found ${failures} merge(s) that bypassed locked scope.`);
|
|
59
|
+
return 1;
|
|
60
|
+
}
|
|
61
|
+
console.log('\n[bastion] Audit complete: no locked-scope bypasses detected.');
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import * as fs from 'node:fs';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { readConfigFromDisk } from '../config.js';
|
|
4
|
+
import { execGit, getRepoRoot } from '../git.js';
|
|
5
|
+
function isProcessAlive(pid) {
|
|
6
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
7
|
+
return false;
|
|
8
|
+
try {
|
|
9
|
+
process.kill(pid, 0);
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function removeDirWithRetry(dir, retries = 3) {
|
|
17
|
+
for (let i = 0; i < retries; i++) {
|
|
18
|
+
try {
|
|
19
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
if (i === retries - 1)
|
|
24
|
+
throw err;
|
|
25
|
+
const start = Date.now();
|
|
26
|
+
while (Date.now() - start < 150) {
|
|
27
|
+
// brief synchronous backoff for Windows file handle release
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Clean leftover Bastion worktrees and temporary node branches (`bastion/<node>`).
|
|
34
|
+
* Dry-run by default: requires `--yes` to actually delete. Preserves `bastion/run-*`
|
|
35
|
+
* integration branches unless `--runs` is also passed (and only deletes merged ones).
|
|
36
|
+
*/
|
|
37
|
+
export function runClean(opts) {
|
|
38
|
+
const repoRoot = getRepoRoot(opts.cwd);
|
|
39
|
+
if (!repoRoot) {
|
|
40
|
+
console.error('[bastion] Error: not inside a git repository.');
|
|
41
|
+
return 1;
|
|
42
|
+
}
|
|
43
|
+
const pidFile = path.join(repoRoot, '.bastion', 'run.pid');
|
|
44
|
+
if (fs.existsSync(pidFile)) {
|
|
45
|
+
const pid = Number(fs.readFileSync(pidFile, 'utf8').trim());
|
|
46
|
+
if (isProcessAlive(pid)) {
|
|
47
|
+
console.error(`[bastion] Refusing to clean: active \`bastion run\` process (PID ${pid}) is still running.`);
|
|
48
|
+
return 1;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const dryRun = !opts.yes;
|
|
52
|
+
const worktreesDir = path.join(repoRoot, '.bastion', 'worktrees');
|
|
53
|
+
const worktreeEntries = fs.existsSync(worktreesDir) ? fs.readdirSync(worktreesDir) : [];
|
|
54
|
+
const currentRes = execGit(['rev-parse', '--abbrev-ref', 'HEAD'], repoRoot);
|
|
55
|
+
const currentBranch = currentRes.ok ? currentRes.stdout.trim() : '';
|
|
56
|
+
let baseBranch = 'main';
|
|
57
|
+
try {
|
|
58
|
+
baseBranch = readConfigFromDisk(repoRoot).baseBranch;
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// fallback to main
|
|
62
|
+
}
|
|
63
|
+
const mergedRes = execGit(['branch', '--merged', baseBranch, '--list', 'bastion/*'], repoRoot);
|
|
64
|
+
const mergedSet = new Set(mergedRes.ok
|
|
65
|
+
? mergedRes.stdout.split(/\r?\n/).map((l) => l.replace(/^\*?\s+/, '').trim()).filter(Boolean)
|
|
66
|
+
: []);
|
|
67
|
+
const branchRes = execGit(['branch', '--list', 'bastion/*'], repoRoot);
|
|
68
|
+
const branches = branchRes.ok
|
|
69
|
+
? branchRes.stdout.split(/\r?\n/).map((l) => l.replace(/^\*?\s+/, '').trim()).filter(Boolean)
|
|
70
|
+
: [];
|
|
71
|
+
const toDeleteBranches = [];
|
|
72
|
+
const preservedBranches = [];
|
|
73
|
+
for (const b of branches) {
|
|
74
|
+
if (b === currentBranch) {
|
|
75
|
+
preservedBranches.push(`${b} (checked out)`);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (b.startsWith('bastion/run-')) {
|
|
79
|
+
if (opts.runs && mergedSet.has(b)) {
|
|
80
|
+
toDeleteBranches.push(b);
|
|
81
|
+
}
|
|
82
|
+
else {
|
|
83
|
+
preservedBranches.push(opts.runs ? `${b} (unmerged into ${baseBranch} — kept safe)` : `${b} (integration branch)`);
|
|
84
|
+
}
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
toDeleteBranches.push(b);
|
|
88
|
+
}
|
|
89
|
+
const stateFile = path.join(repoRoot, '.bastion', 'run-state.json');
|
|
90
|
+
const logsDir = path.join(repoRoot, '.bastion', 'logs');
|
|
91
|
+
const hasState = fs.existsSync(stateFile);
|
|
92
|
+
const hasLogs = fs.existsSync(logsDir);
|
|
93
|
+
if (dryRun) {
|
|
94
|
+
console.log('[bastion] Dry-run (pass --yes to delete):');
|
|
95
|
+
if (worktreeEntries.length > 0)
|
|
96
|
+
console.log(` - Would remove .bastion/worktrees/ (${worktreeEntries.length} item(s))`);
|
|
97
|
+
for (const b of toDeleteBranches)
|
|
98
|
+
console.log(` - Would delete branch: ${b}`);
|
|
99
|
+
if (hasState)
|
|
100
|
+
console.log(' - Would remove .bastion/run-state.json');
|
|
101
|
+
if (hasLogs)
|
|
102
|
+
console.log(' - Would remove .bastion/logs/');
|
|
103
|
+
if (preservedBranches.length > 0) {
|
|
104
|
+
console.log(' Preserved:');
|
|
105
|
+
for (const b of preservedBranches)
|
|
106
|
+
console.log(` - ${b}`);
|
|
107
|
+
}
|
|
108
|
+
return 0;
|
|
109
|
+
}
|
|
110
|
+
if (fs.existsSync(worktreesDir)) {
|
|
111
|
+
for (const entry of worktreeEntries) {
|
|
112
|
+
const full = path.join(worktreesDir, entry);
|
|
113
|
+
execGit(['worktree', 'remove', '--force', full], repoRoot);
|
|
114
|
+
if (fs.existsSync(full))
|
|
115
|
+
removeDirWithRetry(full);
|
|
116
|
+
}
|
|
117
|
+
removeDirWithRetry(worktreesDir);
|
|
118
|
+
console.log('[bastion] Removed .bastion/worktrees/');
|
|
119
|
+
}
|
|
120
|
+
execGit(['worktree', 'prune'], repoRoot);
|
|
121
|
+
for (const b of toDeleteBranches) {
|
|
122
|
+
const del = execGit(['branch', '-D', b], repoRoot);
|
|
123
|
+
if (del.ok)
|
|
124
|
+
console.log(`[bastion] Deleted branch: ${b}`);
|
|
125
|
+
}
|
|
126
|
+
if (hasState) {
|
|
127
|
+
fs.unlinkSync(stateFile);
|
|
128
|
+
console.log('[bastion] Removed .bastion/run-state.json');
|
|
129
|
+
}
|
|
130
|
+
if (hasLogs) {
|
|
131
|
+
removeDirWithRetry(logsDir);
|
|
132
|
+
console.log('[bastion] Removed .bastion/logs/');
|
|
133
|
+
}
|
|
134
|
+
if (fs.existsSync(pidFile))
|
|
135
|
+
fs.unlinkSync(pidFile);
|
|
136
|
+
if (preservedBranches.length > 0) {
|
|
137
|
+
console.log('[bastion] Preserved:');
|
|
138
|
+
for (const b of preservedBranches)
|
|
139
|
+
console.log(` - ${b}`);
|
|
140
|
+
}
|
|
141
|
+
console.log('[bastion] Clean complete.');
|
|
142
|
+
return 0;
|
|
143
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { CONFIG_REL_PATH, LOCK_REL_PATH, PLAN_REL_PATH, readConfigFromDisk, readConfigFromRef, readLockFromRef, } from '../config.js';
|
|
2
|
+
import { getChangedFilesBetween, getDirtyFiles, getRepoRoot, resolveRef, } from '../git.js';
|
|
3
|
+
import { matchesAnyGlob, runTestCommand, runTestCommandAsync } from '../runner.js';
|
|
4
|
+
function checkGateIntegrity(opts) {
|
|
5
|
+
const repoRoot = getRepoRoot(opts.cwd);
|
|
6
|
+
if (!repoRoot) {
|
|
7
|
+
const msg = '[bastion] Error: not inside a git repository.';
|
|
8
|
+
console.error(msg);
|
|
9
|
+
return { ok: false, feedback: msg };
|
|
10
|
+
}
|
|
11
|
+
let baseRef = opts.baseRef;
|
|
12
|
+
if (!baseRef && process.env.GITHUB_BASE_REF) {
|
|
13
|
+
baseRef = `origin/${process.env.GITHUB_BASE_REF}`;
|
|
14
|
+
}
|
|
15
|
+
if (!baseRef) {
|
|
16
|
+
const diskConfig = readConfigFromDisk(repoRoot);
|
|
17
|
+
baseRef = diskConfig.baseBranch;
|
|
18
|
+
}
|
|
19
|
+
const resolvedBase = resolveRef(baseRef, repoRoot);
|
|
20
|
+
if (!resolvedBase) {
|
|
21
|
+
const msg = `[bastion] GATE FAIL: cannot resolve baseline ref "${baseRef}".`;
|
|
22
|
+
console.error(msg);
|
|
23
|
+
return { ok: false, feedback: msg };
|
|
24
|
+
}
|
|
25
|
+
const baseConfig = readConfigFromRef(resolvedBase, repoRoot);
|
|
26
|
+
const baseLock = readLockFromRef(resolvedBase, repoRoot);
|
|
27
|
+
const lockedSet = new Set(baseLock.lockedFiles.map((f) => f.path));
|
|
28
|
+
const patterns = [...baseConfig.lockedGlobs, ...baseConfig.extraLockedPaths];
|
|
29
|
+
const violations = [];
|
|
30
|
+
const changedCommits = getChangedFilesBetween(resolvedBase, 'HEAD', repoRoot);
|
|
31
|
+
for (const rel of changedCommits) {
|
|
32
|
+
if (rel === CONFIG_REL_PATH || rel === LOCK_REL_PATH || rel === PLAN_REL_PATH) {
|
|
33
|
+
violations.push(`Baseline bastion file modified in branch: ${rel}`);
|
|
34
|
+
}
|
|
35
|
+
else if (lockedSet.has(rel) || matchesAnyGlob(rel, patterns)) {
|
|
36
|
+
violations.push(`Locked test/config file modified in branch: ${rel}`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
const dirtyFiles = getDirtyFiles(repoRoot);
|
|
40
|
+
for (const rel of dirtyFiles) {
|
|
41
|
+
if (rel === CONFIG_REL_PATH || rel === LOCK_REL_PATH || rel === PLAN_REL_PATH) {
|
|
42
|
+
violations.push(`Uncommitted modification to bastion file: ${rel}`);
|
|
43
|
+
}
|
|
44
|
+
else if (lockedSet.has(rel) || matchesAnyGlob(rel, patterns)) {
|
|
45
|
+
violations.push(`Uncommitted modification to locked file: ${rel}`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (violations.length > 0) {
|
|
49
|
+
const lines = [
|
|
50
|
+
'[bastion] GATE FAIL: locked scope integrity violation(s):',
|
|
51
|
+
...violations.map((v) => ` - ${v}`),
|
|
52
|
+
'',
|
|
53
|
+
'If a locked test genuinely has a defect, a human must confirm and amend the lock on the baseline.',
|
|
54
|
+
];
|
|
55
|
+
console.error(lines.join('\n'));
|
|
56
|
+
return { ok: false, feedback: lines.join('\n') };
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
ok: true,
|
|
60
|
+
repoRoot,
|
|
61
|
+
baseRef,
|
|
62
|
+
resolvedBase,
|
|
63
|
+
cmdToRun: opts.testCommandOverride ?? baseConfig.testCommand,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function tailLines(text, maxLines = 40) {
|
|
67
|
+
const lines = text.trimEnd().split(/\r?\n/);
|
|
68
|
+
return lines.slice(-maxLines).join('\n');
|
|
69
|
+
}
|
|
70
|
+
export function runGate(opts) {
|
|
71
|
+
const check = checkGateIntegrity(opts);
|
|
72
|
+
if (!check.ok)
|
|
73
|
+
return 1;
|
|
74
|
+
console.log(`[bastion] Integrity OK against ${check.baseRef} (${check.resolvedBase.slice(0, 8)}).`);
|
|
75
|
+
console.log(`[bastion] Running baseline testCommand: ${check.cmdToRun}`);
|
|
76
|
+
const run = runTestCommand(check.cmdToRun, check.repoRoot);
|
|
77
|
+
if (run.stdout.trim())
|
|
78
|
+
process.stdout.write(run.stdout + (run.stdout.endsWith('\n') ? '' : '\n'));
|
|
79
|
+
if (run.stderr.trim())
|
|
80
|
+
process.stderr.write(run.stderr + (run.stderr.endsWith('\n') ? '' : '\n'));
|
|
81
|
+
if (run.exitCode !== 0) {
|
|
82
|
+
console.error(`\n[bastion] GATE FAIL: testCommand exited with code ${run.exitCode} (${run.durationMs}ms).`);
|
|
83
|
+
return 1;
|
|
84
|
+
}
|
|
85
|
+
console.log(`\n[bastion] GATE PASS: all checks passed in ${run.durationMs}ms.`);
|
|
86
|
+
return 0;
|
|
87
|
+
}
|
|
88
|
+
/** Async gate runner for parallel worktrees, returning detailed test failure output for retry feedback. */
|
|
89
|
+
export async function runGateAsync(opts) {
|
|
90
|
+
const check = checkGateIntegrity(opts);
|
|
91
|
+
if (!check.ok)
|
|
92
|
+
return { exitCode: 1, feedback: check.feedback };
|
|
93
|
+
console.log(`[bastion] Integrity OK against ${check.baseRef} (${check.resolvedBase.slice(0, 8)}).`);
|
|
94
|
+
console.log(`[bastion] Running baseline testCommand: ${check.cmdToRun}`);
|
|
95
|
+
const run = await runTestCommandAsync(check.cmdToRun, check.repoRoot);
|
|
96
|
+
if (run.stdout.trim())
|
|
97
|
+
process.stdout.write(run.stdout + (run.stdout.endsWith('\n') ? '' : '\n'));
|
|
98
|
+
if (run.stderr.trim())
|
|
99
|
+
process.stderr.write(run.stderr + (run.stderr.endsWith('\n') ? '' : '\n'));
|
|
100
|
+
if (run.exitCode !== 0) {
|
|
101
|
+
const combined = `${run.stdout}\n${run.stderr}`.trim();
|
|
102
|
+
const feedback = `Test command "${check.cmdToRun}" failed (exit ${run.exitCode}):\n${tailLines(combined, 40)}`;
|
|
103
|
+
console.error(`\n[bastion] GATE FAIL: testCommand exited with code ${run.exitCode} (${run.durationMs}ms).`);
|
|
104
|
+
return { exitCode: 1, feedback };
|
|
105
|
+
}
|
|
106
|
+
console.log(`\n[bastion] GATE PASS: all checks passed in ${run.durationMs}ms.`);
|
|
107
|
+
return { exitCode: 0, feedback: '' };
|
|
108
|
+
}
|