From b9d401ae7ced7703756024d12b09317f09b3fdb7 Mon Sep 17 00:00:00 2001 From: Negrescu Alexandru <124818050+negoro26@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:01:39 +0200 Subject: [PATCH 1/6] fix(port): ship upstream's pause list and merge policy as written - Delete rules.sed section 10 and the dead gate rules in sections 11 and 12, with their stale-exempt rows. - poteto-mode Autonomy, the session-override line, worker.md, and the never-block principle now match upstream 9e278fe. - pstack-omp no longer says the root keeps merges, so Shipping and Autopilot-full owners merge as upstream says. - poteto-help names pstackpolicy and what it refuses. - Set RELEASE to 2, publishing 0.15.4802. --- .omp-plugin/marketplace.json | 4 +- omp-port/RELEASE | 2 +- omp-port/rules.sed | 46 ++----------------- omp-port/stale-exempt.tsv | 4 -- plugins/pstack/package.json | 2 +- plugins/pstack/skills/poteto-help/SKILL.md | 2 +- plugins/pstack/skills/poteto-mode/SKILL.md | 4 +- plugins/pstack/skills/poteto-mode/worker.md | 2 +- .../SKILL.md | 2 +- plugins/pstack/skills/pstack-omp/SKILL.md | 2 +- 10 files changed, 13 insertions(+), 57 deletions(-) diff --git a/.omp-plugin/marketplace.json b/.omp-plugin/marketplace.json index dfacd8f..e0881cb 100644 --- a/.omp-plugin/marketplace.json +++ b/.omp-plugin/marketplace.json @@ -5,13 +5,13 @@ }, "metadata": { "description": "pstack, poteto's engineering methodology for Cursor, ported to oh-my-pi. Model and provider agnostic.", - "version": "0.15.4801" + "version": "0.15.4802" }, "plugins": [ { "name": "pstack", "description": "60 skills, 22 playbooks, 24 principles, the poteto-mode pin, and two agents. Upstream cursor/plugins pstack 0.15.48 at 9e278fe.", - "version": "0.15.4801", + "version": "0.15.4802", "category": "development", "license": "MIT", "source": "./plugins/pstack" diff --git a/omp-port/RELEASE b/omp-port/RELEASE index d00491f..0cfbf08 100644 --- a/omp-port/RELEASE +++ b/omp-port/RELEASE @@ -1 +1 @@ -1 +2 diff --git a/omp-port/rules.sed b/omp-port/rules.sed index f355d75..7b9fb85 100644 --- a/omp-port/rules.sed +++ b/omp-port/rules.sed @@ -45,7 +45,7 @@ s#When the model rule is missing and it matters,#When required role overrides ar s#^- Now: give them `/setup-pstack` to type, and answer their question too\.$#- Now: point them to [Choose models](../omp-mechanics/SKILL.md\#choose-models), and answer their question too.# s#^- Later: answer their question, and add one line saying every role keeps its default model until they run `/setup-pstack`\.$#- Later: answer their question, and say agent frontmatter or parent inheritance remains in effect until they configure exact role overrides.# s#^If cost is the worry, say where the tokens go and how to spend fewer\..*$#If cost is the worry, explain that extra workers and review panels spend more tokens. To spend fewer, pick a lower effort or cheaper available models per [Choose models](../omp-mechanics/SKILL.md\#choose-models). An agent without a model override uses its frontmatter or inherits the chat model. Never write `auto` or `inherit-parent` as an OMP model selector. Save `/poteto-mode` for work that needs rigor.# -s#Installing changes nothing until the user invokes a skill\. Only `/setup-pstack` loads from the user's words\.#Skills run when invoked or routed. The installed extension also provides the session pin commands.# +s#Installing changes nothing until the user invokes a skill\. Only `/setup-pstack` loads from the user's words\.#Skills run when invoked or routed. The installed `potetomode` extension provides the session pin commands. The installed `pstackpolicy` extension is active from install and refuses two things: a force-push to the default branch, main, master, or trunk, and deleting the repository. Merges and every other forge action are not gated, because pstack follows upstream's pause list and the operator's prompt is the permission to land.# s#^Whether `/poteto-mode` stays on depends on how the user starts it:$#Choose whether to invoke the router once or pin it for the session:# s#^- Enter on `/poteto-mode` attaches.*$#- `/skill:poteto-mode` invokes the router for a task; it does not enable the persistent pin.# s#^- Option\+Enter on Mac or Alt\+Enter on Windows,.*$#- `/poteto-mode on` pins the router for every turn, `/poteto-mode off` unpins it, and `/poteto-mode status` reports the current pin. These are the installed extension's OMP commands, not Cursor's Custom Mode UI.# @@ -399,30 +399,8 @@ s#stop at the first one without `PASS` or `PASS\+NOTES`\.#stop at the first one # Cursor's help names another harness's install commands and an adapter the port does not ship. s#^pstack is built for Cursor, and it also installs in Claude Code with .*a one-line note\.$#pstack installs in omp with `/marketplace add negoro26/pstack-omp`, then `/marketplace install pstack@pstack-omp`. Invoke skills as `/skill:`, such as `/skill:poteto-mode`. Read `skill://pstack-omp` for the live task and runtime contract and `skill://omp-mechanics` for pstack-specific OMP differences.# -## 10. Irreversible actions, and what the runtime actually enforces. Every replacement below -## exists because the original either contradicted another sentence in the same tree, named a -## surface omp does not have, or told an agent to do something the harness cannot stop. The -## machine half is plugins/pstack/extensions/pstackpolicy, which refuses the forge mutations -## unless the operator set PSTACK_LANDING_GRANT; prose alone cannot, because yolo auto-approves -## the exec tier and every pstack owner is a headless subagent. - -# Landing is the one action the port routes a human toward and then never gated. The --auto branch -# of this same step already carries "and the user asked"; the immediate branch did not, so an agent -# reading step 5 alone had licence to merge under yolo with nothing to stop it. -s#If the bottom PR is mergeable now, squash it with#Merge only on an explicit request. If the bottom PR is mergeable now and the user asked to land, ship, or merge it, squash it with# - -# The pause list is the port's only global gate and it omitted every forge action its own -# autopilots perform, so those actions fell through it entirely. -s#^\*\*Always pause\*\* for irreversible writes: force-push to shared branches, deploys, data deletion, customer messages\.$#**Always pause** for irreversible writes: pushing to trunk, merging a pull request, retargeting a pull request base, force-pushing a shared or trunk branch, closing a pull request, an issue, or a review thread, posting a review or review comment, resolving a review thread, deleting a branch on the forge, deploys, data deletion, customer messages.# - -# Two lines below an unqualified "keep going" reads as "do not pause". It is not; it is the -# autonomy switch for reversible work. -s#^\*\*Session overrides:\*\* "Don't stop" / "going to bed" / "run until done" / "be fully autonomous" → keep going\.$#**Session overrides:** "Don't stop" / "going to bed" / "run until done" / "be fully autonomous" → keep going on reversible work. They never waive the pause list above; a request to be autonomous is not authorisation to land.# - -# The worker kickoff's stop list (poteto-mode/worker.md) is upstream's copy of the router's pause -# list. It names the port's pause list verbatim and in order, so a worker stops for every forge -# action the router pauses for and pstackpolicy refuses. -s#Stop only for a deploy, deleted data, a force-push to a shared branch, or a message to someone outside the run\.#Stop only for pushing to trunk, merging a pull request, retargeting a pull request base, force-pushing a shared or trunk branch, closing a pull request, an issue, or a review thread, posting a review or review comment, resolving a review thread, deleting a branch on the forge, deploys, data deletion, or customer messages.# +## 10. Policy text is never rewritten in this table. The Autonomy section, the session-override +## line, and worker.md ship as upstream wrote them. # Leftover mode vocabulary. The four Cursor modes are gone, so naming one here contradicts the # playbook this index points at. @@ -432,20 +410,6 @@ s#\*\*You own the merge frontier\. Declare a mode, clear one PR at a time, stop ## contradicted another sentence in the same tree. None is a Cursor residue; they are the port's ## own claims about itself, which is the class nothing upstream can fix for us. -# autopilot-stack grants --force-with-lease and base retarget but omits the one line its sibling -# carries verbatim, so an agent reading only this playbook has licence to rewrite any branch in the -# chain, including one a human pushed to. -s#push with `--force-with-lease` only after an `ls-remote` check, and set the PR base to the parent branch\.#push with `--force-with-lease` only after an `ls-remote` check, and set the PR base to the parent branch. Never force-push a shared branch.# - -# shipping step 4 retargets a base with no consent clause, and step 7 re-runs steps 3-6 for every PR -# in the stack, so an unguarded retarget here reaches the whole chain. -s#4\. \*\*Prepare only the bottom PR\.\*\* Fetch current trunk\.#4. **Prepare only the bottom PR**, and retarget only on the operator's explicit go: an operator approval to land a PR is not approval to rewrite the base of every PR above it. Fetch current trunk.# - -# The autonomy sentence contradicted the pause-list scope added in section 10, and the index routes -# "full autopilot" straight here, so the trigger phrase the operator types is the phrase that clause -# disqualified. -s#The operator's full-autonomy grant plus the root's clean verdict is the merge authorization that babysitting alone never has\.#A full-autonomy grant authorises the owner to keep working without checking in; the root's clean verdict authorises a merge only inside that grant. Neither is implied by "go faster", and both still require the operator to have armed PSTACK_LANDING_GRANT for the merge itself.# - # `trash` is macOS, so the step could not be followed on this host, and the sentence forbade the one # fallback that would work. Handled in zz-live-runtime-routing.patch instead, because that line is # the patch's own output and a sed rule cannot see it. @@ -483,10 +447,6 @@ s#the system prompt names (the|this) path#`history://` is the documented sur # omp discovers skills one level under the root; the nested shape this prescribes is explicitly # not discovered, so the skill it produces silently never registers. -# Unqualified force-push blocks the port's own rebase flow, which `pstackpolicy` explicitly permits -# and `autopilot-stack` prescribes. Scope the pause the way the rest of the port scopes it. -s#force-push, delete production data, send external messages#force-push to a shared or trunk branch, delete production data, send external messages# - ## 13. Cursor's `Task` tool name. omp's tool is lowercase `task`, and capitalised it names nothing. ## Last on purpose: every sentence rule above quotes the capitalised form in its left-hand side, so ## this net only ever sees what no sentence rule claimed. The gate's `cursor tool names` check diff --git a/omp-port/stale-exempt.tsv b/omp-port/stale-exempt.tsv index a1f9795..2c042fe 100644 --- a/omp-port/stale-exempt.tsv +++ b/omp-port/stale-exempt.tsv @@ -64,10 +64,6 @@ Re-read the execution playbook from trunk and the armed /g superseded: upstream - `Read` tool calls against any superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. - `Task` prompts that name a skill path superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. Use Glob to find directories and files, Grep to find key s upstream removed how's explorer prompt at bf0c7cd; retain the lowercase tool names if that sentence returns. -If the bottom PR is mergeable now, squash it with superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. -push with `--force-with-lease` only after an `ls-remote` c superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. -4\. \*\*Prepare only the bottom PR\.\*\* Fetch current tru superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. -The operator's full-autonomy grant plus the root's clean v superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. - Workers never rebase and never run `gt`\. superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. s#The strict `scout` definition has no MCP grant, so never a superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. s#an exact discovered full-access worker for citation spot-c superseded: upstream reworded this sentence and a different rule now covers the current phrasing. Kept because the reword is cheap for upstream to undo. diff --git a/plugins/pstack/package.json b/plugins/pstack/package.json index 2045911..6c30d7b 100644 --- a/plugins/pstack/package.json +++ b/plugins/pstack/package.json @@ -1,6 +1,6 @@ { "name": "pstack", - "version": "0.15.4801", + "version": "0.15.4802", "license": "MIT", "omp": { "extensions": [ diff --git a/plugins/pstack/skills/poteto-help/SKILL.md b/plugins/pstack/skills/poteto-help/SKILL.md index d51e51a..2d625b6 100644 --- a/plugins/pstack/skills/poteto-help/SKILL.md +++ b/plugins/pstack/skills/poteto-help/SKILL.md @@ -39,7 +39,7 @@ When required role overrides are missing and model selection matters, ask whethe 2. Models need no configuration. Each agent runs on its frontmatter model, then on the chat model. To pick models per agent, follow [Choose models](../omp-mechanics/SKILL.md#choose-models). Offer once each to generate a verification skill with `/skill:create-verification-skill` and a formal verification skill with `/skill:create-formal-verification-skill`, unless the project already has one. 3. Start a real task with `/poteto-mode`, a goal, and a check that can pass or fail. -Skills run when invoked or routed. The installed extension also provides the session pin commands. The [README](../../README.md) and [guide page 1](https://github.com/cursor/plugins/blob/main/pstack/docs/guide/01-setup.md) have the details. Offer to word their first prompt with them, per [`references/prompting.md`](references/prompting.md). +Skills run when invoked or routed. The installed `potetomode` extension provides the session pin commands. The installed `pstackpolicy` extension is active from install and refuses two things: a force-push to the default branch, main, master, or trunk, and deleting the repository. Merges and every other forge action are not gated, because pstack follows upstream's pause list and the operator's prompt is the permission to land. The [README](../../README.md) and [guide page 1](https://github.com/cursor/plugins/blob/main/pstack/docs/guide/01-setup.md) have the details. Offer to word their first prompt with them, per [`references/prompting.md`](references/prompting.md). If cost is the worry, explain that extra workers and review panels spend more tokens. To spend fewer, pick a lower effort or cheaper available models per [Choose models](../omp-mechanics/SKILL.md#choose-models). An agent without a model override uses its frontmatter or inherits the chat model. Never write `auto` or `inherit-parent` as an OMP model selector. Save `/poteto-mode` for work that needs rigor. diff --git a/plugins/pstack/skills/poteto-mode/SKILL.md b/plugins/pstack/skills/poteto-mode/SKILL.md index 8c24ed0..4a05886 100644 --- a/plugins/pstack/skills/poteto-mode/SKILL.md +++ b/plugins/pstack/skills/poteto-mode/SKILL.md @@ -77,9 +77,9 @@ Read the leaf skill in full for any principle you apply. Each entry names when i **Just do it.** Use any MCP tool. Reversible work and external actions (team chat, ticket updates, kicking off evals) proceed without asking. -**Always pause** for irreversible writes: pushing to trunk, merging a pull request, retargeting a pull request base, force-pushing a shared or trunk branch, closing a pull request, an issue, or a review thread, posting a review or review comment, resolving a review thread, deleting a branch on the forge, deploys, data deletion, customer messages. +**Always pause** for irreversible writes: force-push to shared branches, deploys, data deletion, customer messages. -**Session overrides:** "Don't stop" / "going to bed" / "run until done" / "be fully autonomous" → keep going on reversible work. They never waive the pause list above; a request to be autonomous is not authorisation to land. +**Session overrides:** "Don't stop" / "going to bed" / "run until done" / "be fully autonomous" → keep going. **No is an acceptable answer.** Asked whether to do something, invited to add scope, or shown an approach, reply with your real judgment. Decline, push back, or say "this doesn't earn its place" when true. A recommendation is a judgment, not a validation. Agreement is not the default, candor over sycophancy. diff --git a/plugins/pstack/skills/poteto-mode/worker.md b/plugins/pstack/skills/poteto-mode/worker.md index d716901..213fd63 100644 --- a/plugins/pstack/skills/poteto-mode/worker.md +++ b/plugins/pstack/skills/poteto-mode/worker.md @@ -4,7 +4,7 @@ You are working for the operator. The operator is the person this whole run work - The bar in your kickoff is the whole bar. Add no check, gate, sign-off or review round above it. - With no bar stated, the change must be no worse than its base and pass its own tests. - Hold or block only for a failing run at this head or a bug a user would hit. Report a problem the base already has in one line. -- Never call a tool that shows a person a question. Make any choice you can undo, then say what you chose and why. Stop only for pushing to trunk, merging a pull request, retargeting a pull request base, force-pushing a shared or trunk branch, closing a pull request, an issue, or a review thread, posting a review or review comment, resolving a review thread, deleting a branch on the forge, deploys, data deletion, or customer messages. +- Never call a tool that shows a person a question. Make any choice you can undo, then say what you chose and why. Stop only for a deploy, deleted data, a force-push to a shared branch, or a message to someone outside the run. - Open every PR ready for review, never as a draft. - PR title: `type(scope): subject`. - PR body: 40 lines at most, with these `##` headings in this order, empty ones dropped: `Why`, `What changed`, `Scope`, `Tradeoffs`, `Blast Radius`, `Verification`. diff --git a/plugins/pstack/skills/principle-never-block-on-the-human/SKILL.md b/plugins/pstack/skills/principle-never-block-on-the-human/SKILL.md index 685a3f8..4f59bdc 100644 --- a/plugins/pstack/skills/principle-never-block-on-the-human/SKILL.md +++ b/plugins/pstack/skills/principle-never-block-on-the-human/SKILL.md @@ -10,6 +10,6 @@ The human supervises asynchronously. Agents must stay unblocked. Make reasonable - Proceed, then present. Do the work, show the result. Don't ask "should I do X?" Do X, explain why. - Make the system self-healing. When you notice a problem, log it and fix it in the next round. -- Irreversible actions (force-push to a shared or trunk branch, delete production data, send external messages) still require confirmation. +- Irreversible actions (force-push, delete production data, send external messages) still require confirmation. - Reversible actions (write code, edit notes, split tasks) should proceed without blocking. - Product direction comes from the human. Execution should not block. diff --git a/plugins/pstack/skills/pstack-omp/SKILL.md b/plugins/pstack/skills/pstack-omp/SKILL.md index 7ed49c5..ead72de 100644 --- a/plugins/pstack/skills/pstack-omp/SKILL.md +++ b/plugins/pstack/skills/pstack-omp/SKILL.md @@ -117,6 +117,6 @@ Observe one branch/head/generation and one exact predicate, with stop conditions ## Root ownership -The root keeps user interaction, scope, approvals, integration, external-write authorization, merges, deletion decisions, and final verification acceptance. Ordinary workers skip shared formatting, linting, and project-wide suites unless their brief explicitly assigns that verification lane. Do not race validation against unfinished sibling edits. +The root keeps user interaction, scope, integration, and final verification acceptance. A step a playbook gives to an owner stays with that owner, such as an Autopilot-full owner merging its own PR. Ordinary workers skip shared formatting, linting, and project-wide suites unless their brief explicitly assigns that verification lane. Do not race validation against unfinished sibling edits. A new commit, rebase, conflict resolution, or applied patch requires rechecking the evidence generation. Preserve patch-id exceptions only when the Shipping playbook explicitly permits them. Report PASS, ISSUES, or BLOCKED with exact paths, generation, executed commands, results, deviations, and remaining gaps. A successful worker exit is not artifact acceptance. From 6eb369e9844756aa4eec67cea09090390115999b Mon Sep 17 00:00:00 2001 From: Negrescu Alexandru <124818050+negoro26@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:01:46 +0200 Subject: [PATCH 2/6] fix(pstackpolicy): refuse only a force-push to the default branch and repository deletion - Drop the landing grant and every rule for merges, closes, reviews, retargets, branch deletes, releases, secrets, curl, Graphite, and plain pushes. - Read the default branch and the checked-out branch from git, so HEAD, a missing refspec, and a non-main default branch are judged by fact. - The refusal tells the agent to stop and return the step to the operator. - Smoke asserts the refused force-push never reaches the git shim and gh pr merge reaches the gh shim. --- omp-port/check-port.sh | 4 +- omp-port/smoke-plugin.mjs | 33 +- .../pstack/extensions/pstackpolicy/index.js | 410 +++++++--------- .../extensions/pstackpolicy/index.test.js | 454 ++++++++---------- 4 files changed, 416 insertions(+), 485 deletions(-) diff --git a/omp-port/check-port.sh b/omp-port/check-port.sh index d1eac00..2e1ed36 100755 --- a/omp-port/check-port.sh +++ b/omp-port/check-port.sh @@ -682,8 +682,8 @@ for ext in potetomode pstackpolicy; do [ -f "extensions/$ext/index.js" ] || unreg="${unreg}extensions/$ext/index.js is missing"$'\n' done -grep -qF 'PSTACK_LANDING_GRANT' extensions/pstackpolicy/index.js 2>/dev/null || - unreg="${unreg}extensions/pstackpolicy no longer names PSTACK_LANDING_GRANT"$'\n' +grep -qF 'Stop here and return this step to the operator' extensions/pstackpolicy/index.js 2>/dev/null || + unreg="${unreg}extensions/pstackpolicy refusal no longer returns the step to the operator"$'\n' if [ -n "$unreg" ]; then report "extensions" "FAIL" while read -r u; do [ -n "$u" ] && violate "$u"; done <<<"$unreg" diff --git a/omp-port/smoke-plugin.mjs b/omp-port/smoke-plugin.mjs index 83c35fd..009085e 100755 --- a/omp-port/smoke-plugin.mjs +++ b/omp-port/smoke-plugin.mjs @@ -1,13 +1,15 @@ #!/usr/bin/env bun // Loads the plugin tree into a real omp once per install shape and checks what only omp can answer: // every skill directory registers as a command, the pin extension records and reloads its state, a -// pinned turn's system prompt carries the poteto-mode reminder, and pstackpolicy refuses a bash -// `gh pr merge` before gh runs. Turns go to a scripted model on loopback, so no credential is used. +// pinned turn's system prompt carries the poteto-mode reminder, pstackpolicy refuses a bash +// force-push to main before git runs, and `gh pr merge` still reaches gh. Turns go to a scripted +// model on loopback, so no credential is used. // // bun omp-port/smoke-plugin.mjs [checkout] checkout defaults to this repository // // No omp on PATH prints SKIPPED and exits 0, unless OMP_SMOKE_REQUIRED=1 makes that a failure. import assert from "node:assert"; +import { existsSync } from "node:fs"; import { spawn, spawnSync } from "node:child_process"; import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -40,6 +42,9 @@ const skills = (await readdir(join(plugin, "skills"), { withFileTypes: true })) .sort(); const MERGE = "gh pr merge 1 --repo pstack-verify/no-such-repo --squash"; +const FORCE_PUSH = "git push --force origin main"; +const PLAIN_PUSH = "git push origin HEAD:main"; +const realGit = spawnSync("sh", ["-c", "command -v git"], { encoding: "utf8" }).stdout.trim(); // --plugin-dir adds the tree to skill discovery but does not load package.json omp.extensions, so // the -e shape passes the directory twice. --no-extensions also drops a linked plugin's skills and @@ -62,6 +67,7 @@ async function leg(shape) { const home = await mkdtemp(join(tmpdir(), "pstack-smoke-")); const bin = join(home, "bin"); const ghCalls = join(home, "gh-calls.log"); + const pushCalls = join(home, "push-calls.log"); const model = scriptedModel(); let child; let exited; @@ -86,6 +92,13 @@ async function leg(shape) { await writeFile(join(bin, "gh"), `#!/bin/sh\nprintf '%s\\n' "$*" >>'${ghCalls}'\necho "gh-shim: $*"\n`, { mode: 0o755, }); + // Only a push is intercepted, so omp's own git calls and pstackpolicy's branch reads still run + // the real git. + await writeFile( + join(bin, "git"), + `#!/bin/sh\nfor a in "$@"; do\n if [ "$a" = push ]; then printf '%s\\n' "$*" >>'${pushCalls}'; echo "git-shim: $*"; exit 0; fi\ndone\nexec '${realGit}' "$@"\n`, + { mode: 0o755 }, + ); // As under env -i, nothing from the operator's environment reaches omp. That keeps out every // credential, every variable that moves omp's roots past the scratch HOME, and the real gh. const env = { HOME: home, PATH: `${bin}:/usr/local/bin:/usr/bin:/bin` }; @@ -95,7 +108,7 @@ async function leg(shape) { assert(ran.status === 0, `omp ${argv.join(" ")} exited ${ran.status}: ${ran.stderr.trim()}`); } - // Under yolo only pstackpolicy's tool_call veto stands between bash and gh. That is its case. + // Under yolo only pstackpolicy's tool_call veto stands between bash and git or gh. That is its case. child = spawn( omp, [ @@ -190,10 +203,16 @@ async function leg(shape) { assert(systemPrompt(pinned).includes("skill://poteto-mode"), "the pinned turn's system prompt lacks the poteto-mode reminder"); assert((await bash("gh --version")).includes("gh-shim: --version"), "bash did not resolve gh to the logging shim"); - const merged = await bash(MERGE); - assert(merged.includes("pstackpolicy: refused"), `the model got ${JSON.stringify(merged.slice(0, 200))} back for ${MERGE}`); + const forced = await bash(FORCE_PUSH); + assert(forced.includes("pstackpolicy: refused"), `the model got ${JSON.stringify(forced.slice(0, 200))} back for ${FORCE_PUSH}`); + assert(forced.includes("return this step to the operator"), "the refusal does not hand the step back to the operator"); + assert(!existsSync(pushCalls), "git push ran for the refused force-push"); + assert((await bash(MERGE)).includes("gh-shim: pr merge 1"), "gh pr merge did not reach the gh shim"); + assert((await bash(PLAIN_PUSH)).includes("git-shim: push origin HEAD:main"), "a plain push did not reach the git shim"); const calls = (await readFile(ghCalls, "utf8")).trim().split("\n"); - assert.deepStrictEqual(calls, ["--version"], `gh ran for: ${calls.join(" | ")}`); + assert.deepStrictEqual(calls, ["--version", MERGE.slice(3)], `gh ran for: ${calls.join(" | ")}`); + const pushes = (await readFile(pushCalls, "utf8")).trim().split("\n"); + assert.deepStrictEqual(pushes, ["push origin HEAD:main"], `git push ran for: ${pushes.join(" | ")}`); await command("/poteto-mode off"); assert((await pinEntry()) === false, "/poteto-mode off did not record pinned: false"); @@ -224,7 +243,7 @@ for (const shape of shapes) { console.log( `smoke-plugin: PASS ${version.stdout.trim()} via ${shape.name}: ${skills.length}/${skills.length} skills ` + "registered; /poteto-mode on/off recorded; pinned system prompt names skill://poteto-mode; " + - "pstackpolicy refused the merge and gh never ran; pin reloaded on new_session", + "pstackpolicy refused the force-push to main and git never pushed; gh pr merge reached gh; pin reloaded on new_session", ); } catch (error) { console.error(`smoke-plugin: FAIL ${version.stdout.trim()} via ${shape.name}: ${error.message}`); diff --git a/plugins/pstack/extensions/pstackpolicy/index.js b/plugins/pstack/extensions/pstackpolicy/index.js index 0b11889..d6f8a71 100644 --- a/plugins/pstack/extensions/pstackpolicy/index.js +++ b/plugins/pstack/extensions/pstackpolicy/index.js @@ -1,84 +1,53 @@ -// pstackpolicy: the machine backstop for the one gate the port has no prose answer for. +// pstackpolicy: a veto for the two actions pstack's pause list names and a command can show. // -// pstack's playbooks say "only under an operator landing grant", "never merge without an -// explicit request", "stop where the human's call begins". Those are instructions, and an -// instruction is not enforcement. On this harness they cannot be, either: +// poteto-mode says "Always pause for irreversible writes: force-push to shared branches, deploys, +// data deletion, customer messages." On this harness that sentence has nothing behind it: // -// - `omp://approval-mode.md`: yolo auto-approves the `read`, `write`, AND `exec` tiers, so -// `gh pr merge` inside a bash call runs with no prompt. -// - same file, Subagents: "Subagents run headless with `tools.approvalMode: yolo`... The -// parent `task` approval is the authorization boundary." Every pstack owner is a subagent. -// - same file: bash's built-in critical patterns cover `rm -rf /`, fork bombs, -// remote-fetch-then-execute, `/etc/passwd`, and host shutdown. A merge is not on that list. +// - `omp://approval-mode.md`: yolo auto-approves the `read`, `write`, AND `exec` tiers. +// - same file, Subagents: they run headless yolo, and the parent `task` approval is the +// authorization boundary. Every pstack owner is a subagent. // -// So an agent that reads a playbook step in isolation has licence to land the stack. This -// closes that with `tool_call`, the one native veto point that sits in front of execution. +// So this refuses exactly two things, in front of execution through `tool_call`: // -// What it reaches, and what it does not. Two tools carry a shell command into the process and -// both are inspected: `bash` through `event.input.command`, and `eval` through -// `event.input.code`, because the `eval` tool declares the `exec` tier too -// (`omp://approval-mode.md`) and a `Bun.$` or `subprocess.run` inside a cell is the same -// execution a bash rule would have been caught for. Stated rather than implied, because this -// is a backstop for a port that mostly drives git and gh through `bash`, not a sandbox: -// `omp://hooks.md` records that the `browser` and `computer` preludes are host bridge calls -// that emit no `tool_call`, so they are out of reach here, and a command assembled from string -// concatenation inside a cell (`["gh", "pr", "merge"].join(" ")`) matches no string rule. +// - a force-push to the repository's default branch or to main, master, or trunk +// - deleting the repository // -// The grant is deliberately an environment variable rather than a flag or a command, because a -// flag the agent can pass is not a grant the operator made. The operator arms it; a subagent -// cannot set its own process environment. +// Everything else passes: merging, closing, reviews, retargeting, branch deletion and plain +// pushes are the playbooks' own work, and the operator's prompt is the permission for them. +// Deploys, data deletion and customer messages have no command shape this file could read, so +// they stay with the prose. // -// PSTACK_LANDING_GRANT=1 allow the forge mutations below for this process +// Two tools carry a shell command into the process and both are inspected: `bash` through +// `event.input.command`, and `eval` through `event.input.code`, because the `eval` tool declares +// the exec tier too. This is a backstop, not a sandbox. `omp://hooks.md` records that the +// `browser` and `computer` preludes emit no `tool_call`, and a command assembled from string +// concatenation inside a cell matches no rule here. // -// Three shapes of rule, because no one shape covers the ground. The `gh` rules are regexes, so -// they have to tolerate flags on both sides of the command group. `gh --repo o/r pr merge` is -// the documented way to target a non-default repo and the port uses it constantly, gh reads -// `gh pr -R o/r merge` as the same merge, and anchoring on `gh pr merge` let both through. The -// `git push` and `git branch -D` rules are token scans, because "does this push land on trunk" -// is a question about refspecs, not a substring: `git push origin HEAD:main` moves trunk with no -// force flag at all, which a force-token regex cannot see, and a naive trunk-word lookahead then -// blocks `feature/main-menu`. And both of those token scans have to read past git's global -// options, because `git -C push ...` and `/usr/bin/git push ...` are the same push; a scan -// keyed on two adjacent raw tokens of exactly `git` then `push` was proven to let -// `git -C /tmp/bypass/work push -q origin HEAD:trunk` create a branch on a real remote. +// Git is read as tokens, not substrings. `git -C push ...` and `/usr/bin/git push ...` are +// the same push, so the scan skips git's global options to find the subcommand, and a refspec is +// judged by its destination: `git push -f origin HEAD:main` forces trunk with no `main` token +// next to the flag, while `feature/main-menu` is not trunk. -const GRANT = "PSTACK_LANDING_GRANT"; +import { execFileSync } from "node:child_process"; +import { resolve } from "node:path"; -const TRUNK = new Set(["main", "master", "trunk", "develop", "release"]); +const TRUNK = new Set(["main", "master", "trunk"]); -// Regexes cannot read a Set, and some rules have to name trunk inside a pattern. -const TRUNK_ALT = [...TRUNK].join("|"); - -// gh accepts flags before the command group and between the group and its verb. Each rule -// permits any number of them, including `--repo owner/name`, which is the form the port uses. +// gh accepts flags before the command group and between the group and its verb, including +// `--repo owner/name`, which the port uses constantly. const GH_FLAGS = String.raw`(?:\s+(?:-[A-Za-z]|[-]{2}[A-Za-z][\w-]*)(?:[= ]\S+)?)*`; -// Any run of characters that is not a newline, except a backslash immediately followed by one. A -// plain `[^\n]*` let `gh pr edit 12 \` + newline + `--base main` past every flag rule, because -// the flag it gates sits on the far side of the continuation. -const CONT = String.raw`(?:[^\n\\]|\\\n)*`; - const gh = (group, verbs) => String.raw`\bgh\b${GH_FLAGS}\s+(?:${group})${GH_FLAGS}\s+(?:${verbs})\b`; -const GH_API = String.raw`\bgh\b${GH_FLAGS}\s+api\b`; - -// Every API spelling of a merge: the pull request and branch merge endpoints, and the GraphQL -// mutations that merge or arm a merge. -const API_MERGE = String.raw`\/merges?\b|mergePullRequest|mergeBranch|enablePullRequestAutoMerge`; +const REPO_DELETE = new RegExp(gh("repo", "delete")); -// Three normalisations, because these rules match text and the text is not always a shell line. -// -// Quotes are syntax once the shell or the host language has read them, so `gh "pr" merge 12` is -// `gh pr merge 12` and `'HEAD:main'` is one refspec. And inside an `eval` cell the command is -// usually a list literal -- `subprocess.run(["git", "push", "origin", "HEAD:main"])`, or -// `tool.bash({ command: "gh repo delete o/r --yes" })` -- where a comma and a bracket separate -// what separated nothing in a shell line. Both are rewritten to a space. Only the loose direction -// is taken: an unpaired quote is left alone, and a comma between two branch names becomes two -// branch names, which this scan already treats as two refspecs. -// -// A backtick substitution becomes `$` and its command, the text a `$(...)` leaves once its -// brackets go. So `` `git push origin main` `` is still a push, and a refspec built from one reads +// Quotes are syntax once the shell or the host language has read them, so `gh "repo" delete` is +// `gh repo delete` and `'HEAD:main'` is one refspec. Inside an `eval` cell the command is usually +// a list literal, `subprocess.run(["git", "push", "origin", "HEAD:main"])`, where a comma and a +// bracket separate what separated nothing in a shell line. Both become a space. Only the loose +// direction is taken: an unpaired quote is left alone. A backtick substitution becomes `$` and +// its command, the text a `$(...)` leaves once its brackets go, so a refspec built from one reads // as a value the shell fills in when it runs. const normalize = (command) => command @@ -86,78 +55,6 @@ const normalize = (command) => .replace(/`([^`]*)`/g, "$$ $1 ") .replace(/[()[\]{},]/g, " "); -const FORBIDDEN = [ - // Ahead of the plain merge rule, which matches every `--auto` merge as well. - [ - "armoring merge-when-ready", - new RegExp( - String.raw`${gh("pr", "merge")}${CONT}--auto\b|${GH_API}${CONT}enablePullRequestAutoMerge` - ), - ], - ["merging a pull request", new RegExp(gh("pr", "merge"))], - ["merging through the API", new RegExp(String.raw`${GH_API}${CONT}(?:${API_MERGE})`)], - [ - "closing, reopening, or deleting a pull request, issue, or thread", - new RegExp( - String.raw`${gh("pr|issue", "close|reopen|delete")}|${GH_API}${CONT}(?:-X\s*DELETE[^\n]*\/(issues|pulls|git\/refs)|state\s*=\s*closed|closePullRequest|closeIssue)` - ), - ], - [ - "moving a trunk branch through the API", - // The ref is a path, so the method decides. gh api sends GET unless told otherwise, and a - // PATCH to a feature ref is the API's feature-branch force push, which stays allowed. - new RegExp( - String.raw`${GH_API}(?=${CONT}\s(?:-X\s*|--method[= ]\s*)(?!GET\b)[A-Za-z])${CONT}\bgit\/refs\/heads\/(?:${TRUNK_ALT})(?![\w/-])` - ), - ], - [ - "moving or deleting a ref through the GraphQL API, which may be trunk", - // GraphQL names the ref by node ID or inside an input list, so no text rule can tell trunk - // from a feature branch. Every ref update or delete is refused wherever it points. - new RegExp(String.raw`(?:${GH_API}|\bcurl\b)${CONT}\b(?:updateRefs?|deleteRef)\b`), - ], - [ - "retargeting a pull request base, which rewrites the whole stack under it", - new RegExp(String.raw`${gh("pr", "edit")}${CONT}--base\b`), - ], - [ - "posting a review or resolving a review thread", - new RegExp( - String.raw`${gh("pr", "review")}|${GH_API}${CONT}(?:-X\s*POST[^\n]*(?:\/reviews|pulls\/\d+\/(comments|reviews))|resolveReviewThread|addPullRequestReview)` - ), - ], - // The enumeration below used to stop at the verbs the port happened to use, so every other - // forge mutation gh ships was a clean pass: `gh repo delete` destroys the repository the whole - // stack lives in, and a release publish or a secret write is not undoable from a later step. - ["deleting the repository", new RegExp(gh("repo", "delete|remove|rm"))], - ["publishing, replacing, or deleting a release", new RegExp(gh("release", "create|delete|upload"))], - [ - "writing a secret or a deployment variable on the forge", - new RegExp(gh("secret|variable", "set|delete")), - ], - [ - "running a workflow against a trunk branch", - // `--ref` is the trigger, and the ref is what decides: `gh workflow run ci.yml --ref - // feature/x` is the port's own CI path and stays allowed. - new RegExp( - String.raw`${gh("workflow", "run")}${CONT}(?:--ref|-r)(?![A-Za-z0-9-])[= ]+["']?(?:${TRUNK_ALT})(?![\w-])` - ), - ], - [ - "merging, closing, or deleting forge state with curl, which no gh rule can see", - // Same request as the `gh api` rules above, and equally available with the token already in - // the environment. The trigger is the method or a request body, since curl POSTs by default. - new RegExp( - String.raw`\bcurl\b${CONT}(?:(?:-X|--request)\s*[A-Za-z]+|--data[\s=])${CONT}(?:${API_MERGE}|state\s*=\s*closed|\/git\/refs)`, - "i" - ), - ], - [ - "merging through Graphite", - new RegExp(String.raw`\bgt\s+(submit|rebase|restack|merge)\b`), - ], -]; - // `;`, `|` and `&` end a shell word and the simple command it is in, except inside a redirection: // the `&` of `2>&1`, `<&` or `&>`, and the `|` of `>|`. function separates(text, i) { @@ -279,7 +176,9 @@ function simpleCommands(command) { // git, or git under any path: an absolute binary is the same program with the same global // options in front of the subcommand. -const GIT_BASENAME = /(?:^|[/\\])git(?:\.exe)?$/; +const BASENAME = (name) => (token) => new RegExp(`(?:^|[/\\\\])${name}(?:\\.exe)?$`).test(token); +const isGit = BASENAME("git"); +const isGh = BASENAME("gh"); /** * The git global options that take a separate value token. `--git-dir=` needs no entry @@ -299,10 +198,8 @@ const GIT_VALUE_OPTIONS = new Set([ /** * Index of the subcommand token after the git binary at `start`, skipping global options, or -1. - * - * This is the fix for the proven bypass: `git -C /tmp/bypass/work push ...`, `git -c foo=bar - * push ...`, `git --git-dir=... push ...` and `/usr/bin/git push ...` all resolve to `push` - * here, where a scan for two adjacent tokens of exactly `git` then `push` found nothing. + * `git -C /tmp/work push ...`, `git -c foo=bar push ...` and `/usr/bin/git push ...` all resolve + * to `push` here. */ function gitSubcommand(tokens, start) { for (let i = start + 1; i < tokens.length; i += 1) { @@ -314,137 +211,195 @@ function gitSubcommand(tokens, start) { return -1; } +/** The directory `git` runs in: the session directory, moved by each `-C ` in turn. */ +function gitDirectory(tokens, start, at) { + let dir = process.cwd(); + for (let i = start + 1; i < at; i += 1) { + if (tokens[i] === "-C" && i + 1 < at) { + dir = resolve(dir, tokens[i + 1]); + i += 1; + } else if (GIT_VALUE_OPTIONS.has(tokens[i])) i += 1; + } + return dir; +} + /** Every `git ` in the command, with the arguments its own simple command gives it. */ function eachGitCommand(command, visit) { for (const simple of simpleCommands(command)) { const tokens = shellTokens(normalize(simple)); for (let i = 0; i < tokens.length; i += 1) { - if (!GIT_BASENAME.test(tokens[i])) continue; + if (!isGit(tokens[i])) continue; const at = gitSubcommand(tokens, i); if (at < 0) continue; - visit(tokens[at], tokens.slice(at + 1)); + visit(tokens[at], tokens.slice(at + 1), gitDirectory(tokens, i, at)); } } } +function probe(dir, args) { + try { + return execFileSync("git", ["-C", dir, ...args], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + timeout: 3000, + }).trim(); + } catch { + return null; + } +} + +/** The branch the remote's HEAD names, or null when the checkout never recorded one. */ +function defaultBranch(dir, remote) { + const ref = probe(dir, ["symbolic-ref", "--short", `refs/remotes/${remote}/HEAD`]); + return ref?.startsWith(`${remote}/`) ? ref.slice(remote.length + 1) : null; +} + +const currentBranch = (dir) => probe(dir, ["symbolic-ref", "--short", "HEAD"]); + // A redirection with its target glued on, and an operator alone, whose target is the next token. // The target names a file, not a refspec. const REDIRECTION = /^(?:\d+|&)?[<>]/; const REDIRECTION_ALONE = /^(?:\d+|&)?[<>]+[&|]?$/; -/** - * Why a push destination may be trunk although it names no trunk branch, or null. - * - * `HEAD` is whatever this checkout is on, which from a trunk checkout is trunk, and `git push - * origin HEAD` is the idiom an agent actually writes. `$` opens a parameter or command - * substitution, and normalize spells a backtick one with `$` too, so the shell fills the name in - * when it runs. `*` is a pattern git matches against every local branch. - */ -function unreadable(dest) { - if (dest === "HEAD") return "pushing the current branch, which may be trunk"; - if (/[$*]/.test(dest)) { - return "pushing a refspec that resolves only when it runs, which may be trunk"; - } - return null; -} +const REASON_TRUNK = "force-pushing a default or trunk branch"; /** - * Why this `git push` is refused, or null. - * - * Deliberately blocks every push whose refspec lands on a trunk branch, not only forced ones: - * the port's own pause list now names "pushing to trunk" as irreversible, and a plain - * `git push origin HEAD:main` does that with no force flag to key on. A push to a feature branch - * is the port's normal rebase flow and stays allowed. A destination this scan cannot read is - * refused too, but only once no refspec is certainly trunk, so the reason names the surest one. + * Why this `git push` is a force-push to the default branch or to main, master, or trunk, or + * null. A push is forced by `--force`, `--force-with-lease`, `-f`, or a `+` on the refspec, and + * `--mirror` always is. Where the destination is `HEAD` or absent, git pushes the checked-out + * branch, so that branch is read; a destination only the shell can fill in is not a fact the + * command shows, so it passes. A delete refspec is not a force-push. */ -function pushRefuse(argv) { +function pushRefuse(argv, dir) { const args = argv.filter( (token, i) => !REDIRECTION.test(token) && !REDIRECTION_ALONE.test(argv[i - 1] ?? "") ); const has = (token) => args.includes(token); - if (has("--dry-run") || has("-n")) return null; - if (has("--mirror") || has("--all") || has("--tags")) { - return "pushing every ref, or mirroring the whole repository, at the remote"; + if (has("--dry-run") || has("-n") || has("--delete")) return null; + if (has("--mirror")) { + return "mirroring the repository, which force-updates every ref including the default branch"; } - if (has("--delete")) return "deleting a branch on the forge"; - const forced = args.some((t) => /^--force/.test(t) || t === "-f"); + const forced = args.some((t) => /^--force/.test(t) || /^-[A-Za-z]*f[A-Za-z]*$/.test(t)); + if (forced && has("--all")) return "force-pushing every branch, including the default branch"; let sawRefspec = false; - let unsure = null; - // The first bare, colon-free, non-HEAD token is the remote name, not a refspec. Counting it as - // one made `git push origin` look like a push with a destination. + // The first bare, colon-free, non-HEAD token is the remote name, not a refspec. const bare = args.filter((t) => !t.startsWith("-")); + let remote = "origin"; let remoteSeen = bare.length === 0 || bare[0].includes(":") || bare[0] === "HEAD"; + const onTrunk = (branch, name) => branch && (TRUNK.has(branch) || branch === defaultBranch(dir, name)); for (const token of args) { - // `:branch` is git's refspec delete form; it carries no --delete flag. - if (token.startsWith(":")) return "deleting a branch on the forge"; if (token.startsWith("-")) continue; if (!remoteSeen && !token.includes(":")) { remoteSeen = true; + remote = token; continue; } sawRefspec = true; - // The destination follows the last colon, or is the whole token. A leading `+` is git's own - // force spelling, and the destination can still be trunk. + if (token.startsWith(":")) continue; + if (!forced && !token.startsWith("+")) continue; const dest = token .slice(token.lastIndexOf(":") + 1) .replace(/^\+/, "") .replace(/^refs\/heads\//, ""); - if (TRUNK.has(dest)) return forced ? "rewriting history on a trunk branch" : "pushing to trunk"; - unsure ??= unreadable(dest); + if (dest === "*") return "force-pushing every branch, including the default branch"; + if (dest === "HEAD") { + if (onTrunk(currentBranch(dir), remote)) return `${REASON_TRUNK} through HEAD`; + continue; + } + if (onTrunk(dest, remote)) return REASON_TRUNK; + } + if (forced && !sawRefspec && onTrunk(currentBranch(dir), remote)) { + return `${REASON_TRUNK} through the checked-out branch`; } - if (unsure) return unsure; - // No refspec at all: `git push` with only flags, or `git push origin`. Same reasoning as HEAD. - if (!sawRefspec) return "pushing without an explicit refspec, which may be trunk"; return null; } function pushOffence(command) { let why = null; - eachGitCommand(command, (subcommand, args) => { - if (subcommand === "push" && !why) why = pushRefuse(args); + eachGitCommand(command, (subcommand, args, dir) => { + if (subcommand === "push" && !why) why = pushRefuse(args, dir); }); return why; } -/** - * Why this git command destroys local history, or null. - * - * Tokenised for the same reason the push scan is: `git -C /tmp/repo branch -D feat` was proven - * to pass a regex that required `\bgit\s+branch`. The `update-ref` carve-out is pre-existing and - * deliberate in shape: a delete is the same class as the `git branch -d` this file allows, while - * `update-ref ` moves a ref out from under the worktree with no signal. - */ -function localDestruction(command) { +// gh api flags that consume the next token, so the endpoint is the first token that is not one. +const GH_API_VALUE_FLAGS = new Set([ + "-X", + "--method", + "-f", + "-F", + "--field", + "--raw-field", + "-H", + "--header", + "--input", + "-q", + "--jq", + "-t", + "--template", + "--cache", + "--hostname", + "-p", + "--preview", +]); + +/** `gh [flags] api ` calls, as the method, the endpoint and the field tokens each carries. */ +function eachGhApi(command, visit) { + for (const simple of simpleCommands(command)) { + for (const text of [simple, normalize(simple)]) { + const tokens = shellTokens(text); + for (let i = 0; i < tokens.length; i += 1) { + if (!isGh(tokens[i])) continue; + let at = i + 1; + while (at < tokens.length && tokens[at].startsWith("-")) { + at += tokens[at] === "-R" || tokens[at] === "--repo" || tokens[at] === "--hostname" ? 2 : 1; + } + if (tokens[at] !== "api") continue; + let method = "GET"; + let endpoint = null; + const fields = []; + for (let j = at + 1; j < tokens.length; j += 1) { + const token = tokens[j]; + const long = /^(?:--method|-X)=?(.+)$/.exec(token); + if (long && token !== "--method" && token !== "-X") method = long[1].toUpperCase(); + else if (token === "-X" || token === "--method") method = (tokens[(j += 1)] ?? "").toUpperCase(); + else if (GH_API_VALUE_FLAGS.has(token)) fields.push(tokens[(j += 1)] ?? ""); + else if (token.startsWith("-")) fields.push(token); + else endpoint ??= token; + } + visit(method, endpoint?.split("?")[0] ?? "", fields); + } + } + } +} + +const REPO_ENDPOINT = /^\/?repos\/[^/\s]+\/[^/\s]+\/?$/; +const HEADS_ENDPOINT = /^\/?repos\/[^/\s]+\/[^/\s]+\/git\/refs\/heads\/(.+)$/; +const FORCE_FIELD = /(?:^|[=:])force=true$/i; + +/** Why this `gh api` call is repository deletion or a forced update of a trunk ref, or null. */ +function apiOffence(command) { let why = null; - eachGitCommand(command, (subcommand, args) => { + eachGhApi(command, (method, endpoint, fields) => { if (why) return; - const has = (token) => args.includes(token); - if (subcommand === "branch" && has("-D")) why = "destroying local history"; - else if (subcommand === "update-ref" && !has("-d") && !has("--delete")) { - why = "destroying local history"; - } else if ( - subcommand === "reflog" && - args[0] === "expire" && - args.slice(1).includes("--expire=now") && - args.includes("--all") - ) { - why = "destroying local history"; - } else if ( - subcommand === "reset" && - has("--hard") && - args.some((t) => t.startsWith("origin/")) - ) { - why = "destroying local history"; + if (method === "DELETE" && REPO_ENDPOINT.test(endpoint)) { + why = "deleting the repository through the API"; + return; + } + const heads = HEADS_ENDPOINT.exec(endpoint); + if (heads && method !== "GET" && fields.some((f) => FORCE_FIELD.test(f.replace(/^-[fF]/, "")))) { + const branch = heads[1].replace(/\/$/, ""); + if (TRUNK.has(branch)) why = `${REASON_TRUNK} through the API`; } }); return why; } -function granted() { - const raw = process.env[GRANT]; - // Anything but an explicit affirmative is absent. A stray "0" or "false" must not read as - // consent, and an unset variable must not either. - return raw === "1" || raw === "true"; +function repoDeletion(command) { + for (const simple of simpleCommands(command)) { + if (REPO_DELETE.test(normalize(simple))) return "deleting the repository"; + } + return null; } /** @@ -465,24 +420,17 @@ export default function pstackpolicy(pi) { pi.on("tool_call", async (event) => { const command = subject(event); if (!command) return; - if (granted()) return; - - const text = normalize(command); - const why = - pushOffence(command) ?? - (FORBIDDEN.find(([, pattern]) => pattern.test(text)) ?? null)?.[0] ?? - localDestruction(command); + const why = pushOffence(command) ?? repoDeletion(command) ?? apiOffence(command); if (why) { return { block: true, reason: - `pstackpolicy: refused ${why}. pstack's playbooks require an operator landing grant for ` + - `this and no prose can enforce it: yolo auto-approves the exec tier, subagents run ` + - `headless yolo, and bash's critical-pattern list does not cover forge mutations. If you ` + - `are the operator and want it allowed for this run, restart with ${GRANT}=1. Otherwise ` + - `return the step to the human and say what is blocked.`, + `pstackpolicy: refused ${why}. pstack's pause list says to always pause for ` + + `irreversible writes, and a force-push to the default branch and repository deletion ` + + `are two of them. Stop here and return this step to the operator, saying what is ` + + `blocked. Do not look for another way to run it.`, }; } }); -} \ No newline at end of file +} diff --git a/plugins/pstack/extensions/pstackpolicy/index.test.js b/plugins/pstack/extensions/pstackpolicy/index.test.js index e57f048..813bbb9 100644 --- a/plugins/pstack/extensions/pstackpolicy/index.test.js +++ b/plugins/pstack/extensions/pstackpolicy/index.test.js @@ -1,10 +1,14 @@ -import { describe, expect, test } from "bun:test"; +import { afterAll, describe, expect, test } from "bun:test"; +import { execFileSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import policy from "./index.js"; // The handler is the whole backstop, so it is tested against commands that must be refused and // commands that must not be. A rule set that blocks nothing is indistinguishable from no -// backstop at all until something tries to merge. Every call awaits: the handler is async, and -// comparing a Promise against undefined would pass for the wrong reason. +// backstop at all until something tries to force-push trunk. Every call awaits: the handler is +// async, and comparing a Promise against undefined would pass for the wrong reason. // // omp vetoes only from `tool_call`, so the handler is looked up under that name. A fake host that // ignored the event name passed every test with the backstop registered on `tool_result`. @@ -12,306 +16,266 @@ const handlers = new Map(); policy({ on: (event, fn) => handlers.set(event, fn) }); const toolCall = handlers.get("tool_call"); -async function call(toolName, input, env) { - const saved = {}; - for (const [k, v] of Object.entries(env ?? {})) { - saved[k] = process.env[k]; - if (v === undefined) delete process.env[k]; - else process.env[k] = v; - } - try { - return await toolCall({ toolName, input }); - } finally { - for (const [k, v] of Object.entries(saved)) { - if (v === undefined) delete process.env[k]; - else process.env[k] = v; - } - } -} +const run = (command) => toolCall({ toolName: "bash", input: { command } }); +const evalCell = (code) => toolCall({ toolName: "eval", input: { language: "py", code } }); -async function run(command, env) { - return call("bash", { command }, env); -} +// Checkouts the refusal reads. A command without `-C` would read whatever branch the test runner +// sits on, so every case that depends on a checkout names one. They exist before the case tables +// below are built, because those tables interpolate the paths. +const git = (...args) => execFileSync("git", args, { stdio: "ignore" }); +const root = mkdtempSync(join(tmpdir(), "pstackpolicy-")); +const trunk = join(root, "trunk"); +const feature = join(root, "feature"); +const develop = join(root, "develop"); +git("init", "-q", "-b", "main", trunk); +git("init", "-q", "-b", "feature/x", feature); +git("init", "-q", "-b", "develop", develop); +git("-C", develop, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/develop"); +git("-C", feature, "symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/develop"); + +afterAll(() => rmSync(root, { recursive: true, force: true })); // Each command with a fragment of the reason its own rule gives, so a command refused by the // wrong rule fails and a rule another rule shadows cannot hide. const MUST_BLOCK = [ - // A refspec this port cannot read is not a refspec. `git push origin HEAD` and a bare - // `git push` land on whatever the checkout is on, which from a trunk checkout is trunk, and a - // quoted refspec hid the destination from the colon split. - ["git push origin HEAD", "current branch"], - ["git push", "explicit refspec"], - ["git push origin", "explicit refspec"], - ["git push --force origin", "explicit refspec"], - ["git push origin 'HEAD:main'", "pushing to trunk"], - ["gh pr edit 12 \\\n --base main", "retargeting"], - ["gh pr merge 12 \\\n --auto", "merge-when-ready"], - ["gh --repo o/r pr merge 12 \\\n --squash", "merging a pull request"], - // The forms that defeated the first version of this file. - ["gh --repo o/r pr merge 12 --squash", "merging a pull request"], - ["gh --repo o/r pr edit 12 --base main", "retargeting"], - ["gh --repo o/r pr review 12 --approve", "posting a review"], - ["gh --repo o/r issue close 5", "closing, reopening"], - ["git push origin HEAD:main", "pushing to trunk"], - ["git push origin main:main", "pushing to trunk"], - ["git push origin HEAD:refs/heads/main", "pushing to trunk"], - ["git push origin +main", "pushing to trunk"], - ["git push origin :feature/x", "deleting a branch on the forge"], + // A force-push is --force, --force-with-lease, -f, or a `+` on the refspec. + ["git push --force origin main", "default or trunk"], + ["git push origin main --force-with-lease", "default or trunk"], + ["git push --force-with-lease=main:abc123 origin main", "default or trunk"], + ["git push -f origin master", "default or trunk"], + ["git push -fu origin trunk", "default or trunk"], + ["git push origin +main", "default or trunk"], + ["git push origin +HEAD:refs/heads/main", "default or trunk"], + ["git push --force-with-lease origin +HEAD:refs/heads/trunk", "default or trunk"], + ["git push origin +feature/x:main", "default or trunk"], + ["git push origin '+refs/heads/main'", "default or trunk"], + ["git push -f origin HEAD:main", "default or trunk"], + ["git push origin HEAD:refs/heads/master --force", "default or trunk"], + ["git push --force origin main:main", "default or trunk"], + ["git push --force origin 'HEAD:main'", "default or trunk"], + ["git push --force --all origin", "every branch"], + ["git push --force origin 'refs/heads/*:refs/heads/*'", "every branch"], ["git push --mirror git@github.com:o/r.git", "mirroring"], - ["git update-ref refs/heads/main abc123", "local history"], - [ - 'gh api graphql -f query=\'mutation{mergePullRequest(input:{pullRequestId:"x"}){clientMutationId}}\'', - "merging through the API", - ], - ["gh api -X PATCH repos/o/r/pulls/12 -f state=closed", "closing, reopening"], - ["gh api -X DELETE /repos/o/r/git/refs/heads/main", "closing, reopening"], - // The forms it always caught. - ["gh pr merge 12 --squash --delete-branch", "merging a pull request"], - ["gh pr merge 12 --squash --auto", "merge-when-ready"], - ["gh pr edit 12 --base main", "retargeting"], - ["gh pr close 12", "closing, reopening"], - ["gh pr review 12 --approve", "posting a review"], - ["git push --force origin main", "rewriting history"], - ["git push origin main --force-with-lease", "rewriting history"], - ["git push origin --delete feature/x", "deleting a branch on the forge"], - ["git branch -D feature/x", "local history"], - ["gh api repos/o/r/pulls/12/merge -X PUT", "merging through the API"], - ["gt submit --stack", "merging through Graphite"], - ['if [ -z "$x" ]; then gh pr merge 3; fi', "merging a pull request"], - ["cd /tmp && gh pr merge 9 --squash", "merging a pull request"], + ["git -C /tmp/repo push -q --mirror origin", "mirroring"], // git's global options between the binary and the subcommand. A push scan keyed on two // adjacent raw tokens of exactly `git` then `push` found none of these; the first of them was // executed against a real bare remote and created refs/heads/trunk there. - ["git -C /tmp/bypass/work push -q origin HEAD:trunk", "pushing to trunk"], - ["git -c user.name=bot push origin HEAD:main", "pushing to trunk"], - ["git --git-dir=/tmp/repo/.git push origin main", "pushing to trunk"], - ["git --work-tree=/tmp/wt push origin HEAD:refs/heads/main", "pushing to trunk"], - ["git --namespace=refs/ns push origin master", "pushing to trunk"], - ["git --exec-path=/usr/lib/git-core push origin develop", "pushing to trunk"], - ["/usr/bin/git push origin HEAD:main", "pushing to trunk"], - ["/usr/bin/git -C /tmp/work push origin HEAD", "current branch"], - ["git --git-dir=/tmp/repo/.git push", "explicit refspec"], - ["git -c core.hooksPath=/dev/null push origin release", "pushing to trunk"], - ["git --bare push origin HEAD:trunk", "pushing to trunk"], - ["git -C /tmp/repo push -q origin :feature/x", "deleting a branch on the forge"], - ["git -C /tmp/repo push -q --mirror origin", "mirroring"], - // The same gap defeated the local-history rules. - ["git -C /tmp/repo branch -D feat", "local history"], - ["git --git-dir=/tmp/repo/.git update-ref refs/heads/main abc123", "local history"], - ["git -C /tmp/repo reflog expire --expire=now --all", "local history"], - ["git --work-tree=/tmp/wt reset --hard origin/main", "local history"], - // The gh verbs the enumeration never listed. - ["gh repo delete o/r --yes", "deleting the repository"], - ["gh --repo o/r repo delete --yes", "deleting the repository"], - ["gh release create v1.2.3", "a release"], - ["gh release delete v1.2.3", "a release"], - ["gh secret set DEPLOY_TOKEN", "a secret"], - ["gh variable set FLAG", "a secret"], - ["gh workflow run deploy.yml --ref main", "running a workflow"], - ["gh workflow run deploy.yml --ref=trunk", "running a workflow"], - // A quoted subcommand is the same token to gh once the shell strips it. - ['gh "pr" merge 12', "merging a pull request"], - ["gh 'pr' merge 12 --squash", "merging a pull request"], - ['gh "repo" delete o/r --yes', "deleting the repository"], - ['gh "workflow" run deploy.yml --ref main', "running a workflow"], - // curl reaches the same endpoints with the token already in the environment. - ["curl -sS -X PUT https://api.github.com/repos/o/r/pulls/1/merge -d '{}'", "with curl"], - [ - "curl --request POST -H 'Authorization: token x' https://api.github.com/repos/o/r/pulls/1/merge", - "with curl", - ], - ["curl -X PATCH https://api.github.com/repos/o/r/pulls/1 -d state=closed", "with curl"], - ["curl -X DELETE https://api.github.com/repos/o/r/git/refs/heads/main", "with curl"], - // gh reads flags between the command group and its verb as well, so each of these is the - // same call as its `gh -R o/r ` spelling above. - ["gh pr -R o/r merge 12", "merging a pull request"], - ["gh pr --repo o/r merge 12 --squash", "merging a pull request"], - ["gh pr -R o/r merge 12 --auto", "merge-when-ready"], - ["gh pr -R o/r edit 12 --base main", "retargeting"], - ["gh pr --repo=o/r close 12", "closing, reopening"], - ["gh pr -R o/r review 12 --approve", "posting a review"], - ["gh issue -R o/r close 5", "closing, reopening"], - ["gh release -R o/r create v1.2.3", "a release"], - ["gh secret -R o/r set DEPLOY_TOKEN", "a secret"], - ["gh workflow -R o/r run deploy.yml --ref main", "running a workflow"], - // Merges the API rule never named, and trunk moved without a push. - ["gh api repos/o/r/merges -f base=main -f head=feature/x", "merging through the API"], - [ - 'gh api graphql -f query=\'mutation{mergeBranch(input:{repositoryId:"r",base:"main",head:"x"}){clientMutationId}}\'', - "merging through the API", - ], - [ - 'gh api graphql -f query=\'mutation{enablePullRequestAutoMerge(input:{pullRequestId:"x"}){clientMutationId}}\'', - "merge-when-ready", - ], - ["gh api -X PATCH repos/o/r/git/refs/heads/main -f sha=abc -F force=true", "moving a trunk branch"], - ["gh api --method=PATCH repos/o/r/git/refs/heads/release -f sha=abc", "moving a trunk branch"], - [ - `curl -X POST https://api.github.com/repos/o/r/merges -d '{"base":"main","head":"x"}'`, - "with curl", - ], - ["gt merge", "merging through Graphite"], + ["git -C /tmp/bypass/work push -f -q origin HEAD:trunk", "default or trunk"], + ["git -c user.name=bot push --force origin HEAD:main", "default or trunk"], + ["git --git-dir=/tmp/repo/.git push -f origin main", "default or trunk"], + ["git --work-tree=/tmp/wt push -f origin HEAD:refs/heads/main", "default or trunk"], + ["git --namespace=refs/ns push -f origin master", "default or trunk"], + ["git --exec-path=/usr/lib/git-core push -f origin trunk", "default or trunk"], + ["/usr/bin/git push --force origin HEAD:main", "default or trunk"], + ["git -c core.hooksPath=/dev/null push -f origin main", "default or trunk"], + ["git --bare push -f origin HEAD:trunk", "default or trunk"], + // HEAD and a missing refspec push the checked-out branch, which is read from the checkout. + [`git -C ${trunk} push --force origin HEAD`, "through HEAD"], + [`git -C ${trunk} push -f`, "checked-out branch"], + [`git -C ${trunk} push --force-with-lease origin`, "checked-out branch"], + [`/usr/bin/git -C ${trunk} push -f origin HEAD`, "through HEAD"], + // The default branch is whatever the remote's HEAD names, which need not be main. + [`git -C ${feature} push --force origin develop`, "default or trunk"], + [`git -C ${develop} push -f origin HEAD`, "through HEAD"], + [`git -C ${develop} push -f`, "checked-out branch"], // Cutting a command line into simple commands must not open a hole. A redirection is not a // separator, a substitution belongs to the push it feeds, and a heredoc body can be run. - ["git push origin 2>&1 HEAD:main", "pushing to trunk"], - ["git push 2>&1", "explicit refspec"], - ["git push origin $(echo feature; echo main)", "pushing to trunk"], - ["bash <<'EOF'\ngit push origin HEAD:main\nEOF", "pushing to trunk"], - ["cat > land.sh <<'EOF'\ngh pr merge 12 --squash\nEOF", "merging a pull request"], - // A separator glued to a refspec is not part of it. Both of these were allowed as a push of - // `main;`, which is not trunk. - ["git push origin main; echo done", "pushing to trunk"], - ["(git push origin main; true)", "pushing to trunk"], - // A subshell still ends its commands, and a substitution inside one still feeds its push. - ["(cd x && git push origin main)", "pushing to trunk"], - ["(git push origin $(echo feature; echo main))", "pushing to trunk"], - // GraphQL names a ref by node ID or inside an input list, so any ref mutation may be trunk. - [ - 'gh api graphql -f query=\'mutation{updateRef(input:{refId:"r",oid:"abc",force:true}){clientMutationId}}\'', - "through the GraphQL API", - ], - [ - 'gh api graphql -f query=\'mutation{updateRefs(input:{repositoryId:"r",refUpdates:[{name:"refs/heads/main",afterOid:"abc",force:true}]}){clientMutationId}}\'', - "through the GraphQL API", - ], - [ - 'gh api graphql -f query=\'mutation{deleteRef(input:{refId:"r"}){clientMutationId}}\'', - "through the GraphQL API", - ], - [ - `curl https://api.github.com/graphql -d '{"query":"mutation{updateRef(input:{refId:\\"r\\",oid:\\"abc\\"}){clientMutationId}}"}'`, - "through the GraphQL API", - ], - // A refspec the shell or git expands is only known when it runs, and it may be trunk. - ["git push origin $(git branch --show-current)", "resolves only when it runs"], - ["git push origin `git branch --show-current`", "resolves only when it runs"], - ['git push origin "${BRANCH}"', "resolves only when it runs"], - ['git push -u origin "$BRANCH"', "resolves only when it runs"], - ['git push origin HEAD:"$(git branch --show-current)"', "resolves only when it runs"], - ["git push origin 'refs/heads/*:refs/heads/*'", "resolves only when it runs"], + ["git push -f origin 2>&1 HEAD:main", "default or trunk"], + ["git push -f origin $(echo feature; echo main)", "default or trunk"], + ["bash <<'EOF'\ngit push --force origin HEAD:main\nEOF", "default or trunk"], + // A separator glued to a refspec is not part of it. + ["git push -f origin main; echo done", "default or trunk"], + ["(git push -f origin main; true)", "default or trunk"], + ["(cd x && git push -f origin main)", "default or trunk"], + ["(git push -f origin $(echo feature; echo main))", "default or trunk"], + ["cd /tmp && git push --force origin main", "default or trunk"], + ['if [ -z "$x" ]; then git push -f origin main; fi', "default or trunk"], // A backtick substitution runs the command inside it, the same as `$(...)`. - ["echo `git push origin main`", "pushing to trunk"], + ["echo `git push -f origin main`", "default or trunk"], // A comment ends at its newline whatever quotes it holds, and `$#` is a parameter, not a comment. - ["# don't push trunk from here\ngit push origin main", "pushing to trunk"], - ["git status # it's clean\ngit push origin HEAD:main", "pushing to trunk"], - ["echo $#; git push origin main", "pushing to trunk"], + ["# don't push trunk from here\ngit push -f origin main", "default or trunk"], + ["git status # it's clean\ngit push -f origin HEAD:main", "default or trunk"], + ["echo $#; git push -f origin main", "default or trunk"], + // The same update through the API. + ["gh api -X PATCH repos/o/r/git/refs/heads/main -f sha=abc -F force=true", "through the API"], + ["gh api --method=PATCH /repos/o/r/git/refs/heads/master -f sha=abc -f force=true", "through the API"], + // Repository deletion. + ["gh repo delete o/r --yes", "deleting the repository"], + ["gh --repo o/r repo delete --yes", "deleting the repository"], + ['gh "repo" delete o/r --yes', "deleting the repository"], + ["gh repo -R o/r delete --yes", "deleting the repository"], + ["gh api -X DELETE repos/o/r", "deleting the repository through the API"], + ["gh api --method DELETE /repos/o/r", "deleting the repository through the API"], + ["gh api repos/o/r -X DELETE", "deleting the repository through the API"], + ["gh api -XDELETE repos/o/r/", "deleting the repository through the API"], + ["gh api --method=DELETE 'repos/{owner}/{repo}'", "deleting the repository through the API"], + ["gh api repos/{owner}/{repo} -X DELETE", "deleting the repository through the API"], + ["cd /tmp && gh repo delete o/r --yes", "deleting the repository"], ]; +// What the operator's prompt authorizes, and what only the shell can fill in. Each of these was +// refused by the earlier gate and is now the playbooks' own work. const MUST_PASS = [ - "gh pr view 12", - "gh pr list --state open", - "gh pr diff 12", - "git push origin feature/x", + "gh pr merge 12 --squash", + "gh pr merge 12 --squash --delete-branch", + "gh pr merge 12 --squash --auto", + "gh --repo o/r pr merge 12 --squash", + "gh pr -R o/r merge 12", + "gh pr merge 12 \\\n --auto", + 'gh "pr" merge 12', + "gh pr edit 12 --base main", + "gh pr close 12", + "gh issue -R o/r close 5", + "gh pr review 12 --approve", + "origin pr merge 12", + "origin pr merge 12 --squash", + "gh api -X POST repos/o/r/pulls/12/comments/5/replies -f body=done", + "gh api --method POST repos/o/r/pulls/12/comments/5/replies -f body=done", + "gh api --method=POST repos/o/r/pulls/12/reviews -f event=APPROVE", + `gh api graphql -f query='mutation{resolveReviewThread(input:{threadId:"t"}){clientMutationId}}'`, + "gh api repos/o/r/pulls/12/merge -X PUT", + "gh api repos/o/r/merges -f base=main -f head=feature/x", + `gh api graphql -f query='mutation{mergePullRequest(input:{pullRequestId:"x"}){clientMutationId}}'`, + `gh api graphql -f query='mutation{updateRef(input:{refId:"r",oid:"abc",force:true}){clientMutationId}}'`, + "gh api -X DELETE repos/o/r/git/refs/heads/feature/x", + "gh api -X DELETE repos/o/r/issues/comments/5", + "gh api -X PATCH repos/o/r -f description=docs", + "gh api -X PATCH repos/o/r/git/refs/heads/main -f sha=abc", + "gh api -X PATCH repos/o/r/git/refs/heads/feature/main-menu -f sha=abc -F force=true", + "gh release create v1.2.3", + "gh secret set DEPLOY_TOKEN", + "gh workflow run deploy.yml --ref main", + "curl -sS -X PUT https://api.github.com/repos/o/r/pulls/1/merge -d '{}'", + "gt submit --stack", + "gt merge", + "git push origin HEAD:main", + "git push origin main", + "git push", + "git push origin HEAD", + "git push -u origin feature/x", + "git push origin :feature/x", + "git push origin --delete feature/x", + "git push --all origin", + "git branch -D feature/x", + "git update-ref refs/heads/main abc123", + "git reflog expire --expire=now --all", + "git reset --hard origin/main", + // A force-push to anything that is not the default branch is the port's own rebase flow. "git push --force-with-lease origin feature/x", - "git status --porcelain", - "bun run test", - "git push --force-with-lease origin main-menu", + "git push -f origin feature/x", "git push --force origin feature/main-menu", - 'git commit -m "merge main into feature"', - "gh pr list --search main", - "git log main..HEAD", + "git push --force-with-lease origin main-menu", + "git push origin +feature/x", + "git push --force origin :feature/x", + "git push --force --delete origin feature/x", + `git -C ${feature} push --force-with-lease origin HEAD`, + `git -C ${feature} push -f`, + `git -C ${feature} push --force-with-lease origin`, + `git -C ${develop} push -f origin feature/x`, + "git push -f origin $BRANCH", + "git push --force origin \"$(git branch --show-current)\"", + "git push -f origin 'refs/heads/feature/*:refs/heads/feature/*'", + "git push --force-with-lease origin feature/x:feature/x", // The global-option tolerance must not cost the feature-branch push. - "git -C /tmp/work push origin feature/x", + "git -C /tmp/work push --force-with-lease origin feature/x", "git --git-dir=/tmp/repo/.git push --force-with-lease origin feature/x", - "/usr/bin/git push origin feature/x", - "git -C /tmp/wt push --dry-run origin HEAD:main", - "git -c user.name=bot push origin feature/head", - "git --work-tree=/tmp/wt push -q origin feature/main-menu", - "git -C /tmp/repo branch -d feat", - "git update-ref -d refs/heads/feature/x", - "git reflog expire --expire=now --all-older-than=1wk", + "/usr/bin/git push -f origin feature/x", + "git -c user.name=bot push -f origin feature/head", + "git --work-tree=/tmp/wt push -f -q origin feature/main-menu", + // A dry run moves nothing. + "git -C /tmp/wt push --dry-run -f origin HEAD:main", + "git push -n --force origin main", + // Reads and unrelated commands. + "gh pr view 12", + "gh pr list --state open", + "gh pr list --search main", + "gh pr diff 12", "gh repo view o/r", + "gh repo -R o/r view", "gh release list", - "gh release view v1.2.3", - "gh secret list", - "gh workflow list", - "gh workflow run deploy.yml --ref feature/x", - "gh 'workflow' run ci.yml --ref feature/x", - "curl -sSL https://api.github.com/repos/o/r/pulls/1", - "curl -X GET https://api.github.com/repos/o/r", - "gh api repos/o/r/pulls/12", - "gh api -X GET repos/o/r/branches/main", - // Flags after the command group must not turn a read into a mutation. - "gh pr -R o/r view 12", - "gh pr -R o/r list --search merge", - // Reading a trunk ref, or moving a feature ref, is not moving trunk. + "gh api repos/o/r", + "gh api -X GET repos/o/r", "gh api repos/o/r/git/refs/heads/main", "gh api -X GET repos/o/r/git/refs/heads/main --jq .object.sha", - "gh api -X PATCH repos/o/r/git/refs/heads/feature/main-menu -f sha=abc -F force=true", + "gh pr -R o/r view 12", + "git status --porcelain", + "git log main..HEAD", + 'git commit -m "merge main into feature"', + "bun run test", + "curl -sSL https://api.github.com/repos/o/r/pulls/1", + "curl -X GET https://api.github.com/repos/o/r", // A later command's arguments are not the push's refspecs. - "git push origin feature && git rev-parse HEAD", - "git push origin feature || git rev-parse HEAD", - "git push origin feature; git checkout main", - "git push origin feature | grep main", - "git push origin feature\ngit log -1 HEAD", - "git push origin feature 2>&1 && git rev-parse HEAD", - "cat > notes.md <<'EOF'\nPush with git push origin feature.\nEOF\ngit rev-parse HEAD", + "git push -f origin feature && git rev-parse HEAD", + "git push -f origin feature || git rev-parse HEAD", + "git push -f origin feature; git checkout main", + "git push -f origin feature | grep main", + "git push -f origin feature\ngit log -1 HEAD", + "git push -f origin feature 2>&1 && git rev-parse HEAD", + "cat > notes.md <<'EOF'\nForce-push with git push -f origin feature when told to.\nEOF\ngit rev-parse HEAD", // A subshell or brace group cuts the same as the commands written without it. - "(cd x && git push origin feature && git rev-parse HEAD)", - "{ git push origin feature; git rev-parse HEAD; }", + "(cd x && git push -f origin feature && git rev-parse HEAD)", + "{ git push -f origin feature; git rev-parse HEAD; }", // A comment is not an argument, and a redirection target is not a refspec. - "git push origin feature # never main", - 'git push origin feature > "$LOG" 2>&1', + "git push -f origin feature # never main", + 'git push -f origin feature > "$LOG" 2>&1', // Reading a ref through GraphQL is not moving it. "gh api graphql -f query='query{repository(owner:\"o\",name:\"r\"){ref(qualifiedName:\"main\"){target{oid}}}}'", ]; describe("pstackpolicy", () => { - test.each(MUST_BLOCK)("refuses %p as %p without a grant", async (command, rule) => { - const result = await run(command, { PSTACK_LANDING_GRANT: undefined }); + test.each(MUST_BLOCK)("refuses %p as %p", async (command, rule) => { + const result = await run(command); expect(result?.block).toBe(true); expect(result?.reason).toContain(rule); - expect(result?.reason).toContain("PSTACK_LANDING_GRANT"); }); test.each(MUST_PASS)("allows %p", async (command) => { - expect(await run(command, { PSTACK_LANDING_GRANT: undefined })).toBeUndefined(); - }); - - test("an operator grant lifts every rule", async () => { - for (const [command] of MUST_BLOCK) { - expect(await run(command, { PSTACK_LANDING_GRANT: "1" }), `granted: ${command}`) - .toBeUndefined(); - } + expect(await run(command)).toBeUndefined(); }); - test("only an explicit affirmative counts as a grant", async () => { - for (const value of ["0", "false", "", "yes", "no"]) { - const result = await run("gh pr merge 12 --squash", { PSTACK_LANDING_GRANT: value }); - expect(result?.block, `not a grant: ${JSON.stringify(value)}`).toBe(true); - } - const ok = await run("gh pr merge 12 --squash", { PSTACK_LANDING_GRANT: "true" }); - expect(ok?.block).toBeUndefined(); + test("the refusal tells the agent to stop and return the step to the operator", async () => { + const result = await run("git push --force origin main"); + expect(result?.reason).toContain("pause list"); + expect(result?.reason).toContain("Stop here and return this step to the operator"); }); // omp://approval-mode.md: eval declares the exec tier and can spawn a shell, so a rule that // only read bash's `command` field was not a rule about the command. test.each([ - ["await Bun.$`gh pr merge 12 --squash`", "merging a pull request"], - ['subprocess.run(["git", "push", "origin", "HEAD:main"])', "pushing to trunk"], + ["await Bun.$`git push --force origin HEAD:main`", "default or trunk"], + ['subprocess.run(["git", "push", "--force", "origin", "HEAD:main"])', "default or trunk"], ['await tool.bash({ command: "gh repo delete o/r --yes" })', "deleting the repository"], // A list literal broken over lines is still one command, and a comment inside it does not // open a quote that hides the rest. - ['subprocess.run([\n "git", "push", "origin", "feature",\n "HEAD:main",\n])', "pushing to trunk"], - ['subprocess.run([\n "git", "push", "origin", # don\'t\n "HEAD:main",\n])', "pushing to trunk"], - ["await Bun.$`git push origin HEAD:main`", "pushing to trunk"], + [ + 'subprocess.run([\n "git", "push", "-f", "origin", "feature",\n "HEAD:main",\n])', + "default or trunk", + ], + [ + 'subprocess.run([\n "git", "push", "-f", "origin", # don\'t\n "HEAD:main",\n])', + "default or trunk", + ], + ['subprocess.run(["gh", "api", "-X", "DELETE", "repos/o/r"])', "deleting the repository"], ])("refuses the eval cell %p as %p", async (code, rule) => { - const result = await call("eval", { language: "py", code }, { PSTACK_LANDING_GRANT: undefined }); + const result = await evalCell(code); expect(result?.block).toBe(true); expect(result?.reason).toContain(rule); }); test.each([ - 'print("git push origin feature/x")', - 'subprocess.run(["git", "push", "origin", "feature"])\nsubprocess.run(["git", "rev-parse", "HEAD"])', + 'print("git push -f origin feature/x")', + 'subprocess.run(["git", "push", "--force-with-lease", "origin", "feature"])\nsubprocess.run(["git", "rev-parse", "HEAD"])', "await Bun.$`git push origin feature`", + "await Bun.$`gh pr merge 12 --squash`", + 'subprocess.run(["git", "push", "origin", "HEAD:main"])', ])("allows the eval cell %p", async (code) => { - expect(await call("eval", { language: "py", code }, { PSTACK_LANDING_GRANT: undefined })) - .toBeUndefined(); + expect(await evalCell(code)).toBeUndefined(); }); test("ignores tools that carry no command", async () => { - expect(await toolCall({ toolName: "read", input: { command: "gh pr merge 12" } })).toBeUndefined(); + expect( + await toolCall({ toolName: "read", input: { command: "git push -f origin main" } }) + ).toBeUndefined(); expect(await toolCall({ toolName: "bash", input: {} })).toBeUndefined(); expect(await toolCall({ toolName: "eval", input: {} })).toBeUndefined(); }); From 5a07b858f64ac7d535818c3ca0a0b9f98fefd1ec Mon Sep 17 00:00:00 2001 From: Negrescu Alexandru <124818050+negoro26@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:01:46 +0200 Subject: [PATCH 3/6] test(verify): rework the landing gate recipe into an irreversible-action gate - Replace the grant launch with a git push shim beside the gh shim. - Prompts cover a refused force-push to main, an eval force-push, a repo delete, and allowed merge and feature-push controls. --- .omp/skills/verify-pstack-omp/SKILL.md | 19 ++++---- .../verify-pstack-omp/features/README.md | 8 ++-- .../features/irreversible-action-gate.md | 44 +++++++++++++++++++ .../features/landing-gate.md | 44 ------------------- .../prompts/gate-eval-force-push.txt | 1 + .../prompts/gate-feature-push.txt | 1 + .../prompts/gate-force-push-main.txt | 1 + .../{landing-merge.txt => gate-merge.txt} | 0 .../prompts/gate-repo-delete.txt | 1 + .../prompts/landing-eval-merge.txt | 1 - .../prompts/landing-push-trunk.txt | 1 - .../prompts/landing-view.txt | 1 - .../prompts/user-bang-force-push.txt | 1 + .../prompts/user-bang-merge.txt | 1 - .../verify-pstack-omp/scripts/control-pstack | 20 +++++---- 15 files changed, 74 insertions(+), 70 deletions(-) create mode 100644 .omp/skills/verify-pstack-omp/features/irreversible-action-gate.md delete mode 100644 .omp/skills/verify-pstack-omp/features/landing-gate.md create mode 100644 .omp/skills/verify-pstack-omp/prompts/gate-eval-force-push.txt create mode 100644 .omp/skills/verify-pstack-omp/prompts/gate-feature-push.txt create mode 100644 .omp/skills/verify-pstack-omp/prompts/gate-force-push-main.txt rename .omp/skills/verify-pstack-omp/prompts/{landing-merge.txt => gate-merge.txt} (100%) create mode 100644 .omp/skills/verify-pstack-omp/prompts/gate-repo-delete.txt delete mode 100644 .omp/skills/verify-pstack-omp/prompts/landing-eval-merge.txt delete mode 100644 .omp/skills/verify-pstack-omp/prompts/landing-push-trunk.txt delete mode 100644 .omp/skills/verify-pstack-omp/prompts/landing-view.txt create mode 100644 .omp/skills/verify-pstack-omp/prompts/user-bang-force-push.txt delete mode 100644 .omp/skills/verify-pstack-omp/prompts/user-bang-merge.txt diff --git a/.omp/skills/verify-pstack-omp/SKILL.md b/.omp/skills/verify-pstack-omp/SKILL.md index 65d77c4..ba0c381 100644 --- a/.omp/skills/verify-pstack-omp/SKILL.md +++ b/.omp/skills/verify-pstack-omp/SKILL.md @@ -7,7 +7,7 @@ description: Drive the pstack plugin inside a real, isolated omp TUI and the por Users meet this repo in two places. -- The plugin tree `plugins/pstack` loaded into omp. Users type skills as `/skill:`, pin poteto-mode with the `potetomode` extension, and run under the `pstackpolicy` extension, which refuses forge mutations in model-issued `bash` and `eval` calls unless `PSTACK_LANDING_GRANT=1`. This is the primary target. +- The plugin tree `plugins/pstack` loaded into omp. Users type skills as `/skill:`, pin poteto-mode with the `potetomode` extension, and run under the `pstackpolicy` extension, which refuses a force-push to the default branch or to main, master, or trunk, and repository deletion, in model-issued `bash` and `eval` calls. Everything else, merges included, is the playbooks' work and passes. This is the primary target. - The maintainer's port CLI, `omp-port/check-port.sh` and `omp-port/sync-upstream.sh`. `omp-port/smoke-plugin.mjs` is CI's RPC check for registration and the pin. This skill reuses its isolation recipe (scratch HOME, stripped environment, `--plugin-dir` plus `-e` on the same tree, a local provider in `models.yml`) and adds a TUI in tmux plus a scripted model, so a drive can make omp issue real tool calls. @@ -22,15 +22,15 @@ P=.omp/skills/verify-pstack-omp/prompts ## Launch ```bash -$C launch [--grant] [-- ] +$C launch [-- ] ``` `` is 1 to 40 characters of `[a-z0-9-]`, one per drive. Launch refuses a run id whose scratch dir or tmux server already exists. It does this: -1. Creates scratch `${TMPDIR:-/tmp}/verify-pstack-omp-/` with `home/` as omp's HOME, `work/` as its cwd, and `bin/gh`, a shim that appends its argv to `gh-calls.log` and never touches the network. +1. Creates scratch `${TMPDIR:-/tmp}/verify-pstack-omp-/` with `home/` as omp's HOME, `work/` as its cwd, `bin/gh`, a shim that appends its argv to `gh-calls.log` and never touches the network, and `bin/git`, a shim that logs any `push` to `git-calls.log` and exits without pushing, and runs the real git for every other command. 2. Writes `home/.omp/agent/config.yml` with `setupVersion: 2`, which skips omp's first-run login wizard. 3. Starts a private tmux server, `tmux -L verify-pstack-omp- -f /dev/null`. Session `model` runs `scripts/scripted-model.mjs` on a free loopback port. `models.yml` names it as provider `verify`, model `scripted`. -4. Starts session `omp` under `env -i` with only HOME, USER, TERM, LANG, SHELL, and PATH, with the scratch `bin` first. `--grant` adds `PSTACK_LANDING_GRANT=1`. The flags are `--no-session --no-title --no-lsp --no-rules --no-extensions --plugin-dir -e --model verify/scripted --approval-mode yolo`. yolo is the mode pstackpolicy exists for. +4. Starts session `omp` under `env -i` with only HOME, USER, TERM, LANG, SHELL, and PATH, with the scratch `bin` first. The flags are `--no-session --no-title --no-lsp --no-rules --no-extensions --plugin-dir -e --model verify/scripted --approval-mode yolo`. yolo is the mode pstackpolicy exists for. 5. Waits up to 30s for the status line to name `scripted`, which means omp accepts input. It took about 2s on this host. Launch then writes `launch.txt` to the evidence dir and prints the attach command. Overrides are `VERIFY_OMP_BIN` (default `omp` on PATH), `VERIFY_PSTACK_PLUGIN` (default this checkout's `plugins/pstack`), and `VERIFY_PSTACK_EVIDENCE` (the evidence root). @@ -47,7 +47,7 @@ Teardown is [Cleanup](#cleanup). $C doctor ``` -Read-only. It prints one `ok` or `FAIL` line per check and exits 1 on any FAIL. It checks that both tmux sessions exist, the omp pane is alive and runs `VERIFY_OMP_BIN` at the printed version, omp loads the expected plugin path, omp's HOME is the scratch home, omp's environment holds no credential or omp root variable, the scripted model answers `/health`, and the status line names `scripted`. The last line reports `grant armed` or `grant absent`. Run it first, and again whenever a drive surprises you. +Read-only. It prints one `ok` or `FAIL` line per check and exits 1 on any FAIL. It checks that both tmux sessions exist, the omp pane is alive and runs `VERIFY_OMP_BIN` at the printed version, omp loads the expected plugin path, omp's HOME is the scratch home, omp's environment holds no credential or omp root variable, the scripted model answers `/health`, the status line names `scripted`, and omp's environment holds no `PSTACK_` variable. Run it first, and again whenever a drive surprises you. ## Drive @@ -69,7 +69,7 @@ $C capture # evidence snapshot, see below `wait` reads the whole pane with scrollback and succeeds only when it holds more matching lines than it did at the last `press`. So a second `wait 'tool result received'` waits for the second turn instead of matching the first. Wait on output the action produces, never on text you typed, because the typed text moves from the editor into the transcript and the count does not grow. -Type a prompt that names a forge mutation with `type-file`. When the agent driving this skill runs omp with pstack installed, pstackpolicy reads that agent's own bash command line too, so `$C type '...gh pr merge...'` is refused in the driver's session and never reaches tmux. `prompts/` holds every such prompt. +Type a prompt that names a force-push to trunk or a repository delete with `type-file`. When the agent driving this skill runs omp with pstack installed, pstackpolicy reads that agent's own bash command line too, so `$C type '...git push --force origin main...'` is refused in the driver's session and never reaches tmux. `prompts/` holds every such prompt. Editor handles that the recipes rely on: @@ -82,11 +82,12 @@ Editor handles that the recipes rely on: Evidence goes to `${VERIFY_PSTACK_EVIDENCE:-${XDG_STATE_HOME:-$HOME/.local/state}/verify-pstack-omp}//`. It is outside the repository and the scratch dir, and cleanup never removes it. `$C evidence ` creates and prints it. -- `launch.txt` names the run, the omp binary and version, the plugin path, its git HEAD with a dirty-file count, the grant, the extra flags, and the scratch path. +- `launch.txt` names the run, the omp binary and version, the plugin path, its git HEAD with a dirty-file count, the extra flags, and the scratch path. - `actions.log` timestamps every launch, type, type-file, press, capture, clone, and cleanup. - `.pane.txt` is the whole pane with scrollback, so it holds the typed prompt, the tool block, and its output. - `.model-requests.jsonl` is every request omp sent the model, so it holds the system prompt and the tool result the agent got back. - `.gh-calls.log` is the argv of every `gh` call that reached a shell. An empty file means none did. +- `.git-calls.log` is the argv of every `git push` that reached a shell. An empty file means none did. - `omp-logs/` is omp's own log directory, copied at cleanup. For the port CLI, `tee` the command's stdout and stderr into the evidence dir, append its exit code, and save `git status --porcelain` before and after. @@ -95,8 +96,8 @@ Proof standards: - Drive through the TUI the way a user does, with typed prompts and slash commands. Importing an extension module is the unit tests' job (`plugins/pstack/extensions/*/index.test.js`), not this skill's. - Capture the action and the resulting state. The pane shows the prompt and the result, and the model log shows what the agent received. -- Verify side effects. A refusal proof needs an empty `gh-calls.log` plus a control in which the same launch reaches the shim, through an allowed command or the same command under `--grant`. Without the control, an empty log could also mean the shim was never on PATH. -- The scripted model and the `gh` shim are the only stand-ins. The model replaces the provider at its HTTP boundary. The shim replaces `gh` on PATH, so a gate failure cannot reach the forge. omp, the plugin, both extensions, and the bash and eval tools are real. +- Verify side effects. A refusal proof needs an empty `git-calls.log` or `gh-calls.log` for the refused command plus a control in which the same launch reaches the shim through an allowed command. Without the control, an empty log could also mean the shim was never on PATH. +- The scripted model and the `gh` and `git` shims are the only stand-ins. The model replaces the provider at its HTTP boundary. The shims replace `gh` and the push half of `git` on PATH, so a gate failure cannot reach the forge. omp, the plugin, both extensions, and the bash and eval tools are real. - Skip model requests whose `tools` list is empty when asserting. Those are omp compressing skill descriptions in the background. - `sync-upstream.sh ` and `rebuild` rewrite the checkout. Run them only inside `$C clone `, and read the result with `git status --porcelain` and `git diff --stat` there. diff --git a/.omp/skills/verify-pstack-omp/features/README.md b/.omp/skills/verify-pstack-omp/features/README.md index c7b9d89..8eb5b04 100644 --- a/.omp/skills/verify-pstack-omp/features/README.md +++ b/.omp/skills/verify-pstack-omp/features/README.md @@ -11,7 +11,7 @@ This directory is the maintained source for verifying what users of pstack-omp c ## Driving conventions -- Type prompts that name a forge mutation with `$C type-file`, never inline. The driver's own pstackpolicy refuses an inline one. +- Type prompts that name a force-push to trunk or a repository delete with `$C type-file`, never inline. The driver's own pstackpolicy refuses an inline one. - Wait on visible text with `$C wait`, not on a fixed sleep. The pane strings each recipe names are stable output of the plugin or omp. - Assert on model requests whose `tools` list is non-empty. Requests with an empty list are background skill-description compression. - Run anything that rewrites `plugins/pstack` inside `$C clone `, never in the checkout. @@ -20,9 +20,9 @@ This directory is the maintained source for verifying what users of pstack-omp c ## Proof and skip reporting - Capture the user action and the resulting state with `$C capture `, not only the final screen. -- A refusal proof pairs an empty `.gh-calls.log` with a control capture in which the same launch reaches the `gh` shim. +- A refusal proof pairs an empty `.git-calls.log` or `.gh-calls.log` with a control capture in which the same launch reaches the `gh` or `git` shim. - Port proof includes the command, stdout and stderr, the exit code, and `git status --porcelain` before and after. -- Record the feature file and sub-feature ID in the capture name, for example `landing-gate.gate-refuse-bash`. +- Record the feature file and sub-feature ID in the capture name, for example `irreversible-action-gate.gate-refuse-force-push`. - Report an unreachable path with the attempted command and the unmet precondition. - Do not report a skipped entry point as verified through a different path. @@ -41,6 +41,6 @@ Keep implementation details out of the map. Name only user paths, stable handles - [Skill commands](./skill-commands.md) covers registration of every skill directory, `/skill:` autocomplete, and invoking a skill. - [poteto-mode pin](./poteto-mode-pin.md) covers `/poteto-mode`, the status pill, the per-turn reminder, the `--poteto` flag, the shortcut, and `/new`. -- [Landing gate](./landing-gate.md) covers pstackpolicy refusing forge mutations from model-issued `bash` and `eval` calls, the allowed control, the grant, and the user's own `!` commands. +- [Irreversible-action gate](./irreversible-action-gate.md) covers pstackpolicy refusing a force-push to the default branch and repository deletion from model-issued `bash` and `eval` calls, the allowed merge and feature-push controls, and the user's own `!` commands. - [Port gate](./port-gate.md) covers `omp-port/check-port.sh` at the pin and against another upstream sha. - [Upstream sync](./upstream-sync.md) covers `omp-port/sync-upstream.sh check`, `rebuild`, and a sync to a target sha. diff --git a/.omp/skills/verify-pstack-omp/features/irreversible-action-gate.md b/.omp/skills/verify-pstack-omp/features/irreversible-action-gate.md new file mode 100644 index 0000000..6a5fa5f --- /dev/null +++ b/.omp/skills/verify-pstack-omp/features/irreversible-action-gate.md @@ -0,0 +1,44 @@ +# Irreversible-action gate + +The pstackpolicy extension refuses two irreversible actions that the model issues through the `bash` or `eval` tool, a force-push to the repository's default branch or to main, master, or trunk, and deleting the repository. These are the two items of upstream's pause list that a command can show. The refused command never runs. The agent receives the refusal as its tool result and is told to stop and return the step to the operator. Everything else passes, merges included, because the operator's prompt is the permission to land. + +## Sub-features + +- `gate-refuse-force-push` refuses a model `bash` call that force-pushes main, past the global option, and git never pushes. +- `gate-refuse-eval` refuses a model `eval` cell that force-pushes main through a Python argv list with `--force-with-lease` and a `+` refspec. +- `gate-refuse-repo-delete` refuses a model `bash` call that deletes the repository through the API. +- `gate-agent-told` returns the refusal text to the agent as the tool result, with the instruction to return the step to the operator. +- `gate-allow-merge` lets a `gh pr merge` reach the `gh` shim in the same session. +- `gate-allow-feature-push` lets a force-push to a feature branch reach the `git` shim. +- `gate-user-bang` leaves the user's own `!` command ungated, because the operator typed it. + +## How to get to it (user POV) + +- Ask the agent to do something that ends in a force-push to the default branch or a repository delete. The gate fires when the model's tool call carries the command. +- Ask the agent to merge a pull request or force-push a feature branch. Nothing fires. +- Type `!` to run a shell command yourself. + +## Driving it with control-pstack + +Preconditions: + +- `$C launch gate-` succeeded, and `$C doctor gate-` prints no `FAIL`, including the line that omp's environment holds no `PSTACK_` variable. +- The run id is new, so `$C evidence gate-` prints a directory that did not exist before. + +- **Refuse a bash force-push.** Run `$C type-file gate- $P/gate-force-push-main.txt`, `$C press gate- Enter`, `$C wait gate- 'refused force-pushing a default or trunk branch'`, `$C wait gate- 'tool result received'`, and `$C capture gate- irreversible-action-gate.gate-refuse-force-push`. The pane shows the typed `tool:bash` prompt, a tool block whose command line is `git -C . push --force origin main`, and output starting `pstackpolicy: refused force-pushing a default or trunk branch.` `irreversible-action-gate.gate-refuse-force-push.git-calls.log` is empty. +- **Agent receives the refusal.** Run `jq -r 'select(.body.messages[-1].role=="tool") | .body.messages[-1].content' "$($C evidence gate-)/irreversible-action-gate.gate-refuse-force-push.model-requests.jsonl"`. It prints the same `pstackpolicy: refused` text, which ends with `Stop here and return this step to the operator`. +- **Refuse an eval force-push.** Run `$C type-file gate- $P/gate-eval-force-push.txt`, `$C press gate- Enter`, `$C wait gate- 'refused force-pushing a default or trunk branch'`, `$C wait gate- 'tool result received'`, and `$C capture gate- irreversible-action-gate.gate-refuse-eval`. The pane shows the `tool:eval` prompt followed by the refusal. The git-calls log is still empty. +- **Refuse a repository delete.** Run `$C type-file gate- $P/gate-repo-delete.txt`, `$C press gate- Enter`, `$C wait gate- 'refused deleting the repository'`, `$C wait gate- 'tool result received'`, and `$C capture gate- irreversible-action-gate.gate-refuse-repo-delete`. The gh-calls log is empty. +- **Allowed merge.** Run `$C type-file gate- $P/gate-merge.txt`, `$C press gate- Enter`, `$C wait gate- 'gh-shim: pr merge'`, `$C wait gate- 'tool result received'`, and `$C capture gate- irreversible-action-gate.gate-allow-merge`. The tool block output is `gh-shim: pr merge 1 --repo pstack-verify/no-such-repo --squash`, and that capture's gh-calls log has exactly that one line. This is the control that proves the shim was reachable while the refusals above ran. +- **Allowed feature push.** Run `$C type-file gate- $P/gate-feature-push.txt`, `$C press gate- Enter`, `$C wait gate- 'git-shim: -C . push'`, `$C wait gate- 'tool result received'`, and `$C capture gate- irreversible-action-gate.gate-allow-feature-push`. The git-calls log has exactly `-C . push --force-with-lease origin feature/verify`. +- **User bang command.** Run `$C type-file gate- $P/user-bang-force-push.txt`, `$C press gate- Enter`, `$C wait gate- 'git-shim: push --force origin main'`, and `$C capture gate- irreversible-action-gate.gate-user-bang`. The pane shows the shim output with no model turn after it, and the git-calls log gains a `push --force origin main` line. +- **Clean up.** Run `$C cleanup gate-`, then `ls` the evidence dir. + +## Gotchas + +- The driver's own pstackpolicy refuses an inline prompt or a `grep` whose command line contains a force-push to main. Use `type-file` for prompts and read evidence with `read` or a pattern such as `'push --force'`. +- The shim logs are cumulative for a run. Capture each refusal before the allowed controls, or the refusal capture shows the control's line. +- Wait for `tool result received` before typing the next prompt, so each capture holds one finished turn. +- The gate reads only model-issued `bash` and `eval` calls. The user's `!` command, the `browser` and `computer` preludes, and a command built by string concatenation inside a cell are outside it by design. +- The scratch `work/` directory is not a git checkout, so a force-push to a feature branch passes because the extension finds no default branch and no checked-out trunk there. +- The prompts target `pstack-verify/no-such-repo`. If the shims were missing, the real `gh` would still fail, since the scratch HOME has no login. diff --git a/.omp/skills/verify-pstack-omp/features/landing-gate.md b/.omp/skills/verify-pstack-omp/features/landing-gate.md deleted file mode 100644 index 4a1726a..0000000 --- a/.omp/skills/verify-pstack-omp/features/landing-gate.md +++ /dev/null @@ -1,44 +0,0 @@ -# Landing gate - -The pstackpolicy extension refuses forge mutations that the model issues through the `bash` or `eval` tool, such as merging a pull request or pushing to trunk, unless the operator started omp with `PSTACK_LANDING_GRANT=1`. The refused command never runs. The agent receives the refusal as its tool result, and the user sees it in the tool block. - -## Sub-features - -- `gate-refuse-bash` refuses a model `bash` call that merges a pull request, and nothing runs. -- `gate-refuse-eval` refuses a model `eval` cell that merges a pull request through a Python argv list. -- `gate-refuse-push` refuses a model `git -C . push origin HEAD:main`, past the global option. -- `gate-agent-told` returns the refusal text to the agent as the tool result. -- `gate-allow-read` lets a non-mutating `gh pr view` run in the same session. -- `gate-grant` lets the same merge run when omp started with `PSTACK_LANDING_GRANT=1`. -- `gate-user-bang` leaves the user's own `!` command ungated, because the operator typed it. - -## How to get to it (user POV) - -- Ask the agent to do something that ends in a merge, a close, a base retarget, a review post, a trunk push, a release, or a repository delete. The gate fires when the model's tool call carries the command. -- Start omp with `PSTACK_LANDING_GRANT=1` in its environment to allow those commands for that process. -- Type `!` to run a shell command yourself. - -## Driving it with control-pstack - -Preconditions: - -- `$C launch gate-` succeeded without `--grant`, and `$C doctor gate-` prints `grant absent` and no `FAIL`. -- The run id is new, so `$C evidence gate-` prints a directory that did not exist before. - -- **Refuse a bash merge.** Run `$C type-file gate- $P/landing-merge.txt`, `$C press gate- Enter`, `$C wait gate- 'refused merging a pull request'`, `$C wait gate- 'tool result received'`, and `$C capture gate- landing-gate.gate-refuse-bash`. The pane shows the typed `tool:bash` prompt, a tool block whose command line is the merge, and output starting `pstackpolicy: refused merging a pull request.` `landing-gate.gate-refuse-bash.gh-calls.log` is empty. -- **Agent receives the refusal.** Run `jq -r 'select(.body.messages[-1].role=="tool") | .body.messages[-1].content' "$($C evidence gate-)/landing-gate.gate-refuse-bash.model-requests.jsonl"`. It prints the same `pstackpolicy: refused merging a pull request.` text. -- **Refuse an eval merge.** Run `$C type-file gate- $P/landing-eval-merge.txt`, `$C press gate- Enter`, `$C wait gate- 'refused merging a pull request'`, `$C wait gate- 'tool result received'`, and `$C capture gate- landing-gate.gate-refuse-eval`. The pane shows the `tool:eval` prompt followed by `pstackpolicy: refused merging a pull request.` The gh-calls log is still empty. -- **Refuse a trunk push.** Run `$C type-file gate- $P/landing-push-trunk.txt`, `$C press gate- Enter`, `$C wait gate- 'refused pushing to trunk'`, `$C wait gate- 'tool result received'`, and `$C capture gate- landing-gate.gate-refuse-push`. The tool block shows `$ git -C . push origin HEAD:main` and `pstackpolicy: refused pushing to trunk.` The gh-calls log is still empty. -- **Allowed control.** Run `$C type-file gate- $P/landing-view.txt`, `$C press gate- Enter`, `$C wait gate- 'gh-shim: pr view'`, `$C wait gate- 'tool result received'`, and `$C capture gate- landing-gate.gate-allow-read`. The tool block output is `gh-shim: pr view 1 --repo pstack-verify/no-such-repo`, and that capture's gh-calls log has exactly that one line. This proves the shim was reachable while the refusals above ran. -- **User bang command.** Run `$C type-file gate- $P/user-bang-merge.txt`, `$C press gate- Enter`, `$C wait gate- 'gh-shim: pr merge'`, and `$C capture gate- landing-gate.gate-user-bang`. The pane shows the shim output with no model turn after it, and the gh-calls log gains a `pr merge 1 ...` line. -- **Grant.** Run `$C cleanup gate-`, then `$C launch gate--grant --grant`. `$C doctor gate--grant` prints `grant armed`. Type `$P/landing-merge.txt` the same way, `$C wait gate--grant 'gh-shim: pr merge'`, and capture `landing-gate.gate-grant`. Its gh-calls log has `pr merge 1 --repo pstack-verify/no-such-repo --squash`. -- **Clean up.** Run `$C cleanup` for each run id used, then `ls` both evidence dirs. - -## Gotchas - -- The driver's own pstackpolicy refuses an inline prompt or a `grep` whose command line contains `gh` followed by `pr merge`. Use `type-file` for prompts and read evidence with `read` or a pattern such as `'pr merge'`. -- The shim log is cumulative for a run. Capture each refusal before the allowed control, or the refusal capture shows the control's line. -- Wait for `tool result received` before typing the next prompt, so each capture holds one finished turn. -- The gate reads only model-issued `bash` and `eval` calls. The user's `!` command, the `browser` and `computer` preludes, and a command built by string concatenation inside a cell are outside it by design. -- The grant is read from omp's process environment. Exporting it in the driver's shell does nothing, because launch runs omp under `env -i`. Use `--grant`. -- The prompts target `pstack-verify/no-such-repo`. If the shim were missing, the real `gh` would still fail, since the scratch HOME has no login. diff --git a/.omp/skills/verify-pstack-omp/prompts/gate-eval-force-push.txt b/.omp/skills/verify-pstack-omp/prompts/gate-eval-force-push.txt new file mode 100644 index 0000000..6c0b6ca --- /dev/null +++ b/.omp/skills/verify-pstack-omp/prompts/gate-eval-force-push.txt @@ -0,0 +1 @@ +tool:eval {"language":"py","code":"import subprocess; print(subprocess.run([\"git\", \"push\", \"--force-with-lease\", \"origin\", \"+HEAD:main\"], capture_output=True, text=True).stdout)"} diff --git a/.omp/skills/verify-pstack-omp/prompts/gate-feature-push.txt b/.omp/skills/verify-pstack-omp/prompts/gate-feature-push.txt new file mode 100644 index 0000000..d7cb4dd --- /dev/null +++ b/.omp/skills/verify-pstack-omp/prompts/gate-feature-push.txt @@ -0,0 +1 @@ +tool:bash {"command":"git -C . push --force-with-lease origin feature/verify","i":"Force-pushing a feature branch"} diff --git a/.omp/skills/verify-pstack-omp/prompts/gate-force-push-main.txt b/.omp/skills/verify-pstack-omp/prompts/gate-force-push-main.txt new file mode 100644 index 0000000..d431174 --- /dev/null +++ b/.omp/skills/verify-pstack-omp/prompts/gate-force-push-main.txt @@ -0,0 +1 @@ +tool:bash {"command":"git -C . push --force origin main","i":"Force-pushing the default branch"} diff --git a/.omp/skills/verify-pstack-omp/prompts/landing-merge.txt b/.omp/skills/verify-pstack-omp/prompts/gate-merge.txt similarity index 100% rename from .omp/skills/verify-pstack-omp/prompts/landing-merge.txt rename to .omp/skills/verify-pstack-omp/prompts/gate-merge.txt diff --git a/.omp/skills/verify-pstack-omp/prompts/gate-repo-delete.txt b/.omp/skills/verify-pstack-omp/prompts/gate-repo-delete.txt new file mode 100644 index 0000000..37f00a6 --- /dev/null +++ b/.omp/skills/verify-pstack-omp/prompts/gate-repo-delete.txt @@ -0,0 +1 @@ +tool:bash {"command":"gh api -X DELETE repos/pstack-verify/no-such-repo","i":"Deleting the verification repository"} diff --git a/.omp/skills/verify-pstack-omp/prompts/landing-eval-merge.txt b/.omp/skills/verify-pstack-omp/prompts/landing-eval-merge.txt deleted file mode 100644 index 2343219..0000000 --- a/.omp/skills/verify-pstack-omp/prompts/landing-eval-merge.txt +++ /dev/null @@ -1 +0,0 @@ -tool:eval {"language":"py","code":"import subprocess; print(subprocess.run([\"gh\", \"pr\", \"merge\", \"1\", \"--repo\", \"pstack-verify/no-such-repo\"], capture_output=True, text=True).stdout)"} diff --git a/.omp/skills/verify-pstack-omp/prompts/landing-push-trunk.txt b/.omp/skills/verify-pstack-omp/prompts/landing-push-trunk.txt deleted file mode 100644 index fa04cb4..0000000 --- a/.omp/skills/verify-pstack-omp/prompts/landing-push-trunk.txt +++ /dev/null @@ -1 +0,0 @@ -tool:bash {"command":"git -C . push origin HEAD:main","i":"Pushing to trunk"} diff --git a/.omp/skills/verify-pstack-omp/prompts/landing-view.txt b/.omp/skills/verify-pstack-omp/prompts/landing-view.txt deleted file mode 100644 index 7fb68e5..0000000 --- a/.omp/skills/verify-pstack-omp/prompts/landing-view.txt +++ /dev/null @@ -1 +0,0 @@ -tool:bash {"command":"gh pr view 1 --repo pstack-verify/no-such-repo","i":"Reading the verification PR"} diff --git a/.omp/skills/verify-pstack-omp/prompts/user-bang-force-push.txt b/.omp/skills/verify-pstack-omp/prompts/user-bang-force-push.txt new file mode 100644 index 0000000..198432d --- /dev/null +++ b/.omp/skills/verify-pstack-omp/prompts/user-bang-force-push.txt @@ -0,0 +1 @@ +!git push --force origin main diff --git a/.omp/skills/verify-pstack-omp/prompts/user-bang-merge.txt b/.omp/skills/verify-pstack-omp/prompts/user-bang-merge.txt deleted file mode 100644 index 39930d3..0000000 --- a/.omp/skills/verify-pstack-omp/prompts/user-bang-merge.txt +++ /dev/null @@ -1 +0,0 @@ -!gh pr merge 1 --repo pstack-verify/no-such-repo --squash diff --git a/.omp/skills/verify-pstack-omp/scripts/control-pstack b/.omp/skills/verify-pstack-omp/scripts/control-pstack index 93c01c5..5d77c9c 100755 --- a/.omp/skills/verify-pstack-omp/scripts/control-pstack +++ b/.omp/skills/verify-pstack-omp/scripts/control-pstack @@ -1,7 +1,7 @@ #!/usr/bin/env bash # Drives the pstack plugin inside a real, isolated omp TUI. ../SKILL.md is the workflow. # -# control-pstack launch [--grant] [-- ] +# control-pstack launch [-- ] # control-pstack doctor # control-pstack type types literal text into the omp editor # control-pstack type-file types the file's first line @@ -61,10 +61,9 @@ wait_for() { } launch() { - local grant=() extra=() + local extra=() while [ $# -gt 0 ]; do case $1 in - --grant) grant=(PSTACK_LANDING_GRANT=1) ;; --) shift; extra=("$@"); break ;; *) die "launch: unknown argument '$1'" ;; esac @@ -78,7 +77,9 @@ launch() { mkdir -p "$scratch"/{home/.omp/agent,work,bin} "$evidence" printf 'setupVersion: 2\n' >"$scratch/home/.omp/agent/config.yml" printf '#!/bin/sh\nprintf "%%s\\n" "$*" >>%q\necho "gh-shim: $*"\n' "$scratch/gh-calls.log" >"$scratch/bin/gh" - chmod +x "$scratch/bin/gh" + printf '#!/bin/sh\nfor a in "$@"; do\n\tif [ "$a" = push ]; then printf "%%s\\n" "$*" >>%q; echo "git-shim: $*"; exit 0; fi\ndone\nexec %q "$@"\n' \ + "$scratch/git-calls.log" "$(command -v git)" >"$scratch/bin/git" + chmod +x "$scratch/bin/gh" "$scratch/bin/git" tm new-session -d -s model -x 200 -y 10 \ env -i "$marker" PATH=/usr/local/bin:/usr/bin:/bin "$(command -v bun)" "$here/scripted-model.mjs" "$scratch" @@ -97,15 +98,15 @@ launch() { tm new-session -d -s omp -x 200 -y 50 -c "$scratch/work" \ env -i "$marker" USER="$USER" TERM=tmux-256color LANG="${LANG:-C.UTF-8}" SHELL=/bin/bash \ - PATH="$scratch/bin:/usr/local/bin:/usr/bin:/bin" "${grant[@]}" \ + PATH="$scratch/bin:/usr/local/bin:/usr/bin:/bin" \ "$omp_bin" --no-session --no-title --no-lsp --no-rules --no-extensions \ --plugin-dir "$plugin" -e "$plugin" --model verify/scripted --approval-mode yolo "${extra[@]}" - note launch "grant=${grant[*]:-none}" "extra=${extra[*]:-none}" + note launch "extra=${extra[*]:-none}" wait_for ' scripted > ' 30 - printf 'run\t%s\nomp\t%s %s\nplugin\t%s\nplugin_head\t%s\ngrant\t%s\nextra\t%s\nscratch\t%s\n' \ + printf 'run\t%s\nomp\t%s %s\nplugin\t%s\nplugin_head\t%s\nextra\t%s\nscratch\t%s\n' \ "$run" "$omp_bin" "$("$omp_bin" --version)" "$plugin" \ "$(git -C "$plugin" rev-parse HEAD) $(git -C "$plugin" status --porcelain -- . | wc -l) dirty" \ - "${grant[*]:-none}" "${extra[*]:-none}" "$scratch" >"$evidence/launch.txt" + "${extra[*]:-none}" "$scratch" >"$evidence/launch.txt" printf 'ready: tmux -L verify-pstack-omp-%s attach -t omp\nevidence: %s\n' "$run" "$evidence" } @@ -127,7 +128,7 @@ doctor() { check "scripted model answers on port $(cat "$scratch/model.port" 2>/dev/null)" \ '[ "$(curl -fsS "http://127.0.0.1:$(cat "$scratch/model.port")/health")" = ok ]' check "status line shows the scripted model" 'pane | grep -q " scripted > "' - printf 'grant %s\n' "$(grep -q '^PSTACK_LANDING_GRANT=1$' <<<"$env" && echo armed || echo absent)" + check "omp env carries no PSTACK_ variable" '! grep -q "^PSTACK_" <<<"$env"' exit $bad } @@ -137,6 +138,7 @@ capture() { pane >"$evidence/$name.pane.txt" cp "$scratch/model-requests.jsonl" "$evidence/$name.model-requests.jsonl" 2>/dev/null || : >"$evidence/$name.model-requests.jsonl" cp "$scratch/gh-calls.log" "$evidence/$name.gh-calls.log" 2>/dev/null || : >"$evidence/$name.gh-calls.log" + cp "$scratch/git-calls.log" "$evidence/$name.git-calls.log" 2>/dev/null || : >"$evidence/$name.git-calls.log" note capture "$name" wc -l "$evidence/$name".* } From 73122a203274d732ab7ffdb512ab58157b661687 Mon Sep 17 00:00:00 2001 From: Negrescu Alexandru <124818050+negoro26@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:01:46 +0200 Subject: [PATCH 4/6] docs: describe the pause list, the narrowed extension, and operator-prompt merge permission - README, plugin README, and PORTING say pstackpolicy refuses two actions and does not enforce the playbooks. --- PORTING.md | 62 ++++++++++++++++++++++++---------------- README.md | 9 +++--- plugins/pstack/README.md | 48 +++++++++++++++++-------------- 3 files changed, 69 insertions(+), 50 deletions(-) diff --git a/PORTING.md b/PORTING.md index a230908..18b440f 100644 --- a/PORTING.md +++ b/PORTING.md @@ -240,8 +240,8 @@ Everything below `pstack/skills` and `pstack/agents` is outside this port. The b four reviewer and synthesizer prompts. Architect and reflect are now one paragraph each and spawn nothing. The rules, exemptions, and gate fixtures that served only those files went with them. - **Added** at 0b46ec3: `skills/poteto-mode/worker.md`, the operator rules the router tells every - kickoff to read first. It ships as upstream wrote it apart from its stop list, which `rules.sed` - replaces with the router's pause list, naming the same actions in the same order. + kickoff to read first. It ships as upstream wrote it, stop list included. The port follows + upstream's pause list and does not rewrite it, as the next section records. - **Not carried** `assets/logo.png` and its `"logo": "assets/logo.png"` field. They are a Cursor marketplace image with no omp consumer. An earlier tree vendored the manifest beside it so that future drift diffs would show only real changes; that ended when the build narrowed to the two @@ -451,11 +451,11 @@ The injected reminder is a pointer, not the playbook. It tells the agent to read - **Never-block.** Subagents run `approvalMode: yolo`, so a worker cannot stop to ask. **Nothing here vetoes a malformed subagent result.** The plugin ships two extensions, `potetomode` and `pstackpolicy`, and neither one registers a `session_stop`; `pstackpolicy` vetoes at `tool_call` - and only for the forge mutations, so a result that is merely wrong still gets through. What - pstack relies on for that is the root's own acceptance discipline: `skill://pstack-omp` requires - the root to read each result and accept or reject it, and a `judge`/`verifier` role is the - independent check on a worker's claim. That is the whole backstop for a malformed result. Landing - is a separate gate and it is enforced in process rather than in prose; see + and only for a force-push to the default branch and repository deletion, so a result that is + merely wrong still gets through. What pstack relies on for that is the root's own acceptance + discipline: `skill://pstack-omp` requires the root to read each result and accept or reject it, + and a `judge`/`verifier` role is the independent check on a worker's claim. That is the whole + backstop for a malformed result. The two refusals are described in [What omp can actually stop](#what-omp-can-actually-stop) below. Returning `{"decision":"block"}` from `session_stop` is the one native veto contract, and `~/.omp/agent/extensions/proofgate/` implements it, dormant unless `$OMP_PROOF_FILE` is set, so @@ -538,12 +538,22 @@ thinking id for judgment work. ### What omp can actually stop -The playbooks say "stop where the human's call begins", and until recently that was advice with -nothing behind it. Three facts from `omp://approval-mode.md`, on omp 18.14.1, decide what an -instruction is worth here: - -- `yolo` auto-approves the `read`, `write`, **and `exec`** tiers. A `gh pr merge` inside a bash - call is an `exec` call, so it runs with no prompt. +The port follows upstream's pause list and does not widen it. `poteto-mode` ships the Autonomy +section as upstream wrote it: "**Always pause** for irreversible writes: force-push to shared +branches, deploys, data deletion, customer messages." and the session-override line that lets "going +to bed", "run until done", and "be fully autonomous" mean keep going. `worker.md` ships its stop +list unchanged: a deploy, deleted data, a force-push to a shared branch, or a message to someone +outside the run. Merge permission is the operator's prompt. Upstream's README example is "land the +stack even if ci flakes. i want everything merged by morning", and in upstream Shipping and +Autopilot-full owners merge while Babysit stops at merge-ready. An earlier revision widened the +list to merging, trunk pushes, retargeting, closing, reviews and branch deletion, told the router +that autonomy "is not authorisation to land", and refused those commands unless omp started with an +environment grant. That contradicted upstream's own owners, who merge, so it was removed. + +Three facts from `omp://approval-mode.md`, on omp 18.14.1, decide what an instruction is worth here: + +- `yolo` auto-approves the `read`, `write`, **and `exec`** tiers, so a command inside a bash call + runs with no prompt. - Subagents run headless with `tools.approvalMode: yolo`, and "the parent `task` approval is the authorization boundary". Every pstack owner is a subagent, so the boundary is the spawn, not the instruction. @@ -551,15 +561,17 @@ instruction is worth here: to answer it. A backstop therefore has to *refuse*, not prompt. bash's built-in critical-pattern list covers `rm -rf /`, fork bombs, remote-fetch-then-execute, -`/etc/passwd`, and host shutdown. **A merge is not on it.** So is not a force-push to trunk, a base -retarget, a PR close, or a review comment. - -That is why the port now ships `plugins/pstack/extensions/pstackpolicy`, a second extension beside -the mode pin. It registers `tool_call` and refuses the forge mutations outright unless the operator -set `PSTACK_LANDING_GRANT=1`. The grant is an environment variable rather than a flag or a slash -command because a flag an agent can pass is not a grant a human made, and an agent cannot set its -own process environment. Refusals name the variable, so the operator is told exactly what to set. - -A force push to a **feature** branch stays allowed: that is the port's own rebase flow, and blocking -it would fail every stack owner mid-rebase and make the extension unusable without a grant. A force -push that names a trunk ref is refused, which is the case the playbooks keep escalating. +`/etc/passwd`, and host shutdown. A force-push to trunk and a repository delete are not on it. + +So `plugins/pstack/extensions/pstackpolicy`, a second extension beside the mode pin, refuses at +`tool_call` the two items of upstream's pause list that a command can show. One is a force-push +(`--force`, `-f`, `--force-with-lease`, a `+` refspec, `--mirror`) to the repository's default branch +or to `main`, `master`, or `trunk`. The other is deleting the repository, with `gh repo delete` or +`gh api -X DELETE repos//` and no further path. The refusal tells the agent to stop and +return the step to the operator, which is what "Always pause" asks for. Everything else passes, +including `gh pr merge`, merge APIs, closing, reviews, retargeting, branch deletion, and plain +pushes. Deploys, data deletion and customer messages have no command shape to read, so they stay +with the prose. The extension does not enforce the playbooks. It is a backstop for two irreversible +actions, not a sandbox, and it reads only `bash` and `eval` calls. + +A force push to a **feature** branch stays allowed: that is the port's own rebase flow. diff --git a/README.md b/README.md index ea5bae5..6a97c4a 100644 --- a/README.md +++ b/README.md @@ -45,10 +45,11 @@ check the model each panel agent resolves to before you trust a panel verdict. - `.github/workflows/upstream-sync.yml` syncs once a day. It runs `check-port.sh` on `main` and against the new upstream commit, builds the sync, runs the gate again on the result, and merges the sync pull request only when the build and the gate pass. -- The `pstackpolicy` extension refuses the forge mutations the playbooks otherwise only ask for in - prose, such as `gh pr merge`, closing or retargeting a pull request, posting a review, and a push to - `main`. It allows them only when omp starts with `PSTACK_LANDING_GRANT=1`. The full list is in - [`plugins/pstack/README.md`](plugins/pstack/README.md). +- The `pstackpolicy` extension is active from install. It refuses two actions from upstream's pause + list that a command can show: a force-push to the default branch or to `main`, `master`, or + `trunk`, and deleting the repository. Everything else passes, merges included, because the port + follows upstream's pause list and your prompt is the permission to land. The extension does not + enforce the playbooks. The details are in [`plugins/pstack/README.md`](plugins/pstack/README.md). - The `potetomode` extension pins `poteto-mode` per session. `/poteto-mode on|off|status`, `alt+shift+t`, and `omp --poteto` set the pin, and a resumed session keeps its saved state. diff --git a/plugins/pstack/README.md b/plugins/pstack/README.md index edb7641..4a8b7ee 100644 --- a/plugins/pstack/README.md +++ b/plugins/pstack/README.md @@ -36,27 +36,33 @@ Then `/poteto-mode on`, or `alt+shift+t`, or `omp -p --poteto '...'` for headles ## What the policy extension refuses `pstackpolicy` loads with the plugin and needs no configuration. It registers `tool_call` on `bash` -and `eval`, and refuses the forge mutations the playbooks only ask for in prose: `gh pr merge`, -merge and close through `gh api`, `gh pr close|reopen|delete`, `gh pr edit --base`, `gh pr review`, -merge-when-ready, a trunk ref moved through `gh api`, the GraphQL `updateRef`, `updateRefs` and -`deleteRef` mutations, `gh repo delete`, `gh release create|delete|upload`, -`gh secret|variable set|delete`, `gh workflow run --ref `, the same forge calls made with -`curl`, and `gt submit|rebase|restack|merge`. A `gh` flag such as -`-R o/r` may sit before or after the command group. Locally it refuses `git update-ref`, -`git branch -D`, `git reset --hard` against a remote, and `git reflog expire --expire=now --all`. -Any `git push` whose refspec lands on `main`, `master`, `trunk`, `develop`, or `release` is -refused, forced or not; a force push to a feature branch stays allowed, because that is the port's -own rebase flow. A refspec the scan cannot read may be trunk and is refused too: `HEAD`, no refspec -at all, a `$VAR`, `${VAR}`, `$(...)` or backtick substitution, and a `*` pattern. A push's -refspecs end at its own command, so a later `&&`, `||`, `;`, `|` or newline does not lend it -arguments, inside a subshell or brace group as well. A comment ends at its newline whatever quotes -it holds, and a redirection target is not a refspec. Each line of a heredoc body is checked as a -command, because a shell may run it. - -To land, set `PSTACK_LANDING_GRANT=1` in the environment omp starts from. It is an environment -variable and not a flag or a slash command because a flag an agent can pass is not a grant you made. -The refusal names the variable, so the agent tells you exactly what to set. `PORTING.md`'s -"What omp can actually stop" carries the measurement behind the list. +and `eval` and refuses exactly two things, the two items of upstream's pause list that a command can +show. + +- A force-push to the repository's default branch, or to `main`, `master`, or `trunk`. A push is + forced by `--force`, `--force-with-lease`, `-f` (also inside a flag cluster such as `-fu`), a `+` + on the refspec, or `--mirror`. `HEAD` or a missing refspec pushes the checked-out branch, which the + extension reads from the checkout. The default branch is whatever the remote's `HEAD` names. A + `gh api` update of a trunk ref that sends `force=true` counts too. A force-push to any other + branch stays allowed, because that is the port's own rebase flow. +- Deleting the repository, with `gh repo delete` or `gh api -X DELETE repos//` and no + further path. + +Everything else passes: merging, closing, reviews, retargeting a base, deleting a branch, plain +pushes, releases and secrets. Those are the playbooks' own work, and the operator's prompt is the +permission for them. `poteto-mode` ships upstream's pause list and its session-override line as +upstream wrote them, so a prompt such as "land the stack, I'm going to bed" is the permission to +merge, and the playbooks that land (Shipping, Autopilot-full) merge on it. Babysit still stops at +merge-ready. Deploys, data deletion and customer messages have no command shape this file could +read, so they stay with the prose. + +A refusal tells the agent to stop and return the step to the operator, as the pause list says. The +extension does not enforce the playbooks and is no sandbox. It reads only model-issued `bash` and +`eval` calls. The `browser` and `computer` preludes emit no `tool_call`, and a command assembled by +string concatenation inside a cell matches no rule. A push's refspecs end at its own command, a +comment ends at its newline whatever quotes it holds, a redirection target is not a refspec, and +each line of a heredoc body is checked as a command, because a shell may run it. +`PORTING.md`'s "What omp can actually stop" carries the measurement behind it. ## What this plugin does not enforce From 25e90331e22f4e29fb669a0bbdd589b4a5a85e33 Mon Sep 17 00:00:00 2001 From: Negrescu Alexandru <124818050+negoro26@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:07:42 +0200 Subject: [PATCH 5/6] fix(pstackpolicy): refuse a forced push whose destination the shell fills in --- plugins/pstack/extensions/pstackpolicy/index.js | 6 ++++-- plugins/pstack/extensions/pstackpolicy/index.test.js | 9 +++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/plugins/pstack/extensions/pstackpolicy/index.js b/plugins/pstack/extensions/pstackpolicy/index.js index d6f8a71..887585c 100644 --- a/plugins/pstack/extensions/pstackpolicy/index.js +++ b/plugins/pstack/extensions/pstackpolicy/index.js @@ -267,8 +267,9 @@ const REASON_TRUNK = "force-pushing a default or trunk branch"; * Why this `git push` is a force-push to the default branch or to main, master, or trunk, or * null. A push is forced by `--force`, `--force-with-lease`, `-f`, or a `+` on the refspec, and * `--mirror` always is. Where the destination is `HEAD` or absent, git pushes the checked-out - * branch, so that branch is read; a destination only the shell can fill in is not a fact the - * command shows, so it passes. A delete refspec is not a force-push. + * branch, so that branch is read. A forced destination the shell fills in, such as `$BRANCH` or + * `$(git branch --show-current)`, can be trunk and the command cannot show it is not, so it is + * refused; writing the branch name out lets it through. A delete refspec is not a force-push. */ function pushRefuse(argv, dir) { const args = argv.filter( @@ -301,6 +302,7 @@ function pushRefuse(argv, dir) { .slice(token.lastIndexOf(":") + 1) .replace(/^\+/, "") .replace(/^refs\/heads\//, ""); + if (dest.startsWith("$")) return `${REASON_TRUNK} that the shell names at run time`; if (dest === "*") return "force-pushing every branch, including the default branch"; if (dest === "HEAD") { if (onTrunk(currentBranch(dir), remote)) return `${REASON_TRUNK} through HEAD`; diff --git a/plugins/pstack/extensions/pstackpolicy/index.test.js b/plugins/pstack/extensions/pstackpolicy/index.test.js index 813bbb9..c1fd0a5 100644 --- a/plugins/pstack/extensions/pstackpolicy/index.test.js +++ b/plugins/pstack/extensions/pstackpolicy/index.test.js @@ -90,6 +90,11 @@ const MUST_BLOCK = [ ["(git push -f origin $(echo feature; echo main))", "default or trunk"], ["cd /tmp && git push --force origin main", "default or trunk"], ['if [ -z "$x" ]; then git push -f origin main; fi', "default or trunk"], + // A forced destination the shell fills in may be trunk, so the command cannot clear it. + ["git push -f origin $BRANCH", "shell names at run time"], + ['git push --force origin "$(git branch --show-current)"', "shell names at run time"], + ["git push origin +${branch}", "shell names at run time"], + ["git push --force-with-lease origin `git branch --show-current`", "shell names at run time"], // A backtick substitution runs the command inside it, the same as `$(...)`. ["echo `git push -f origin main`", "default or trunk"], // A comment ends at its newline whatever quotes it holds, and `$#` is a parameter, not a comment. @@ -172,8 +177,8 @@ const MUST_PASS = [ `git -C ${feature} push -f`, `git -C ${feature} push --force-with-lease origin`, `git -C ${develop} push -f origin feature/x`, - "git push -f origin $BRANCH", - "git push --force origin \"$(git branch --show-current)\"", + "git push origin $BRANCH", + 'git push -u origin "$(git branch --show-current)"', "git push -f origin 'refs/heads/feature/*:refs/heads/feature/*'", "git push --force-with-lease origin feature/x:feature/x", // The global-option tolerance must not cost the feature-branch push. From 8e980bafe02f1883fdb800b60fadfb07e225ffbf Mon Sep 17 00:00:00 2001 From: Negrescu Alexandru <124818050+negoro26@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:25:31 +0200 Subject: [PATCH 6/6] fix(pstackpolicy): read git state from the call's directory and close the quoting gaps - Resolve the checked-out branch and default branch from ctx.cwd moved by the call's own cwd, not process.cwd(). Isolated owners in worktrees got the wrong answer in both directions. - Tell the agent to write the branch name out literally when a forced destination is shell-named. A real trunk refusal still says to stop and return to the operator. - Join quoted and unquoted pieces of a word as the shell does, so "HEAD":main, "ma"in and m""ain no longer pass. - Strip backslash-newline before the repository-delete match and accept an absolute api.github.com endpoint. - Document the shell-named rule and the untracked cd in README.md, plugins/pstack/README.md and PORTING.md, and reword the gate.yml smoke comment. --- .github/workflows/gate.yml | 2 +- PORTING.md | 9 +- README.md | 10 ++- plugins/pstack/README.md | 10 ++- .../pstack/extensions/pstackpolicy/index.js | 73 ++++++++++------ .../extensions/pstackpolicy/index.test.js | 83 ++++++++++++++++++- 6 files changed, 153 insertions(+), 34 deletions(-) diff --git a/.github/workflows/gate.yml b/.github/workflows/gate.yml index c039b80..d0a4bc6 100644 --- a/.github/workflows/gate.yml +++ b/.github/workflows/gate.yml @@ -54,7 +54,7 @@ jobs: smoke: # A real omp loads plugins/pstack through -e, `omp plugin link`, and a local marketplace install, # and runs scripted turns: every skill registers, the pinned prompt names poteto-mode, and - # pstackpolicy refuses a merge before gh runs. omp-port/smoke-plugin.mjs names each check. + # pstackpolicy refuses a force-push to main and `gh pr merge` still reaches gh. omp-port/smoke-plugin.mjs names each check. runs-on: ubuntu-latest timeout-minutes: 10 steps: diff --git a/PORTING.md b/PORTING.md index 18b440f..4947314 100644 --- a/PORTING.md +++ b/PORTING.md @@ -574,4 +574,11 @@ pushes. Deploys, data deletion and customer messages have no command shape to re with the prose. The extension does not enforce the playbooks. It is a backstop for two irreversible actions, not a sandbox, and it reads only `bash` and `eval` calls. -A force push to a **feature** branch stays allowed: that is the port's own rebase flow. +A force push to a **feature** branch stays allowed: that is the port's own rebase flow. The one +exception is a forced destination the shell fills in, such as `$BRANCH` or +`$(git branch --show-current)`. The command cannot show it is not trunk, so the refusal tells the +agent to write the branch name out literally and retry, where a real trunk force-push is told to +stop and return to the operator. The branch the checked-out rules read comes from `ctx.cwd`, the +session's directory, moved by the call's own `cwd` and each `git -C`. omp's launch directory is not +that directory for an isolated owner in a worktree. A `cd x && git push` inside the command line is +not tracked. diff --git a/README.md b/README.md index 6a97c4a..6211376 100644 --- a/README.md +++ b/README.md @@ -47,9 +47,13 @@ check the model each panel agent resolves to before you trust a panel verdict. sync pull request only when the build and the gate pass. - The `pstackpolicy` extension is active from install. It refuses two actions from upstream's pause list that a command can show: a force-push to the default branch or to `main`, `master`, or - `trunk`, and deleting the repository. Everything else passes, merges included, because the port - follows upstream's pause list and your prompt is the permission to land. The extension does not - enforce the playbooks. The details are in [`plugins/pstack/README.md`](plugins/pstack/README.md). + `trunk`, and deleting the repository. A forced push whose destination the shell fills in, such as + `$BRANCH`, is refused too, because the command cannot show it is not trunk. Write the branch name + out literally and it passes. Everything else passes, merges included, because the port follows + upstream's pause list and your prompt is the permission to land. The extension reads the checked-out + branch from the tool call's directory, the session cwd or the call's own `cwd`, and does not follow + a `cd x && git push` inside the command line. It does not enforce the playbooks. The details are in + [`plugins/pstack/README.md`](plugins/pstack/README.md). - The `potetomode` extension pins `poteto-mode` per session. `/poteto-mode on|off|status`, `alt+shift+t`, and `omp --poteto` set the pin, and a resumed session keeps its saved state. diff --git a/plugins/pstack/README.md b/plugins/pstack/README.md index 4a8b7ee..c34ae60 100644 --- a/plugins/pstack/README.md +++ b/plugins/pstack/README.md @@ -42,9 +42,13 @@ show. - A force-push to the repository's default branch, or to `main`, `master`, or `trunk`. A push is forced by `--force`, `--force-with-lease`, `-f` (also inside a flag cluster such as `-fu`), a `+` on the refspec, or `--mirror`. `HEAD` or a missing refspec pushes the checked-out branch, which the - extension reads from the checkout. The default branch is whatever the remote's `HEAD` names. A - `gh api` update of a trunk ref that sends `force=true` counts too. A force-push to any other - branch stays allowed, because that is the port's own rebase flow. + extension reads from the directory the tool call runs in: the session cwd, or the `cwd` the call + passes, moved by each `git -C`. A `cd x && git push` inside the command line is not tracked. The + default branch is whatever the remote's `HEAD` names. A `gh api` update of a trunk ref that sends + `force=true` counts too. A force-push to any other branch stays allowed, because that is the + port's own rebase flow, except where the shell names the destination, as in + `git push --force-with-lease origin "$BRANCH"`. The command cannot show that value is not trunk, so + it is refused with the instruction to write the branch name out literally and retry. - Deleting the repository, with `gh repo delete` or `gh api -X DELETE repos//` and no further path. diff --git a/plugins/pstack/extensions/pstackpolicy/index.js b/plugins/pstack/extensions/pstackpolicy/index.js index 887585c..b23ea34 100644 --- a/plugins/pstack/extensions/pstackpolicy/index.js +++ b/plugins/pstack/extensions/pstackpolicy/index.js @@ -43,15 +43,18 @@ const gh = (group, verbs) => const REPO_DELETE = new RegExp(gh("repo", "delete")); // Quotes are syntax once the shell or the host language has read them, so `gh "repo" delete` is -// `gh repo delete` and `'HEAD:main'` is one refspec. Inside an `eval` cell the command is usually -// a list literal, `subprocess.run(["git", "push", "origin", "HEAD:main"])`, where a comma and a -// bracket separate what separated nothing in a shell line. Both become a space. Only the loose -// direction is taken: an unpaired quote is left alone. A backtick substitution becomes `$` and -// its command, the text a `$(...)` leaves once its brackets go, so a refspec built from one reads -// as a value the shell fills in when it runs. +// `gh repo delete` and `'HEAD:main'` is one refspec. A quoted piece joins the text beside it as +// the shell joins it, so `"HEAD":main`, `"ma"in` and `m""ain` stay one word and quotes never +// split one. Inside an `eval` cell the command is usually a list literal, +// `subprocess.run(["git", "push", "origin", "HEAD:main"])`, where a comma and a bracket separate +// what separated nothing in a shell line. Both become a space. A backslash-newline is a line +// continuation the shell deletes. Only the loose direction is taken: an unpaired quote is left +// alone. A backtick substitution becomes `$` and its command, the text a `$(...)` leaves once its +// brackets go, so a refspec built from one reads as a value the shell fills in when it runs. const normalize = (command) => command - .replace(/(["'])([^"'\n]*)\1\s*,?/g, "$2 ") + .replace(/\\\n/g, "") + .replace(/(["'])([^"'\n]*)\1(\s*,)?/g, (_, _quote, body, comma) => (comma ? `${body} ` : body)) .replace(/`([^`]*)`/g, "$$ $1 ") .replace(/[()[\]{},]/g, " "); @@ -211,9 +214,9 @@ function gitSubcommand(tokens, start) { return -1; } -/** The directory `git` runs in: the session directory, moved by each `-C ` in turn. */ -function gitDirectory(tokens, start, at) { - let dir = process.cwd(); +/** The directory `git` runs in: the tool call's directory, moved by each `-C ` in turn. */ +function gitDirectory(tokens, start, at, base) { + let dir = base; for (let i = start + 1; i < at; i += 1) { if (tokens[i] === "-C" && i + 1 < at) { dir = resolve(dir, tokens[i + 1]); @@ -224,14 +227,14 @@ function gitDirectory(tokens, start, at) { } /** Every `git ` in the command, with the arguments its own simple command gives it. */ -function eachGitCommand(command, visit) { +function eachGitCommand(command, base, visit) { for (const simple of simpleCommands(command)) { const tokens = shellTokens(normalize(simple)); for (let i = 0; i < tokens.length; i += 1) { if (!isGit(tokens[i])) continue; const at = gitSubcommand(tokens, i); if (at < 0) continue; - visit(tokens[at], tokens.slice(at + 1), gitDirectory(tokens, i, at)); + visit(tokens[at], tokens.slice(at + 1), gitDirectory(tokens, i, at, base)); } } } @@ -262,6 +265,7 @@ const REDIRECTION = /^(?:\d+|&)?[<>]/; const REDIRECTION_ALONE = /^(?:\d+|&)?[<>]+[&|]?$/; const REASON_TRUNK = "force-pushing a default or trunk branch"; +const REASON_SHELL_NAMED = `${REASON_TRUNK} that the shell names at run time`; /** * Why this `git push` is a force-push to the default branch or to main, master, or trunk, or @@ -302,7 +306,7 @@ function pushRefuse(argv, dir) { .slice(token.lastIndexOf(":") + 1) .replace(/^\+/, "") .replace(/^refs\/heads\//, ""); - if (dest.startsWith("$")) return `${REASON_TRUNK} that the shell names at run time`; + if (dest.startsWith("$")) return REASON_SHELL_NAMED; if (dest === "*") return "force-pushing every branch, including the default branch"; if (dest === "HEAD") { if (onTrunk(currentBranch(dir), remote)) return `${REASON_TRUNK} through HEAD`; @@ -316,9 +320,9 @@ function pushRefuse(argv, dir) { return null; } -function pushOffence(command) { +function pushOffence(command, base) { let why = null; - eachGitCommand(command, (subcommand, args, dir) => { + eachGitCommand(command, base, (subcommand, args, dir) => { if (subcommand === "push" && !why) why = pushRefuse(args, dir); }); return why; @@ -375,8 +379,11 @@ function eachGhApi(command, visit) { } } -const REPO_ENDPOINT = /^\/?repos\/[^/\s]+\/[^/\s]+\/?$/; -const HEADS_ENDPOINT = /^\/?repos\/[^/\s]+\/[^/\s]+\/git\/refs\/heads\/(.+)$/; +const API_ORIGIN = String.raw`(?:https://api\.github\.com)?`; +const REPO_ENDPOINT = new RegExp(String.raw`^${API_ORIGIN}/?repos/[^/\s]+/[^/\s]+/?$`); +const HEADS_ENDPOINT = new RegExp( + String.raw`^${API_ORIGIN}/?repos/[^/\s]+/[^/\s]+/git/refs/heads/(.+)$` +); const FORCE_FIELD = /(?:^|[=:])force=true$/i; /** Why this `gh api` call is repository deletion or a forced update of a trunk ref, or null. */ @@ -418,21 +425,39 @@ function subject(event) { return null; } +/** + * The directory the call runs in. bash runs in the session's cwd, which `ctx.cwd` carries and + * which differs from the omp launch directory for an isolated owner in a worktree, and a call + * can pass its own `cwd`. A `cd x && git push` inside the command line is not tracked. + */ +const baseDirectory = (event, ctx) => + resolve(ctx.cwd, typeof event.input?.cwd === "string" ? event.input.cwd : ""); + +const STOP = "Stop here and return this step to the operator, saying what is blocked."; + export default function pstackpolicy(pi) { - pi.on("tool_call", async (event) => { + pi.on("tool_call", async (event, ctx) => { const command = subject(event); if (!command) return; - const why = pushOffence(command) ?? repoDeletion(command) ?? apiOffence(command); - if (why) { + const why = + pushOffence(command, baseDirectory(event, ctx)) ?? repoDeletion(command) ?? apiOffence(command); + if (!why) return; + if (why === REASON_SHELL_NAMED) { return { block: true, reason: - `pstackpolicy: refused ${why}. pstack's pause list says to always pause for ` + - `irreversible writes, and a force-push to the default branch and repository deletion ` + - `are two of them. Stop here and return this step to the operator, saying what is ` + - `blocked. Do not look for another way to run it.`, + `pstackpolicy: refused ${why}. The command does not show which branch it forces. ` + + `If the branch is not the default branch, write its name out literally and retry. ` + + `If it is the default branch, pstack's pause list says to always pause for that. ${STOP}`, }; } + return { + block: true, + reason: + `pstackpolicy: refused ${why}. pstack's pause list says to always pause for ` + + `irreversible writes, and a force-push to the default branch and repository deletion ` + + `are two of them. ${STOP} Do not look for another way to run it.`, + }; }); } diff --git a/plugins/pstack/extensions/pstackpolicy/index.test.js b/plugins/pstack/extensions/pstackpolicy/index.test.js index c1fd0a5..0d365ba 100644 --- a/plugins/pstack/extensions/pstackpolicy/index.test.js +++ b/plugins/pstack/extensions/pstackpolicy/index.test.js @@ -16,8 +16,12 @@ const handlers = new Map(); policy({ on: (event, fn) => handlers.set(event, fn) }); const toolCall = handlers.get("tool_call"); -const run = (command) => toolCall({ toolName: "bash", input: { command } }); -const evalCell = (code) => toolCall({ toolName: "eval", input: { language: "py", code } }); +// The handler resolves git's directory from `ctx.cwd` and the call's own `cwd`, never from the +// directory the runner was launched in. `root` holds no checkout, so a case that reads a branch +// names its checkout with `-C`, a `cwd` input, or a `ctx` of its own. +const callIn = (toolName, input, cwd) => toolCall({ toolName, input }, { cwd }); +const run = (command, cwd = root, input = {}) => callIn("bash", { command, ...input }, cwd); +const evalCell = (code) => callIn("eval", { language: "py", code }, root); // Checkouts the refusal reads. A command without `-C` would read whatever branch the test runner // sits on, so every case that depends on a checkout names one. They exist before the case tables @@ -95,6 +99,12 @@ const MUST_BLOCK = [ ['git push --force origin "$(git branch --show-current)"', "shell names at run time"], ["git push origin +${branch}", "shell names at run time"], ["git push --force-with-lease origin `git branch --show-current`", "shell names at run time"], + ['git push --force-with-lease="$BRANCH:$SHA" origin "$BRANCH"', "shell names at run time"], + // A quote never splits a word, so quoting part of a refspec hides nothing. + ['git push -f origin "HEAD":main', "default or trunk"], + ["git push -f origin 'HEAD':refs/heads/main", "default or trunk"], + ['git push -f origin "ma"in', "default or trunk"], + ['git push -f origin m""ain', "default or trunk"], // A backtick substitution runs the command inside it, the same as `$(...)`. ["echo `git push -f origin main`", "default or trunk"], // A comment ends at its newline whatever quotes it holds, and `$#` is a parameter, not a comment. @@ -109,6 +119,9 @@ const MUST_BLOCK = [ ["gh --repo o/r repo delete --yes", "deleting the repository"], ['gh "repo" delete o/r --yes', "deleting the repository"], ["gh repo -R o/r delete --yes", "deleting the repository"], + ["gh \\\n repo delete o/r --yes", "deleting the repository"], + ["gh api -X DELETE https://api.github.com/repos/o/r", "deleting the repository through the API"], + ["gh api https://api.github.com/repos/o/r/ --method DELETE", "deleting the repository through the API"], ["gh api -X DELETE repos/o/r", "deleting the repository through the API"], ["gh api --method DELETE /repos/o/r", "deleting the repository through the API"], ["gh api repos/o/r -X DELETE", "deleting the repository through the API"], @@ -242,6 +255,72 @@ describe("pstackpolicy", () => { const result = await run("git push --force origin main"); expect(result?.reason).toContain("pause list"); expect(result?.reason).toContain("Stop here and return this step to the operator"); + expect(result?.reason).not.toContain("write its name out literally"); + }); + + test("a shell-named forced destination is told to write the branch out, and the literal passes", async () => { + const named = await run('git push --force-with-lease="$BRANCH:$SHA" origin "$BRANCH"'); + expect(named?.block).toBe(true); + expect(named?.reason).toContain("If the branch is not the default branch, write its name out literally and retry"); + expect(named?.reason).toContain("Stop here and return this step to the operator"); + expect(named?.reason).not.toContain("Do not look for another way"); + expect(await run('git push --force-with-lease="feature/x:$SHA" origin "feature/x"')).toBeUndefined(); + expect(await run("git push --force-with-lease=feature/x:abc123 origin feature/x")).toBeUndefined(); + }); + + // bash runs in the session cwd, which is not the directory omp was launched from when an + // isolated owner works in a worktree, and a call can pass its own cwd. + describe("the directory git runs in", () => { + const from = async (launch, fn) => { + const before = process.cwd(); + process.chdir(launch); + try { + return await fn(); + } finally { + process.chdir(before); + } + }; + const BARE = "git push --force-with-lease"; + + test("ctx.cwd on a feature branch allows a bare push when omp was launched on trunk", async () => { + await from(trunk, async () => { + expect(await run(BARE, feature)).toBeUndefined(); + expect(await run("git push -f origin HEAD", feature)).toBeUndefined(); + }); + }); + + test("ctx.cwd on trunk refuses a bare push when omp was launched on a feature branch", async () => { + await from(feature, async () => { + for (const command of [BARE, "git push -f origin HEAD"]) { + const result = await run(command, trunk); + expect(result?.block).toBe(true); + expect(result?.reason).toContain("trunk"); + } + }); + }); + + test("an input cwd on a trunk checkout refuses, relative or absolute", async () => { + await from(feature, async () => { + const absolute = await run(BARE, feature, { cwd: trunk }); + expect(absolute?.block).toBe(true); + expect(absolute?.reason).toContain("checked-out branch"); + const relative = await run(BARE, root, { cwd: "trunk" }); + expect(relative?.block).toBe(true); + }); + }); + + test("an input cwd on a feature checkout allows when ctx.cwd is trunk", async () => { + expect(await run(BARE, trunk, { cwd: feature })).toBeUndefined(); + }); + + test("-C moves from the call's directory", async () => { + expect((await run("git -C ../trunk push -f", feature))?.block).toBe(true); + expect(await run("git -C ../feature push -f", trunk)).toBeUndefined(); + }); + + test("a cd inside the command line is not tracked", async () => { + expect(await run(`cd ${trunk} && ${BARE}`, feature)).toBeUndefined(); + }); }); // omp://approval-mode.md: eval declares the exec tier and can spawn a shell, so a rule that