diff --git a/plugins/bstack/agents/judge.md b/plugins/bstack/agents/judge.md index df75c8b..b92af5e 100644 --- a/plugins/bstack/agents/judge.md +++ b/plugins/bstack/agents/judge.md @@ -14,6 +14,7 @@ You did not write this change, and you get no credit for agreeing with it. Your 3. **Break it**: list attack hypotheses for this diff (run twice, partial failure, empty and huge input, duplicates, encoding, concurrency, another user's id, an old-format row, a consumer of the old name) and reproduce each on fixture data, on base and head. Never touch real accounts or outbound targets; never commit, push or post. 4. **Blocking**: a defect on normal input that this change introduces or newly exposes, an unproven or broken criterion, a weakened check the PR body does not explain (`risk-tier.mjs --pr ` lists them). "Base was weaker", "looks deliberate" and "the gap is older" do not make it a note unless the PR body states that trade-off. 5. A reproduction names a repo-relative command or file; never an absolute path or a name outside the repo. +6. A green `bstack/checks` status on the head covers the full suite: run only the tests your proofs need. Your context is cached five minutes: run anything longer in the background and poll with sleeps of at most 240 s. Report under 60 lines: criteria and their proof, findings, dropped hypotheses. `blocks`: `regression`, `criterion` (quote it), `weakened-check`, `no`. Base pass, head fail blocks whatever its label; a blocking finding means FAIL. A proof needing a tool, device or access you lack: the object form with `missing`, UNPROVEN. End, right before the last line, with: ```json bstack-findings diff --git a/plugins/bstack/agents/worker.md b/plugins/bstack/agents/worker.md index c984a93..3eef231 100644 --- a/plugins/bstack/agents/worker.md +++ b/plugins/bstack/agents/worker.md @@ -11,7 +11,8 @@ You implement one change. Follow the bstack session rules and the playbook named - Stay inside the stated goal and files. Anything else you notice goes in your report, not into the diff. - Bug fixes start with the failing test, committed before the fix. - Commit messages are Conventional Commits: `type(scope): subject`. -- Run the repo's checks and the proving check before you report. Paste the decisive output lines. +- While working, run only the tests your change touches. The full suite runs once per head, through `checks.mjs` after the push. Paste the decisive output lines. +- Your context is cached five minutes: run anything longer in the background and poll with sleeps of at most 240 s. - You may push your branch and open or update the PR. Push once, when the round is done and its checks pass. The parent merges, after the judge. - Findings on your change come back to you: fix all of them in one round, at the cause you now know, and push once. diff --git a/plugins/bstack/scripts/cargo-lock.mjs b/plugins/bstack/scripts/cargo-lock.mjs index cfc8b33..3096e1a 100644 --- a/plugins/bstack/scripts/cargo-lock.mjs +++ b/plugins/bstack/scripts/cargo-lock.mjs @@ -3,17 +3,18 @@ // together. Cargo's own lock covers compiling only, so worktrees sharing one target dir otherwise rebuild // each other's test binaries between build and run (#153). Worktrees of one workspace also get the same // build hashes, and cargo judges freshness by mtime, so a worktree whose sources are older than another's -// build would run that build: the wrapper first marks this worktree's workspace sources as changed. -// Without a target dir it only runs the command; `cargo run` takes no lock, as its app may run for hours. +// build would run that build: the wrapper marks this worktree's workspace sources as changed when another worktree built last. +// Without a target dir, or for a cargo command that builds nothing, it only runs the command; `cargo run` takes no lock, as its app may run for hours. // Usage: node cargo-lock.mjs cargo test --workspace --locked import { spawn, spawnSync } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { setTimeout as sleep } from 'node:timers/promises'; -import { cargoSubcommand, configArgTargetDir, configFileTargetDir, holdsNoLock, isCargo, optionValues } from './lib/cargo.mjs'; +import { buildsNothing, cargoSubcommand, configArgTargetDir, configFileTargetDir, holdsNoLock, isCargo, optionValues } from './lib/cargo.mjs'; const LOCK_NAME = '.bstack-cargo.lock'; +const LAST_BUILDER_NAME = '.bstack-cargo.last'; const POLL_MS = 250; const WORKSPACE_SOURCES = ['src', 'tests', 'benches', 'examples', 'build.rs', 'Cargo.toml']; const say = msg => process.stderr.write(`bstack cargo-lock: ${msg}\n`); @@ -107,12 +108,13 @@ function cargoTargetDir(args, env) { return file ? path.resolve(file.base, file.dir) : undefined; } -function workspaceMembers(program, args) { +function workspaceOf(program, args) { const manifest = optionValue(args, '--manifest-path'); const cwd = path.resolve(optionValue(args, '-C') ?? '.'); const metadata = spawnSync(program, ['metadata', '--no-deps', '--format-version', '1', ...(manifest ? ['--manifest-path', manifest] : [])], { cwd, encoding: 'utf8' }); - if (metadata.status !== 0) return []; - return JSON.parse(metadata.stdout).packages.map(p => path.dirname(p.manifest_path)); + if (metadata.status !== 0) return { root: null, members: [] }; + const { workspace_root: root, packages } = JSON.parse(metadata.stdout); + return { root: root ?? null, members: packages.map(p => path.dirname(p.manifest_path)) }; } function touch(entry, now) { @@ -121,11 +123,16 @@ function touch(entry, now) { else if (stat) fs.utimesSync(entry, now, now); } -function markSourcesChanged(program, args) { +function markSourcesChanged(program, args, target, { locked }) { + const { root, members } = workspaceOf(program, args); + const lastBuilder = path.join(target, LAST_BUILDER_NAME); + if (locked && root && readOrNull(lastBuilder) === root) return; const now = new Date(); - for (const member of workspaceMembers(program, args)) { + for (const member of members) { for (const name of WORKSPACE_SOURCES) touch(path.join(member, name), now); } + if (locked && root) fs.writeFileSync(lastBuilder, root); + else fs.rmSync(lastBuilder, { force: true }); } function run(program, args, onSpawn = () => {}) { @@ -145,17 +152,17 @@ async function main([program, ...args]) { return 2; } const target = isCargo(program) ? cargoTargetDir(args, process.env) : process.env.CARGO_TARGET_DIR; - if (!target) return run(program, args); + if (!target || (isCargo(program) && buildsNothing(cargoSubcommand(args)))) return run(program, args); + const lock = path.join(path.resolve(target), LOCK_NAME); + fs.mkdirSync(path.dirname(lock), { recursive: true }); if (isCargo(program) && holdsNoLock(cargoSubcommand(args))) { say('cargo run takes no lock: the app it starts may run for hours, and cargo\'s own lock covers its build'); - markSourcesChanged(program, args); + markSourcesChanged(program, args, path.dirname(lock), { locked: false }); return run(program, args); } - const lock = path.join(path.resolve(target), LOCK_NAME); - fs.mkdirSync(path.dirname(lock), { recursive: true }); await acquire(lock); try { - if (isCargo(program)) markSourcesChanged(program, args); + if (isCargo(program)) markSourcesChanged(program, args, path.dirname(lock), { locked: true }); return await run(program, args, childPid => recordChild(lock, childPid)); } finally { release(lock); diff --git a/plugins/bstack/scripts/checks.mjs b/plugins/bstack/scripts/checks.mjs index 0e85b9f..1bb641d 100644 --- a/plugins/bstack/scripts/checks.mjs +++ b/plugins/bstack/scripts/checks.mjs @@ -5,6 +5,7 @@ import { execFileSync, spawnSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; +import { fileURLToPath } from 'node:url'; import { repoOfUrl } from './lib/pending.mjs'; import { readBasePolicy } from './lib/base-policy.mjs'; import { CHECKS_CONTEXT } from './lib/checks-context.mjs'; @@ -25,6 +26,10 @@ const short = sha => String(sha).slice(0, 7); export const commandsOf = text => text.split(/\r?\n/).map(l => l.trim()).filter(l => l && !l.startsWith('#')); +const CARGO_LOCK = fileURLToPath(new URL('./cargo-lock.mjs', import.meta.url)).replace(/\\/g, '/'); + +export const underTargetLock = command => /^cargo\s/.test(command) ? `"${process.execPath}" "${CARGO_LOCK}" ${command}` : command; + function parseArgs(argv) { const opts = { pr: null, repo: null }; for (let i = 0; i < argv.length; i += 2) { @@ -151,7 +156,7 @@ function main() { process.exitCode = checks(process.argv.slice(2), { git: (args, opts) => capture('git', args, opts), gh: args => capture('gh', args), - run: (command, { cwd, env }) => spawnSync(command, { shell: true, stdio: 'inherit', cwd, env }).status ?? 1, + run: (command, { cwd, env }) => spawnSync(underTargetLock(command), { shell: true, stdio: 'inherit', cwd, env }).status ?? 1, readFile: file => fs.readFileSync(file, 'utf8'), env: process.env, log: line => console.log(line), diff --git a/plugins/bstack/scripts/context.mjs b/plugins/bstack/scripts/context.mjs index 148789e..fd870fd 100644 --- a/plugins/bstack/scripts/context.mjs +++ b/plugins/bstack/scripts/context.mjs @@ -11,6 +11,7 @@ const mode = process.argv[2] === 'subagent' ? 'subagent' : 'session'; const read = name => fs.readFileSync(path.join(root, 'rules', name), 'utf8').trim(); let text = read('core.md').replaceAll('{{PLUGIN_ROOT}}', root.replace(/\\/g, '/')); +if (process.env.CARGO_TARGET_DIR) text += `\n\nCargo: CARGO_TARGET_DIR is shared, so put \`node "${root.replace(/\\/g, '/')}/scripts/cargo-lock.mjs"\` right before every cargo build, test and clippy.`; if (mode === 'session') text += `\n\n${read('style.md')}`; if (mode === 'session') { try { startPrune(); } catch { /* pruning old lanes waits for the next session */ } diff --git a/plugins/bstack/scripts/lib/cargo.mjs b/plugins/bstack/scripts/lib/cargo.mjs index 74747c6..e3914c2 100644 --- a/plugins/bstack/scripts/lib/cargo.mjs +++ b/plugins/bstack/scripts/lib/cargo.mjs @@ -15,6 +15,8 @@ export function cargoSubcommand(args) { export const holdsNoLock = subcommand => /^(run|r)$/.test(subcommand ?? ''); +export const buildsNothing = subcommand => /^(fmt|machete|metadata|tree|fetch|update|audit|deny)$/.test(subcommand ?? ''); + // Cargo's own options end at `--`; what follows goes to the test binary or the app. export function optionValues(args, name) { const values = []; diff --git a/plugins/bstack/skills/mode/SKILL.md b/plugins/bstack/skills/mode/SKILL.md index 031a709..21e81a4 100644 --- a/plugins/bstack/skills/mode/SKILL.md +++ b/plugins/bstack/skills/mode/SKILL.md @@ -53,6 +53,7 @@ Spend weekly quota where risk is. - A scoped change goes to a `bstack:worker`. - Fix rounds stay with the builder: fix your own change, continue the worker that built one (SendMessage), a fresh one only when it is gone. +- A new ticket gets a fresh worker. At most three builders at once where builds share a target dir (`CARGO_TARGET_DIR`): more only queue on its lock. - Big read-only searches go to Explore. Parallel work in one repo uses one worktree per agent. ## Gates diff --git a/plugins/bstack/skills/verify/SKILL.md b/plugins/bstack/skills/verify/SKILL.md index 37a8ab5..a5e93b8 100644 --- a/plugins/bstack/skills/verify/SKILL.md +++ b/plugins/bstack/skills/verify/SKILL.md @@ -11,6 +11,7 @@ description: Run the app and prove behaviour on the real surface. Start it safel - Use the repo's launch configuration (`.claude/launch.json`) or its documented dev command on test fixtures, in a worktree, via `run_in_background`, on its own absolute temp path (`DATA_DIR=/tmp/review`). Never production data, production URLs or real accounts. - **Side effects first.** Before running any path that could publish, send mail, call webhooks or paid APIs, or write to shared storage, confirm the app is in a dry-run, simulator or test mode and that outbound targets are empty or local mocks. If the mode lives in a database or a settings page, check it there, not in the code. A "test" mode that still talks to the real platform is not safe. If you cannot confirm it, do not run that path; report the gap. +- A binary in a shared target dir (`CARGO_TARGET_DIR`): start a copy on your temp path; a running exe blocks other worktrees' builds. - No launch configuration: start it per the README or Dockerfile and list "add a launch config on fixtures" as a finding. ## Find the surface diff --git a/tests/cargo-lock.test.mjs b/tests/cargo-lock.test.mjs index 13a61fb..f17294f 100644 --- a/tests/cargo-lock.test.mjs +++ b/tests/cargo-lock.test.mjs @@ -162,6 +162,36 @@ test('real cargo: a test that fails only on one worktree fails there, also when assert.match(second.stdout + second.stderr, /left: "broken"/); }); +test('real cargo: sources are marked changed only when another worktree built last, and never for cargo fmt', { skip: !hasCargo && 'cargo is not on PATH' }, async () => { + const target = tempDir('cargo-target'); + const [mine, other] = [crateWorktree('ok'), crateWorktree('ok')]; + const lib = dir => fs.statSync(path.join(dir, 'src', 'lib.rs')).mtimeMs; + const cargo = (cwd, ...args) => wrapped(['cargo', ...args], { cwd, targetDir: target }); + await cargo(mine, 'test', '--offline', '--quiet'); + const afterFirst = lib(mine); + await cargo(mine, 'test', '--offline', '--quiet'); + await cargo(mine, 'fmt', '--version'); + assert.equal(lib(mine), afterFirst); + await cargo(other, 'test', '--offline', '--quiet'); + await new Promise(r => setTimeout(r, 20)); + await cargo(mine, 'test', '--offline', '--quiet'); + assert.ok(lib(mine) > afterFirst); +}); + +test('real cargo: a cargo run, which builds without the lock, leaves no last builder, so the next locked run marks its sources', { skip: !hasCargo && 'cargo is not on PATH' }, async () => { + const target = tempDir('cargo-target'); + const mine = crateWorktree('ok'); + const lib = () => fs.statSync(path.join(mine, 'src', 'lib.rs')).mtimeMs; + const cargo = (...args) => wrapped(['cargo', ...args], { cwd: mine, targetDir: target }); + await cargo('test', '--offline', '--quiet'); + await cargo('run', '--offline', '--quiet'); + assert.equal(fs.existsSync(path.join(target, '.bstack-cargo.last')), false); + const afterRun = lib(); + await new Promise(r => setTimeout(r, 20)); + await cargo('test', '--offline', '--quiet'); + assert.ok(lib() > afterRun); +}); + // A program named cargo that is node: `cargo run` then runs the file `run` in its working directory. // Windows runs no script without a shell, so there it is node itself, else a stub that execs node. function fakeCargo() { diff --git a/tests/checks.test.mjs b/tests/checks.test.mjs index a7cbef5..78c07ec 100644 --- a/tests/checks.test.mjs +++ b/tests/checks.test.mjs @@ -228,3 +228,9 @@ test('the CLI runs every command in a real repo and reports why nothing was post fs.rmSync(dir, { recursive: true, force: true }); } }); + +test('a cargo command runs under the target lock, any other command as written', async () => { + const { underTargetLock } = await import('../plugins/bstack/scripts/checks.mjs'); + assert.match(underTargetLock('cargo test --workspace'), /cargo-lock\.mjs" cargo test --workspace$/); + assert.equal(underTargetLock('npm test'), 'npm test'); +}); diff --git a/tools/check-plugin.mjs b/tools/check-plugin.mjs index 2f8525a..3929120 100644 --- a/tools/check-plugin.mjs +++ b/tools/check-plugin.mjs @@ -29,7 +29,7 @@ const BUDGET = { const NOT_GUARDS = new Set(['${CLAUDE_PLUGIN_ROOT}/scripts/verdict.mjs handback']); const PLAYBOOK_BUDGET = 3584; const SKILL_BUDGET = 6144; -const TOTAL_TEXT_BUDGET = 64169; +const TOTAL_TEXT_BUDGET = 64848; function frontmatter(file) { const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(fs.readFileSync(file, 'utf8'));