@a2f0/agent-tool 0.1.57 → 0.1.59

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/README.md CHANGED
@@ -78,8 +78,9 @@ validation suite, and release procedures.
78
78
  ## Documentation
79
79
 
80
80
  - [Shared workflows](docs/workflows.md): branches, commit trust, copied hooks,
81
- PR checks/threads, cleanup, CI aggregate gates, release verification, durable
82
- validation receipts, and toolchain/protection diagnostics.
81
+ declared push gates, PR checks/threads, default-branch health, cleanup, CI
82
+ aggregate gates, release verification, durable validation receipts, and
83
+ toolchain/protection diagnostics.
83
84
  - [CLI reference](docs/reference.md): existing review, version, skill installation,
84
85
  command capture, import-graph checks, configuration, and distribution contracts.
85
86
  - [Development](docs/development.md): setup, source layout, validation, and release
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@a2f0/agent-tool",
3
- "version": "0.1.57",
3
+ "version": "0.1.59",
4
4
  "packageManager": "bun@1.4.4",
5
5
  "type": "module",
6
6
  "description": "Portable cross-agent review, PR workflows, and shared skills",
@@ -54,6 +54,9 @@ until the next review completes. Preserve unrelated work.
54
54
 
55
55
  Before reporting success, confirm HEAD still matches the reviewed commit and
56
56
  that an existing PR points to that same commit. If the base moved, refresh it and
57
- review again before shipping. Report reviewer, exact base and head IDs, verdict,
58
- remaining findings, validation, and any repairs performed. This skill does not
59
- authorize pushing, opening a PR, or merging unless the user requested that work.
57
+ review again before shipping, unless the new HEAD only integrated the base and
58
+ prepared versions and `agent-tool review carry <reviewed-head> <new-head>`
59
+ accepts it; then report the review as carried, with both heads. Report
60
+ reviewer, exact base and head IDs, verdict, remaining findings, validation, and
61
+ any repairs performed. This skill does not authorize pushing, opening a PR, or
62
+ merging unless the user requested that work.
@@ -20,21 +20,41 @@ or a targeted search; never dump an entire suite log or pipe checks into `tail`.
20
20
  The receipt proves process completion, not absence of warnings: inspect required
21
21
  warning, coverage, timing, or artifact evidence before accepting a check. Keep
22
22
  machine-readable receipts and review findings visible by running `versions
23
- prepare`, `review`, and other commands whose output drives a decision directly.
24
- Prefer documented compact test reporters when they preserve required evidence;
25
- do not reduce test scope, skip checks, silence warnings, or mask failures.
26
- Start servers, watchers, and other long-running processes with
23
+ prepare`, `review`, `repo base-health`, and other commands whose output drives a
24
+ decision directly. Prefer documented compact test reporters when they preserve
25
+ required evidence; do not reduce test scope, skip checks, silence warnings, or
26
+ mask failures. Start servers, watchers, and other long-running processes with
27
27
  `agent-tool proc start --label <name> -- <command>`, never a backgrounded shell
28
28
  command, so they can be found and stopped.
29
29
 
30
- 1. Finish the requested change on a feature branch. Use
30
+ 1. Start from the base branch's health: `agent-tool repo base-health` (with
31
+ `--branch <base-branch>` for another base). `green`, `pending`, and `no-ci`
32
+ need nothing more; report `no-ci` as missing CI on pushes. When it is
33
+ `red`, read the failing jobs' logs (`gh run view <run-id> --log-failed`
34
+ through `agent-tool run`) and relate them to the merges in
35
+ `breakingRange`. Broken logic from combined merges: fix it and add the test
36
+ that would have caught the combination. A flaky or timing-dependent test:
37
+ remove the race, ordering dependence, or shared state. Infrastructure or an
38
+ outside service: record it; rerun only when the log shows the cause was
39
+ external. Never retry until green, skip, or loosen an assertion. When
40
+ `openRepairs` lists a PR, do not duplicate it. Otherwise ship the repair
41
+ through this workflow as its own PR, naming the failing run in its body,
42
+ ahead of the requested change; when the change touches the same code, make
43
+ the repair a separate commit in that PR and say so in its description. A
44
+ red base does not block an unrelated change; stop only when the change
45
+ cannot be validated without the repair. A PR failure with the same job and
46
+ error as on the base is repaired on the base. Reverting the breaking merge
47
+ is allowed when the fix is not small and the break blocks a deploy or
48
+ publish; the revert names the merge and the follow-up that restores it.
49
+ 2. Finish the requested change on a feature branch. Use
31
50
  `agent-tool branch create <branch> --base <base-branch> --remote <remote>`
32
51
  from a clean checkout; it fetches and pins the base, checks naming policy and
33
52
  collisions, and creates without a local upstream. Use `branch check` with
34
- explicit destination names in CI or hooks.
35
- Validate it with appropriate project checks and commit only the intended
36
- files.
37
- 2. Use `agent-tool repo context --fetch` to resolve the PR's base repository
53
+ explicit destination names in CI or hooks. Before pushing, validate with the
54
+ repository's push gate and the tests that target the changed code, not the
55
+ full suite: CI runs everything and is the authority. Commit only the
56
+ intended files.
57
+ 3. Use `agent-tool repo context --fetch` to resolve the PR's base repository
38
58
  and branch, or the default branch when no PR exists, and fetch its exact base.
39
59
  Record the returned base/head identities. Integrate the fetched base
40
60
  using the repository's normal workflow, resolving conflicts without losing
@@ -45,28 +65,41 @@ command, so they can be found and stopped.
45
65
  `agent-tool versions resolve-conflicts` resolves conflicts confined to
46
66
  version fields. Review the resulting committed HEAD with an independent
47
67
  reviewer using the bundled cross-agent-review skill. Repair blocking findings
48
- and review every changed HEAD again. Review failure blocks shipping.
49
- 3. Run `agent-tool branch push <reviewed-head> --remote <remote>` through
68
+ and review every changed HEAD again. Review failure blocks shipping. One
69
+ change keeps a review: after a clean review, a new HEAD that only integrated
70
+ the base and prepared versions (as when another PR took the same version
71
+ first). When `agent-tool review carry <reviewed-head> <new-head>` exits 0
72
+ with `ok: true`, the earlier clean review stands, and the new HEAD is the
73
+ reviewed head from then on; report the review as carried, giving the
74
+ reviewed head and the command's JSON output. Every other changed HEAD,
75
+ including one the command rejects, gets an independent review, and CI
76
+ still runs on the new HEAD.
77
+ 4. Run `agent-tool branch push <reviewed-head> --remote <remote>` through
50
78
  normal hooks; it verifies local and remote identity afterward. If a hook
51
79
  changed content or HEAD, review that result.
52
80
  Open the PR using the open-pr skill, or update the existing PR as needed.
53
- 4. Allow configured review bots time to respond, then use
81
+ 5. Allow configured review bots time to respond, then use
54
82
  `agent-tool pr threads list` to fetch review threads and all comments. Follow repository policy for feedback: fix valid findings,
55
83
  reply with `pr threads reply <comment-id>` (body file or stdin), and use
56
84
  `pr threads resolve <thread-id>` only for fully addressed findings.
57
85
  Validate, commit, push, and independently review every feedback or CI repair.
58
86
  Wait with `agent-tool pr checks --wait --head <reviewed-head>`, whose limit
59
- defaults to `agent-tool.json` `merge.checksTimeoutSeconds`; when a job
60
- fails, read its log with `agent-tool pr logs --head <reviewed-head>`. When it
61
- stops with `behind: true`, the base moved: cancel the stale head's CI with
62
- `agent-tool pr cancel-runs --head <reviewed-head>`, integrate the reported
63
- base, validate, review, push the new head, and wait on it. Then run
87
+ defaults to `agent-tool.json` `merge.checksTimeoutSeconds`. When a job
88
+ fails, read its log with `agent-tool pr logs --head <reviewed-head>`, fix it
89
+ in a new commit, review it, push, and wait on the new head. A base that
90
+ moved (`behind: true`) needs no integration unless GitHub reports a
91
+ conflict, `versions check` fails against the live base, or the repository
92
+ sets `merge.requireStrictBaseFreshness`; under that policy the wait stops
93
+ early, so cancel the stale head's CI with
94
+ `agent-tool pr cancel-runs --head <reviewed-head>`, then integrate,
95
+ validate, review (or carry the review, as in step 3), push, and wait again.
96
+ Then run
64
97
  `agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` to
65
- recheck CI, live base, PR identity, local state, and explicit version policy.
66
- A changed base requires integration, validation, and another review. When
67
- versions are managed, `agent-tool versions check <base-oid>` must pass for the
68
- live base. Use the squash-merge skill to merge the exact reviewed HEAD.
69
- 5. After confirmed MERGED, follow the reset skill: run
98
+ recheck CI, conflicts, the live base, PR identity, local state, and explicit
99
+ version policy. When versions are managed,
100
+ `agent-tool versions check <live-base-oid>` must pass. Use the squash-merge
101
+ skill to merge the exact reviewed HEAD.
102
+ 6. After confirmed MERGED, follow the reset skill: run
70
103
  `agent-tool repo cleanup <PR-number> <reviewed-head> --apply` to return to the
71
104
  updated default branch and prune the shipped feature branch, honoring
72
105
  stronger repository cleanup rules. Never prune with raw `git branch -D` or
@@ -75,12 +108,20 @@ command, so they can be found and stopped.
75
108
  both feature refs. Check the cleanup receipt and verify the local feature ref
76
109
  is absent unless preserved; report incomplete cleanup explicitly. Apply
77
110
  documented dependency/hook setup.
78
- 6. When the project publishes npm packages, use `agent-tool release verify
111
+ 7. When the project publishes npm packages, use `agent-tool release verify
79
112
  <package> <version> <merge-oid> --workflow <publish-workflow>` to verify the
80
113
  exact workflow and tarball, allowing registry propagation time. When the
81
114
  project deploys the merged branch, verify that deployment and documented
82
115
  live checks. Report deployment failures
83
- separately from a successful merge; follow project policy for repairs.
116
+ separately from a successful merge; follow project policy for repairs. A
117
+ release that fails because another merge published the same version needs
118
+ a follow-up version bump through this workflow.
119
+ 8. Run `agent-tool repo base-health` again until it is no longer `pending` and
120
+ the merge commit, or a newer tip, has runs (`tip.hasRuns`). When no run
121
+ starts within about ten minutes, as with path filters or PR-only CI, or the
122
+ status is `no-ci`, report that and stop waiting. A failure there belongs to
123
+ this session: fix it forward through this workflow before reporting the
124
+ work done.
84
125
 
85
126
  Before the final report, run `agent-tool teardown` in each repository this work
86
127
  touched. Stop what the work started (`teardown --apply`, `proc stop`), stop any
@@ -88,9 +129,10 @@ untracked process it started, and remove worktrees it added. Report what
88
129
  remains and why; the work is not done while teardown fails for anything it
89
130
  started.
90
131
 
91
- Never infer a clean review from process success alone or carry a review across
92
- content changes. Do not weaken configured CI policy to get a merge through.
93
- If a step fails, preserve useful intermediate work and report the concrete
132
+ Never infer a clean review from process success alone, or carry a review to a
133
+ HEAD that `review carry` does not accept. Do not weaken configured CI policy to
134
+ get a merge through. If a step fails, preserve useful intermediate work and report the concrete
94
135
  remaining issue. Report PR link, merged commit, review verdict, validation, final
95
- checkout state, the teardown result, and whether the shipped local branch was
96
- pruned or preserved.
136
+ checkout state, the base's health at the start and end and anything repaired or
137
+ hardened, the teardown result, and whether the shipped local branch was pruned
138
+ or preserved.
@@ -13,15 +13,22 @@ Follow the repository's review-bot policy and require all actionable blocking
13
13
  review feedback to be addressed before merging.
14
14
 
15
15
  Wait with `agent-tool pr checks --wait --head <reviewed-head>`, which waits for
16
- checks to appear and for every workflow/job/event entry to finish, and stops
17
- early with `behind: true` once the live base moves past the head; then cancel
18
- that head's runs with `agent-tool pr cancel-runs --head <reviewed-head>` and
19
- integrate, validate, review, and push again. Run
16
+ checks to appear and for every workflow/job/event entry to finish, and reports
17
+ `behind: true` when the live base has moved past the head. A moved base alone
18
+ needs no integration: integrate, validate, review, and push again only when
19
+ GitHub reports a conflict, when `versions check` fails against the live base,
20
+ or when the repository sets `merge.requireStrictBaseFreshness`. Under that
21
+ policy the wait stops early at `behind: true`; cancel that head's runs with
22
+ `agent-tool pr cancel-runs --head <reviewed-head>` first. Run
20
23
  `agent-tool pr preflight <reviewed-head> <base-branch> <reviewed-base>` immediately
21
- before merging. It checks local and PR identity, live base, ancestry, explicit
22
- version policy, merge readiness, configured strict rulesets, and passing checks.
23
- If an identity changed, refresh, integrate, validate, and review again. Read
24
- unresolved feedback with `pr threads list` and follow project review policy.
24
+ before merging. It checks local and PR identity, that the head contains the
25
+ reviewed base, conflicts and merge readiness, explicit version policy against
26
+ the live base, configured strict rulesets, and passing checks; under the strict
27
+ policy the live base must also equal the reviewed one. If an identity changed,
28
+ refresh, integrate, validate, and review again; a new HEAD that
29
+ `agent-tool review carry <reviewed-head> <new-head>` accepts keeps the earlier
30
+ clean review. Read unresolved feedback with `pr threads list` and follow
31
+ project review policy.
25
32
 
26
33
  Use a title that satisfies `agent-tool.json` and pass both reviewed HEAD and
27
34
  base branch:
@@ -32,8 +39,9 @@ agent-tool pr merge 'feat: describe the change' <reviewed-head-oid> <base-branch
32
39
 
33
40
  The helper enforces HEAD atomically through GitHub's `expectedHeadOid`, checks
34
41
  CI, rejects queued or automatic merges, and creates a subject-only squash with
35
- the PR reference. GitHub has no atomic expected-base argument in this mutation;
36
- repository branch protection must enforce any required base freshness. With
42
+ the PR reference. GitHub has no atomic expected-base argument in this mutation,
43
+ so a base can move between preflight and merge; without the strict policy that
44
+ is accepted, and a break the combination causes is repaired on the base. With
37
45
  `merge.requireStrictBaseFreshness`, the helper refuses to merge unless an
38
46
  active strict status ruleset that the actor cannot bypass protects the base. Do
39
47
  not retarget the PR concurrently with merging.
package/src/cli.ts CHANGED
@@ -8,6 +8,7 @@ import { checkGraph } from "./graph/check";
8
8
  import { stateMachinesCommand } from "./stateMachines/command";
9
9
  import { buildScreenshots, describeScreenshots } from "./screenshots/build";
10
10
  import { review } from "./harnesses";
11
+ import { carryReviewCommand } from "./review/carry";
11
12
  import { runAgentToolAction } from "./runAgentToolAction";
12
13
  import { BUNDLED_SKILLS } from "./skills/bundled";
13
14
  import { checkSkills, installSkills } from "./skills/install";
@@ -24,6 +25,7 @@ import { runGroup, listRuns } from "./commands/group";
24
25
  import { branchCommand } from "./workflows/branch";
25
26
  import { commitsCommand, binariesCommand, gateCommand } from "./workflows/checks";
26
27
  import { hooksCommand } from "./workflows/hooks";
28
+ import { pushGateCommand } from "./workflows/pushGate";
27
29
  import { repoCommand, policyCommand, toolchainCommand } from "./workflows/repository";
28
30
  import { mergeReviewedHead, prWorkflowCommand } from "./workflows/pr";
29
31
  import { releaseCommand } from "./release/commands";
@@ -47,13 +49,17 @@ Usage: agent-tool [--repo <directory>] [--config <file>] <command>
47
49
  commits check --message-file <file> Commit-msg attribution and subject policy
48
50
  checks binaries [--staged|--all|--range range|--from-upstream]
49
51
  hooks install [--apply] [--adopt] | check
52
+ push-gate hook | check Canonical pre-push body; static check: no tests, builds, or installs
53
+ push-gate run --pre-push <remote> <url> Built-in guards, then pushGate steps (the pre-push body)
50
54
  repo context [--fetch] | cleanup <PR> <shipped-head> [--apply] [--keep-branch]
55
+ repo base-health [--branch name] [--limit N] CI health of the default branch's tip (GitHub only)
51
56
  policy check | toolchain check
52
57
  ci gate <needs.json|-> [--policy policy.json]
53
58
  release plan <package.json> [--github-output] [--allow-private-source]
54
59
  release verify <package> <version> <merge-oid> --workflow name [--timeout seconds]
55
60
  logs <file> [--max-bytes N] [--tail-lines N] Bounded local log tail
56
61
  review <claude|codex|opencode> [effort] [--base <local-ref>]
62
+ review carry <reviewed-head> <new-head> [--base <ref>] Whether a clean review covers a base-merge and versions-only head
57
63
  pr open [title] [--body-file file] Body from the file or stdin; branch already pushed
58
64
  pr merge <subject-or-empty> <head-oid> <base-branch>
59
65
  pr context | checks [--wait] [--head oid] [--allow-behind] [--timeout seconds]
@@ -201,6 +207,8 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
201
207
  output({ applied: apply, changes: installSkills(process.cwd(), target, apply) }); return 0;
202
208
  }
203
209
  if (command === "bun") return bunCommand(args);
210
+ // The hook body needs no checkout, and `run` must resolve the root before clearing Git's hook environment.
211
+ if (command === "push-gate") return pushGateCommand(args);
204
212
  if (command === "permissions") {
205
213
  const action = args.shift();
206
214
  usage(action === "show" || action === "install" || action === "check", "Usage: agent-tool permissions <show|install|check> [--harness <all|claude|codex>] [--apply]");
@@ -231,6 +239,7 @@ export function main(argv = process.argv.slice(2)): number | Promise<number> {
231
239
  if (command === "run-group") return runGroup(args);
232
240
  if (command === "runs") return listRuns(args);
233
241
  if (command === "checks") { usage(args.shift() === "binaries", "Usage: checks binaries [--staged|--all|--range range|--from-upstream]"); return binariesCommand(args); }
242
+ if (command === "review" && args[0] === "carry") return carryReviewCommand(root, args.slice(1));
234
243
  if (command === "review") {
235
244
  const name = args.shift(); usage(!!name, "Usage: agent-tool review <claude|codex|opencode> [effort] [--base ref]");
236
245
  let effort: string | undefined, base: string | undefined;
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { execFileSync } from "node:child_process";
3
- import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, writeFileSync } from "node:fs";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, writeFileSync } from "node:fs";
4
4
  import { constants } from "node:os";
5
5
  import path from "node:path";
6
6
  import { FORWARDED_SIGNALS, runCommand, type RunReceipt } from "./run";
@@ -11,17 +11,51 @@ export interface SourceState { headOid: string; treeOid: string; branch: string
11
11
  export function sourceState(): SourceState {
12
12
  const hash = createHash("sha256");
13
13
  const add = (value: string | Buffer) => { hash.update(String(Buffer.byteLength(value))); hash.update(":" ); hash.update(value); };
14
- const rawDiff = (args: string[]) => execFileSync("git", ["diff", "--no-ext-diff", "--no-textconv", "--binary", ...args, "--"], { env: gitEnvironment(), maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
15
- add(rawDiff(["HEAD"])); add(rawDiff(["--cached"]));
16
- for (const record of git(["status", "--porcelain=v2", "--ignore-submodules=none", "-z"]).split("\0")) {
14
+ fingerprintCheckout(add, process.cwd(), "", gitEnvironment(), ["HEAD"]);
15
+ return { headOid: head(), treeOid: git(["rev-parse", "HEAD^{tree}"]), branch: git(["branch", "--show-current"]) || null, fingerprint: hash.digest("hex") };
16
+ }
17
+
18
+ /** Where Git finds a repository; a hook may export them, and a nested repository's reads must find its own. */
19
+ const GIT_LOCATION = ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY", "GIT_ALTERNATE_OBJECT_DIRECTORIES", "GIT_COMMON_DIR", "GIT_PREFIX", "GIT_IMPLICIT_WORK_TREE", "GIT_GRAFT_FILE", "GIT_SHALLOW_FILE", "GIT_REPLACE_REF_BASE"];
20
+
21
+ /**
22
+ * Hash a checkout's tracked changes (against `diffBase`), its staged changes,
23
+ * and its nonignored untracked files, naming each file with `prefix`. Git lists
24
+ * an untracked nested repository as one `dir/` entry without descending into
25
+ * it; that repository is hashed the same way from its own root, after its HEAD
26
+ * (or `unborn`), so a commit, edit, or new file inside it changes the result.
27
+ */
28
+ function fingerprintCheckout(add: (value: string | Buffer) => void, cwd: string, prefix: string, env: NodeJS.ProcessEnv, diffBase: string[]): void {
29
+ const read = (args: string[]) => execFileSync("git", args, { cwd, env, maxBuffer: 64 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
30
+ const rawDiff = (args: string[]) => read(["diff", "--no-ext-diff", "--no-textconv", "--binary", ...args, "--"]);
31
+ add(rawDiff(diffBase)); add(rawDiff(["--cached"]));
32
+ for (const record of read(["status", "--porcelain=v2", "--ignore-submodules=none", "-z"]).toString("utf8").split("\0")) {
17
33
  if (/^[12] /.test(record)) { const submodule = record.split(" ")[2]!; assert(!submodule.startsWith("S") || submodule === "S...", "Dirty submodules cannot be fingerprinted; validate from a clean submodule state."); }
18
34
  }
19
- for (const file of git(["ls-files", "--others", "--exclude-standard", "-z"]).split("\0").filter(Boolean).sort()) {
20
- add(file); const stat = lstatSync(file); add(String(stat.mode));
21
- if (stat.isSymbolicLink()) add(readlinkSync(file));
22
- else { assert(stat.isFile(), `Cannot fingerprint non-file '${file}'.`); add(readFileSync(file)); }
35
+ let nestedEnv: NodeJS.ProcessEnv | undefined;
36
+ for (const file of read(["ls-files", "--others", "--exclude-standard", "-z"]).toString("utf8").split("\0").filter(Boolean).sort()) {
37
+ const full = path.join(cwd, file);
38
+ add(prefix + file); const stat = lstatSync(full); add(String(stat.mode));
39
+ if (stat.isSymbolicLink()) add(readlinkSync(full));
40
+ else if (stat.isFile()) add(readFileSync(full));
41
+ else {
42
+ nestedEnv ??= Object.fromEntries(Object.entries(env).filter(([name]) => !GIT_LOCATION.includes(name)));
43
+ const headOid = stat.isDirectory() && file.endsWith("/") ? nestedHead(full, nestedEnv) : undefined;
44
+ assert(headOid !== undefined, `Cannot fingerprint non-file '${prefix + file}'.`);
45
+ add(headOid ?? "unborn");
46
+ // Without a commit there is no HEAD to diff against; the index stands in for it.
47
+ fingerprintCheckout(add, full, prefix + file, nestedEnv, headOid === null ? [] : ["HEAD"]);
48
+ }
23
49
  }
24
- return { headOid: head(), treeOid: git(["rev-parse", "HEAD^{tree}"]), branch: git(["branch", "--show-current"]) || null, fingerprint: hash.digest("hex") };
50
+ }
51
+
52
+ /** The HEAD commit of the repository rooted at `directory` (null when unborn), or undefined when Git does not see one there. */
53
+ function nestedHead(directory: string, env: NodeJS.ProcessEnv): string | null | undefined {
54
+ const top = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: directory, env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
55
+ // A `.git` Git cannot open makes it resolve the enclosing repository instead.
56
+ if (top.status !== 0 || realpathSync(top.stdout.trim()) !== realpathSync(directory)) return undefined;
57
+ const resolved = spawnSync("git", ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"], { cwd: directory, env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
58
+ return resolved.status === 0 ? resolved.stdout.trim() : null;
25
59
  }
26
60
 
27
61
  function reportsDirectory(): string { return path.join(git(["rev-parse", "--path-format=absolute", "--git-common-dir"]), "agent-tool", "runs"); }
@@ -30,9 +64,9 @@ function save(file: string, value: unknown): void {
30
64
  writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" });
31
65
  renameSync(temporary, file);
32
66
  }
33
- interface Step { label: string; command: string[] }
34
- export function parseGroup(source: string): { label: string; steps: Step[] } {
35
- const plan = JSON.parse(source) as { label: string; steps: Step[] };
67
+ export interface PlanStep { label: string; command: string[] }
68
+ export function parseGroup(source: string): { label: string; steps: PlanStep[] } {
69
+ const plan = JSON.parse(source) as { label: string; steps: PlanStep[] };
36
70
  const label = (value: unknown) => typeof value === "string" && value.length > 0 && value.length <= 120 && !/[\x00-\x1f]/.test(value);
37
71
  assert(plan && typeof plan === "object" && !Array.isArray(plan) && Object.keys(plan).every(key => ["label", "steps"].includes(key)) && label(plan.label) && Array.isArray(plan.steps) && plan.steps.length > 0, "Invalid run-group plan; expected label and nonempty steps.");
38
72
  const labels = new Set<string>();
@@ -109,6 +143,26 @@ function assertNever(value: never): never { throw new Error(`Unhandled run-group
109
143
  export async function runGroup(args: string[]): Promise<number> {
110
144
  assert(args.length === 1, "Usage: run-group <plan.json>");
111
145
  const plan = parseGroup(readFileSync(args[0]!, "utf8"));
146
+ const result = await executeGroup(plan, (record, report) => output({ ...record, report }));
147
+ return reraiseGroupSignal(result);
148
+ }
149
+
150
+ export interface GroupResult { record: GroupRecord; report: string; code: number; signal: NodeJS.Signals | null }
151
+
152
+ /** Preserve signal termination for calling shells and supervisors, as `run` does. */
153
+ export async function reraiseGroupSignal({ code, signal }: Pick<GroupResult, "code" | "signal">): Promise<number> {
154
+ if (!signal) return code;
155
+ process.kill(process.pid, signal);
156
+ await new Promise(resolve => setTimeout(resolve, 100));
157
+ return 128 + (constants.signals[signal] ?? 0);
158
+ }
159
+
160
+ /**
161
+ * Run a plan's steps and save its report. `publish` runs once the report is
162
+ * final, while signals still reach the group's handlers (which then ignore
163
+ * them), so publishing cannot be cut short. The caller re-raises `signal`.
164
+ */
165
+ export async function executeGroup(plan: { label: string; steps: PlanStep[] }, publish: (record: GroupRecord, report: string) => void): Promise<GroupResult> {
112
166
  const before = sourceState();
113
167
  const directory = reportsDirectory(); mkdirSync(directory, { recursive: true, mode: 0o700 });
114
168
  const id = `${new Date().toISOString().replaceAll(":", "-")}-${randomUUID()}`;
@@ -149,20 +203,13 @@ export async function runGroup(args: string[]): Promise<number> {
149
203
  await handleSignals();
150
204
  send({ type: "finished", passed: code === 0, endedAt, durationMs }); send(settle);
151
205
  save(report, record);
152
- output({ ...record, report });
206
+ publish(record, report);
153
207
  // Signals that arrived while publishing reach the handlers, which ignore them now.
154
208
  await handleSignals();
155
209
  } finally {
156
210
  for (const [value, handler] of handlers) process.removeListener(value, handler);
157
211
  }
158
- const { signal } = interrupt;
159
- if (signal) {
160
- // Preserve signal termination for calling shells and supervisors, as `run` does.
161
- process.kill(process.pid, signal);
162
- await new Promise(resolve => setTimeout(resolve, 100));
163
- return 128 + (constants.signals[signal] ?? 0);
164
- }
165
- return code;
212
+ return { record, report, code, signal: interrupt.signal };
166
213
  }
167
214
 
168
215
  export function listRuns(args: string[]): number {
package/src/config.ts CHANGED
@@ -11,6 +11,10 @@ export interface RequiredCheck {
11
11
  workflow?: string;
12
12
  }
13
13
 
14
+ /** A declared push-gate step: run-group's step shape plus a visible reason when it may be slow. */
15
+ export interface PushGateStep { label: string; command: string[]; allowSlow?: string }
16
+ export interface PushGateConfig { steps: PushGateStep[]; budgetSeconds: number }
17
+
14
18
  export interface AgentToolConfig extends WorkflowConfig {
15
19
  schemaVersion: 1;
16
20
  subject: { conventional: boolean; maxLength: number; types: string[]; lowercaseInitial: boolean; rejectTerminalPeriod: boolean; ignoreGenerated: boolean };
@@ -22,6 +26,8 @@ export interface AgentToolConfig extends WorkflowConfig {
22
26
  screenshots: ScreenshotsConfig;
23
27
  graph: GraphConfig;
24
28
  permissions: { executables: Record<string, PermissionClass> };
29
+ /** Null when the repository declares no push gate. */
30
+ pushGate: PushGateConfig | null;
25
31
  }
26
32
 
27
33
  export const DEFAULT_CONFIG: AgentToolConfig = {
@@ -43,8 +49,35 @@ export const DEFAULT_CONFIG: AgentToolConfig = {
43
49
  screenshots: structuredClone(SCREENSHOTS_DEFAULTS),
44
50
  graph: structuredClone(GRAPH_DEFAULTS),
45
51
  permissions: { executables: {} },
52
+ pushGate: null,
46
53
  };
47
54
 
55
+ export const PUSH_GATE_BUDGET_SECONDS = 120;
56
+
57
+ /** Same step rules as run-group plans, plus an optional non-empty `allowSlow` reason. */
58
+ function parsePushGate(value: unknown): PushGateConfig {
59
+ const input = object(value, "pushGate");
60
+ keys(input, ["steps", "budgetSeconds"], "pushGate");
61
+ const invalid = (setting: string): never => { throw new Error(`Invalid config setting 'pushGate.${setting}'.`); };
62
+ const budgetSeconds = input.budgetSeconds ?? PUSH_GATE_BUDGET_SECONDS;
63
+ if (!Number.isSafeInteger(budgetSeconds) || (budgetSeconds as number) < 1 || (budgetSeconds as number) > 86400) invalid("budgetSeconds");
64
+ const steps = input.steps ?? [];
65
+ if (!Array.isArray(steps)) invalid("steps");
66
+ const label = (text: unknown) => typeof text === "string" && text.length > 0 && text.length <= 120 && !/[\x00-\x1f]/.test(text);
67
+ const labels = new Set<string>();
68
+ const parsed = (steps as unknown[]).map(step => {
69
+ const entry = object(step, "pushGate.steps entry");
70
+ keys(entry, ["label", "command", "allowSlow"], "pushGate.steps entry");
71
+ const { command, allowSlow } = entry;
72
+ if (!label(entry.label) || labels.has(entry.label as string)) invalid("steps");
73
+ if (!Array.isArray(command) || !command.length || !command.every(arg => typeof arg === "string" && !arg.includes("\0")) || !command[0]) invalid("steps");
74
+ if (allowSlow !== undefined && (typeof allowSlow !== "string" || !allowSlow.trim() || /[\x00-\x1f]/.test(allowSlow))) invalid("steps");
75
+ labels.add(entry.label as string);
76
+ return { label: entry.label as string, command: [...command as string[]], ...(allowSlow === undefined ? {} : { allowSlow: allowSlow as string }) };
77
+ });
78
+ return { steps: parsed, budgetSeconds: budgetSeconds as number };
79
+ }
80
+
48
81
  function object(value: unknown, name: string): Record<string, unknown> {
49
82
  if (!value || typeof value !== "object" || Array.isArray(value)) {
50
83
  throw new Error(`${name} must be an object.`);
@@ -77,6 +110,7 @@ export function parseConfig(source: string): AgentToolConfig {
77
110
  if (input.images !== undefined) result.images = parseImages(input.images);
78
111
  if (input.screenshots !== undefined) result.screenshots = parseScreenshots(input.screenshots);
79
112
  if (input.graph !== undefined) result.graph = parseGraph(input.graph);
113
+ if (input.pushGate !== undefined && input.pushGate !== null) result.pushGate = parsePushGate(input.pushGate);
80
114
  if (input.branch !== undefined && !Object.hasOwn(input.branch as object, "enforce")) result.branch.enforce = true;
81
115
  const invalid = (setting: string): never => { throw new Error(`Invalid config setting '${setting}'.`); };
82
116
  if (typeof result.subject.conventional !== "boolean") invalid("subject.conventional");
@@ -19,7 +19,7 @@ export type Decision = "allow" | "ask";
19
19
  export interface CatalogEntry { command: string; class: PermissionClass; applyClass?: PermissionClass }
20
20
 
21
21
  export const CATALOG: CatalogEntry[] = [
22
- ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
22
+ ...["--help", "--version", "logs", "runs list", "doctor", "config show", "branch check", "branch status", "commits check", "checks binaries", "repo context", "policy check", "toolchain check", "ci gate", "release plan", "release verify", "pr context", "pr checks", "pr logs", "pr preflight", "pr threads list", "versions plan", "versions check", "dependencies check-terraform-plan", "dependencies diff", "skills list", "skills check", "hooks check", "push-gate hook", "push-gate check", "repo base-health", "review carry", "images list", "graph check", "state-machines", "permissions show", "permissions check", "proc list"]
23
23
  .map(command => ({ command, class: "read" as const })),
24
24
  ...["bun install", "bun update", "bun remove", "bun test", "branch create", "versions bump", "versions prepare", "versions resolve-conflicts", "images build", "screenshots build", "review", "init", "proc stop"]
25
25
  .map(command => ({ command, class: "local" as const })),
@@ -38,7 +38,7 @@ export const CATALOG: CatalogEntry[] = [
38
38
  ...["bumpVersions", "resolveVersionConflicts", "solicitClaudeCodeReview", "solicitCodexReview", "solicitOpencodeReview"].map(command => ({ command, class: "local" as const })),
39
39
  { command: "openPr", class: "share" },
40
40
  ];
41
- // `run`, `run-group` and `proc start` execute arbitrary commands, so they stay unclassified and keep the harness default.
41
+ // `run`, `run-group`, `push-gate run` and `proc start` execute arbitrary commands, so they stay unclassified and keep the harness default.
42
42
  // `bun x` runs only executables that `permissions.executables` classifies; project.ts adds those.
43
43
  // Package scripts are not classified, so `bun run` keeps the harness default.
44
44
 
@@ -113,6 +113,14 @@ export function installPermissions(rootDir: string, target: string, apply = fals
113
113
  return changes.map(({ relative, status }) => ({ path: relative, status }));
114
114
  }
115
115
 
116
+ /** The `--harness` a repository's rules were installed for, from its manifest, or null when it has none. */
117
+ export function installedPermissionHarness(rootDir: string): string | null {
118
+ const root = realpathSync(rootDir);
119
+ if (!existsSync(destination(root, MANIFEST))) return null;
120
+ const manifest = readManifest(root);
121
+ return manifest.claude && !manifest.codex ? "claude" : manifest.codex && !manifest.claude ? "codex" : "all";
122
+ }
123
+
116
124
  /** Read-only CI gate: generated rules are current and recorded as managed. */
117
125
  export function checkPermissions(rootDir: string, target: string): PermissionCheck[] {
118
126
  const root = realpathSync(rootDir);