@cratis/pi 7.41.0 → 7.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package/corpus/harnesses/copilot/instructions/local-work-artifacts.instructions.md +12 -6
- package/package/corpus/harnesses/pi/extensions/cratis-hooks/index.ts +35 -2
- package/package/corpus/hooks/README.md +24 -0
- package/package/corpus/hooks/scripts/cratis-cleanup-worktrees.sh +184 -0
- package/package/corpus/hooks/settings.template.json +21 -0
- package/package/corpus/prompts/ship-changes.prompt.md +15 -0
- package/package/corpus/rules/local-work-artifacts.md +12 -6
- package/package.json +1 -1
|
@@ -38,12 +38,18 @@ dumps, and similar coordination files. These are **work records, not documentati
|
|
|
38
38
|
- **A worktree is a work record too.** Create it outside the repository tree, for
|
|
39
39
|
example in a sibling `../.worktrees/` directory. A nested worktree inherits the
|
|
40
40
|
parent's `.globalconfig` alongside its own, causing .NET's `MultipleGlobalAnalyzerKeys`
|
|
41
|
-
errors or silently changing analyzer severities.
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
41
|
+
errors or silently changing analyzer severities. **Delivered work is cleaned up by
|
|
42
|
+
`.cratis/ai/hooks/scripts/cratis-cleanup-worktrees.sh`, not by memory:** run it from the
|
|
43
|
+
main checkout when a pull request merges or you finish a task (hooks also run it after
|
|
44
|
+
`gh pr merge` and at session start where the harness supports them, and **ship-changes**
|
|
45
|
+
ends with it). It removes a worktree and its branch only on evidence the work reached the
|
|
46
|
+
default branch — pushed is not merged — and never forces; ignored files such as a nested
|
|
47
|
+
`.ai-work/`, `.env` files and local databases are deleted with it, so move anything you
|
|
48
|
+
still need out first. Do not hand-remove worktrees or `git branch -D` a delivered branch
|
|
49
|
+
when the script can; and `gh pr merge --delete-branch` from inside a worktree leaves the
|
|
50
|
+
worktree and branch behind, which is why the script exists. If the branch must outlive the
|
|
51
|
+
task unmerged, leave the worktree and say so in the handoff. Never `--force` a removal; a
|
|
52
|
+
refusal means look, not push harder.
|
|
47
53
|
- **A decision log is not a work record.** A decision — a durable choice with a
|
|
48
54
|
decider and a date — is documentation: it lives in **`decisions/`** (or the
|
|
49
55
|
repository's documented decisions folder) and is reviewed like any other
|
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-store-mutations.sh (exit 2 = block)
|
|
11
11
|
* Claude PreToolUse (Bash) → Pi `tool_call` → cratis-guard-pr-body.sh (exit 2 = block)
|
|
12
12
|
* Claude PostToolUse (Write|Edit) → Pi `tool_result` → cratis-pattern-scan.sh (advisory context)
|
|
13
|
+
* Claude PostToolUse (Bash) → Pi `tool_result` → cratis-cleanup-worktrees.sh --hook (removes delivered worktrees/branches)
|
|
14
|
+
* Claude SessionStart → Pi `session_start` → cratis-cleanup-worktrees.sh --hook (sweeps orphans left by any earlier session)
|
|
13
15
|
* Explicit Pi `cratis_quality_gate` tool → cratis-quality-gate.sh (exit 2 = failed)
|
|
14
16
|
*
|
|
15
17
|
* The quality gate is the one deliberate difference from Claude. It builds and tests the repository, which can
|
|
@@ -80,11 +82,11 @@ interface ScriptRun {
|
|
|
80
82
|
* writes it exists to refuse. Callers decide what to do with `failed`; this function only reports
|
|
81
83
|
* it honestly.
|
|
82
84
|
*/
|
|
83
|
-
function runScript(script: string, stdinJson: string, cwd: string, signal?: AbortSignal): Promise<ScriptRun> {
|
|
85
|
+
function runScript(script: string, stdinJson: string, cwd: string, signal?: AbortSignal, args: string[] = []): Promise<ScriptRun> {
|
|
84
86
|
return new Promise<ScriptRun>((resolve) => {
|
|
85
87
|
let proc: ReturnType<typeof spawn>;
|
|
86
88
|
try {
|
|
87
|
-
proc = spawn("bash", [script], { cwd, stdio: ["pipe", "pipe", "pipe"] });
|
|
89
|
+
proc = spawn("bash", [script, ...args], { cwd, stdio: ["pipe", "pipe", "pipe"] });
|
|
88
90
|
} catch (error) {
|
|
89
91
|
resolve({ code: 127, stdout: "", stderr: String(error), failed: true });
|
|
90
92
|
return;
|
|
@@ -187,6 +189,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
187
189
|
const guardPrBody = path.join(scriptsDir, "cratis-guard-pr-body.sh");
|
|
188
190
|
const patternScan = path.join(scriptsDir, "cratis-pattern-scan.sh");
|
|
189
191
|
const qualityGate = path.join(scriptsDir, "cratis-quality-gate.sh");
|
|
192
|
+
const cleanupWorktrees = path.join(scriptsDir, "cratis-cleanup-worktrees.sh");
|
|
190
193
|
|
|
191
194
|
// The explicit gate owns its subprocesses; shutdown also cancels a still-running tool.
|
|
192
195
|
const activeGateRuns = new Map<AbortController, Promise<void>>();
|
|
@@ -230,8 +233,38 @@ export default function (pi: ExtensionAPI) {
|
|
|
230
233
|
return runBlockingGuard(guardWrites, "cratis-guard-writes", "write", payload, ctx, "write guards");
|
|
231
234
|
});
|
|
232
235
|
|
|
236
|
+
// ── Cleanup of delivered worktrees and branches ──
|
|
237
|
+
// The script decides on evidence that the work reached the default branch and only then removes anything; this
|
|
238
|
+
// bridge just fires it at the same moments Claude does: after a delivering command, and when a session starts.
|
|
239
|
+
// A failure here must never fail the tool call that already succeeded, so it is reported, not thrown.
|
|
240
|
+
async function sweepDelivered(hookEvent: "PostToolUse" | "SessionStart", command: string | undefined, cwd: string, signal?: AbortSignal): Promise<string> {
|
|
241
|
+
if (!isInstalled(cleanupWorktrees)) return "";
|
|
242
|
+
const payload = JSON.stringify({ hook_event_name: hookEvent, cwd, tool_input: command ? { command } : undefined });
|
|
243
|
+
const run = await runScript(cleanupWorktrees, payload, cwd, signal, ["--hook"]);
|
|
244
|
+
if (run.failed) return "cratis-cleanup-worktrees is installed but could not be run, so delivered worktrees were not cleaned up.";
|
|
245
|
+
try {
|
|
246
|
+
return JSON.parse(run.stdout)?.hookSpecificOutput?.additionalContext?.trim() ?? run.stderr.trim();
|
|
247
|
+
} catch {
|
|
248
|
+
return run.stderr.trim();
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
252
|
+
const message = await sweepDelivered("SessionStart", undefined, ctx.cwd);
|
|
253
|
+
if (message) pi.sendMessage({ customType: "cratis-cleanup-worktrees", content: message, display: true });
|
|
254
|
+
});
|
|
255
|
+
async function sweepAfterBash(event: any, ctx: ExtensionContext) {
|
|
256
|
+
if (event.isError) return;
|
|
257
|
+
const command = event.input?.command;
|
|
258
|
+
if (typeof command !== "string") return;
|
|
259
|
+
const message = await sweepDelivered("PostToolUse", command, ctx.cwd, ctx.signal);
|
|
260
|
+
if (!message) return;
|
|
261
|
+
const existing = Array.isArray(event.content) ? event.content : [];
|
|
262
|
+
return { content: [...existing, { type: "text", text: `\n\n[cratis-hooks]\n${message}` }] };
|
|
263
|
+
}
|
|
264
|
+
|
|
233
265
|
// ── PostToolUse → deterministic pattern scan (advisory; injects reminders the model sees) ──
|
|
234
266
|
pi.on("tool_result", async (event, ctx) => {
|
|
267
|
+
if (event.toolName === "bash") return sweepAfterBash(event, ctx);
|
|
235
268
|
if (event.toolName !== "write" && event.toolName !== "edit") return;
|
|
236
269
|
if (event.isError) return;
|
|
237
270
|
const { filePath } = writeTarget(event.toolName, (event as any).input);
|
|
@@ -12,6 +12,7 @@ Three layers:
|
|
|
12
12
|
| Hard block | `PreToolUse` on a write | `scripts/cratis-guard-writes.sh` | zero | exits **2** — the write does not happen |
|
|
13
13
|
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-store-mutations.sh` | zero; parses only commands that mention `cratis` | exits **2** — the store-changing `cratis chronicle` command does not run |
|
|
14
14
|
| Hard block | `PreToolUse` on `Bash` | `scripts/cratis-guard-pr-body.sh` | fetches shared rules only for `gh pr create/edit` | exits **2** for inline bodies, invalid notes or conflicting release labels; warns and allows when offline with no cache |
|
|
15
|
+
| Cleanup of delivered work | `PostToolUse` on `Bash` (`gh pr merge`, `git pull/merge/worktree`) and `SessionStart` (Pi: `tool_result` and `session_start`) | `scripts/cratis-cleanup-worktrees.sh --hook` | zero when the command is unrelated | never blocks; removes delivered worktrees and branches, reports what it kept |
|
|
15
16
|
| Quality gate (Claude) | `Stop` | `scripts/cratis-quality-gate.sh` | one build/test run, only when relevant files changed | exits **2** — the turn does not end |
|
|
16
17
|
| Quality gate (Pi) | explicit `cratis_quality_gate` tool | same script | only at a requested verification checkpoint | error on failure; no turn-end hook |
|
|
17
18
|
|
|
@@ -60,6 +61,29 @@ conversion and Git's assume-unchanged or skip-worktree settings can hide raw dis
|
|
|
60
61
|
use those settings, independently verify raw file contents or remove the hiding settings before
|
|
61
62
|
relying on this check.
|
|
62
63
|
|
|
64
|
+
## Cleanup of delivered work
|
|
65
|
+
|
|
66
|
+
`scripts/cratis-cleanup-worktrees.sh` is the one place that removes linked worktrees and local
|
|
67
|
+
branches after their work shipped; worktrees pile up otherwise (`gh pr merge --delete-branch`
|
|
68
|
+
cannot delete a branch that a worktree still has checked out, so the pair is left behind) and eat disk.
|
|
69
|
+
It removes only on **evidence of delivery**, never on a guess: the tip is merged into `origin/<default>`
|
|
70
|
+
and was integrated rather than merely sitting on the default branch's first-parent history (where a
|
|
71
|
+
brand-new empty branch sits), or it is merged and its upstream is gone, or GitHub reports a merged pull
|
|
72
|
+
request whose head is exactly that tip. It never forces: a dirty, locked or current worktree is kept, as
|
|
73
|
+
is anything undelivered, and every kept item is reported with its reason. Ignored files (`node_modules`,
|
|
74
|
+
build output, `.ai-work/`) go with a delivered worktree; they are the disk being reclaimed.
|
|
75
|
+
|
|
76
|
+
- **When it runs.** After a Bash command that delivers or integrates work, and at the start of every
|
|
77
|
+
session, so orphans left by any earlier session, crash or harness are collected too.
|
|
78
|
+
Claude Code and Pi are wired (`settings.template.json`, the `cratis-hooks` Pi extension).
|
|
79
|
+
Harnesses with no hook wiring (Copilot, Cursor, OpenCode) rely on the **ship-changes** prompt, whose
|
|
80
|
+
final step runs the same script, and on running it by hand.
|
|
81
|
+
- **By hand.** `bash .cratis/ai/hooks/scripts/cratis-cleanup-worktrees.sh [--dry-run]` from any worktree;
|
|
82
|
+
run from the main checkout to also collect the worktree you are standing in.
|
|
83
|
+
- **Self-test.** `--self-test` plants delivered, dirty, unmerged and brand-new cases and fails if any is
|
|
84
|
+
handled wrongly.
|
|
85
|
+
- **Opt out.** `CRATIS_HOOKS_SKIP_CLEANUP=1`.
|
|
86
|
+
|
|
63
87
|
## What is enforced
|
|
64
88
|
|
|
65
89
|
Rule numbers refer to the numbered list in [`../rules/general.md`](../rules/general.md).
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Copyright (c) Cratis. All rights reserved.
|
|
3
|
+
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
|
|
4
|
+
#
|
|
5
|
+
# Deterministic cleanup of delivered work: linked worktrees and local branches whose work has
|
|
6
|
+
# reached the default branch. One script, every harness: Claude Code and Pi run it from hooks, and
|
|
7
|
+
# the ship-changes prompt runs it as a mandatory last step for harnesses without hooks.
|
|
8
|
+
#
|
|
9
|
+
# A worktree or branch is removed only on EVIDENCE that its work was delivered, never on a guess:
|
|
10
|
+
# 1. its tip is merged into origin/<default> AND was integrated (it is not simply sitting on the
|
|
11
|
+
# default branch's first-parent history, which is where a brand-new, empty branch sits), or
|
|
12
|
+
# 2. its tip is merged into origin/<default> and its upstream is gone (the PR branch was deleted), or
|
|
13
|
+
# 3. GitHub reports a merged pull request whose head commit is exactly this tip.
|
|
14
|
+
# Anything else is KEPT and reported with the reason. Nothing is ever forced: a dirty, locked or
|
|
15
|
+
# current worktree is kept, and `git worktree remove` is never given --force.
|
|
16
|
+
#
|
|
17
|
+
# Usage:
|
|
18
|
+
# cratis-cleanup-worktrees.sh [--dry-run] [--quiet] [--no-fetch] run in the repository (any worktree)
|
|
19
|
+
# cratis-cleanup-worktrees.sh --hook Claude hook mode: reads the hook JSON
|
|
20
|
+
# on stdin, acts only when relevant
|
|
21
|
+
# cratis-cleanup-worktrees.sh --self-test plants cases and fails if any is wrong
|
|
22
|
+
#
|
|
23
|
+
# Exit: 0 ran (kept items are not failures), 2 could not run. Opt out: CRATIS_HOOKS_SKIP_CLEANUP=1.
|
|
24
|
+
# Portable: bash 3.2, BSD + GNU userland.
|
|
25
|
+
# shellcheck disable=SC2016 # the self-test checks are single-quoted on purpose: they are eval-ed later
|
|
26
|
+
set -uo pipefail
|
|
27
|
+
|
|
28
|
+
DRY=0; QUIET=0; FETCH=1; HOOK=0; SELFTEST=0
|
|
29
|
+
for a in "$@"; do
|
|
30
|
+
case "$a" in
|
|
31
|
+
--dry-run) DRY=1 ;; --quiet) QUIET=1 ;; --no-fetch) FETCH=0 ;;
|
|
32
|
+
--hook) HOOK=1; QUIET=1 ;; --self-test) SELFTEST=1 ;;
|
|
33
|
+
*) echo "cratis-cleanup-worktrees: unknown argument '$a'" >&2; exit 2 ;;
|
|
34
|
+
esac
|
|
35
|
+
done
|
|
36
|
+
|
|
37
|
+
# ── Hook mode: decide whether this event is worth a sweep ─────────────────────
|
|
38
|
+
EVENT="PostToolUse"
|
|
39
|
+
if [ "$HOOK" = 1 ]; then
|
|
40
|
+
payload=''; IFS= read -r -d '' payload || true
|
|
41
|
+
[ "${CRATIS_HOOKS_SKIP_CLEANUP:-}" = 1 ] && exit 0
|
|
42
|
+
case "$payload" in *'"SessionStart"'*) EVENT="SessionStart" ;; esac
|
|
43
|
+
if [ "$EVENT" = "PostToolUse" ]; then
|
|
44
|
+
flat=${payload//\\n/ }; flat=${flat//\\\"/\"}
|
|
45
|
+
# Only commands that deliver or integrate work; everything else costs nothing.
|
|
46
|
+
if [[ ! "$flat" =~ (gh[[:space:]]+pr[[:space:]]+merge|git[[:space:]]+(-C[[:space:]]+[^[:space:]]+[[:space:]]+)?(pull|merge|worktree[[:space:]]+(add|remove|prune))|git[[:space:]]+push[[:space:]].*--delete) ]]; then
|
|
47
|
+
exit 0
|
|
48
|
+
fi
|
|
49
|
+
fi
|
|
50
|
+
cwd=""
|
|
51
|
+
command -v jq >/dev/null 2>&1 && cwd=$(printf '%s' "$payload" | jq -r '.cwd // empty' 2>/dev/null)
|
|
52
|
+
if [ -n "$cwd" ] && [ -d "$cwd" ]; then cd "$cwd" || exit 0; fi
|
|
53
|
+
fi
|
|
54
|
+
[ "${CRATIS_HOOKS_SKIP_CLEANUP:-}" = 1 ] && [ "$SELFTEST" = 0 ] && exit 0
|
|
55
|
+
|
|
56
|
+
# ── Self-test ─────────────────────────────────────────────────────────────────
|
|
57
|
+
if [ "$SELFTEST" = 1 ]; then
|
|
58
|
+
self=$(cd "$(dirname "$0")" && pwd)/$(basename "$0")
|
|
59
|
+
t=$(mktemp -d "${TMPDIR:-/tmp}/cleanup-selftest.XXXXXX"); trap 'rm -rf "$t"' EXIT
|
|
60
|
+
export GIT_AUTHOR_NAME=t GIT_AUTHOR_EMAIL=t@t GIT_COMMITTER_NAME=t GIT_COMMITTER_EMAIL=t@t CRATIS_CLEANUP_NO_GH=1
|
|
61
|
+
git init -q --bare -b main "$t/origin.git"
|
|
62
|
+
git clone -q "$t/origin.git" "$t/repo" 2>/dev/null; cd "$t/repo" || exit 2
|
|
63
|
+
git checkout -q -b main 2>/dev/null; echo a > a; git add a; git commit -qm base; git push -q origin main
|
|
64
|
+
mk() { git worktree add -q -b "$1" "$t/wt-$1" main; }
|
|
65
|
+
mk delivered; (cd "$t/wt-delivered" && echo d > d && git add d && git commit -qm d)
|
|
66
|
+
mk dirty; (cd "$t/wt-dirty" && echo x > x && git add x && git commit -qm x)
|
|
67
|
+
mk unmerged; (cd "$t/wt-unmerged" && echo u > u && git add u && git commit -qm u)
|
|
68
|
+
mk fresh # brand new, no commits: must survive
|
|
69
|
+
git branch loose-delivered main; (git checkout -q loose-delivered && echo l > l && git add l && git commit -qm l && git checkout -q main)
|
|
70
|
+
git merge -q --no-ff delivered -m "merge delivered" && git merge -q --no-ff dirty -m "merge dirty" && git merge -q --no-ff loose-delivered -m "merge loose"
|
|
71
|
+
git push -q origin main
|
|
72
|
+
echo junk > "$t/wt-dirty/untracked" # makes the merged worktree dirty
|
|
73
|
+
out=$("$self" --no-fetch 2>&1) || { echo "FAIL: exit $?"; echo "$out"; exit 1; }
|
|
74
|
+
fail=0; chk() { if ! eval "$2"; then echo "FAIL: $1"; fail=1; fi; }
|
|
75
|
+
chk "delivered worktree removed" '[ ! -d "$t/wt-delivered" ]'
|
|
76
|
+
chk "delivered branch removed" '! git rev-parse -q --verify refs/heads/delivered >/dev/null'
|
|
77
|
+
chk "loose merged branch removed" '! git rev-parse -q --verify refs/heads/loose-delivered >/dev/null'
|
|
78
|
+
chk "dirty worktree kept" '[ -d "$t/wt-dirty" ]'
|
|
79
|
+
chk "unmerged worktree kept" '[ -d "$t/wt-unmerged" ]'
|
|
80
|
+
chk "unmerged branch kept" 'git rev-parse -q --verify refs/heads/unmerged >/dev/null'
|
|
81
|
+
chk "fresh worktree kept" '[ -d "$t/wt-fresh" ]'
|
|
82
|
+
chk "fresh branch kept" 'git rev-parse -q --verify refs/heads/fresh >/dev/null'
|
|
83
|
+
chk "main kept" 'git rev-parse -q --verify refs/heads/main >/dev/null'
|
|
84
|
+
chk "report names the removal" 'printf "%s" "$out" | grep -q "removed worktree"'
|
|
85
|
+
[ "$fail" = 0 ] && echo "cratis-cleanup-worktrees self-test: 10 checks passed" && exit 0
|
|
86
|
+
echo "$out"; exit 1
|
|
87
|
+
fi
|
|
88
|
+
|
|
89
|
+
# ── Locate the repository ─────────────────────────────────────────────────────
|
|
90
|
+
git rev-parse --git-dir >/dev/null 2>&1 || { [ "$QUIET" = 1 ] || echo "cratis-cleanup-worktrees: not in a git repository" >&2; exit "$([ "$HOOK" = 1 ] && echo 0 || echo 2)"; }
|
|
91
|
+
here=$(pwd -P)
|
|
92
|
+
main_wt=$(git worktree list --porcelain | awk 'NR==1 && $1=="worktree"{sub(/^worktree /,""); print; exit}')
|
|
93
|
+
if [ ! -d "$main_wt" ]; then echo "cratis-cleanup-worktrees: cannot find the main worktree" >&2; exit 2; fi
|
|
94
|
+
cd "$main_wt" || exit 2
|
|
95
|
+
|
|
96
|
+
if [ "$FETCH" = 1 ]; then git fetch --prune --quiet origin >/dev/null 2>&1 || LOG_NOFETCH=1; fi
|
|
97
|
+
default=$(git symbolic-ref --quiet --short refs/remotes/origin/HEAD 2>/dev/null || true)
|
|
98
|
+
[ -n "$default" ] || { for c in origin/main origin/master; do git rev-parse -q --verify "refs/remotes/$c" >/dev/null && default=$c && break; done; }
|
|
99
|
+
[ -n "$default" ] || { [ "$QUIET" = 1 ] || echo "cratis-cleanup-worktrees: no origin default branch; nothing to compare against" >&2; exit "$([ "$HOOK" = 1 ] && echo 0 || echo 2)"; }
|
|
100
|
+
default_local=${default#origin/}
|
|
101
|
+
|
|
102
|
+
firstparent=$(mktemp "${TMPDIR:-/tmp}/cleanup-fp.XXXXXX"); trap 'rm -f "$firstparent"' EXIT
|
|
103
|
+
git rev-list --first-parent "$default" > "$firstparent" 2>/dev/null
|
|
104
|
+
|
|
105
|
+
REMOVED=(); KEPT=(); FREED_KB=0
|
|
106
|
+
note_removed() { REMOVED+=("$1"); }
|
|
107
|
+
note_kept() { KEPT+=("$1"); }
|
|
108
|
+
|
|
109
|
+
# delivered <sha> <branch|""> <upstream-track> → prints the evidence, returns 0 when delivered
|
|
110
|
+
delivered() {
|
|
111
|
+
local sha="$1" br="$2" track="$3"
|
|
112
|
+
if git merge-base --is-ancestor "$sha" "$default" 2>/dev/null; then
|
|
113
|
+
if ! grep -qx "$sha" "$firstparent"; then echo "merged into $default"; return 0; fi
|
|
114
|
+
if [ "$track" = "[gone]" ]; then echo "merged into $default, upstream gone"; return 0; fi
|
|
115
|
+
fi
|
|
116
|
+
if [ -n "$br" ] && [ "${CRATIS_CLEANUP_NO_GH:-}" != 1 ] && command -v gh >/dev/null 2>&1; then
|
|
117
|
+
if gh pr list --head "$br" --state merged --json headRefOid -q '.[].headRefOid' 2>/dev/null | grep -qx "$sha"; then
|
|
118
|
+
echo "pull request merged at this commit"; return 0
|
|
119
|
+
fi
|
|
120
|
+
fi
|
|
121
|
+
return 1
|
|
122
|
+
}
|
|
123
|
+
track_of() { git for-each-ref --format='%(upstream:track)' "refs/heads/$1" 2>/dev/null; }
|
|
124
|
+
|
|
125
|
+
# ── Worktrees ─────────────────────────────────────────────────────────────────
|
|
126
|
+
git worktree prune >/dev/null 2>&1
|
|
127
|
+
wt=""; sha=""; br=""; locked=0; first=1
|
|
128
|
+
process_worktree() {
|
|
129
|
+
[ -n "$wt" ] || return 0
|
|
130
|
+
if [ "$first" = 1 ]; then first=0; return 0; fi # the main worktree is never removed
|
|
131
|
+
local name="${br:-detached}" ev
|
|
132
|
+
if [ "$locked" = 1 ]; then note_kept "worktree $wt ($name): locked"; return 0; fi
|
|
133
|
+
case "$here/" in "$wt"/*) note_kept "worktree $wt ($name): it is the current directory - run the sweep from the main checkout"; return 0 ;; esac
|
|
134
|
+
if ! ev=$(delivered "$sha" "$br" "$([ -n "$br" ] && track_of "$br")"); then
|
|
135
|
+
note_kept "worktree $wt ($name): work not delivered to $default"; return 0
|
|
136
|
+
fi
|
|
137
|
+
if [ -n "$(git -C "$wt" status --porcelain 2>/dev/null)" ]; then note_kept "worktree $wt ($name): delivered but has uncommitted changes"; return 0; fi
|
|
138
|
+
local kb; kb=$(du -sk "$wt" 2>/dev/null | awk '{print $1}')
|
|
139
|
+
if [ "$DRY" = 1 ]; then note_removed "worktree $wt ($name): would remove, $ev"; return 0; fi
|
|
140
|
+
if git worktree remove "$wt" >/dev/null 2>&1; then
|
|
141
|
+
FREED_KB=$((FREED_KB + ${kb:-0})); note_removed "worktree $wt ($name): $ev"
|
|
142
|
+
else note_kept "worktree $wt ($name): git refused to remove it"; fi
|
|
143
|
+
}
|
|
144
|
+
while IFS= read -r line; do
|
|
145
|
+
case "$line" in
|
|
146
|
+
"worktree "*) process_worktree; wt=${line#worktree }; sha=""; br=""; locked=0 ;;
|
|
147
|
+
"HEAD "*) sha=${line#HEAD } ;;
|
|
148
|
+
"branch "*) br=${line#branch refs/heads/} ;;
|
|
149
|
+
"locked"*) locked=1 ;;
|
|
150
|
+
esac
|
|
151
|
+
done < <(git worktree list --porcelain; echo)
|
|
152
|
+
process_worktree
|
|
153
|
+
|
|
154
|
+
# ── Local branches ────────────────────────────────────────────────────────────
|
|
155
|
+
in_use=$(git worktree list --porcelain | sed -n 's#^branch refs/heads/##p')
|
|
156
|
+
while IFS='|' read -r b bsha; do
|
|
157
|
+
if [ -z "$b" ] || [ "$b" = "$default_local" ]; then continue; fi
|
|
158
|
+
printf '%s\n' "$in_use" | grep -qx "$b" && continue
|
|
159
|
+
if ev=$(delivered "$bsha" "$b" "$(track_of "$b")"); then
|
|
160
|
+
if [ "$DRY" = 1 ]; then note_removed "branch $b: would delete, $ev"
|
|
161
|
+
elif git branch -D "$b" >/dev/null 2>&1; then note_removed "branch $b: $ev"
|
|
162
|
+
else note_kept "branch $b: git refused to delete it"; fi
|
|
163
|
+
else
|
|
164
|
+
note_kept "branch $b: work not delivered to $default"
|
|
165
|
+
fi
|
|
166
|
+
done < <(git for-each-ref --format='%(refname:short)|%(objectname)' refs/heads)
|
|
167
|
+
|
|
168
|
+
# ── Report ────────────────────────────────────────────────────────────────────
|
|
169
|
+
summary="cratis-cleanup-worktrees: ${#REMOVED[@]} removed, ${#KEPT[@]} kept"
|
|
170
|
+
[ "$FREED_KB" -gt 0 ] && summary="$summary, $((FREED_KB / 1024)) MB freed"
|
|
171
|
+
[ "${LOG_NOFETCH:-0}" = 1 ] && summary="$summary (fetch failed: compared against the last fetched $default)"
|
|
172
|
+
if [ "$HOOK" = 1 ]; then
|
|
173
|
+
[ "${#REMOVED[@]}" -gt 0 ] || { [ "$EVENT" = "SessionStart" ] && [ "${#KEPT[@]}" -gt 0 ]; } || exit 0
|
|
174
|
+
msg="$summary."
|
|
175
|
+
[ "${#KEPT[@]}" -gt 0 ] && msg="$msg Kept (not delivered or not safe to remove): $(printf '%s; ' "${KEPT[@]}")"
|
|
176
|
+
command -v jq >/dev/null 2>&1 && jq -nc --arg m "$msg" --arg e "$EVENT" '{systemMessage:$m,hookSpecificOutput:{hookEventName:$e,additionalContext:$m}}' || printf '%s\n' "$msg" >&2
|
|
177
|
+
exit 0
|
|
178
|
+
fi
|
|
179
|
+
if [ "$QUIET" = 0 ]; then
|
|
180
|
+
echo "$summary"
|
|
181
|
+
for r in "${REMOVED[@]+"${REMOVED[@]}"}"; do echo " removed $r"; done
|
|
182
|
+
for k in "${KEPT[@]+"${KEPT[@]}"}"; do echo " kept $k"; done
|
|
183
|
+
fi
|
|
184
|
+
exit 0
|
|
@@ -25,7 +25,28 @@
|
|
|
25
25
|
]
|
|
26
26
|
}
|
|
27
27
|
],
|
|
28
|
+
"SessionStart": [
|
|
29
|
+
{
|
|
30
|
+
"hooks": [
|
|
31
|
+
{
|
|
32
|
+
"type": "command",
|
|
33
|
+
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-cleanup-worktrees.sh --hook",
|
|
34
|
+
"timeout": 90
|
|
35
|
+
}
|
|
36
|
+
]
|
|
37
|
+
}
|
|
38
|
+
],
|
|
28
39
|
"PostToolUse": [
|
|
40
|
+
{
|
|
41
|
+
"matcher": "Bash",
|
|
42
|
+
"hooks": [
|
|
43
|
+
{
|
|
44
|
+
"type": "command",
|
|
45
|
+
"command": "bash \"$CLAUDE_PROJECT_DIR\"/.cratis/ai/hooks/scripts/cratis-cleanup-worktrees.sh --hook",
|
|
46
|
+
"timeout": 90
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
},
|
|
29
50
|
{
|
|
30
51
|
"matcher": "Write|Edit|MultiEdit|NotebookEdit",
|
|
31
52
|
"hooks": [
|
|
@@ -52,3 +52,18 @@ The description is published verbatim as the release notes, so it follows the co
|
|
|
52
52
|
deploy order) right after creating the PR with `gh pr comment <n> --body-file .ai-work/pr-notes.md`.
|
|
53
53
|
Never put them in the description, even for `no-release`.
|
|
54
54
|
- After pushing, if `verify-release-notes` fails, fix it by editing the description; it re-runs on edit.
|
|
55
|
+
|
|
56
|
+
## Cleanup — the last step, never skipped
|
|
57
|
+
|
|
58
|
+
Shipping is not finished until the delivered work is cleaned up. Worktrees and branches left behind
|
|
59
|
+
cost real disk and accumulate across sessions. After the merge succeeds:
|
|
60
|
+
|
|
61
|
+
1. Leave the worktree you worked in: `cd` to the main checkout (`git worktree list` shows it first).
|
|
62
|
+
2. Run `bash .cratis/ai/hooks/scripts/cratis-cleanup-worktrees.sh` and report its summary line.
|
|
63
|
+
It fetches, checks out nothing, and removes only worktrees and local branches whose work is
|
|
64
|
+
verifiably on the default branch (this one included); it never forces and reports what it kept and why.
|
|
65
|
+
3. `git switch main && git pull --ff-only` in the main checkout so it matches the merged result.
|
|
66
|
+
|
|
67
|
+
Claude Code and Pi also run the script from a hook after `gh pr merge` and at session start; running it
|
|
68
|
+
here as well is deliberate, because Copilot, Cursor and OpenCode have no hook and this step is their only
|
|
69
|
+
trigger. If the script reports the shipped worktree as kept, say why in the final message.
|
|
@@ -37,12 +37,18 @@ dumps, and similar coordination files. These are **work records, not documentati
|
|
|
37
37
|
- **A worktree is a work record too.** Create it outside the repository tree, for
|
|
38
38
|
example in a sibling `../.worktrees/` directory. A nested worktree inherits the
|
|
39
39
|
parent's `.globalconfig` alongside its own, causing .NET's `MultipleGlobalAnalyzerKeys`
|
|
40
|
-
errors or silently changing analyzer severities.
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
40
|
+
errors or silently changing analyzer severities. **Delivered work is cleaned up by
|
|
41
|
+
`.cratis/ai/hooks/scripts/cratis-cleanup-worktrees.sh`, not by memory:** run it from the
|
|
42
|
+
main checkout when a pull request merges or you finish a task (hooks also run it after
|
|
43
|
+
`gh pr merge` and at session start where the harness supports them, and **ship-changes**
|
|
44
|
+
ends with it). It removes a worktree and its branch only on evidence the work reached the
|
|
45
|
+
default branch — pushed is not merged — and never forces; ignored files such as a nested
|
|
46
|
+
`.ai-work/`, `.env` files and local databases are deleted with it, so move anything you
|
|
47
|
+
still need out first. Do not hand-remove worktrees or `git branch -D` a delivered branch
|
|
48
|
+
when the script can; and `gh pr merge --delete-branch` from inside a worktree leaves the
|
|
49
|
+
worktree and branch behind, which is why the script exists. If the branch must outlive the
|
|
50
|
+
task unmerged, leave the worktree and say so in the handoff. Never `--force` a removal; a
|
|
51
|
+
refusal means look, not push harder.
|
|
46
52
|
- **A decision log is not a work record.** A decision — a durable choice with a
|
|
47
53
|
decider and a date — is documentation: it lives in **`decisions/`** (or the
|
|
48
54
|
repository's documented decisions folder) and is reviewed like any other
|