pi-pstack-workflow-kit 0.0.0-stage → 0.1.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.
Files changed (138) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -2
  3. package/agents/ci-watcher.md +1 -0
  4. package/agents/comment-sicko.md +1 -0
  5. package/agents/poteto-agent.md +1 -0
  6. package/agents/quality-agent.md +1 -0
  7. package/agents/worker.md +3 -0
  8. package/extensions/catalog-ui.ts +86 -0
  9. package/extensions/delegate.ts +357 -0
  10. package/extensions/forge.ts +245 -0
  11. package/extensions/git.ts +23 -0
  12. package/extensions/index.ts +25 -0
  13. package/extensions/models.ts +115 -0
  14. package/extensions/parent-diff.ts +63 -0
  15. package/extensions/plan.ts +181 -0
  16. package/extensions/records.ts +81 -0
  17. package/extensions/session.ts +124 -0
  18. package/extensions/support.ts +46 -0
  19. package/extensions/worktrees.ts +188 -0
  20. package/lib/catalog-data.json +560 -0
  21. package/lib/catalog.ts +111 -0
  22. package/lib/jobs.ts +5 -0
  23. package/lib/models.ts +124 -0
  24. package/lib/pool.ts +29 -0
  25. package/lib/state.ts +127 -0
  26. package/lib/transcript.ts +44 -0
  27. package/lib/validation.ts +16 -0
  28. package/package.json +68 -4
  29. package/reference/GAPS.md +21 -0
  30. package/reference/PARITY.md +169 -0
  31. package/reference/benny/config.example.json +12 -0
  32. package/reference/benny/repro.md +3 -0
  33. package/reference/benny/setup.md +3 -0
  34. package/reference/benny/triage.md +3 -0
  35. package/reference/parity.json +3095 -0
  36. package/reference/rules/no-inline-imports.md +3 -0
  37. package/reference/rules/typescript-exhaustive-switch.md +3 -0
  38. package/reference/source-map.json +8594 -0
  39. package/scripts/job-input.ts +191 -0
  40. package/scripts/run-job.mjs +119 -0
  41. package/skills/architect/SKILL.md +16 -0
  42. package/skills/arena/SKILL.md +16 -0
  43. package/skills/automate-me/SKILL.md +10 -0
  44. package/skills/benchmark-checklist/SKILL.md +10 -0
  45. package/skills/blast-radius/SKILL.md +10 -0
  46. package/skills/bro/SKILL.md +10 -0
  47. package/skills/check-compiler-errors/SKILL.md +10 -0
  48. package/skills/control-cli/SKILL.md +10 -0
  49. package/skills/control-ui/SKILL.md +10 -0
  50. package/skills/correct/SKILL.md +10 -0
  51. package/skills/create-formal-verification-skill/SKILL.md +16 -0
  52. package/skills/create-verification-skill/SKILL.md +16 -0
  53. package/skills/deslop/SKILL.md +10 -0
  54. package/skills/figure-it-out/SKILL.md +17 -0
  55. package/skills/fix-ci/SKILL.md +10 -0
  56. package/skills/fix-merge-conflicts/SKILL.md +10 -0
  57. package/skills/get-pr-comments/SKILL.md +10 -0
  58. package/skills/how/SKILL.md +10 -0
  59. package/skills/in-your-own-words/SKILL.md +11 -0
  60. package/skills/interrogate/SKILL.md +17 -0
  61. package/skills/ketchup/SKILL.md +10 -0
  62. package/skills/ketchup-video/SKILL.md +10 -0
  63. package/skills/loop-on-ci/SKILL.md +10 -0
  64. package/skills/maintain-formal-verification-skill/SKILL.md +16 -0
  65. package/skills/maintain-verification-skill/SKILL.md +16 -0
  66. package/skills/make-bot-ui/SKILL.md +10 -0
  67. package/skills/make-pr-easy-to-review/SKILL.md +10 -0
  68. package/skills/new-branch-and-pr/SKILL.md +10 -0
  69. package/skills/no-comments/SKILL.md +16 -0
  70. package/skills/poteto-help/SKILL.md +11 -0
  71. package/skills/poteto-mode/SKILL.md +60 -0
  72. package/skills/poteto-mode/playbooks/authoring-a-skill.md +20 -0
  73. package/skills/poteto-mode/playbooks/autonomous-run.md +20 -0
  74. package/skills/poteto-mode/playbooks/autopilot-full.md +25 -0
  75. package/skills/poteto-mode/playbooks/autopilot-stack.md +20 -0
  76. package/skills/poteto-mode/playbooks/babysit.md +21 -0
  77. package/skills/poteto-mode/playbooks/bug-fix.md +26 -0
  78. package/skills/poteto-mode/playbooks/eval.md +20 -0
  79. package/skills/poteto-mode/playbooks/feature.md +26 -0
  80. package/skills/poteto-mode/playbooks/hillclimb.md +24 -0
  81. package/skills/poteto-mode/playbooks/investigation.md +19 -0
  82. package/skills/poteto-mode/playbooks/multi-phase-plan.md +19 -0
  83. package/skills/poteto-mode/playbooks/opening-a-pr.md +20 -0
  84. package/skills/poteto-mode/playbooks/pause-safely.md +18 -0
  85. package/skills/poteto-mode/playbooks/perf-issue.md +24 -0
  86. package/skills/poteto-mode/playbooks/prototype.md +21 -0
  87. package/skills/poteto-mode/playbooks/refactoring.md +23 -0
  88. package/skills/poteto-mode/playbooks/runtime-forensics.md +20 -0
  89. package/skills/poteto-mode/playbooks/session-pickup.md +20 -0
  90. package/skills/poteto-mode/playbooks/shipping.md +24 -0
  91. package/skills/poteto-mode/playbooks/trace-forensics.md +20 -0
  92. package/skills/poteto-mode/playbooks/visual-parity.md +22 -0
  93. package/skills/poteto-mode/playbooks/worktree-cleanup.md +19 -0
  94. package/skills/pr-review-canvas/SKILL.md +10 -0
  95. package/skills/principle-attack-the-premise/SKILL.md +12 -0
  96. package/skills/principle-boundary-discipline/SKILL.md +12 -0
  97. package/skills/principle-build-the-lever/SKILL.md +12 -0
  98. package/skills/principle-encode-lessons-in-structure/SKILL.md +12 -0
  99. package/skills/principle-exhaust-the-design-space/SKILL.md +12 -0
  100. package/skills/principle-experience-first/SKILL.md +12 -0
  101. package/skills/principle-explain-the-number/SKILL.md +12 -0
  102. package/skills/principle-fix-root-causes/SKILL.md +12 -0
  103. package/skills/principle-foundational-thinking/SKILL.md +12 -0
  104. package/skills/principle-guard-the-context-window/SKILL.md +12 -0
  105. package/skills/principle-laziness-protocol/SKILL.md +12 -0
  106. package/skills/principle-make-operations-idempotent/SKILL.md +12 -0
  107. package/skills/principle-migrate-callers-then-delete-legacy-apis/SKILL.md +12 -0
  108. package/skills/principle-minimize-reader-load/SKILL.md +12 -0
  109. package/skills/principle-model-the-domain/SKILL.md +12 -0
  110. package/skills/principle-never-block-on-the-human/SKILL.md +12 -0
  111. package/skills/principle-outcome-oriented-execution/SKILL.md +12 -0
  112. package/skills/principle-prove-it-works/SKILL.md +12 -0
  113. package/skills/principle-redesign-from-first-principles/SKILL.md +12 -0
  114. package/skills/principle-separate-before-serializing-shared-state/SKILL.md +12 -0
  115. package/skills/principle-sequence-verifiable-units/SKILL.md +12 -0
  116. package/skills/principle-subtract-before-you-add/SKILL.md +12 -0
  117. package/skills/principle-test-behavior-not-implementation/SKILL.md +12 -0
  118. package/skills/principle-type-system-discipline/SKILL.md +12 -0
  119. package/skills/recall/SKILL.md +10 -0
  120. package/skills/reflect/SKILL.md +10 -0
  121. package/skills/review-and-ship/SKILL.md +10 -0
  122. package/skills/run-smoke-tests/SKILL.md +10 -0
  123. package/skills/setup-pstack/SKILL.md +17 -0
  124. package/skills/sharpen/SKILL.md +11 -0
  125. package/skills/show-me-your-work/SKILL.md +16 -0
  126. package/skills/statechart/SKILL.md +10 -0
  127. package/skills/swarm/SKILL.md +16 -0
  128. package/skills/tdd/SKILL.md +10 -0
  129. package/skills/teach/SKILL.md +17 -0
  130. package/skills/technical-writing/SKILL.md +10 -0
  131. package/skills/thermo-nuclear-code-quality-review/SKILL.md +10 -0
  132. package/skills/typescript-best-practices/SKILL.md +10 -0
  133. package/skills/unslop/SKILL.md +10 -0
  134. package/skills/verify-this/SKILL.md +17 -0
  135. package/skills/weekly-review/SKILL.md +10 -0
  136. package/skills/what-did-i-get-done/SKILL.md +10 -0
  137. package/skills/why/SKILL.md +10 -0
  138. package/skills/workflow-from-chats/SKILL.md +10 -0
@@ -0,0 +1,81 @@
1
+ import { appendFile, mkdir, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+
4
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
6
+
7
+ import { catalog, packageFile } from "../lib/catalog.ts";
8
+ import { isJobKind } from "../lib/jobs.ts";
9
+ import { artifacts, hasErrorCode, result, tsvRow, type Notify } from "./support.ts";
10
+
11
+ export function registerRecords(pi: ExtensionAPI, notify: Notify) {
12
+ pi.registerCommand("pstack-automation", {
13
+ description: "Draft a headless Pi automation (disabled)",
14
+ handler: async (args, ctx) => {
15
+ const kind = args.trim();
16
+ if (!isJobKind(kind)) return notify(ctx, "Choose benny-triage, benny-repro, or custom.");
17
+ const path = join(artifacts(ctx), `${kind}.job.json`);
18
+ const draft =
19
+ kind === "custom"
20
+ ? { instructions: "Supply explicit task, approved tools, trigger and finish predicate." }
21
+ : {
22
+ instructions: packageFile(catalog.paths[kind]),
23
+ config: JSON.parse(packageFile("reference/benny/config.example.json")),
24
+ };
25
+ const job = { version: 1, enabled: false, kind, cwd: ctx.cwd, tools: [], ...draft };
26
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
27
+ await writeFile(path, JSON.stringify(job, null, 2), { flag: "wx", mode: 0o600 });
28
+ notify(ctx, `Disabled draft: ${path}. No scheduler or service was enabled.`);
29
+ },
30
+ });
31
+ pi.registerTool({
32
+ name: "pstack_log",
33
+ label: "Pstack decision log",
34
+ description:
35
+ "Append a timestamped decision with phase, rationale, evidence and result to a session TSV.",
36
+ executionMode: "sequential",
37
+ parameters: Type.Object({
38
+ phase: Type.String(),
39
+ decision: Type.String(),
40
+ reason: Type.String(),
41
+ evidence: Type.String(),
42
+ result: Type.String(),
43
+ }),
44
+ async execute(_id, p, _signal, _update, ctx) {
45
+ const dir = artifacts(ctx);
46
+ await mkdir(dir, { recursive: true, mode: 0o700 });
47
+ const path = join(dir, "decisions.tsv");
48
+ try {
49
+ await writeFile(path, "time\tphase\tdecision\treason\tevidence\tresult\n", {
50
+ flag: "wx",
51
+ mode: 0o600,
52
+ });
53
+ } catch (e) {
54
+ if (!hasErrorCode(e, "EEXIST")) throw e;
55
+ }
56
+ await appendFile(
57
+ path,
58
+ tsvRow([new Date().toISOString(), p.phase, p.decision, p.reason, p.evidence, p.result]),
59
+ );
60
+ return result(path);
61
+ },
62
+ });
63
+ pi.registerTool({
64
+ name: "pstack_history",
65
+ label: "Pstack session history",
66
+ description:
67
+ "Read bounded current branch session entries and artifact directory; use Pi resume/tree for other sessions.",
68
+ parameters: Type.Object({ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100 })) }),
69
+ async execute(_id, p, _signal, _update, ctx) {
70
+ const entries = ctx.sessionManager
71
+ .getBranch()
72
+ .slice(-(p.limit ?? 20))
73
+ .map((e) => ({ type: e.type, id: e.id, data: JSON.stringify(e).slice(0, 4000) }));
74
+ return result({
75
+ session: ctx.sessionManager.getSessionFile(),
76
+ artifacts: artifacts(ctx),
77
+ entries,
78
+ });
79
+ },
80
+ });
81
+ }
@@ -0,0 +1,124 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { packageFile, routeTriggers } from "../lib/catalog.ts";
4
+ import {
5
+ activePlan,
6
+ initialState,
7
+ restore,
8
+ stateType,
9
+ stopped,
10
+ type State,
11
+ type TaskStatus,
12
+ type Wake,
13
+ } from "../lib/state.ts";
14
+
15
+ const markers: Record<TaskStatus, string> = {
16
+ pending: "[ ]",
17
+ active: "[>]",
18
+ done: "[x]",
19
+ blocked: "[!]",
20
+ skipped: "[-]",
21
+ };
22
+
23
+ function statusLine({ mode, plan, wake }: State) {
24
+ if (!mode && !plan && !wake?.running) return undefined;
25
+ const closed = plan?.tasks.filter((t) => t.status === "done" || t.status === "skipped").length;
26
+ const progress = plan ? ` | ${plan.route} ${closed}/${plan.tasks.length}` : "";
27
+ return `pstack ${mode ? "on" : "off"}${progress}${wake?.running ? " | loop" : ""}`;
28
+ }
29
+
30
+ function systemPromptAdditions(state: State) {
31
+ const plan = activePlan(state);
32
+ return [
33
+ ...(state.mode
34
+ ? [
35
+ packageFile("skills/poteto-mode/SKILL.md"),
36
+ `Native playbook triggers:\n${routeTriggers()
37
+ .map((r) => `${r.id}: ${r.when}`)
38
+ .join("\n")}`,
39
+ ]
40
+ : []),
41
+ ...(state.goal ? [`Persistent operator goal: ${state.goal}`] : []),
42
+ ...(plan
43
+ ? [`Branch-local task state (call pstack_plan to update): ${JSON.stringify(plan)}`]
44
+ : []),
45
+ ];
46
+ }
47
+
48
+ export function createSession(pi: ExtensionAPI) {
49
+ let state = initialState();
50
+ let timer: ReturnType<typeof setTimeout> | undefined;
51
+
52
+ function clearTimer() {
53
+ if (timer) clearTimeout(timer);
54
+ timer = undefined;
55
+ }
56
+ function refresh(ctx: ExtensionContext) {
57
+ if (!ctx.hasUI) return;
58
+ ctx.ui.setStatus("pstack", statusLine(state));
59
+ ctx.ui.setWidget(
60
+ "pstack",
61
+ state.plan?.tasks.map((t) => `${markers[t.status]} ${t.id}. ${t.text}`),
62
+ );
63
+ }
64
+ function commit(ctx: ExtensionContext, change: Partial<State>) {
65
+ state = { ...state, ...change };
66
+ if (!state.wake?.running) clearTimer();
67
+ pi.appendEntry(stateType, structuredClone(state));
68
+ refresh(ctx);
69
+ }
70
+ const stopWake = (ctx: ExtensionContext, evidence?: string) =>
71
+ commit(ctx, { wake: stopped(state.wake, evidence) });
72
+
73
+ function wakeUp(ctx: ExtensionContext) {
74
+ timer = undefined;
75
+ const wake = state.wake;
76
+ if (!wake?.running) return;
77
+ if (!ctx.isIdle() || ctx.hasPendingMessages()) return schedule(ctx);
78
+ if (wake.count >= wake.max) return stopWake(ctx);
79
+ const count = wake.count + 1;
80
+ commit(ctx, { wake: { ...wake, count } });
81
+ pi.sendMessage(
82
+ {
83
+ customType: "pstack-wake",
84
+ content: `Wake ${count}/${wake.max}. Check the actual predicate: ${wake.predicate}. Inspect new evidence, take one authorized step if needed, record it, and call pstack_wake action stop when verified or blocked. Do not assume completion.`,
85
+ display: true,
86
+ },
87
+ { triggerTurn: true, deliverAs: "followUp" },
88
+ );
89
+ }
90
+ function schedule(ctx: ExtensionContext) {
91
+ if (timer || !state.wake?.running || ctx.mode !== "tui") return;
92
+ timer = setTimeout(() => wakeUp(ctx), state.wake.seconds * 1000);
93
+ }
94
+ function startWake(ctx: ExtensionContext, wake: Wake) {
95
+ clearTimer();
96
+ commit(ctx, { wake });
97
+ schedule(ctx);
98
+ }
99
+ function restoreBranch(ctx: ExtensionContext) {
100
+ clearTimer();
101
+ state = restore(ctx.sessionManager.getBranch());
102
+ refresh(ctx);
103
+ }
104
+
105
+ pi.on("session_start", (_event, ctx) => restoreBranch(ctx));
106
+ pi.on("session_tree", (_event, ctx) => restoreBranch(ctx));
107
+ pi.on("session_shutdown", () => {
108
+ clearTimer();
109
+ state = { ...state, wake: stopped(state.wake) };
110
+ });
111
+ pi.on("agent_settled", (event, ctx) => {
112
+ const wake = state.wake;
113
+ if (wake?.running && (event.aborted || wake.count >= wake.max)) stopWake(ctx);
114
+ else schedule(ctx);
115
+ });
116
+ pi.on("before_agent_start", (event) => {
117
+ const additions = systemPromptAdditions(state);
118
+ if (!additions.length) return undefined;
119
+ return { systemPrompt: [event.systemPrompt, ...additions].join("\n\n") };
120
+ });
121
+
122
+ return { state: () => state, commit, stopWake, startWake };
123
+ }
124
+ export type Session = ReturnType<typeof createSession>;
@@ -0,0 +1,46 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, rename, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
5
+
6
+ import { StringEnum } from "@earendil-works/pi-ai";
7
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
8
+ import { Type } from "typebox";
9
+
10
+ import { isRecord } from "../lib/validation.ts";
11
+
12
+ export const agentDir = () => process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
13
+ export const artifacts = (ctx: ExtensionContext) =>
14
+ join(agentDir(), "pstack", "sessions", ctx.sessionManager.getSessionId());
15
+ export const text = (value: unknown) =>
16
+ typeof value === "string" ? value : JSON.stringify(value, null, 2);
17
+ export const result = (value: unknown) => ({
18
+ content: [{ type: "text" as const, text: text(value) }],
19
+ details: undefined,
20
+ });
21
+ export const stringEnum = <const T extends readonly string[]>(values: T) =>
22
+ Type.Unsafe<T[number]>(StringEnum(values));
23
+ export function fail(message: string): never {
24
+ throw new Error(message);
25
+ }
26
+ export function unreachable(value: never): never {
27
+ throw new Error(`Unhandled case: ${String(value)}`);
28
+ }
29
+ export const hasErrorCode = (error: unknown, code: string) =>
30
+ isRecord(error) && error.code === code;
31
+ export async function atomicWrite(path: string, data: string) {
32
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
33
+ const temporary = `${path}.${randomUUID()}.tmp`;
34
+ await writeFile(temporary, data, { mode: 0o600, flag: "wx" });
35
+ await rename(temporary, path);
36
+ }
37
+ export function tsvRow(values: unknown[]) {
38
+ return values.map((v) => String(v).replaceAll(/[\t\r\n]/g, " ")).join("\t") + "\n";
39
+ }
40
+ export type Notify = (ctx: ExtensionContext, message: string) => void;
41
+ export const notifier =
42
+ (pi: ExtensionAPI): Notify =>
43
+ (ctx, message) => {
44
+ if (ctx.hasUI) ctx.ui.notify(message, "info");
45
+ else pi.sendMessage({ customType: "pstack-output", content: message, display: true });
46
+ };
@@ -0,0 +1,188 @@
1
+ import { mkdir, realpath } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+
4
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import { Type } from "typebox";
6
+
7
+ import { pool } from "../lib/pool.ts";
8
+ import { gitIn, type Git } from "./git.ts";
9
+ import { artifacts, fail, hasErrorCode, result, stringEnum } from "./support.ts";
10
+
11
+ export interface Worktree {
12
+ path: string;
13
+ head?: string;
14
+ branch?: string;
15
+ locked: boolean;
16
+ prunable: boolean;
17
+ bare: boolean;
18
+ }
19
+ export function parseWorktrees(porcelain: string): Worktree[] {
20
+ const separator = porcelain.includes("\0") ? "\0" : "\n";
21
+ return porcelain
22
+ .split(separator.repeat(2))
23
+ .filter(Boolean)
24
+ .map((block) => {
25
+ const fields = new Map(
26
+ block
27
+ .split(separator)
28
+ .filter(Boolean)
29
+ .map((line): [string, string] => {
30
+ const i = line.indexOf(" ");
31
+ return i < 0 ? [line, ""] : [line.slice(0, i), line.slice(i + 1)];
32
+ }),
33
+ );
34
+ return {
35
+ path: fields.get("worktree") ?? "",
36
+ head: fields.get("HEAD"),
37
+ branch: fields.get("branch"),
38
+ locked: fields.has("locked"),
39
+ prunable: fields.has("prunable"),
40
+ bare: fields.has("bare"),
41
+ };
42
+ });
43
+ }
44
+
45
+ function ancestry(exitCode: number | undefined) {
46
+ if (exitCode === 0) return true;
47
+ if (exitCode === 1) return false;
48
+ return null;
49
+ }
50
+
51
+ const validName = (name: string) => /^[a-z0-9][a-z0-9-]{0,48}$/.test(name);
52
+
53
+ async function commit(git: Git, ref: string) {
54
+ if (ref.startsWith("-")) fail("Invalid base ref");
55
+ return (await git.run(["rev-parse", "--verify", `${ref}^{commit}`])).trim();
56
+ }
57
+ async function targetBranch(git: Git, ref: string) {
58
+ if (ref.startsWith("-")) fail("Invalid base ref");
59
+ const name = (await git.run(["rev-parse", "--verify", "--symbolic-full-name", ref])).trim();
60
+ if (!/^refs\/(heads|remotes)\//.test(name)) fail("Merged target must be a branch");
61
+ return name;
62
+ }
63
+ const list = async (git: Git) =>
64
+ parseWorktrees(await git.run(["worktree", "list", "--porcelain", "-z"]));
65
+ const status = (git: Git, tree: string) =>
66
+ git.run(["status", "--porcelain", "--untracked-files=all", "--ignore-submodules=none"], tree);
67
+ async function ignoredPaths(git: Git, tree: string) {
68
+ const args = ["ls-files", "--others", "--ignored", "--exclude-standard", "-z"];
69
+ return (await git.run(args, tree)).split("\0").filter(Boolean);
70
+ }
71
+
72
+ export async function createWorktree(git: Git, ctx: ExtensionContext, name: string, ref = "HEAD") {
73
+ if (!validName(name)) fail("Invalid worktree name");
74
+ const base = await commit(git, ref);
75
+ const requested = join(artifacts(ctx), "worktrees", name);
76
+ await mkdir(dirname(requested), { recursive: true, mode: 0o700 });
77
+ const path = join(await realpath(dirname(requested)), name);
78
+ await git.run(["worktree", "add", "--detach", path, base]);
79
+ return { path, base };
80
+ }
81
+
82
+ async function audit(git: Git, ref: string, active: ReadonlySet<string>) {
83
+ const trees = await list(git);
84
+ const base = await commit(git, ref);
85
+ return pool(trees, 4, async (tree) => {
86
+ const inspectable = !tree.bare && !tree.prunable;
87
+ const dirty = inspectable ? !!(await status(git, tree.path)) : null;
88
+ const ignored = inspectable ? (await ignoredPaths(git, tree.path)).length : null;
89
+ const ancestor = tree.head
90
+ ? await git.probe(["merge-base", "--is-ancestor", tree.head, base])
91
+ : undefined;
92
+ return {
93
+ ...tree,
94
+ dirty,
95
+ ignored,
96
+ merged: ancestry(ancestor?.code),
97
+ activeWorker: active.has(tree.path),
98
+ base,
99
+ ownership: "Confirm active or pinned Pi sessions before removal",
100
+ };
101
+ });
102
+ }
103
+
104
+ function assertRemovable(
105
+ tree: Worktree | undefined,
106
+ path: string,
107
+ active: ReadonlySet<string>,
108
+ ): asserts tree is Worktree & { head: string } {
109
+ if (!tree?.head || tree.branch || tree.locked || tree.prunable || tree.bare || active.has(path)) {
110
+ fail("Not a removable inactive package-owned detached tree");
111
+ }
112
+ }
113
+
114
+ function removalPrompt(ignored: string[]) {
115
+ if (!ignored.length) return { title: "Remove clean merged worktree?", loss: "" };
116
+ const shown = ignored.slice(0, 10).join("\n");
117
+ const more = ignored.length > 10 ? `\n… and ${ignored.length - 10} more` : "";
118
+ return {
119
+ title: "Remove merged worktree and its ignored files?",
120
+ loss: `\nThis permanently deletes ${ignored.length} ignored path(s) Git does not track:\n${shown}${more}`,
121
+ };
122
+ }
123
+
124
+ async function removeWorktree(
125
+ git: Git,
126
+ ctx: ExtensionContext,
127
+ name: string,
128
+ ref: string | undefined,
129
+ active: ReadonlySet<string>,
130
+ ) {
131
+ if (!validName(name)) fail("Invalid name");
132
+ if (!ctx.hasUI) fail("Removal not authorized without an interactive Pi UI");
133
+ if (!ref) fail("Specify merged target ref");
134
+ const directory = await realpath(join(artifacts(ctx), "worktrees")).catch((error: unknown) => {
135
+ if (hasErrorCode(error, "ENOENT")) fail("No package-owned worktrees in this session");
136
+ throw error;
137
+ });
138
+ const path = join(directory, name);
139
+ async function inspect() {
140
+ const tree = (await list(git)).find((entry) => entry.path === path);
141
+ assertRemovable(tree, path, active);
142
+ if (await status(git, path)) fail("Worktree has uncommitted changes");
143
+ return { head: tree.head, ignored: await ignoredPaths(git, path) };
144
+ }
145
+ const target = await targetBranch(git, ref);
146
+ const base = await commit(git, target);
147
+ const { head, ignored } = await inspect();
148
+ await git.run(["merge-base", "--is-ancestor", head, base]);
149
+ const { title, loss } = removalPrompt(ignored);
150
+ const approved = await ctx.ui.confirm(
151
+ title,
152
+ `${path}\nHEAD ${head} is merged into ${target} (${base}).${loss}\nConfirm no active or pinned session uses this path.`,
153
+ );
154
+ if (!approved) fail("Removal not authorized");
155
+ const after = await inspect();
156
+ if (
157
+ after.head !== head ||
158
+ after.ignored.join("\0") !== ignored.join("\0") ||
159
+ (await commit(git, target)) !== base ||
160
+ active.has(path)
161
+ ) {
162
+ fail("Worktree or target ref changed after approval");
163
+ }
164
+ await git.run(["worktree", "remove", path]);
165
+ return { removed: path };
166
+ }
167
+
168
+ export function registerWorktrees(pi: ExtensionAPI, active: ReadonlySet<string>) {
169
+ pi.registerTool({
170
+ name: "pstack_worktree",
171
+ label: "Pstack worktree",
172
+ description:
173
+ "Audit Git worktrees or create a new detached isolated worktree from HEAD. Audit reports ignored paths. Removal requires explicit user approval and a clean package-owned detached tree merged into a branch; the approval lists ignored files that would be deleted.",
174
+ executionMode: "sequential",
175
+ parameters: Type.Object({
176
+ action: stringEnum(["audit", "create", "remove"]),
177
+ name: Type.Optional(Type.String()),
178
+ base: Type.Optional(Type.String()),
179
+ }),
180
+ async execute(_id, p, signal, _update, ctx) {
181
+ const git = gitIn(pi, ctx.cwd, signal);
182
+ if (p.action === "create")
183
+ return result(await createWorktree(git, ctx, p.name ?? "", p.base));
184
+ if (p.action === "audit") return result(await audit(git, p.base ?? "HEAD", active));
185
+ return result(await removeWorktree(git, ctx, p.name ?? "", p.base, active));
186
+ },
187
+ });
188
+ }