Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .genie/wishes/worktree-isolation-hardening/WISH.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ bun test src/genie-commands/ && bun run check:fast
**Goal:** Review verdicts anchor to an immutable tree even while writers continue in the primary checkout.

**Deliverables:**
1. Prose-only, deliberately: `skills/review/SKILL.md` (+ mirror) documents the snapshot contract with the EXACT commands — provision `git worktree add --detach <worktreesBase>/<repo>-review-<shortsha> <commit>`, teardown `git worktree remove <path>`. No helper module: a helper here would have no caller but its own test (the #2594 decoration pattern this wish condemns), and the commands are natively fail-safe — `worktree add --detach` creates without touching any branch, and `worktree remove` refuses a dirty tree by default. A crashed review's leftover snapshot is foreign to the doctor residue check (detached, never removed by `--fix`); remove it explicitly with `git worktree remove <path>`.
1. Prose-only, deliberately: `skills/review/SKILL.md` (+ mirror) documents the snapshot contract with the EXACT commands — provision `git worktree add --detach <worktreesBase>/<repo>-review-<shortsha>-<unique> <commit>` (unique suffix — collision resistance across concurrent reviews), teardown `git worktree remove <path>`. No helper module: a helper here would have no caller but its own test (the #2594 decoration pattern this wish condemns), and the commands are natively fail-safe — `worktree add --detach` creates without touching any branch, and `worktree remove` refuses a dirty tree by default. A crashed review's leftover snapshot is foreign to the doctor residue check (detached, never removed by `--fix`); remove it explicitly with `git worktree remove <path>`.
2. Reviewer contract in the same prose: work read-only in the snapshot path; verdicts cite the pinned commit.
3. Precondition (owned by the policy group, not re-delivered here): the freeze text's snapshot carve-out (`git worktree add/remove/prune` is orchestrator-side plumbing, permitted; `checkout/switch/reset/stash/rebase` in the shared checkout remain forbidden).

Expand All @@ -150,6 +150,7 @@ bun test src/genie-commands/ && bun run check:fast
```bash
bun run check:fast && bun scripts/sync-plugin-skills.ts --check
```
_(Full `bun run check` — install, lint, complete `bun test` — runs on CI and is the required merge gate; `check:fast` is the local iteration gate.)_

**depends-on:** policy

Expand Down
2 changes: 1 addition & 1 deletion plugins/genie/references/native-surfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Genie skills describe roles and coordination without inventing a cross-client to
| Hermes | Chat/reasoning cockpit; drives the shared skills through `skills.external_dirs` and reads task truth via the read-only MCP tools plus native `genie_status`/`genie_work_plan`/`genie_review_plan` | Genie remains the execution system — Hermes issues no isolated worktrees itself; use `genie launch`/worktrees for per-group Git isolation | Read-only surface: every payload reports `mutation: "none"`; mutations are deferred behind an explicit human gate (see `plugins/hermes-genie/references/mutation-gates.md`) |
| Warp cockpit | `genie launch <slug>` emits one pane per ready group | Dedicated Git worktree per pane | Human-supervised; panes are not awaitable native subagents |

This table says what each runtime offers, not what dispatch is allowed to do with it. The concurrency contract — when parallel writers may share a workspace, and what a shared-workspace subagent must not touch — is stated once in AGENTS.md and the `work` skill's Dispatch section; apply it from there.
This table says what each runtime offers, not what dispatch is allowed to do with it. The concurrency contract — when parallel writers may share a workspace, and what a shared-workspace subagent must not touch — is stated once in AGENTS.md and the `work` skill's Dispatch section (shipped to agents as rule 3 of `references/dispatch-contract.md`); apply it from there.

Every implementation brief opens with the atomic claim:

Expand Down
6 changes: 3 additions & 3 deletions plugins/genie/skills/review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,11 @@ When a failure's root cause is unclear, invoke `trace` before dispatching `fix`
When dispatching a review of committed work, the orchestrator pins the review to an immutable tree — a detached worktree at the exact commit under review — so that writers continuing in the primary checkout cannot move the ground under a verdict in progress. Pin by default when other groups are still writing in the primary checkout; skip it when reviewing an uncommitted working tree, which cannot be pinned:

```bash
git worktree add --detach <worktreesBase>/<repo>-review-<shortsha> <commit> # provision
git worktree remove <path> # teardown, after the verdict
git worktree add --detach <worktreesBase>/<repo>-review-<shortsha>-<unique> <commit> # provision
git worktree remove <path> # teardown, after the verdict
```

(`<worktreesBase>` is `$GENIE_WORKTREES_DIR`, else `<GENIE_HOME>/worktrees` — the same base `genie launch` uses.)
(`<worktreesBase>` is `$GENIE_WORKTREES_DIR`, else `<GENIE_HOME>/worktrees` — the same base `genie launch` uses. `<unique>` is a per-review disambiguator — the reviewer/group name or a `mktemp`-style random suffix — because a bare `<repo>-review-<shortsha>` collides across concurrent reviewers, repeated reviews of one commit, and repos sharing a basename.)

No helper wraps these, because the commands are already fail-safe: `worktree add --detach` creates without touching any branch, and `worktree remove` refuses a dirty tree by default. Teardown is the orchestrator's job and nothing else does it — `genie doctor`'s launch-worktree check only classifies worktrees on a `wish/<slug>-<group>` branch, so a detached snapshot is foreign to it: surfaced only inside the aggregate "other checkouts" count and never removed by `--fix`. If a review crashes before teardown, remove the leftover explicitly with `git worktree remove <path>`. The reviewer works READ-ONLY in the snapshot path (no install, no build, no writes) and the verdict cites the pinned commit. Provisioning and teardown are orchestrator-side plumbing: the git-state freeze in AGENTS.md permits `git worktree add/remove/prune` on snapshot paths, while reviewers themselves never mutate git state.

Expand Down
2 changes: 1 addition & 1 deletion plugins/genie/skills/work/references/native-surfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Genie skills describe roles and coordination without inventing a cross-client to
| Codex | Use the matching `genie_*` custom agent when the CLI-installed profiles are present; otherwise use an available generic subagent | Native subagents share the caller's workspace by default | Use the active native follow-up tool exposed in the session; do not hardcode an undocumented function name into a skill |
| Warp cockpit | `genie launch <slug>` emits one pane per ready group | Dedicated Git worktree per pane | Human-supervised; panes are not awaitable native subagents |

This table says what each runtime offers, not what dispatch is allowed to do with it. The concurrency contract — when parallel writers may share a workspace, and what a shared-workspace subagent must not touch — is stated once in AGENTS.md and the `work` skill's Dispatch section; apply it from there.
This table says what each runtime offers, not what dispatch is allowed to do with it. The concurrency contract — when parallel writers may share a workspace, and what a shared-workspace subagent must not touch — is stated once in AGENTS.md and the `work` skill's Dispatch section (shipped to agents as rule 3 of `references/dispatch-contract.md`); apply it from there.

Every implementation brief opens with the atomic claim:

Expand Down
6 changes: 3 additions & 3 deletions skills/review/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,11 @@ When a failure's root cause is unclear, invoke `trace` before dispatching `fix`
When dispatching a review of committed work, the orchestrator pins the review to an immutable tree — a detached worktree at the exact commit under review — so that writers continuing in the primary checkout cannot move the ground under a verdict in progress. Pin by default when other groups are still writing in the primary checkout; skip it when reviewing an uncommitted working tree, which cannot be pinned:

```bash
git worktree add --detach <worktreesBase>/<repo>-review-<shortsha> <commit> # provision
git worktree remove <path> # teardown, after the verdict
git worktree add --detach <worktreesBase>/<repo>-review-<shortsha>-<unique> <commit> # provision
git worktree remove <path> # teardown, after the verdict
```

(`<worktreesBase>` is `$GENIE_WORKTREES_DIR`, else `<GENIE_HOME>/worktrees` — the same base `genie launch` uses.)
(`<worktreesBase>` is `$GENIE_WORKTREES_DIR`, else `<GENIE_HOME>/worktrees` — the same base `genie launch` uses. `<unique>` is a per-review disambiguator — the reviewer/group name or a `mktemp`-style random suffix — because a bare `<repo>-review-<shortsha>` collides across concurrent reviewers, repeated reviews of one commit, and repos sharing a basename.)

No helper wraps these, because the commands are already fail-safe: `worktree add --detach` creates without touching any branch, and `worktree remove` refuses a dirty tree by default. Teardown is the orchestrator's job and nothing else does it — `genie doctor`'s launch-worktree check only classifies worktrees on a `wish/<slug>-<group>` branch, so a detached snapshot is foreign to it: surfaced only inside the aggregate "other checkouts" count and never removed by `--fix`. If a review crashes before teardown, remove the leftover explicitly with `git worktree remove <path>`. The reviewer works READ-ONLY in the snapshot path (no install, no build, no writes) and the verdict cites the pinned commit. Provisioning and teardown are orchestrator-side plumbing: the git-state freeze in AGENTS.md permits `git worktree add/remove/prune` on snapshot paths, while reviewers themselves never mutate git state.

Expand Down
2 changes: 1 addition & 1 deletion skills/work/references/native-surfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Genie skills describe roles and coordination without inventing a cross-client to
| Codex | Use the matching `genie_*` custom agent when the CLI-installed profiles are present; otherwise use an available generic subagent | Native subagents share the caller's workspace by default | Use the active native follow-up tool exposed in the session; do not hardcode an undocumented function name into a skill |
| Warp cockpit | `genie launch <slug>` emits one pane per ready group | Dedicated Git worktree per pane | Human-supervised; panes are not awaitable native subagents |

This table says what each runtime offers, not what dispatch is allowed to do with it. The concurrency contract — when parallel writers may share a workspace, and what a shared-workspace subagent must not touch — is stated once in AGENTS.md and the `work` skill's Dispatch section; apply it from there.
This table says what each runtime offers, not what dispatch is allowed to do with it. The concurrency contract — when parallel writers may share a workspace, and what a shared-workspace subagent must not touch — is stated once in AGENTS.md and the `work` skill's Dispatch section (shipped to agents as rule 3 of `references/dispatch-contract.md`); apply it from there.

Every implementation brief opens with the atomic claim:

Expand Down
33 changes: 33 additions & 0 deletions src/genie-commands/doctor-worktrees.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,39 @@ describe('doctor wiring', () => {
expect(branchExists(fx.root, 'wish/demo-alpha')).toBe(true);
});

test('an ignored secret (.env) refuses removal; ignored node_modules does not', () => {
const dir = mkdtempSync(join(tmpdir(), 'genie-doctor-wt-'));
scratchRoots.push(dir);
const root = join(dir, 'repo');
const base = join(dir, 'worktrees');
mkdirSync(root);
mkdirSync(base);
git(root, 'init', '-q');
git(root, 'config', 'user.email', 'test@example.com');
git(root, 'config', 'user.name', 'Test');
git(root, 'config', 'commit.gpgsign', 'false');
writeFileSync(join(root, '.gitignore'), '.env\nnode_modules/\n');
git(root, 'add', '-A');
git(root, 'commit', '-q', '-m', 'seed with ignores');
git(root, 'branch', 'dev');
const fx = { dir, root, base };
const wt = addWorktree(fx, 'repo-demo-alpha', 'wish/demo-alpha');

// node_modules alone: disclosed but removable.
mkdirSync(join(wt, 'node_modules'));
writeFileSync(join(wt, 'node_modules', 'dep.js'), 'x\n');
expect(only(fx).disposition).toBe('removable');

// A secret joins: refused, named, and --fix keeps everything.
writeFileSync(join(wt, '.env'), 'API_KEY=hunter2\n');
const entry = only(fx);
expect(entry.disposition).toBe('dirty');
expect(entry.reason).toContain('ignored secret present');
expect(entry.reason).toContain('.env');
expect(runFix(fx)).toEqual([]);
expect(existsSync(join(wt, '.env'))).toBe(true);
});

test("a commit landing between cleanup's scan and the delete is not orphaned (ancestry re-proof)", () => {
const fx = makeFixture();
const wt = addWorktree(fx, 'repo-demo-alpha', 'wish/demo-alpha');
Expand Down
57 changes: 50 additions & 7 deletions src/genie-commands/doctor-worktrees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,15 @@ function gitFailure(stderr: string): GitOutcome {
*/
function git(cwd: string, args: string[]): GitOutcome {
try {
const res = spawnSync('git', args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
const res = spawnSync('git', args, {
cwd,
encoding: 'utf-8',
stdio: ['ignore', 'pipe', 'pipe'],
// Bounded: a probe hanging on a lock, credential prompt, or network mount
// must not wedge `genie doctor`; a timeout surfaces as a refusal.
timeout: 10_000,
maxBuffer: 8 * 1024 * 1024,
Comment on lines +122 to +125

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Do not time out destructive Git commands

When removing a large worktree or one on a slow filesystem takes more than ten seconds, this shared wrapper terminates git worktree remove midway because the timeout applies to mutations as well as probes. That can leave a partially deleted checkout and stale worktree registration while reporting that removal was refused. Keep the bound on read-only probes, but do not kill an in-progress destructive operation at the same fixed deadline.

Useful? React with 👍 / 👎.

});
if (res.error) return gitFailure(res.error.message);
return { ok: res.status === 0, status: res.status, stdout: res.stdout ?? '', stderr: (res.stderr ?? '').trim() };
} catch (error) {
Expand Down Expand Up @@ -190,7 +198,7 @@ export function parseWorktreePorcelain(text: string): WorktreeRecord[] {
* takes `ref`; only human output takes `name`. See {@link resolveIntegration}
* for why the distinction is load-bearing.
*/
interface IntegrationBranch {
export interface IntegrationBranch {
/** Short form, e.g. `dev` or `origin/main`. Display only — never a git argument. */
name: string;
/** Fully-qualified ref, e.g. `refs/heads/dev`. The only form a probe may use. */
Expand Down Expand Up @@ -235,6 +243,31 @@ export function resolveIntegrationBranch(root: string): string | null {
* with a launch branch would prove ITS containment while the `git branch -D`
* below still deletes the branch — orphaning every commit the branch carried.
*/
/**
* Gitignored files are deleted by `git worktree remove` (git's documented
* semantics) and are usually the point of the reclaim — node_modules, build
* output. The exception is user-owned secret material, which must never ride a
* cleanup. The probe refuses removal when an ignored file's basename matches a
* small sensitive-pattern set; everything else stays disclosed-but-removable.
* A probe failure (timeout, oversized listing) refuses via the caller's
* fail-closed error class — an unanswered probe proves nothing.
*/
const SENSITIVE_IGNORED = [/^\.env(\..+)?$/, /\.pem$/, /\.key$/, /^id_(rsa|ed25519|ecdsa)/, /credential/i, /secret/i];

function findIgnoredSecret(path: string): string | null {
// `traditional` collapses a fully-ignored directory (node_modules/) to one
// line, keeping the listing bounded on exactly the worktrees worth reclaiming.
const listing = git(path, ['status', '--porcelain', '--ignored=traditional']);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Inspect files below ignored directories

When a secret is inside an ignored directory whose own basename is not sensitive, such as cache/.env with cache/ ignored, this command emits only !! cache/, so the matcher never sees .env and --fix deletes it. The --ignored=traditional documentation states that ignored directories are collapsed unless --untracked-files=all is specified, which is also reproducible with this exact command. The guard must inspect nested ignored files before declaring the worktree removable.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

if (!listing.ok) return 'unlistable ignored files';
for (const line of listing.stdout.split('\n')) {
if (!line.startsWith('!!')) continue;
const rel = line.slice(2).trim().replace(/\/$/, '');
const base = rel.split('/').pop() ?? rel;
if (SENSITIVE_IGNORED.some((re) => re.test(base))) return rel;
Comment on lines +264 to +266

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Parse ignored paths with NUL-delimited porcelain

When a sensitive ignored filename requires Git quoting, such as private cert.pem, porcelain emits !! "private cert.pem"; the retained closing quote makes /\.pem$/ and /\.key$/ fail, so the worktree remains removable and the secret is deleted. git status -h exposes -z specifically for NUL-terminated machine-readable entries; parse that form rather than trimming line-oriented quoted output.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

}
return null;
}

function classifyEntry(
root: string,
path: string,
Expand All @@ -246,6 +279,8 @@ function classifyEntry(
const status = git(path, ['status', '--porcelain']);
if (!status.ok) return { ...entry, disposition: 'error', reason: firstLine(status.stderr, 'git status failed') };
if (status.stdout.trim() !== '') return { ...entry, disposition: 'dirty', reason: 'uncommitted changes' };
const secret = findIgnoredSecret(path);
if (secret !== null) return { ...entry, disposition: 'dirty', reason: `ignored secret present (${secret})` };
Comment on lines +282 to +283

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Recheck ignored secrets immediately before removal

When a process writes an ignored .env after classification—particularly while cleanup is still scanning and sizing other worktrees—the new guard is never run again. A non-forced git worktree remove still deletes ignored files (confirmed with the CLI; --force is only described as overriding dirty or locked worktrees), so the newly created secret is lost. Repeat the secret check at the removal boundary and refuse if it changes or cannot be listed.

AGENTS.md reference: AGENTS.md:L31-L31

Useful? React with 👍 / 👎.

const ancestry = git(root, ['merge-base', '--is-ancestor', `refs/heads/${branch}`, integration.ref]);
if (ancestry.ok) return { ...entry, disposition: 'removable', reason: 'merged+clean', sizeBytes: safeSizeOf(path) };
// `--is-ancestor` exits 1 for a definitive "no"; anything else is a broken
Expand Down Expand Up @@ -410,18 +445,26 @@ export function removeLaunchWorktree(
entry: LaunchWorktreeEntry,
integration: IntegrationBranch,
): string | null {
// Re-prove ancestry at removal time: a commit landing on the branch between
// the scan and this call would leave the tree clean (so `worktree remove`
// would still succeed) while making `-D` an orphaning force-delete. Once the
// worktree is gone the branch can gain no commits — git refuses a second
// checkout of the same branch — so re-proving HERE closes the whole window.
// Early re-proof: a commit landed since the scan refuses BEFORE the worktree
// is touched, preserving it intact. This probe alone cannot close the race —
// a commit can still land after it — so it is an ergonomic guard, not the
// authoritative one.
if (entry.branch !== null) {
const ancestry = git(root, ['merge-base', '--is-ancestor', `refs/heads/${entry.branch}`, integration.ref]);
if (!ancestry.ok) return `kept: branch advanced past ${integration.name} after the scan (ancestry re-proof failed)`;
}
const removed = git(root, ['worktree', 'remove', entry.path]);
if (!removed.ok) return `git worktree remove refused: ${firstLine(removed.stderr, 'unknown git error')}`;
if (entry.branch === null) return null;
// AUTHORITATIVE re-proof, after removal and before the forced delete: with
// the worktree gone the branch is frozen (git refuses a second checkout of a
// checked-out branch, and no checkout holds it now), so an ancestry answer
// taken HERE cannot be invalidated before `-D` — this is the only point in
// the sequence where the proof and the delete are race-free.
const frozen = git(root, ['merge-base', '--is-ancestor', `refs/heads/${entry.branch}`, integration.ref]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Delete the ref with an expected old object ID

When another process advances this now-unchecked-out branch after the ancestry probe but before git branch -D, the forced deletion removes the new, unmerged tip. Removing the worktree does not freeze the branch; it makes the branch available for another checkout or direct ref update. git branch -h describes -D as deleting even when unmerged, whereas git update-ref -h supports deletion with an <old-val>; use an atomic compare-and-delete against the exact tip that passed the proof.

Useful? React with 👍 / 👎.

if (!frozen.ok) {
return `worktree removed; branch ${entry.branch} kept: commits landed mid-removal (post-removal ancestry re-proof failed)`;
}
const deleted = git(root, ['branch', '-D', entry.branch]);
if (!deleted.ok) {
return `worktree removed; branch ${entry.branch} kept: ${firstLine(deleted.stderr, 'unknown git error')}`;
Expand Down
Loading