@justjoshn/pi-pstack-v2 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,7 +12,7 @@ pi install ./extensions/pi-pstack-v2
12
12
 
13
13
  The npm package `@justjoshn/pi-pstack-v2` is not published yet. Once it is, `pi install npm:@justjoshn/pi-pstack-v2` works too.
14
14
 
15
- Add `--local` to write the declaration to the project's `.pi/settings.json` instead of your personal settings. `pi list` shows what is installed. Pi runs each skill as `/skill:<name>`, so every command in this guide takes that prefix.
15
+ Add `--local` to write the declaration to the project's `.pi/settings.json` instead of your personal settings. `pi list` shows what is installed. Installing adds the skills and tools but starts no workflow. Nothing changes until you send `/skill:poteto-mode` or turn on `/pstack-mode`. Pi runs each skill as `/skill:<name>`, so every command in this guide takes that prefix.
16
16
 
17
17
  The package adds three tools. `pi_spawn` starts a separate Pi in its own tmux session. `tmux_run` runs a shell command in its own tmux session. `tmux_jobs` lists, waits on, and stops both kinds of job. Pi has no sub-agents and no detached shell, so every parallel worker and every watcher in this guide is one of these jobs.
18
18
 
@@ -49,13 +49,13 @@ You might be wondering what happens if you want a role to follow whatever model
49
49
 
50
50
  At the end of setup, `/skill:setup-pstack` looks for a way to prove app behavior in your project, either a `verify-*` skill or an existing harness. If it finds neither, it offers once to generate one with [`/skill:create-verification-skill`](../../skills/create-verification-skill/SKILL.md).
51
51
 
52
- Say yes and it writes `.pi/skills/verify-<app>/`, a project-local skill that teaches agents to drive your app the way a user does. It proves the skill works once before handing it over. Say no and setup moves on. You can run `/skill:create-verification-skill` yourself any time. [Verify and ship](./06-verify-and-ship.md#create-a-project-verification-skill) covers it in depth.
52
+ Say yes and it writes `.pi/skills/verify-<app>/`, a project-local skill that teaches agents to drive your app the way a user does. It proves the skill works once before handing it over. Say no and setup moves on. You can run `/skill:create-verification-skill` yourself any time. Either yes starts a separate generation task. Setup itself installs no browser driver, dependency, or app environment. [Verify and ship](./06-verify-and-ship.md#create-a-project-verification-skill) covers it in depth.
53
53
 
54
54
  If you're new to pstack, say yes. An agent that can check its own work keeps going until the check passes. An agent that can't hands every result back to you to check by hand. Of everything in this guide, the verification skill pays off the most.
55
55
 
56
56
  Then setup offers once to generate a formal verification skill with [`/skill:create-formal-verification-skill`](../../skills/create-formal-verification-skill/SKILL.md), unless the project already has one. Tests check the cases someone thought to write. A formal verification skill checks one key property of your code, such as "a job never runs twice at once", in every case within a stated scope. Say yes when your code has concurrency, retries, a state machine, or a parser, where a bug is costly and tests rarely reach the case that breaks. Otherwise say no, and run it later if that changes. [Verify and ship](./06-verify-and-ship.md#prove-a-property-with-a-formal-verification-skill) covers it.
57
57
 
58
- After setup, start a new session. The model lines apply to new sessions.
58
+ The extension rereads the model file every turn, so the role lines apply from your next message. A new session picks them up too.
59
59
 
60
60
  ## Keep the cost in check
61
61
 
@@ -27,6 +27,27 @@ flowchart TD
27
27
 
28
28
  The diagram shows the common routes. There are also playbooks for hillclimbing a metric, diagnosing runtime symptoms and captured traces, prototypes, visual parity, authoring and evaluating skills, autonomous runs, opening a PR, babysitting a PR or stack to merge-ready, shipping a verified stack, running a PR queue or a stack on autopilot, session pickup, pausing safely, multi-phase plans, and worktree cleanup. The [playbook directory](../../skills/poteto-mode/playbooks/) has the full set.
29
29
 
30
+ ## How code work is accepted
31
+
32
+ For code-producing work, the route ends on evidence. Here is the acceptance flow:
33
+
34
+ ```mermaid
35
+ flowchart TD
36
+ A["Goal, constraints, and acceptance checks"] --> B["Choose playbook; investigate and design"]
37
+ B --> C["Implement and clean"]
38
+ C --> D["Verify actual behavior"]
39
+ D --> E{"Evidence"}
40
+ E -->|Correctable failure| B
41
+ E -->|Blocked or inconclusive| F["Report limits and remaining work"]
42
+ E -->|Verified| G{"Authorized endpoint"}
43
+ G -->|Handoff| H["Deliver artifact and evidence"]
44
+ G -->|Merge| I["Meet independent shipping gates"]
45
+ I --> J["Merge and confirm actual state"]
46
+ I -->|Gate cannot be met| F
47
+ ```
48
+
49
+ The diagram shows acceptance and handoff, not the timing of every step. Autopilot-full, for example, opens its PR while implementation and verification are still running. Investigation and multi-phase plans stop earlier, at their findings or plan. `/skill:reflect` and `/skill:correct` run only when you ask. Opening a PR is not a merge grant. Without one, you get the PR and its evidence. With one, the Shipping playbook lands it behind an independent verifier and reads the merge state back.
50
+
30
51
  ## Say the goal, not the ceremony
31
52
 
32
53
  You don't write a spec. You say what's wrong or what you want, plus anything you already know that saves the agent time:
@@ -77,7 +77,7 @@ Pi's design principle for customizing is to pick the least powerful mechanism th
77
77
  - Pi runs an `auth.json` key that starts with `!` as a command, so the credentials copy holds no command. For a worker's own provider, the root resolves the command once when it starts the worker and puts the resulting key in the copy. Every two seconds, and once more after a job ends, the root carries refreshed OAuth tokens between your `auth.json` and each copy, the later expiry winning, under Pi's lock on both. Only OAuth tokens move, so nothing a job writes as a key or a command reaches your `auth.json`, and a provider you logged out of is never brought back.
78
78
  - A job cannot reach the services that would start a process for it. It can neither connect to nor serve a Unix socket, so every tmux server, Docker's socket, the session bus, and every other local service are out of reach. Socket pairs, which child processes use for pipes, still work. macOS denies binding and connecting Unix sockets apart from DNS's, and Linux refuses opening one through a seccomp filter, which also refuses io_uring. On macOS it also cannot use LaunchServices (`open`), Apple Events, launchd, or preference writes, and it can signal only processes in its own sandbox. On Linux `/run` and the user's runtime directory are hidden, and the job runs in its own PID namespace.
79
79
  - When a job exits, its whole process group is killed before cleanup, so no child it left behind acts after cleanup. Stopping a job sends TERM, then KILL after three seconds. On Linux every process in its PID namespace dies with it.
80
- - A Pi worker's own jobs get their own sandbox, so `readonly` holds at any depth, and a resumed worker keeps its `readonly`. On every platform a sandboxed worker writes the job as a request in its `nested/` directory, and the root Pi launches it under a profile built from the paths it validated. The root refuses any request that would write, or run, outside what it granted the top-level worker, so no worker can hand a descendant more than it was given. The root writes results only under the top-level job, never into a worker's directory, and serves requests while it runs. If you quit the root Pi, nested requests wait until you resume that session.
80
+ - A Pi worker's own jobs get their own sandbox, so `readonly` holds at any depth, and a resumed worker keeps its `readonly`. On every platform a sandboxed worker writes the job as a request in its `nested/` directory, and the root Pi launches it under a profile built from the paths it validated. The root refuses any request that would write, or run, outside what it granted the top-level worker, so no worker can hand a descendant more than it was given. The root writes results only under the top-level job, never into a worker's directory, and serves requests while it runs. A worker's sandbox keeps `.git/worktrees` read-only, so when a worker passes `worktree` to `pi_spawn`, its request carries the branch and base, and the root creates the worktree from the worker's own checkout before it launches the job. The checkout lands in the job's results directory, `<top-level job>/brokered/<hash>/worktree`, which no worker can write, so no worker can swap in a link for git to check out through. The root creates it only for a worker that may write the repository and only at that path, computes the checkout's protected paths itself, keeps a `readonly` job read-only, creates nothing for a request it refuses, and removes the worktree and any branch it created when it cannot launch the job. If you quit the root Pi, nested requests wait until you resume that session.
81
81
  - Start the main session sandboxed too when you want it contained. Pi's guide to isolated environments lists the methods, and not all of them need Docker.
82
82
 
83
83
  ## What the sandbox does not cover
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@justjoshn/pi-pstack-v2",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Use the pstack skills and workflow in Pi, with sandboxed Pi workers and shell jobs running in tmux.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -16,7 +16,7 @@ A good target is a promise the code makes, where a break harms users and tests r
16
16
 
17
17
  ## Let the question choose the tool
18
18
 
19
- Pick the tool that answers the question at the lowest cost: a model checker, a proof assistant, an SMT-backed verifier, or another tool. Whether events can happen in a bad order usually suits a model checker over a small model of the design, and TLA+ is the default for that in any language. Whether the code itself behaves for every input, as with memory safety, overflow, or a data-structure invariant, usually suits a verifier that runs on the code. If no verifier runs on this language, say so, and test the real code with generated inputs, not a hand model of the function. A property that must hold at every size, where a bound is not enough, can need a proof. Prefer a tool that the repo's developers can install and run, and tell the user why you chose it.
19
+ Pick the tool that answers the question at the lowest cost: a model checker, a proof assistant, an SMT-backed verifier, or another tool. Whether events can happen in a bad order usually suits a model checker over a small model of the design, and TLA+ is the default for that in any language. Whether the code itself behaves for every input, as with memory safety, overflow, or a data-structure invariant, usually suits a verifier that runs on the code. If no verifier runs on this language, say so, and test the real code with generated inputs, not a hand model of the function. Report that testing as empirical evidence, never as an exhaustive proof. A property that must hold at every size, where a bound is not enough, can need a proof. Prefer a tool that the repo's developers can install and run, and tell the user why you chose it.
20
20
 
21
21
  ## What makes it good
22
22
 
@@ -12,7 +12,7 @@ Adversaries try to break a change or a design. A finding survives only when a ru
12
12
 
13
13
  ## Frame
14
14
 
15
- The scope is what the user names. Otherwise it is the branch diff from its merge base with the base branch, through the working tree. State the intent with the **in-your-own-words** skill, from the user's message, the commits, and the PR description. Ask the user when the intent is unclear.
15
+ The scope is what the user names. Otherwise it is the branch diff from its merge base with the base branch, through the working tree. State the intent with the **in-your-own-words** skill, from the user's message, the commits, and the PR description. Ask the user when the intent is unclear. A worker, which never stops to ask, picks the likeliest intent and states it as an assumption in the output.
16
16
 
17
17
  ## Fan out
18
18
 
@@ -31,5 +31,5 @@ Skip arena Phases C, D, and E. Adversaries find different failures, so the verdi
31
31
  ## Output
32
32
 
33
33
  - **Intent**: the restatement.
34
- - **Findings**: for each verified finding, the command, its output, how it breaks the intent, and the adversaries that found it. Say "no verified findings" when none survive.
34
+ - **Findings**: for each verified finding, the command, its output, how it breaks the intent, and the adversaries that found it. Say "no verified findings" when none survive. That result is not evidence the change has no bugs.
35
35
  - **Dropped**: for each adversary, the count of dropped findings and why.
@@ -19,7 +19,7 @@ The remaining triggers live only here:
19
19
  - First message → restate the user's goal and the smallest change that meets it, then proceed. Open each worker brief, PR `## Why`, and final report with the goal.
20
20
  - Starting any agent, a `pi_spawn` worker included → the first line of its brief is `Read <path>/worker.md before anything else.`, with `<path>` the absolute path of this skill's folder. The operator's rules live in skills that only load from a `/skill:` command, so they reach another agent no other way. Keep the rest of the brief to the goal and the task, plus this file's absolute path for a `poteto-agent`.
21
21
  - A fork you could settle by running something → prototype it per `playbooks/prototype.md` instead of asking.
22
- - Code → name the data shape first. Across a function boundary → **architect**. Fan-out → **swarm**. Bakeoff → **arena**. Contested design → **interrogate**.
22
+ - Code → name the data shape first. Across a function boundary → **architect**. Fan-out → **swarm**. Bakeoff → **arena**. Contested design, or a change to review → **interrogate**.
23
23
  - Prose, your reply included → **unslop**. Docs, PR descriptions, commit messages → **technical-writing**.
24
24
  - Before commit → `/skill:deslop`. Before review → **no-comments**.
25
25
  - Shipping UI / IDE / CLI → `control-ui` or `control-cli`, which this package ships.
@@ -85,7 +85,7 @@ Read the leaf skill in full for any principle you apply. Each entry names when i
85
85
 
86
86
  Pi has no subagents. A worker is a separate Pi process that `pi_spawn` starts in its own tmux session, inside the sandbox, with a standalone brief. It sees only the brief, never this conversation.
87
87
 
88
- **Use `pi_spawn` with `agent: "poteto-agent"` for any worker you spawn directly inside a playbook step.** The session that receives `/skill:poteto-mode` runs the playbook itself. Routed workflow skills (`interrogate`, `reflect`, `swarm`) set their own `agent` and model. Respect it.
88
+ **Use `pi_spawn` with `agent: "poteto-agent"` for any worker you spawn directly inside a playbook step.** The session that receives `/skill:poteto-mode` runs the playbook itself. Routed workflow skills (`interrogate`, `swarm`) set their own `agent` and model. Respect it.
89
89
 
90
90
  **Defaults for every `pi_spawn` call.** Every worker runs in parallel and wakes you with its report when it exits, so keep working or end your turn while it runs. Use `tmux_jobs` `wait` only for a short, bounded wait on named job ids, never to block until a worker finishes. Give a `tmux_run` job that polls for a condition a deadline, so it exits and wakes you whether or not the condition arrives. Leave `readonly` unset unless the worker must not write. Give file pointers, not inlined context. Pass an explicit model per role. `/skill:setup-pstack` writes `~/.pi/agent/pstack-v2-models.md`, shown to you as the `pstack-models` system-prompt section, whose per-role lines override the defaults and the role models in the routed skills (`arena`, `swarm`, `interrogate`). A role with no line runs on this session's model, so omit `model`. A line of `inherit-parent` or `auto` does the same. Each code playbook reads its own line (`feature, refactoring`, `bug-fix`, `perf-issue`, or `hillclimb`), prose and judgment read `judgment and prose`, and trivial mechanical edits read `swarm workers`. If the file has no `# defaults: 3` line, an older setup wrote it. Keep honoring its lines, and tell the user once per session to rerun `/skill:setup-pstack`.
91
91
 
@@ -104,3 +104,13 @@ Write short declarative sentences with no long dash and no colon as a connector.
104
104
  Write `TODO.md` at the root of your checkout with the matched playbook's steps first, copied in as `- [ ]` items, before any task-specific items. Check items off as you finish them. `TODO.md` is working state, so never stage it. If the checkout already tracks a `TODO.md`, write the checklist to `.pi/TODO.md` instead, under the same rules. This holds wherever a skill says to write `TODO.md`. Match the task to a playbook and open its steps at `playbooks/<title>.md`, with the title in kebab case. Large, cross-cutting, or unattended work, or a task no playbook fits, routes to the **figure-it-out** skill.
105
105
 
106
106
  Investigation, Bug fix, Perf issue, Hillclimb, Runtime forensics, Trace forensics, Feature, Refactoring, Prototype, Visual parity, Authoring a skill, Eval, Babysit, Shipping, Autonomous run, Autopilot-full, Autopilot-stack, Session pickup, Pause safely, Multi-phase plan, Worktree cleanup, Opening a PR.
107
+
108
+ ## Acceptance
109
+
110
+ Code-producing work ends on evidence, never on "implemented". Once you have verified the actual behavior, take the branch the evidence picks.
111
+
112
+ - **Correctable failure.** Return to choosing the playbook, investigating, and designing, then make another justified attempt.
113
+ - **Blocked or inconclusive.** Stop and report what you verified, its limits, and the remaining work. A gap is never a pass.
114
+ - **Verified.** Go to the endpoint the user authorized. Without a merge grant, hand off the artifact and its evidence. With one, run **Shipping**. When a shipping gate cannot be met, report limits and remaining work as above. A merge counts only once its state is read back.
115
+
116
+ This sets acceptance, not timing, so Autopilot-full still opens its PR early. Investigation and Multi-phase plan stop at their own deliverable. **reflect** and **correct** run only when the user asks.
@@ -2,7 +2,7 @@
2
2
 
3
3
  **You own the exit condition. Define done, then drive to it without stopping.**
4
4
 
5
- 1. State the exit condition as a checkable predicate before the first iteration (tests green, repro fixed, all N PRs merged, pixel-diff zero).
5
+ 1. State the exit condition as a checkable predicate before the first iteration (tests green, repro fixed, all N PRs merged, pixel-diff zero). Write down with it the permissions you hold, the workspace (worktree and base), and where the decision trail lives.
6
6
  2. Pick the wake mechanism with `tmux_run`. An event to watch (CI, a merge, a ref advancing) gets a watcher job, which is `tmux_run` of the watcher command with `wake` set to what to do next, with a long time-based heartbeat as fallback. No event gets a fixed-interval heartbeat (`tmux_run` with `command: "sleep <seconds>"`, a `wake` tick prompt, and `repeat: true`) sized to when the result is worth re-checking. Stop a heartbeat with `tmux_jobs` `stop`. Pick each worker's thinking level for the job, per the Spawned Pi workers section.
7
7
  3. Each iteration makes the smallest change the evidence justifies, verifies it against the predicate, commits if it advanced, discards changes that didn't help. Belt-and-suspenders that "might help" gets reverted, not left to ride.
8
8
  Sequence the work via the **sequence-verifiable-units** principle skill, verifying each unit before the next instead of batching checks at the end.
@@ -20,6 +20,6 @@ A verdict covers one patch and green CI covers one head. Step 4 runs a full swar
20
20
  6. **Run the root layer.** Anything that loosens a gate, such as a raised budget or an allowlist entry, needs a verifier's proof and then your fresh countersign, because the owner is the one who wants green. Under a grant that covers approvals, that countersign is the approval, and the owner's record of it points at your countersign for a lane to check. A disabled or soft-failed check always comes out, because it stops guarding every case. Never give or bypass an approval the forge enforces, because no countersign covers it.
21
21
 
22
22
  On the operator's go, arm a heartbeat to audit until no delegated work is left (`tmux_run` with `command: "sleep 3600"`, a `wake` tick prompt, and `repeat: true`), because long runs drift and agents stall silently. Each tick re-reads this playbook from trunk and fixes drift, such as an unreported head or an unrecorded agent, by having its owner record it, because drift is a gap in the record, not a stall. It probes every agent, down to the leaf lanes, and judges each by its side effects, because status text and summaries can hide a stuck child. An agent is stuck when it errors, cannot start turns, or shows nothing new past its stuck-after runtime, and so is an owner that has neither pushed nor written a trail row by the first tick. One waiting on you or the operator is not stuck. It ends its run with the question in its report, and you answer by spawning a fresh worker with consolidated scope. Replace a stuck agent at once, without waiting for its stop to land. A tick that changed something for the operator ends by catching them up per the **ketchup** skill, and one that changed nothing stays quiet.
23
- 7. **Stand down at once on the operator's stop.** A hold reaches every owner as `tmux_jobs` `stop`, after each commits `wip:` per `playbooks/pause-safely.md`, because a print-mode worker takes no mid-run input. Each owner's report says where it stands. The operator's release is a fresh `pi_spawn` per owner with consolidated scope.
23
+ 7. **Stand down at once on the operator's stop.** A hold reaches every owner as `tmux_jobs` `stop`, because a print-mode worker takes no mid-run input and a stopped job sends no report. Then commit each owner's uncommitted edits as one `wip:` commit in its worktree, per `playbooks/pause-safely.md` step 3, and report where each stands from its commits and trail. The operator's release is a fresh `pi_spawn` per owner with consolidated scope.
24
24
 
25
25
  **Reply:** catch the operator up per the **ketchup** skill, covering each PR's state and verdict, what merged, countersigns and why, open operator gates, and parked follow-ups, with links to each PR and the trails.
@@ -1,9 +1,9 @@
1
1
  ### Opening a PR
2
2
 
3
- Invoked at the end of every other playbook.
3
+ Invoked at the end of every code-producing playbook.
4
4
 
5
5
  Work from a git worktree off trunk, and keep unrelated work out of it. Rebase into small, landable commits. Run `/skill:deslop` over the diff before commit.
6
6
 
7
7
  Title: `type(scope): subject`, naming a real symbol when one carries the change. Body: a one-minute briefing under 40 lines with these `##` headings in order, dropping empty ones: `## Why`, `## What changed`, `## Scope`, `## Tradeoffs` (only rejected alternatives a reviewer would otherwise ask about), `## Blast Radius`, `## Verification`.
8
8
 
9
- Stack follow-ups by base branch. Open PRs ready, with `gh pr create` without `--draft`, or `origin pr create --status open` when Origin's CLI resolves the repository. Opening a PR does not start a babysit.
9
+ Stack follow-ups by base branch. Open PRs ready, with `gh pr create` without `--draft`, or `origin pr create --status open` when Origin's CLI resolves the repository. Opening a PR does not start a babysit. An open PR, ready for review, has passed none of the later merge gates. Continue to **Shipping** only when the user granted merge. Otherwise hand off the PR with its evidence.
package/src/index.ts CHANGED
@@ -125,6 +125,31 @@ function addWorktree(cwd: string, path: string, branch: string, base: string | u
125
125
  return !exists;
126
126
  }
127
127
 
128
+ function dropWorktree(repo: string, createdBranch: string | undefined): void {
129
+ git(repo, ['worktree', 'prune']);
130
+ if (createdBranch !== undefined) git(repo, ['branch', '-D', createdBranch]);
131
+ }
132
+
133
+ type CreatedWorktree = { path: string; repo: string; createdBranch: string | undefined };
134
+
135
+ const requestedWorktreePath = (out: string): string => landing(join(out, 'worktree'));
136
+
137
+ function createRequestedWorktree(top: Job, spec: JobSpec, out: string, grant: string[]): CreatedWorktree | { refused: string } {
138
+ const asked: unknown = spec.createWorktree;
139
+ if (spec.kind !== 'pi' || typeof asked !== 'object' || asked === null) return { refused: 'Only a Pi worker request can ask for a worktree.' };
140
+ const { branch, base } = asked as Record<string, unknown>;
141
+ if (typeof branch !== 'string' || (base !== undefined && typeof base !== 'string')) return { refused: 'Its worktree request is malformed.' };
142
+ const repo = top.spec.cwd;
143
+ const common = gitPath(repo, '--git-common-dir');
144
+ if (common === undefined || !within(common, grant)) return { refused: `The worker that asked may not write the repository at ${repo}, so it cannot get a worktree of it.` };
145
+ const path = requestedWorktreePath(out);
146
+ try {
147
+ return { path, repo, createdBranch: addWorktree(repo, path, branch, base) ? branch : undefined };
148
+ } catch (error) {
149
+ return { refused: `pstack could not create the worktree: ${error instanceof Error ? error.message : String(error)}` };
150
+ }
151
+ }
152
+
128
153
  function baseOrSoleRemoteBranch(cwd: string, base: string): string {
129
154
  try {
130
155
  git(cwd, ['rev-parse', '--verify', '--quiet', `${base}^{commit}`]);
@@ -297,30 +322,51 @@ export function serveRequests(top: Job, socket: string, nested: string, requeste
297
322
  settleBrokered(out, 126, 'pstack refused to start this Pi worker. A worker started by another worker cannot start workers of its own.');
298
323
  continue;
299
324
  }
300
- const writable = policy.writable.map(landing);
301
- const refused = [...writable.filter((path) => !within(path, grant)), ...(within(spec.cwd, [top.spec.cwd, ...grant]) ? [] : [`cwd ${spec.cwd}`])];
325
+ const worktree = spec.createWorktree === undefined ? undefined : requestedWorktreePath(out);
326
+ const askedWritable = policy.writable.map(landing);
327
+ const writesWorktree = worktree !== undefined && askedWritable.includes(worktree);
328
+ const checked = askedWritable.filter((path) => path !== worktree);
329
+ const cwdAllowed = worktree === undefined ? within(spec.cwd, [top.spec.cwd, ...grant]) : landing(spec.cwd) === worktree;
330
+ const refused = [...checked.filter((path) => !within(path, grant)), ...(cwdAllowed ? [] : [`cwd ${spec.cwd}`])];
302
331
  if (refused.length) {
303
332
  settleBrokered(out, 126, `pstack refused to launch this job. It asked to write outside what the job that requested it may write: ${refused.join(', ')}`);
304
333
  continue;
305
334
  }
306
- // The sandbox is built from the paths just validated, so swapping a link afterwards changes nothing.
307
- const granted: SandboxPolicy = {
308
- writable,
309
- protect: [...policy.protect, ...top.spec.policy.protect],
310
- lock: [...policy.lock, ...top.spec.policy.lock],
311
- gitDirs: [...policy.gitDirs, ...top.spec.policy.gitDirs],
312
- checkouts: [],
313
- credentials: jobAgentDir(top.dir),
314
- agentDir: getAgentDir(),
315
- jobDir: dir,
316
- };
317
- granted.checkouts = sweepFor(granted).roots;
318
- mkdirSync(out, { recursive: true });
319
- writeFileSync(join(out, 'granted.json'), JSON.stringify(writable));
320
- // The worker supplies tmp, so it is trusted only if it is one of the writable paths validated above.
321
- const { tmp: asked, ...rest } = spec;
322
- const tmp = typeof asked === 'string' && writable.includes(landing(asked)) ? landing(asked) : undefined;
323
- launchBrokered(top.dir, dir, { ...rest, ...(tmp ? { tmp } : {}) }, sweepFor(granted), sandboxed(spec.command, granted), socket);
335
+ const made = worktree === undefined ? undefined : createRequestedWorktree(top, spec, out, grant);
336
+ if (made !== undefined && 'refused' in made) {
337
+ settleBrokered(out, 126, `pstack refused to launch this job. ${made.refused}`);
338
+ continue;
339
+ }
340
+ let launched = false;
341
+ try {
342
+ const common = made === undefined ? undefined : gitPath(made.path, '--git-common-dir');
343
+ const guarded = made === undefined ? policy : protectedPaths(made.path, common);
344
+ const writable = made !== undefined && writesWorktree ? [...checked, made.path, ...(common ? [landing(common)] : [])] : checked;
345
+ // The sandbox is built from the paths just validated, so swapping a link afterwards changes nothing.
346
+ const granted: SandboxPolicy = {
347
+ writable,
348
+ protect: [...guarded.protect, ...top.spec.policy.protect],
349
+ lock: [...guarded.lock, ...top.spec.policy.lock],
350
+ gitDirs: [...guarded.gitDirs, ...top.spec.policy.gitDirs],
351
+ checkouts: [],
352
+ credentials: jobAgentDir(top.dir),
353
+ agentDir: getAgentDir(),
354
+ jobDir: dir,
355
+ };
356
+ granted.checkouts = sweepFor(granted).roots;
357
+ mkdirSync(out, { recursive: true });
358
+ writeFileSync(join(out, 'granted.json'), JSON.stringify(writable));
359
+ // The worker supplies tmp, so it is trusted only if it is one of the writable paths validated above.
360
+ const { tmp: asked, ...rest } = spec;
361
+ const tmp = typeof asked === 'string' && writable.includes(landing(asked)) ? landing(asked) : undefined;
362
+ launched = launchBrokered(top.dir, dir, { ...rest, ...(made ? { cwd: made.path } : {}), ...(tmp ? { tmp } : {}) }, sweepFor(granted), sandboxed(spec.command, granted), socket);
363
+ } catch (error) {
364
+ settleBrokered(out, 127, `pstack could not launch this job: ${error instanceof Error ? error.message : String(error)}`);
365
+ }
366
+ if (made !== undefined && !launched) {
367
+ rmSync(made.path, { recursive: true, force: true });
368
+ dropWorktree(made.repo, made.createdBranch);
369
+ }
324
370
  } catch {
325
371
  // One request failing must not stop the others.
326
372
  }
@@ -534,14 +580,15 @@ export default function pstack(pi: ExtensionAPI) {
534
580
  // The job directory itself stays read-only to the worker, so it cannot rewrite its own spec or exit code.
535
581
  const sessionDir = (prior && flagValue(earlier, '--session-dir')) || join(dir, 'session');
536
582
  const writable = [sessionDir, join(dir, 'nested')];
583
+ const createWorktree = params.worktree !== undefined && brokering() ? { branch: params.worktree, ...(params.base === undefined ? {} : { base: params.base }) } : undefined;
537
584
  let createdBranch = false;
538
585
  try {
539
586
  for (const path of writable) mkdirSync(path, { recursive: true });
540
- const cwd = params.worktree !== undefined && prior === undefined ? join(dir, 'worktree') : base;
541
- if (cwd !== base && params.worktree !== undefined) createdBranch = addWorktree(base, cwd, params.worktree, params.base);
542
- const common = gitPath(cwd, '--git-common-dir');
587
+ const cwd = params.worktree === undefined ? base : createWorktree ? join(resultsDir(process.env[TOP_DIR_ENV] ?? '', dir), 'worktree') : join(dir, 'worktree');
588
+ if (params.worktree !== undefined && !createWorktree) createdBranch = addWorktree(base, cwd, params.worktree, params.base);
589
+ const common = gitPath(base, '--git-common-dir');
543
590
  if (!readonly) writable.push(cwd, ...(common ? [common] : []));
544
- const guarded = protectedPaths(cwd, common);
591
+ const guarded = createWorktree ? { protect: [], lock: [], gitDirs: [] } : protectedPaths(cwd, common);
545
592
  const piCommand = process.argv[1] && isAbsolute(process.argv[1]) ? [process.execPath, process.argv[1]] : ['pi'];
546
593
  const argv = [
547
594
  ...piCommand,
@@ -575,16 +622,15 @@ export default function pstack(pi: ExtensionAPI) {
575
622
  socket: brokering() ? '' : tmuxSocket(owner),
576
623
  sweep: { roots: [], protect: [] },
577
624
  out: dir,
625
+ ...(createWorktree ? { createWorktree } : {}),
578
626
  createdAt: new Date().toISOString(),
579
627
  };
580
628
  const job = start(root, spec, files, resolved);
581
- return text(`Started ${describe(job)}\n cwd: ${cwd}${spec.wake ? '\nYou will be woken with its report when it exits. Keep working or end your turn.' : ''}`);
629
+ const created = createWorktree ? ` (on branch ${createWorktree.branch}, created by the session that started you when it launches the job)` : '';
630
+ return text(`Started ${describe(job)}\n cwd: ${cwd}${created}${spec.wake ? '\nYou will be woken with its report when it exits. Keep working or end your turn.' : ''}`);
582
631
  } catch (error) {
583
632
  rmSync(dir, { recursive: true, force: true });
584
- if (params.worktree !== undefined && gitPath(base, '--git-common-dir')) {
585
- git(base, ['worktree', 'prune']);
586
- if (createdBranch) git(base, ['branch', '-D', params.worktree]);
587
- }
633
+ if (params.worktree !== undefined && !createWorktree && gitPath(base, '--git-common-dir')) dropWorktree(base, createdBranch ? params.worktree : undefined);
588
634
  throw error;
589
635
  }
590
636
  },
package/src/jobs.ts CHANGED
@@ -46,6 +46,7 @@ export interface JobSpec {
46
46
  sweep: { roots: string[]; protect: string[] };
47
47
  /** The $TMPDIR of the worker that started this job, shared so paths it hands the job exist. Unset for a top-level job. */
48
48
  tmp?: string;
49
+ createWorktree?: { branch: string; base?: string };
49
50
  createdAt: string;
50
51
  }
51
52
 
@@ -283,14 +284,16 @@ export function settleBrokered(out: string, code: number, message: string): void
283
284
  }
284
285
 
285
286
  /** Launches a brokered request on the root's tmux server. The caller has already sandboxed argv under a policy it clamped. */
286
- export function launchBrokered(top: string, dir: string, spec: JobSpec, sweepWhat: JobSpec['sweep'], argv: string[], socket: string): void {
287
+ export function launchBrokered(top: string, dir: string, spec: JobSpec, sweepWhat: JobSpec['sweep'], argv: string[], socket: string): boolean {
287
288
  const out = resultsDir(top, dir);
288
289
  mkdirSync(out, { recursive: true });
289
290
  try {
290
291
  run({ kind: spec.kind, cwd: spec.cwd, argv, inventory: takeInventory({ ...spec, sweep: sweepWhat }, out), socket, session: brokeredSession(dir), dir, out, top, tmp: spec.tmp });
291
292
  writeFileSync(join(out, 'launched'), '');
293
+ return true;
292
294
  } catch (error) {
293
295
  settleBrokered(out, 127, `pstack could not launch this job: ${error instanceof Error ? error.message : String(error)}`);
296
+ return false;
294
297
  }
295
298
  }
296
299