opencode-workflow-guard 1.19.5 → 1.19.6
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 +1 -1
- package/docs/policies.md +3 -1
- package/docs/testing.md +2 -0
- package/package.json +1 -1
- package/src/lib/custom-tools.ts +20 -7
- package/src/lib/review.ts +29 -3
- package/src/policies/boundary.ts +29 -1
- package/test/test.mts +183 -2
package/README.md
CHANGED
|
@@ -59,7 +59,7 @@ For complete policy specifications and override rules, see [docs/policies.md](do
|
|
|
59
59
|
Enforcement is only half the surface. The plugin also registers first-class agent tools under the same names on OpenCode 1.x and 2.x, so disciplined workflow is the path of least resistance:
|
|
60
60
|
|
|
61
61
|
* **Task Planning:** `guard_next_tasks` surfaces durable repository planning context at session start or during planning. It reads `TODO.md`, `ROADMAP.md`, `PLAN.md`, `TASKS.md`, `BACKLOG.md`, their `docs/` counterparts, and plans under `docs/plans/`. `guard_status` reports active guardrails, branch protection, mutation counts, outstanding verification and review gates, a read-only git-hygiene snapshot, and the loaded `pluginVersion`.
|
|
62
|
-
* **Review & Verification:** before PR creation, a secondary reviewer subagent evaluates the diff against `guard_review_rubric`. The rubric covers five axes: test integrity, task completeness, cleanliness, security, and platform. The
|
|
62
|
+
* **Review & Verification:** before PR creation, a secondary reviewer subagent evaluates the diff against `guard_review_rubric`. The rubric covers five axes: test integrity, task completeness, cleanliness, security, and platform, and its first line names the workspace, base ref, and diff size it graded. When no listed base yields a diff the tool refuses and names what it tried instead of grading a substitute range. The calling session records the subagent's verdict with `record_review`, and approvals bind to the reviewed worktree content. An opt-in dogfood gate adds a recorded end-to-end run on real hardware with `record_dogfood`.
|
|
63
63
|
* **Worktree Isolation:** `guard_worktree_create` and `guard_worktree_cleanup` give parallel subagents isolated linked worktrees, so concurrent mutations never collide.
|
|
64
64
|
* **Technical Debt:** `guard_review_followups` lists open P2/P3 durable review follow-ups. `guard_review_followup_resolve` closes one after the underlying issue is fixed and verified.
|
|
65
65
|
* **Policy Simulation:** `guard_why` returns the structured policy decision for a tool call or command without performing it. `guard_audit` shows recent audited policy entries.
|
package/docs/policies.md
CHANGED
|
@@ -26,7 +26,7 @@ This is a policy and enforcement layer, not an agent harness. Policies may const
|
|
|
26
26
|
- **Handoff Safety:** An idle subagent whose effective todos are inherited from its parent is not auto-continued. Inherited work belongs to the parent and can be handed back normally.
|
|
27
27
|
- **Durable Planning Context Discovery:** `guard_next_tasks` prefers a repository-root `TODO.md`. When it is absent, it reads conventional `ROADMAP.md`, `PLAN.md`, `TASKS.md`, `BACKLOG.md`, their `docs/` counterparts, and Markdown files under `docs/plans/`. The tool exposes candidate planning context without selecting, prioritizing, or sequencing tasks. These files never replace OpenCode's native runtime todo state.
|
|
28
28
|
- **Subagent Mutation Budget:** Subagent sessions are protected by a mutation safety budget (`maxSubagentMutations` in project config or `WORKFLOW_GUARD_MAX_SUBAGENT_MUTATIONS` env, default 100). The budget terminates runaway edit loops deterministically.
|
|
29
|
-
- **Concurrent File Claims:** Direct `edit`, `write`, and `apply_patch` calls claim each canonical target for the tool-call lifetime. A different active session is blocked from racing the same file, including through symlink aliases. Claims are released after the call, with session idle/deletion as stale-claim cleanup when an after hook is missed. Two provable staleness rules reclaim a leaked claim, each audited, and both stay scoped to the contended paths so a long-running command elsewhere keeps its claim. The idle rule releases a claim created before its owner's last recorded idle timestamp, because that call finished before the turn ended. It writes a `stale_claim_takeover` entry. The TTL rule releases a claim older than the effective claim TTL, which covers a deleted session and a server restart where the owner record cannot be read at all. It writes a `claim_ttl_expired` entry with the owner and claim age. The TTL defaults to five minutes, is raised or lowered with `claimTtlMs` in `.opencode/workflow-guard.json`, and `WORKFLOW_GUARD_CLAIM_TTL_MS` wins over project config. A non-positive or unparseable value falls back to the default. Owners still mid-session within the TTL, clients without a session lookup, and failed lookups keep the block (fail-closed). The block names the owner, the claim age, and the reclaim step. `guard_why` stays read-only and still reports the conflict as blocked. Shell writers
|
|
29
|
+
- **Concurrent File Claims:** Direct `edit`, `write`, and `apply_patch` calls claim each canonical target for the tool-call lifetime. A different active session is blocked from racing the same file, including through symlink aliases. Claims are released after the call, with session idle/deletion as stale-claim cleanup when an after hook is missed. Two provable staleness rules reclaim a leaked claim, each audited, and both stay scoped to the contended paths so a long-running command elsewhere keeps its claim. The idle rule releases a claim created before its owner's last recorded idle timestamp, because that call finished before the turn ended. It writes a `stale_claim_takeover` entry. The TTL rule releases a claim older than the effective claim TTL, which covers a deleted session and a server restart where the owner record cannot be read at all. It writes a `claim_ttl_expired` entry with the owner and claim age. The TTL defaults to five minutes, is raised or lowered with `claimTtlMs` in `.opencode/workflow-guard.json`, and `WORKFLOW_GUARD_CLAIM_TTL_MS` wins over project config. A non-positive or unparseable value falls back to the default. Owners still mid-session within the TTL, clients without a session lookup, and failed lookups keep the block (fail-closed). The block names the owner, the claim age, and the reclaim step. `guard_why` stays read-only and still reports the conflict as blocked. A recognized shell writer is refused with the same reason when its target is claimed: redirection, `tee`, `sed -i`, `cp`/`mv`/`ln`, `rm`, `truncate`, `dd of=`, `git apply`, and `git am`. A `mv` source is checked too, because the move removes it. The check resolves a relative target against the tree the segment actually runs in, so a chained `cd` and a symlink alias are judged where the write lands. A shell write never acquires a claim, so it cannot strand one the edit path must later reclaim, and the provably stale rules release before the conflict is reported. Shell writers remain outside the write-observation and stale-write pre-check, and isolated worktrees remain the better choice for substantial parallel mutations.
|
|
30
30
|
- **Stale-Write Protection:** A successful `read` records a same-session fingerprint for an existing regular file from five fields. Those fields are canonical path, filesystem identity, size, nanosecond mtime, and SHA-256 content digest. A successful `edit`/`write` also records the resulting bytes, and only when the file actually changed. The session authored those bytes, so iterating on a just-created or just-modified file needs no redundant re-read. Before `edit` or `write` replaces an existing file, that fingerprint must exist and still match. Otherwise the call is blocked and must re-read. New-file creation is allowed without a prior read. Fingerprints are not inherited between parent and subagent sessions, and they are cleared on session idle or deletion. `apply_patch` and shell writers sit deliberately outside this bounded mechanism. An `apply_patch` result still seeds the session observation, but its clobbering itself is not pre-checked. The pre-execution comparison also cannot make external changes between the check and OpenCode's write atomic.
|
|
31
31
|
- **Shell-redirect seeding:** An allowed shell command that redirects into a workspace file (`cmd > file`, `cmd >> file`, fd forms) seeds the session's observation of the resulting bytes. It does so in the same change-gated way as direct edits. A file this session just created or rewrote via a shell redirect can therefore be edited without a redundant re-read. Redirects to `/dev/null`, the `/tmp/opencode` scratch directory, or outside the workspace seed nothing. An identical-byte (no-op) redirect does not seed. The not-read block message also suggests coordinating when another session may own the file. Shell writers themselves remain outside the bounded pre-check, so only the observation seeding applies.
|
|
32
32
|
|
|
@@ -264,6 +264,8 @@ Besides enforcement hooks, the guard registers companion tools in OpenCode:
|
|
|
264
264
|
- `guard_status`, `guard_audit`, `guard_why`, `guard_review_rubric`, `record_review`, `guard_review_followups`, and `guard_review_followup_resolve` provide runtime introspection. They cover guardrail state, audit entries, block explanations, reviewer rubric definitions, reviewer decisions, and durable local review debt. `guard_status` also exposes the effective Ralph opt-in, its iteration budget, and the calling-session outcome when applicable. It reports a read-only `gitHygiene` snapshot (local branches already merged into the mainline, prunable worktree admin entries, and the current branch's base-behind distance). Hygiene itself stays manual: the guard reports, it never prunes or deletes branches. `guard_status` also reports `pluginVersion`, the version of the loaded guard package, so a stale installation is visible.
|
|
265
265
|
- On OpenCode 2 the same report is also reachable as the server-side `/guard-status` command (`ctx.command.transform`). It delivers the JSON as a synthetic message with no model turn. That path needs no separately installed TUI companion.
|
|
266
266
|
- **Priority-Ranked Review Gate:** Secondary review approval (`requireReview`) is enforced by default during PR preflight (`gh pr create` / `az repos pr create`). Before creating a pull request, a secondary reviewer subagent must evaluate the changes using `guard_review_rubric` and record approval with `record_review`. Approvals that include active P0 (blocker) or P1 (major defect) issues are rejected until blockers are resolved. Projects can opt out via `.opencode/workflow-guard.json` (`{ "requireReview": false }`) or environment variable `WORKFLOW_GUARD_REQUIRE_REVIEW=0`. Conversely, `WORKFLOW_GUARD_REQUIRE_REVIEW=1` forces the review requirement regardless of project config.
|
|
267
|
+
- **The rubric names what it graded:** `guard_review_rubric` prefixes the prompt with `Provenance: workspace=<abs root> base=<ref> diff=<n> bytes fallback=<none|HEAD~1>`. A session's own checkout and the checkout holding the change are not always the same tree, so the caller checks those three facts before trusting the prompt. Pass `directory` to grade another worktree and `base` to name another base. When no listed base yields a diff, the tool refuses with the workspace, every base it tried, and the remedy. It does not run `git diff HEAD~1` behind the caller's back, because that graded a substitute range and named nothing. `HEAD~1` is graded only when the caller passes `base: "HEAD~1"`, and the provenance line then says `base=HEAD~1 fallback=HEAD~1`.
|
|
268
|
+
- **The calling session records the verdict:** A reviewer agent is often configured with a toolset that omits `record_review`, so the injected guidance and both tool descriptions say the calling session records the subagent's verdict. `record_review` binds that verdict to the recorder's resolved directory or an explicit `directory`.
|
|
267
269
|
- **Review binding is content, not session identity:** A recorded approval satisfies the PR preflight when its binding matches the tree the PR would publish. The binding covers the repository, the commit hash, and the tracked-content worktree fingerprint. Any session may record the verdict or create the PR. Reviewers record from subagent sessions, binding the verdict to their parent or their own directory. Sessions can move between directories (`session_move`), and subagents can spawn from other roots. Keying the gate on the PR-creating session's ID would make the documented flow impossible to satisfy from linked worktrees. Freshness is scoped to the reviewed diff, which is tracked content. Untracked scratch-file cleanup and mutations in sibling worktrees cannot invalidate an approval. Any tracked edit or new commit does.
|
|
268
270
|
- **Commit before you verify and review:** Both evidence gates bind to the HEAD commit hash, so a commit after either one invalidates it. Finish every tracked change first, then run verification, then record the review, then open the PR. That order satisfies both gates in one pass. Any other order costs a re-run. A review recorded before its change is committed keeps the same tracked fingerprint. The preflight then names the commit drift specifically and asks for the review again at the current commit.
|
|
269
271
|
- **`record_review` accepts any recorder session:** Reviewer agents are often configured with a read-only toolset, for example glob, grep, read, and webfetch only. Such a reviewer cannot call `record_review` itself. The tool therefore accepts recorders of any session type and binds the verdict to the recording session's resolved directory. The tool result echoes that binding. The audit entry (`record_review.verdict`) records the binding key and recorder lineage (`recorderRole: root | subagent`), and `guard_status.lastReview` reports the same lineage beside the parent it was recorded for. Prefer relaying through an independent secondary reviewer subagent. The tool result reminds the recorder when it runs from a root session. A verdict recorded against a directory without a computable tracked fingerprint (not a git repository) is rejected loudly and never recorded.
|
package/docs/testing.md
CHANGED
|
@@ -51,6 +51,8 @@ npm run test:all
|
|
|
51
51
|
| **Policy 8: Workspace Boundary** | Verifies path traversal (`../`), symlinks, and absolute path escape protection in `edit`, `write`, `apply_patch`, and shell mutations. Also verifies the `/tmp/opencode` scratch allowance: a real session may write, redirect, patch, and run an interpreter payload there, while a session-less write, a sibling that shares the prefix, a `..` traversal out of it, and a symlink that leaves it stay blocked. |
|
|
52
52
|
| **Policy 10: Evidence Verification** | Verifies isolated verification execution, timeout handling, scrubbed environment, and finalization gating on fresh passing tests. A timeout blocks finalization under its own code, and its reason names the limit and the remedy instead of claiming a failing test. Also verifies `guard_status` names the project config file it read, attributes the effective verify command to `project-config`, `auto-detected`, or neither, and puts the environment ahead of both. A configured command that passes leaves `lastVerify` with a timestamp and commit hash, a later mutation makes it not fresh, and a deliberately failing configured command blocks finalization. |
|
|
53
53
|
| **File-Claim TTL Reclaim** | Verifies a claim within the TTL blocks and names the reclaim step, an expired claim is reclaimed for the next claimant, the reclaim writes a `claim_ttl_expired` audit with the owner and age, the environment override wins, and project config `claimTtlMs` is honored. |
|
|
54
|
+
| **Shell Mutation Claim Conflicts** | Verifies a redirect into a claimed path is refused with the claim reason, `tee -a` with its flag parsed is refused, a symlink alias is refused, a chained `cd` is judged in the tree it lands in, a multi-operand mutation is refused when any operand is claimed, a `mv` source is refused because the move removes it, a subagent is refused on a path its parent claimed, `guard_why` reports the conflict as a shell mutation without acquiring a claim, an unclaimed path stays allowed, and the path is allowed once the owning edit releases its claim. |
|
|
55
|
+
| **Review Rubric Provenance** | Verifies the rubric names the workspace, base ref, and diff byte count it graded; grades a linked worktree named by `directory` rather than the caller's checkout; refuses when no base yields a diff, naming the workspace, every base tried, and the remedy, without emitting a rubric body over a substitute range; and honors an explicit `HEAD~1` base with `base=HEAD~1 fallback=HEAD~1`. Also verifies the injected workflow guidance names the calling session as the recorder rather than the subagent. |
|
|
54
56
|
| **record_review Registration** | Verifies `record_review` stays registered when the review gate is disabled, so a reviewer agent's host permission list, not project config, is what can withhold the call. Under `requireSubagentReview`, verifies a root approval is rejected and `guard_status.lastReview` names the subagent recorder and its parent separately. |
|
|
55
57
|
| **Adversarial Invariants** | Verifies defense against compound shell mutations, symlink escapes, chained git normalization, verify script abuse, and external repo mutations. |
|
|
56
58
|
| **Audit & Permission Events** | Verifies the typed `permission.ask` hook, permission replies, and command journaling in the audit trail. |
|
package/package.json
CHANGED
package/src/lib/custom-tools.ts
CHANGED
|
@@ -44,7 +44,7 @@ import { todoEvidenceReport } from "../policies/todo.ts";
|
|
|
44
44
|
import { existingProjectConfigPath, findGitRoot, loadProjectConfig, projectRootKey } from "./project-config.ts";
|
|
45
45
|
import { detectVerifyCommand, getCurrentGitCommitHash, getGitWorktreeFingerprint, getTrackedWorktreeFingerprint, verifyCommandSource } from "./verify.ts";
|
|
46
46
|
import { evaluateDogfoodGate } from "./dogfood.ts";
|
|
47
|
-
import { buildReviewRubric } from "./review.ts";
|
|
47
|
+
import { buildReviewRubric, type RubricProvenance } from "./review.ts";
|
|
48
48
|
import { createGitWorktree, cleanupGitWorktree, validateHostWorktreeDirectory } from "./worktree.ts";
|
|
49
49
|
import type { HostWorktreePort } from "./host-worktree.ts";
|
|
50
50
|
import { branchHasDocumentationChange } from "../policies/docs.ts";
|
|
@@ -94,7 +94,7 @@ export function buildWorkflowGuardSystemGuidance(options: {
|
|
|
94
94
|
|
|
95
95
|
if (!options.isReadOnly) {
|
|
96
96
|
sections.push(
|
|
97
|
-
"- Review & Verification: Before completing tasks or creating PRs, run tests to produce fresh verification evidence, retrieve the review rubric via `guard_review_rubric` (5 core axes: test integrity, task completeness, cleanliness, security, platform), and spawn a reviewer subagent via `task
|
|
97
|
+
"- Review & Verification: Before completing tasks or creating PRs, run tests to produce fresh verification evidence, retrieve the review rubric via `guard_review_rubric` (5 core axes: test integrity, task completeness, cleanliness, security, platform), and spawn a reviewer subagent via `task`. The calling session records that subagent's verdict with `record_review`: a reviewer agent's own toolset may not carry the tool, so the caller owns the record.",
|
|
98
98
|
"- Worktree Isolation: When orchestrating parallel subagent tasks with `task`, call `guard_worktree_create` to prevent concurrent file conflicts, and `guard_worktree_cleanup` when finished.",
|
|
99
99
|
);
|
|
100
100
|
}
|
|
@@ -352,7 +352,7 @@ export function createCustomTools(options: {
|
|
|
352
352
|
guard_audit: tool({ description: "View recent audit entries recorded by opencode-workflow-guard. Use to diagnose policy decisions, blocked commands, or outcome telemetry.", args: { limit: tool.schema.number().optional().describe("Maximum entries to return (default 10)") }, execute: async (args) => JSON.stringify(getRecentAuditEntries(typeof args?.limit === "number" ? Math.min(args.limit, 50) : 10), null, 2) }),
|
|
353
353
|
guard_why: tool({ description: "Simulate and return the structured policy decision for a specific tool call or command. Proactively use before executing questionable or complex commands to check if they would be blocked by guard policies.", args: { tool: tool.schema.string().describe("Tool name (e.g. bash, edit, write, read, apply_patch)"), input: tool.schema.record(tool.schema.string(), tool.schema.any()).optional().describe("Tool input arguments") }, execute: async (args, toolContext) => JSON.stringify(await runWithRuntimeState(await resolveCallWorkspace(toolContext), client, () => guardToolCallImpl(args.tool, args.input ?? {}, { sessionID: toolContext.sessionID, worktree: toolContext.worktree, directory: toolContext.directory, simulate: true })), null, 2) }),
|
|
354
354
|
record_review: tool({
|
|
355
|
-
description: "Record a secondary reviewer agent's approval or critique of the current changes. The summary must reference the 5 core review axes from guard_review_rubric (test integrity, task completeness, cleanliness, security, platform). Projects with requireSubagentReview enabled only accept APPROVALS recorded from a subagent session (one with a parent session), never from the root session itself.",
|
|
355
|
+
description: "Record a secondary reviewer agent's approval or critique of the current changes. Call it from the session that owns the verdict: a reviewer subagent may not carry this tool at all, because host permissions decide an agent's toolset. The summary must reference the 5 core review axes from guard_review_rubric (test integrity, task completeness, cleanliness, security, platform). Projects with requireSubagentReview enabled only accept APPROVALS recorded from a subagent session (one with a parent session), never from the root session itself.",
|
|
356
356
|
args: {
|
|
357
357
|
reviewer: tool.schema.string().describe("Identifier/name of the reviewer subagent"),
|
|
358
358
|
summary: tool.schema.string().describe("Review findings summary across the 5 core review axes"),
|
|
@@ -547,7 +547,7 @@ export function createCustomTools(options: {
|
|
|
547
547
|
guard_review_followups: tool({ description: "List durable local P2/P3 review follow-ups (technical debt) for this project. Proactively check during planning or before final verification to address open findings.", args: {}, execute: async () => JSON.stringify(followupStore ? listReviewFollowups(followupStore) : [], null, 2) }),
|
|
548
548
|
guard_review_followup_resolve: tool({ description: "Resolve a durable local review follow-up after the underlying issue has been fixed and verified.", args: { id: tool.schema.string() }, execute: async (args) => followupStore && resolveReviewFollowup(followupStore, args.id) ? `[workflow-guard] Review follow-up ${args.id} resolved.` : `[workflow-guard] Review follow-up ${args.id} was not open or was not found.` }),
|
|
549
549
|
guard_review_rubric: tool({
|
|
550
|
-
description: "Get the secondary-review rubric for
|
|
550
|
+
description: "Get the secondary-review rubric for a branch diff across 5 core review axes (test integrity, task completeness, cleanliness, security, platform). The orchestrator should call this before finalizing work or creating a PR, then spawn a reviewer subagent with the rubric as the prompt. The calling session records that subagent's verdict with record_review. The rubric's first line names the workspace, base ref, and diff size it graded, so check those describe the change under review; pass directory and/or base when the change lives in another checkout.",
|
|
551
551
|
args: {
|
|
552
552
|
base: tool.schema.string().optional().describe("Base ref to diff against (default: origin/main, origin/master, main, master)"),
|
|
553
553
|
directory: tool.schema.string().optional().describe("Target repository directory (defaults to active session directory or workspace root)"),
|
|
@@ -559,11 +559,24 @@ export function createCustomTools(options: {
|
|
|
559
559
|
const bases = sanitizedBase ? [sanitizedBase] : ["origin/main", "origin/master", "main", "master"];
|
|
560
560
|
const rubricWorkspace = await resolveCallWorkspace(toolContext, args?.directory);
|
|
561
561
|
let diffText = "";
|
|
562
|
+
let usedBase: string | undefined;
|
|
562
563
|
// Revision before the trailing `--` (LL-001) so the base ref is
|
|
563
564
|
// always parsed as a revision, never as a pathspec.
|
|
564
|
-
for (const base of bases) { const res = spawnSync("git", ["diff", "--no-ext-diff", `${base}...HEAD`, "--"], { cwd: rubricWorkspace, encoding: "utf8", timeout: 10_000 }); if (res.status === 0 && res.stdout.trim()) { diffText = res.stdout; break; } }
|
|
565
|
-
|
|
566
|
-
|
|
565
|
+
for (const base of bases) { const res = spawnSync("git", ["diff", "--no-ext-diff", `${base}...HEAD`, "--"], { cwd: rubricWorkspace, encoding: "utf8", timeout: 10_000 }); if (res.status === 0 && res.stdout.trim()) { diffText = res.stdout; usedBase = base; break; } }
|
|
566
|
+
// No listed base produced a diff. Grading a substitute range
|
|
567
|
+
// returned a rubric over the wrong change and named nothing, so
|
|
568
|
+
// refuse instead. HEAD~1 is graded only when the caller asks for
|
|
569
|
+
// it, and then the provenance line says which range was graded.
|
|
570
|
+
if (!diffText) {
|
|
571
|
+
return `[workflow-guard] No review diff found: workspace=${rubricWorkspace} bases=${bases.join(", ")} diff=0 bytes. No rubric was produced. Remedy: pass base: "<ref>" naming the base that holds the change (base: "HEAD~1" grades the last commit), and directory: "<absolute checkout>" when the change lives in another worktree.`;
|
|
572
|
+
}
|
|
573
|
+
const provenance: RubricProvenance = {
|
|
574
|
+
workspace: rubricWorkspace,
|
|
575
|
+
base: usedBase ?? null,
|
|
576
|
+
diffBytes: Buffer.byteLength(diffText, "utf8"),
|
|
577
|
+
fallback: usedBase === "HEAD~1" ? "HEAD~1" : "none",
|
|
578
|
+
};
|
|
579
|
+
return buildReviewRubric(diffText, undefined, provenance);
|
|
567
580
|
},
|
|
568
581
|
}),
|
|
569
582
|
guard_worktree_create: tool({
|
package/src/lib/review.ts
CHANGED
|
@@ -8,8 +8,32 @@ import {
|
|
|
8
8
|
|
|
9
9
|
export { recordReviewResult, getLastReviewResult, resetReviewState, lastReview, sessionReviews };
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* What a rubric actually graded. A session's own checkout and the checkout
|
|
13
|
+
* holding the change are not always the same tree, so the rubric must name the
|
|
14
|
+
* tree it read and the base it compared against.
|
|
15
|
+
*/
|
|
16
|
+
export interface RubricProvenance {
|
|
17
|
+
/** Absolute workspace root the diff was taken from. */
|
|
18
|
+
workspace: string;
|
|
19
|
+
/** Base ref actually used, or null when the rubric was not produced. */
|
|
20
|
+
base: string | null;
|
|
21
|
+
/** Bytes in the diff the rubric grades, before its own truncation. */
|
|
22
|
+
diffBytes: number;
|
|
23
|
+
/**
|
|
24
|
+
* `HEAD~1` when the graded range is the last commit rather than a branch
|
|
25
|
+
* base. It says which range was graded, not who asked for it: an explicit
|
|
26
|
+
* `base: "HEAD~1"` marks it too, because the range is the same either way.
|
|
27
|
+
*/
|
|
28
|
+
fallback: "none" | "HEAD~1";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function rubricProvenanceLine(provenance: RubricProvenance): string {
|
|
32
|
+
return `Provenance: workspace=${provenance.workspace} base=${provenance.base ?? "none"} diff=${provenance.diffBytes} bytes fallback=${provenance.fallback}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function buildReviewRubric(diffText: string, taskPrompt?: string, provenance?: RubricProvenance): string {
|
|
36
|
+
const lines = [
|
|
13
37
|
"# Secondary Review Agent Quality Gate",
|
|
14
38
|
"",
|
|
15
39
|
"Evaluate this code change independently with fresh context across these 5 core axes:",
|
|
@@ -47,5 +71,7 @@ export function buildReviewRubric(diffText: string, taskPrompt?: string): string
|
|
|
47
71
|
"```",
|
|
48
72
|
"",
|
|
49
73
|
"Provide your verdict: `[APPROVE]` or `[REQUEST_CHANGES]` with concise, actionable findings ranked by priority (P0-P3).",
|
|
50
|
-
]
|
|
74
|
+
];
|
|
75
|
+
if (provenance) lines.unshift(rubricProvenanceLine(provenance), "");
|
|
76
|
+
return lines.join("\n");
|
|
51
77
|
}
|
package/src/policies/boundary.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { isCollaborationInvocation, isProtectedPath, PROTECTED_PATH_REASON } fro
|
|
|
12
12
|
import { isSecretPath, secretIn } from "./secrets.ts";
|
|
13
13
|
import { isGitTreeWriteText, branchGuardReason, onProtectedBranch, parseGitInvocation } from "./git.ts";
|
|
14
14
|
import { findGitRoot, isSameGitRepo, projectRootKey } from "../lib/project-config.ts";
|
|
15
|
-
import { canonicalPath } from "./file-claims.ts";
|
|
15
|
+
import { canonicalPath, fileClaimConflictReason, releaseStaleFileClaims } from "./file-claims.ts";
|
|
16
16
|
import {
|
|
17
17
|
effectiveTodos,
|
|
18
18
|
effectiveTodoOwnerSessionID,
|
|
@@ -798,6 +798,23 @@ export async function guardShellMutation(
|
|
|
798
798
|
// that no command executes is prose, so its lines are not judged either.
|
|
799
799
|
const masked = maskDataHeredocBodies(segment);
|
|
800
800
|
const cleanSegment = isCollaborationInvocation(masked) ? stripQuotedSpans(masked) : masked;
|
|
801
|
+
// Claims are keyed by canonical absolute path, so a relative or
|
|
802
|
+
// `~`-relative target is resolved against the tree this segment runs in
|
|
803
|
+
// before comparing. A provably stale claim is released first, exactly as
|
|
804
|
+
// the edit path does, so the remedy in the conflict message is reachable
|
|
805
|
+
// from the shell too. Shell writes never acquire a claim.
|
|
806
|
+
const claimConflictForTarget = async (candidate: string): Promise<string | undefined> => {
|
|
807
|
+
if (!sessionID) return undefined;
|
|
808
|
+
const expanded = expandShellTargetPath(candidate);
|
|
809
|
+
if (expanded === null) return undefined;
|
|
810
|
+
const claimPath = resolve(runRoot, expanded);
|
|
811
|
+
let conflict = fileClaimConflictReason([claimPath], sessionID, runRoot);
|
|
812
|
+
if (conflict && record) {
|
|
813
|
+
await releaseStaleFileClaims([claimPath], sessionID, runRoot);
|
|
814
|
+
conflict = fileClaimConflictReason([claimPath], sessionID, runRoot);
|
|
815
|
+
}
|
|
816
|
+
return conflict;
|
|
817
|
+
};
|
|
801
818
|
const secretSource = secretSourceInFilesystemCommand(cleanSegment);
|
|
802
819
|
if (secretSource) {
|
|
803
820
|
return `Blocked: shell command would copy, move, or link sensitive file '${secretSource}' under a non-secret name.`;
|
|
@@ -818,6 +835,10 @@ export async function guardShellMutation(
|
|
|
818
835
|
}
|
|
819
836
|
return `Blocked: mv would remove source '${source}' from outside the workspace root (${workspaceRoot}). File mutations must stay within the workspace.`;
|
|
820
837
|
}
|
|
838
|
+
// A move removes its source, so a source another session is
|
|
839
|
+
// editing is a conflict even though the destination is fine.
|
|
840
|
+
const sourceConflict = await claimConflictForTarget(source);
|
|
841
|
+
if (sourceConflict) return sourceConflict;
|
|
821
842
|
}
|
|
822
843
|
}
|
|
823
844
|
const simpleMutations = simpleFilesystemMutations(cleanSegment);
|
|
@@ -867,6 +888,13 @@ export async function guardShellMutation(
|
|
|
867
888
|
if (onProtectedBranch(runRoot)) {
|
|
868
889
|
return branchGuardReason();
|
|
869
890
|
}
|
|
891
|
+
// A direct edit claims its target for the tool-call lifetime so two
|
|
892
|
+
// sessions cannot race it. A shell writer changes the same file, so
|
|
893
|
+
// the same conflict is refused here, with the same reason.
|
|
894
|
+
if (target) {
|
|
895
|
+
const claimConflict = await claimConflictForTarget(target);
|
|
896
|
+
if (claimConflict) return claimConflict;
|
|
897
|
+
}
|
|
870
898
|
const todos = await effectiveTodos(sessionID);
|
|
871
899
|
if (todos !== undefined && !hasActiveTodo(todos)) {
|
|
872
900
|
return (
|
package/test/test.mts
CHANGED
|
@@ -1197,6 +1197,70 @@ try {
|
|
|
1197
1197
|
}
|
|
1198
1198
|
check("blocked multi-target patch leaves no partial claims", !partialPatchClaim);
|
|
1199
1199
|
|
|
1200
|
+
// A shell write mutates the same path a direct edit claims, and the claim was
|
|
1201
|
+
// consulted only in the edit branch: `edit` was refused for a path while a
|
|
1202
|
+
// redirect to that same file was allowed at the same moment. A shell write is
|
|
1203
|
+
// a conflict check only (it never acquires a claim), so it cannot strand one.
|
|
1204
|
+
console.log("- Shell mutation claim conflicts -");
|
|
1205
|
+
writeFileSync(join(claimsDir, "shell-target.ts"), "before");
|
|
1206
|
+
writeFileSync(join(claimsDir, "shell-multi.ts"), "before");
|
|
1207
|
+
writeFileSync(join(claimsDir, "shell-multi2.ts"), "before");
|
|
1208
|
+
symlinkSync(join(claimsDir, "shell-target.ts"), join(claimsDir, "shell-target-link.ts"));
|
|
1209
|
+
await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-target.ts"), "claim-shell-read-target");
|
|
1210
|
+
await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-owner" }, { args: { filePath: join(claimsDir, "shell-target.ts"), content: "a" } });
|
|
1211
|
+
const shellBlockReason = async (command: string): Promise<string> => {
|
|
1212
|
+
try {
|
|
1213
|
+
await claimsBefore?.({ tool: "bash", sessionID: "s-claim-b", callID: "claim-shell-attempt" }, { args: { command } });
|
|
1214
|
+
return "";
|
|
1215
|
+
} catch (error) {
|
|
1216
|
+
return String(error);
|
|
1217
|
+
}
|
|
1218
|
+
};
|
|
1219
|
+
const shellRedirectReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target.ts")}`);
|
|
1220
|
+
check("a shell redirect into a claimed path is refused with the claim reason", shellRedirectReason.includes("is claimed by session") && shellRedirectReason.includes("Reclaim step"));
|
|
1221
|
+
const shellTeeReason = await shellBlockReason(`printf x | tee -a ${join(claimsDir, "shell-target.ts")}`);
|
|
1222
|
+
check("a tee append into a claimed path is refused, with the tee flag parsed", shellTeeReason.includes("is claimed by session"));
|
|
1223
|
+
const shellSymlinkReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target-link.ts")}`);
|
|
1224
|
+
check("a shell write through a symlink alias of a claimed path is refused", shellSymlinkReason.includes("is claimed by session"));
|
|
1225
|
+
const shellChainedReason = await shellBlockReason(`cd ${claimsDir} && echo x > shell-target.ts`);
|
|
1226
|
+
check("a chained shell write into a claimed path is judged in the tree it lands in", shellChainedReason.includes("is claimed by session"));
|
|
1227
|
+
await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-multi2.ts"), "claim-shell-read-multi");
|
|
1228
|
+
await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-multi" }, { args: { filePath: join(claimsDir, "shell-multi2.ts"), content: "a" } });
|
|
1229
|
+
const shellMultiReason = await shellBlockReason(`rm ${join(claimsDir, "shell-multi.ts")} ${join(claimsDir, "shell-multi2.ts")}`);
|
|
1230
|
+
check("a multi-operand shell mutation is refused when any operand is claimed", shellMultiReason.includes("is claimed by session") && shellMultiReason.includes("shell-multi2.ts"));
|
|
1231
|
+
const shellSubagentReason = await (async (): Promise<string> => {
|
|
1232
|
+
fakeParents.set("s-claim-subagent", "s-claim-a");
|
|
1233
|
+
try {
|
|
1234
|
+
await claimsBefore?.({ tool: "bash", sessionID: "s-claim-subagent", callID: "claim-shell-subagent" }, { args: { command: `echo x > ${join(claimsDir, "shell-target.ts")}` } });
|
|
1235
|
+
return "";
|
|
1236
|
+
} catch (error) {
|
|
1237
|
+
return String(error);
|
|
1238
|
+
}
|
|
1239
|
+
})();
|
|
1240
|
+
check("a subagent shell write into a path its parent claimed is refused", shellSubagentReason.includes("is claimed by session"));
|
|
1241
|
+
// mv removes its source, so a claimed source is a conflict even when the
|
|
1242
|
+
// destination is unclaimed.
|
|
1243
|
+
writeFileSync(join(claimsDir, "shell-move-source.ts"), "before");
|
|
1244
|
+
await recordRead(claimsBefore, claimsAfter, "s-claim-a", join(claimsDir, "shell-move-source.ts"), "claim-shell-read-move");
|
|
1245
|
+
await claimsBefore?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-move" }, { args: { filePath: join(claimsDir, "shell-move-source.ts"), content: "a" } });
|
|
1246
|
+
const shellMoveSourceReason = await shellBlockReason(`mv ${join(claimsDir, "shell-move-source.ts")} ${join(claimsDir, "shell-moved-away.ts")}`);
|
|
1247
|
+
check("a mv of a claimed source is refused", shellMoveSourceReason.includes("is claimed by session") && shellMoveSourceReason.includes("shell-move-source.ts"));
|
|
1248
|
+
await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-move", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
1249
|
+
const shellWhy = JSON.parse(String(await claimsHooks.tool?.guard_why?.execute(
|
|
1250
|
+
{ tool: "bash", input: { command: `echo x > ${join(claimsDir, "shell-target.ts")}` } },
|
|
1251
|
+
{ sessionID: "s-claim-b", worktree: claimsDir, directory: claimsDir } as any,
|
|
1252
|
+
)));
|
|
1253
|
+
check(
|
|
1254
|
+
"guard_why reports a shell claim conflict as a shell mutation",
|
|
1255
|
+
shellWhy.code === "shell_mutation" && String(shellWhy.message).includes("is claimed by session"),
|
|
1256
|
+
);
|
|
1257
|
+
const shellUnclaimedReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-multi.ts")}`);
|
|
1258
|
+
check("a shell write to an unclaimed path stays allowed", shellUnclaimedReason === "");
|
|
1259
|
+
await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-owner", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
1260
|
+
await claimsAfter?.({ tool: "edit", sessionID: "s-claim-a", callID: "claim-shell-multi", args: {} }, { title: "edit", output: "edited", metadata: {} });
|
|
1261
|
+
const shellAfterReleaseReason = await shellBlockReason(`echo x > ${join(claimsDir, "shell-target.ts")}`);
|
|
1262
|
+
check("a shell write is allowed once the owning edit releases its claim", shellAfterReleaseReason === "");
|
|
1263
|
+
|
|
1200
1264
|
// Stale claim takeover (missed idle release): a claim created BEFORE its
|
|
1201
1265
|
// owner's last recorded idle timestamp cannot belong to an in-flight tool
|
|
1202
1266
|
// call, so a leaked claim must not block another session forever. Owners that
|
|
@@ -3980,13 +4044,32 @@ check(
|
|
|
3980
4044
|
typeof p0ReviewResult === "string" && p0ReviewResult.includes("P0 or P1 blockers"),
|
|
3981
4045
|
);
|
|
3982
4046
|
|
|
3983
|
-
// The rubric tool emits a real prompt with
|
|
4047
|
+
// The rubric tool emits a real prompt with a real diff. A fixture keeps this
|
|
4048
|
+
// independent of the checkout the suite runs in: once no base yields a diff the
|
|
4049
|
+
// tool now refuses instead of grading a substitute, so an ambient checkout with
|
|
4050
|
+
// nothing to review would assert the wrong thing.
|
|
3984
4051
|
check("plugin registers guard_review_rubric tool", typeof customPlugin.tool?.guard_review_rubric?.execute === "function");
|
|
3985
|
-
const
|
|
4052
|
+
const rubricAxesRepo = join(root, "wg-review-rubric-axes");
|
|
4053
|
+
mkdirSync(rubricAxesRepo, { recursive: true });
|
|
4054
|
+
spawnSync("git", ["init", "-b", "main"], { cwd: rubricAxesRepo });
|
|
4055
|
+
spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricAxesRepo });
|
|
4056
|
+
spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricAxesRepo });
|
|
4057
|
+
writeFileSync(join(rubricAxesRepo, "axes.txt"), "base\n");
|
|
4058
|
+
spawnSync("git", ["add", "axes.txt"], { cwd: rubricAxesRepo });
|
|
4059
|
+
spawnSync("git", ["commit", "-m", "base"], { cwd: rubricAxesRepo });
|
|
4060
|
+
spawnSync("git", ["switch", "-c", "feature/rubric-axes"], { cwd: rubricAxesRepo });
|
|
4061
|
+
writeFileSync(join(rubricAxesRepo, "axes.txt"), "base\nchange\n");
|
|
4062
|
+
spawnSync("git", ["add", "axes.txt"], { cwd: rubricAxesRepo });
|
|
4063
|
+
spawnSync("git", ["commit", "-m", "change"], { cwd: rubricAxesRepo });
|
|
4064
|
+
const rubricOut = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4065
|
+
{ base: "main", directory: rubricAxesRepo },
|
|
4066
|
+
{ sessionID: "s-rubric-axes", worktree: rubricAxesRepo, directory: rubricAxesRepo } as any,
|
|
4067
|
+
);
|
|
3986
4068
|
check(
|
|
3987
4069
|
"guard_review_rubric returns the rubric with axes",
|
|
3988
4070
|
typeof rubricOut === "string" && rubricOut.includes("Test Integrity") && rubricOut.includes("Code Diff Under Review"),
|
|
3989
4071
|
);
|
|
4072
|
+
rmSync(rubricAxesRepo, { recursive: true, force: true });
|
|
3990
4073
|
const rubricOptionFlag = await customPlugin.tool?.guard_review_rubric?.execute({ base: "--output=injected" }, {} as any);
|
|
3991
4074
|
check("guard_review_rubric sanitizes option flags in base ref", typeof rubricOptionFlag === "string" && !existsSync(join(root, "injected")));
|
|
3992
4075
|
|
|
@@ -4045,6 +4128,94 @@ check(
|
|
|
4045
4128
|
);
|
|
4046
4129
|
rmSync(rubricNoOrigin, { recursive: true, force: true });
|
|
4047
4130
|
|
|
4131
|
+
// Provenance: the rubric must name the tree it graded. A session whose own
|
|
4132
|
+
// checkout holds unrelated work must be able to grade a linked worktree, and
|
|
4133
|
+
// the rubric must say which workspace and base it read. Before this fix the
|
|
4134
|
+
// tool returned a rubric over whichever tree it happened to resolve and named
|
|
4135
|
+
// neither, so a real review was graded against the wrong diff.
|
|
4136
|
+
const rubricWtPrimary = join(root, "wg-rubric-wt-primary");
|
|
4137
|
+
mkdirSync(rubricWtPrimary, { recursive: true });
|
|
4138
|
+
spawnSync("git", ["init", "-b", "main"], { cwd: rubricWtPrimary });
|
|
4139
|
+
spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricWtPrimary });
|
|
4140
|
+
spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricWtPrimary });
|
|
4141
|
+
writeFileSync(join(rubricWtPrimary, "seed.txt"), "base\n");
|
|
4142
|
+
spawnSync("git", ["add", "seed.txt"], { cwd: rubricWtPrimary });
|
|
4143
|
+
spawnSync("git", ["commit", "-m", "base"], { cwd: rubricWtPrimary });
|
|
4144
|
+
// The session's own checkout carries unrelated work. Judging THIS tree would
|
|
4145
|
+
// put primaryOnlyMarker in the rubric instead of the worktree's change.
|
|
4146
|
+
spawnSync("git", ["switch", "-c", "feature/primary-unrelated"], { cwd: rubricWtPrimary });
|
|
4147
|
+
writeFileSync(join(rubricWtPrimary, "primary-only.txt"), "primaryOnlyMarker\n");
|
|
4148
|
+
spawnSync("git", ["add", "primary-only.txt"], { cwd: rubricWtPrimary });
|
|
4149
|
+
spawnSync("git", ["commit", "-m", "unrelated primary work"], { cwd: rubricWtPrimary });
|
|
4150
|
+
const rubricWtLinked = join(root, "wg-rubric-wt-linked");
|
|
4151
|
+
spawnSync("git", ["worktree", "add", "-q", "-b", "feature/wt-under-review", rubricWtLinked, "main"], { cwd: rubricWtPrimary });
|
|
4152
|
+
writeFileSync(join(rubricWtLinked, "worktree-change.txt"), "worktreeOnlyMarker\n");
|
|
4153
|
+
spawnSync("git", ["add", "worktree-change.txt"], { cwd: rubricWtLinked });
|
|
4154
|
+
spawnSync("git", ["commit", "-m", "worktree change under review"], { cwd: rubricWtLinked });
|
|
4155
|
+
const rubricWtRoot = String(spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: rubricWtLinked, encoding: "utf8" }).stdout).trim();
|
|
4156
|
+
const rubricWtDiff = String(spawnSync("git", ["diff", "--no-ext-diff", "main...HEAD", "--"], { cwd: rubricWtLinked, encoding: "utf8" }).stdout);
|
|
4157
|
+
const rubricWtOut = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4158
|
+
{ directory: rubricWtLinked },
|
|
4159
|
+
{ sessionID: "s-rubric-wt", worktree: rubricWtPrimary, directory: rubricWtPrimary } as any,
|
|
4160
|
+
);
|
|
4161
|
+
check(
|
|
4162
|
+
"guard_review_rubric grades the requested worktree and names it in the provenance line",
|
|
4163
|
+
typeof rubricWtOut === "string" &&
|
|
4164
|
+
rubricWtOut.includes(`Provenance: workspace=${rubricWtRoot} base=main `) &&
|
|
4165
|
+
rubricWtOut.includes(`diff=${Buffer.byteLength(rubricWtDiff, "utf8")} bytes`) &&
|
|
4166
|
+
rubricWtOut.includes("worktreeOnlyMarker") &&
|
|
4167
|
+
!rubricWtOut.includes("primaryOnlyMarker"),
|
|
4168
|
+
);
|
|
4169
|
+
|
|
4170
|
+
// No matching base: refuse. The old code ran `git diff HEAD~1` and printed a
|
|
4171
|
+
// rubric over that substitute, so the caller got a confident review of the
|
|
4172
|
+
// wrong range with no indication that its base was never found.
|
|
4173
|
+
const rubricNoBase = join(root, "wg-rubric-no-base");
|
|
4174
|
+
mkdirSync(rubricNoBase, { recursive: true });
|
|
4175
|
+
spawnSync("git", ["init", "-b", "main"], { cwd: rubricNoBase });
|
|
4176
|
+
spawnSync("git", ["config", "user.email", "test@test.local"], { cwd: rubricNoBase });
|
|
4177
|
+
spawnSync("git", ["config", "user.name", "Test Runner"], { cwd: rubricNoBase });
|
|
4178
|
+
writeFileSync(join(rubricNoBase, "seed.txt"), "base\n");
|
|
4179
|
+
spawnSync("git", ["add", "seed.txt"], { cwd: rubricNoBase });
|
|
4180
|
+
spawnSync("git", ["commit", "-m", "base"], { cwd: rubricNoBase });
|
|
4181
|
+
writeFileSync(join(rubricNoBase, "last-commit.txt"), "substituteMarker\n");
|
|
4182
|
+
spawnSync("git", ["add", "last-commit.txt"], { cwd: rubricNoBase });
|
|
4183
|
+
spawnSync("git", ["commit", "-m", "last commit"], { cwd: rubricNoBase });
|
|
4184
|
+
const rubricNoBaseRoot = String(spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: rubricNoBase, encoding: "utf8" }).stdout).trim();
|
|
4185
|
+
const rubricNoBaseOut = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4186
|
+
{ directory: rubricNoBase },
|
|
4187
|
+
{ sessionID: "s-rubric-no-base", worktree: rubricNoBase, directory: rubricNoBase } as any,
|
|
4188
|
+
);
|
|
4189
|
+
check(
|
|
4190
|
+
"guard_review_rubric refuses when no base yields a diff instead of grading a substitute",
|
|
4191
|
+
typeof rubricNoBaseOut === "string" &&
|
|
4192
|
+
rubricNoBaseOut.includes("No review diff found") &&
|
|
4193
|
+
rubricNoBaseOut.includes(`workspace=${rubricNoBaseRoot}`) &&
|
|
4194
|
+
rubricNoBaseOut.includes("bases=origin/main, origin/master, main, master") &&
|
|
4195
|
+
rubricNoBaseOut.includes("Remedy") &&
|
|
4196
|
+
!rubricNoBaseOut.includes("substituteMarker") &&
|
|
4197
|
+
!rubricNoBaseOut.includes("Code Diff Under Review"),
|
|
4198
|
+
);
|
|
4199
|
+
|
|
4200
|
+
// HEAD~1 is graded only when the caller asks for it, and the provenance line
|
|
4201
|
+
// says which range was graded so a reader can tell it is the last commit.
|
|
4202
|
+
const rubricHead1Out = await customPlugin.tool?.guard_review_rubric?.execute(
|
|
4203
|
+
{ base: "HEAD~1", directory: rubricNoBase },
|
|
4204
|
+
{ sessionID: "s-rubric-head1", worktree: rubricNoBase, directory: rubricNoBase } as any,
|
|
4205
|
+
);
|
|
4206
|
+
check(
|
|
4207
|
+
"an explicit HEAD~1 base is honored and named in the provenance line",
|
|
4208
|
+
typeof rubricHead1Out === "string" &&
|
|
4209
|
+
rubricHead1Out.includes("base=HEAD~1") &&
|
|
4210
|
+
rubricHead1Out.includes("fallback=HEAD~1") &&
|
|
4211
|
+
rubricHead1Out.includes("substituteMarker") &&
|
|
4212
|
+
rubricHead1Out.includes("Code Diff Under Review"),
|
|
4213
|
+
);
|
|
4214
|
+
rmSync(rubricNoBase, { recursive: true, force: true });
|
|
4215
|
+
spawnSync("git", ["worktree", "remove", "--force", rubricWtLinked], { cwd: rubricWtPrimary });
|
|
4216
|
+
rmSync(rubricWtLinked, { recursive: true, force: true });
|
|
4217
|
+
rmSync(rubricWtPrimary, { recursive: true, force: true });
|
|
4218
|
+
|
|
4048
4219
|
// Reviewer-type agents often lack record_review in their toolset entirely, so
|
|
4049
4220
|
// the tool accepts recorders of any session type: the verdict binds to the
|
|
4050
4221
|
// recording session's directory and the audit trail captures the recorder
|
|
@@ -6580,6 +6751,16 @@ check("tool.definition todowrite enriches with planning and status guidance", to
|
|
|
6580
6751
|
const systemOutput = { system: ["Base system prompt"] };
|
|
6581
6752
|
await defPlugin["experimental.chat.system.transform"]?.({ model: { id: "gemini-flash" } as any }, systemOutput);
|
|
6582
6753
|
check("experimental.chat.system.transform adds workflow guard guidance", systemOutput.system.length === 2 && systemOutput.system[1].includes("## Workflow Guard & Operational Tools") && systemOutput.system[1].includes("guard_next_tasks") && systemOutput.system[1].includes("guard_review_rubric"));
|
|
6754
|
+
// A reviewer agent that denies every action does not carry record_review, so
|
|
6755
|
+
// the injected instruction must name the calling session as the recorder. The
|
|
6756
|
+
// old text told the subagent to record its own verdict, which the fleet
|
|
6757
|
+
// reviewer could not do.
|
|
6758
|
+
check(
|
|
6759
|
+
"injected guidance names the calling session as the review recorder",
|
|
6760
|
+
systemOutput.system[1].includes("The calling session records that subagent's verdict") &&
|
|
6761
|
+
systemOutput.system[1].includes("may not carry the tool") &&
|
|
6762
|
+
!systemOutput.system[1].includes("that records its verdict with `record_review`"),
|
|
6763
|
+
);
|
|
6583
6764
|
const systemOutputIdem = { system: [...systemOutput.system] };
|
|
6584
6765
|
await defPlugin["experimental.chat.system.transform"]?.({ model: { id: "gemini-flash" } as any }, systemOutputIdem);
|
|
6585
6766
|
check("experimental.chat.system.transform is idempotent", systemOutputIdem.system.length === 2);
|