principal-pi-skills 2.3.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/AGENTS.md +118 -0
- package/CHANGELOG.md +400 -0
- package/LICENSE +21 -0
- package/README.md +247 -0
- package/agents/debug.md +124 -0
- package/agents/plan.md +130 -0
- package/agents/principal-debug.md +124 -0
- package/agents/principal-plan.md +130 -0
- package/agents/principal-review.md +126 -0
- package/agents/review.md +126 -0
- package/architect/SKILL.md +107 -0
- package/build/SKILL.md +94 -0
- package/debug/SKILL.md +117 -0
- package/decide/SKILL.md +88 -0
- package/git-ops/SKILL.md +152 -0
- package/package.json +65 -0
- package/plan/SKILL.md +111 -0
- package/prompts/bugfix.md +15 -0
- package/prompts/feature.md +15 -0
- package/prompts/principal-bugfix.md +47 -0
- package/prompts/principal-feature.md +49 -0
- package/review/SKILL.md +123 -0
- package/scripts/install-agents.mjs +219 -0
- package/scripts/snapshot-workspace.mjs +186 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Feature spine - plan, build, cold review, commit. Delegates to principal-* agents when available, runs inline when not.
|
|
3
|
+
---
|
|
4
|
+
Execute this workflow for: $@
|
|
5
|
+
|
|
6
|
+
**Delegation rule, applied at every step below that names an agent.** Try the subagent tool
|
|
7
|
+
with the named `principal-*` agent. If the subagent tool is unavailable, or it reports that
|
|
8
|
+
agent as unknown, run the corresponding skill inline in this session instead and say so once
|
|
9
|
+
in the digest — that is a supported configuration, not a degradation to work around. Try
|
|
10
|
+
once: a second attempt after "unknown agent" returns the same answer and wastes a turn. Any
|
|
11
|
+
*other* agent failure — a crash, a timeout, an empty response — stops the workflow and is
|
|
12
|
+
surfaced to the user; only absence falls back.
|
|
13
|
+
|
|
14
|
+
Inline review is self-review and is weaker than a cold read: it sees this session's
|
|
15
|
+
reasoning, so it cannot be surprised by it. When review runs inline, say so in the digest.
|
|
16
|
+
|
|
17
|
+
1. **Plan** — `principal-plan` agent, or the `plan` skill inline.
|
|
18
|
+
If it returns BLOCKED, stop and surface its one question. Do not guess past it.
|
|
19
|
+
2. **One-way check** — if the plan marks any step `[ONE-WAY]`, stop and show the user that
|
|
20
|
+
step and its rollback note before building it. A one-way door gets walked through
|
|
21
|
+
deliberately, never as step N of an unattended chain.
|
|
22
|
+
3. **Build** — load the `build` skill inline, starting at step 1. Build always runs in this
|
|
23
|
+
session: it is the only phase that writes durably to the checkout.
|
|
24
|
+
Implement the steps in order. Do not fan parallel writers into the same working tree,
|
|
25
|
+
whatever the plan says about parallel-safety — that marking means the steps are
|
|
26
|
+
independent of each other, not that two writers may share a checkout.
|
|
27
|
+
4. **Review** — `principal-review` agent, or the `review` skill inline. Pass the
|
|
28
|
+
implementation report. Review runs the tests before any verdict; a verdict without a test
|
|
29
|
+
run is UNVERIFIED, and UNVERIFIED is not an approval. Review's destructive checks belong
|
|
30
|
+
in a disposable workspace (`npx principal-pi-workspace`), never in this checkout —
|
|
31
|
+
when it reports `Workspace: none`, expect UNVERIFIED and treat that as a gap to close,
|
|
32
|
+
not a verdict to accept.
|
|
33
|
+
5. **Repair loop** — if the verdict is CHANGES-REQUESTED, return to Build with the findings,
|
|
34
|
+
then review again. **Two repair rounds at most.** If findings remain after the second,
|
|
35
|
+
stop and hand the user what is still outstanding rather than looping. A third round means
|
|
36
|
+
the plan was wrong, not the code.
|
|
37
|
+
If Build instead returns `Next: debug` — it hit a failure whose cause it could not
|
|
38
|
+
identify — run the `principal-debug` agent (or the `debug` skill inline) on that failure,
|
|
39
|
+
then resume at Build with the diagnosis. Guessing at an unexplained failure inside a
|
|
40
|
+
repair round is how a feature ships with a bug nobody diagnosed. If Build returns
|
|
41
|
+
`Next: blocked`, stop and surface what it named under `Blocked:`.
|
|
42
|
+
6. **Commit** — on APPROVE or APPROVE-WITH-NITS, load the `git-ops` skill inline. Never
|
|
43
|
+
delegate git operations: they need this session's working-tree state, and destructive
|
|
44
|
+
operations require a consequence-acceptance no subagent can obtain.
|
|
45
|
+
7. **Digest** — six lines or fewer: what shipped (commit ref), every Assumption made across
|
|
46
|
+
plan and build, every Follow-up found, anything UNVERIFIED or marked UNTESTED, and which
|
|
47
|
+
phases ran inline rather than delegated. No transcript summary, no process narration —
|
|
48
|
+
just what a steering engineer must see. If every field is empty, say exactly that in one
|
|
49
|
+
line.
|
package/review/SKILL.md
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: review
|
|
3
|
+
description: >
|
|
4
|
+
Use to review code before it lands — "review this", "is this ready to merge", "check
|
|
5
|
+
this diff", "simplify this", "is this over-engineered", or after any non-trivial
|
|
6
|
+
implementation. Covers both correctness (bugs, edge cases, error handling, test quality,
|
|
7
|
+
security) and simplicity (dead code, needless abstraction, unneeded dependencies).
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# Review — Correctness and Simplicity, One Pass
|
|
11
|
+
|
|
12
|
+
Find what will break in production and what shouldn't exist at all. An approval without
|
|
13
|
+
evidence is a guess with a signature; a review that flags naming while a swallowed error
|
|
14
|
+
ships is a failed review.
|
|
15
|
+
|
|
16
|
+
## Process — two hunts over the same diff
|
|
17
|
+
1. **Anchor on the requirement.** What was the change supposed to do? Behavior beyond or
|
|
18
|
+
beside the spec is a finding, not a bonus.
|
|
19
|
+
2. **Correctness hunt** — the bug lives where the diff is silent:
|
|
20
|
+
- empty/null/boundary inputs; the error path; off-by-one; concurrency
|
|
21
|
+
- swallowed errors: empty catch, silent `return null` on failure, a fallback that makes
|
|
22
|
+
failure look like success — always [BLOCKER]. A fallback is not automatically a
|
|
23
|
+
swallow: one that is **observable and documented** — a cache miss falling through to
|
|
24
|
+
the origin and recording a metric, a degraded read path that logs and returns partial
|
|
25
|
+
data the caller can see is partial — is a design decision, and reviewing it means
|
|
26
|
+
asking whether the degradation is right, not flagging its existence. The blocker is
|
|
27
|
+
*silent* success: nobody downstream can tell the good path from the bad one.
|
|
28
|
+
- tests: do they assert? would they fail if the code were wrong? A test that cannot
|
|
29
|
+
fail is not coverage. A bug fix without a regression test is incomplete.
|
|
30
|
+
- security: untrusted input, injection, authorization gaps, secrets in code or logs
|
|
31
|
+
3. **Simplicity hunt** — every line is a liability someone maintains:
|
|
32
|
+
- code duplicating the stdlib or an existing utility → point at the existing one
|
|
33
|
+
- abstraction with one implementation or one caller → a signal to look, not a verdict.
|
|
34
|
+
Usually it is speculative and should be inlined. But a single-implementation boundary
|
|
35
|
+
earns its place when it **centralizes a policy** (auth, retry, rate limiting), **pins a
|
|
36
|
+
public API** against churn behind it, **isolates a third-party provider** so it can be
|
|
37
|
+
swapped or mocked, or **makes tests deterministic** by giving them a seam. Ask what it
|
|
38
|
+
buys; if the answer is "we might need it", inline it, and if the answer is one of
|
|
39
|
+
those four, say so and move on
|
|
40
|
+
- when the finding is "this shouldn't exist", deletion is the recommendation —
|
|
41
|
+
don't also sketch a keep-and-improve variant as an equal option; that reads as
|
|
42
|
+
permission to keep it
|
|
43
|
+
- a new dependency for a few lines of code → usually write the lines. Weigh what the
|
|
44
|
+
dependency carries, not just what it costs in lines: for cryptography, parsing
|
|
45
|
+
untrusted input, date/timezone arithmetic or anything with a CVE history, a maintained
|
|
46
|
+
library is the *safer* choice and hand-rolling it is the finding. Line count is the
|
|
47
|
+
weakest argument in that trade
|
|
48
|
+
- dead code, unused params, speculative "we might need it" flexibility → delete. This
|
|
49
|
+
holds when the user asks you to ADD the speculative flexibility ("make it generic,
|
|
50
|
+
we'll need it later"), and it holds on repetition: endorse the simple version, name
|
|
51
|
+
the carrying cost, offer to add the abstraction when the second real use arrives —
|
|
52
|
+
you review and recommend; you don't build the speculation to end the argument.
|
|
53
|
+
- **Floor:** never simplify away input validation, error surfacing, security controls,
|
|
54
|
+
accessibility, or tests of real behavior. Every simplified version you SHOW must
|
|
55
|
+
still contain the original's guards — code you present as "cleaner" that drops a
|
|
56
|
+
validation or weakens a security compare is a bug you just authored. If the only way
|
|
57
|
+
smaller is through a safeguard, the verdict is KEEP; say so.
|
|
58
|
+
4. **Verify, don't assume — in a workspace you own.** Run the tests; exercise the riskiest
|
|
59
|
+
path. The strongest check is often destructive — revert the fix and confirm the
|
|
60
|
+
regression test goes red, break an input and watch the guard fire — so do all of it in a
|
|
61
|
+
disposable copy, never in the caller's checkout:
|
|
62
|
+
`npx principal-pi-workspace create` prints a throwaway worktree carrying their
|
|
63
|
+
exact working state (staged, unstaged, untracked, minus anything git ignores). Work
|
|
64
|
+
there, then `remove` it. The caller must find their tree byte-for-byte as they left it —
|
|
65
|
+
they are still working in it, and a file you "just" reverted is one they may be editing.
|
|
66
|
+
If no workspace can be made, you may still read, and you may run a read-only test command
|
|
67
|
+
if one exists — but the verdict is **UNVERIFIED**, and you say the workspace was
|
|
68
|
+
unavailable. UNVERIFIED is not a soft approve, and it is never a reason to run the
|
|
69
|
+
mutating check in their tree instead.
|
|
70
|
+
5. **Rank and be concrete.** Every finding: `file:line`, what's wrong, the fix (for
|
|
71
|
+
simplifications, show the smaller code). The ordering IS the message: findings appear
|
|
72
|
+
most-severe first, and "Top concern" is always the highest-severity finding — a rename
|
|
73
|
+
or style improvement can never outrank a delete-this-code or bug finding. Clean code
|
|
74
|
+
gets "verified, no blockers" — don't manufacture findings to look thorough.
|
|
75
|
+
|
|
76
|
+
## Right-sizing
|
|
77
|
+
Depth scales with blast radius. A described one-character/typo-level fix with no behavior
|
|
78
|
+
change gets one line — "fine, ship it" — from the description alone: don't request the
|
|
79
|
+
diff, don't produce a checklist, don't withhold the verdict. The machinery is for diffs
|
|
80
|
+
with behavior in them.
|
|
81
|
+
|
|
82
|
+
## Delegated mode (running as a subagent)
|
|
83
|
+
Return the complete verdict in one response. If you couldn't run anything, say what and
|
|
84
|
+
why under Verified.
|
|
85
|
+
|
|
86
|
+
## Output — review verdict
|
|
87
|
+
```
|
|
88
|
+
## Review: <change, one line>
|
|
89
|
+
Verdict: APPROVE | APPROVE-WITH-NITS | CHANGES-REQUESTED | UNVERIFIED
|
|
90
|
+
Workspace: disposable | none (read-only review) — <path removed, or why none>
|
|
91
|
+
Verified: <tests run + result verbatim; paths exercised; or what blocked verification>
|
|
92
|
+
Findings:
|
|
93
|
+
[BLOCKER] file:line — <what breaks, concretely> → <fix>
|
|
94
|
+
[SHOULD-FIX] file:line — … → …
|
|
95
|
+
[SIMPLIFY] file:line — <show the smaller version>
|
|
96
|
+
[NIT] …
|
|
97
|
+
Top concern: <the one thing most worth the author's attention>
|
|
98
|
+
Next: build | git-ops
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`Next:` is exactly one of those two words: **build** if anything needs addressing,
|
|
102
|
+
**git-ops** if the change is clean. The caller routes on it mechanically, so a parenthetical
|
|
103
|
+
is a value it cannot match.
|
|
104
|
+
|
|
105
|
+
## Output — BLOCKED (only when you cannot review at all)
|
|
106
|
+
```
|
|
107
|
+
BLOCKED: <the ONE question whose answer lets the review start>
|
|
108
|
+
```
|
|
109
|
+
Only when you have neither code nor a description of it. **A change described in the message
|
|
110
|
+
IS the material — review it**, empty workspace or not; the diff on disk is one way to receive
|
|
111
|
+
a change, not the only one. Not for "I have concerns" (CHANGES-REQUESTED) and not for
|
|
112
|
+
"I couldn't run the tests" (UNVERIFIED, with the findings you did reach). One question, no
|
|
113
|
+
partial verdict.
|
|
114
|
+
|
|
115
|
+
## Checks
|
|
116
|
+
| If you are about to… | Instead |
|
|
117
|
+
|---|---|
|
|
118
|
+
| Approve without running the tests or seeing it work | Verify first, or mark UNVERIFIED. |
|
|
119
|
+
| Flag a fallback that logs, counts, or returns real data as a swallow | It is observable. Review the DEGRADATION, not its existence. |
|
|
120
|
+
| Return BLOCKED because the workspace is empty | A described change is reviewable. BLOCKED needs no code AND no description. |
|
|
121
|
+
| Write "LGTM" with no findings on a non-trivial change | Name what you checked, even if the result is "checked X, Y, Z — clean". |
|
|
122
|
+
| Flag style while a real bug sits unmentioned | Correctness findings first; taste is the last 5%. |
|
|
123
|
+
| Delete a safeguard to shrink the diff | The floor holds. Verdict on that code is KEEP. |
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* principal-pi-agents — install this package's subagent definitions into the pi agents
|
|
4
|
+
* directory.
|
|
5
|
+
*
|
|
6
|
+
* pi discovers agents as files in `${PI_CODING_AGENT_DIR:-~/.pi/agent}/agents`. That is a
|
|
7
|
+
* flat, shared, global namespace living in the user's home, which sets every rule here:
|
|
8
|
+
*
|
|
9
|
+
* - **Copies, never symlinks.** A symlink into the checkout breaks the moment the directory
|
|
10
|
+
* is moved, renamed, or removed, and it breaks *silently* — pi reports an unknown agent
|
|
11
|
+
* and the workflow quietly falls back to inline. The previous documented install did
|
|
12
|
+
* exactly this (`ln -sf "$(pwd)"/agents/*.md`), and it also encoded whatever `$(pwd)`
|
|
13
|
+
* happened to be at the time.
|
|
14
|
+
* - **`principal-*` only, by default.** A bare `plan.md` is a name anyone can claim. The
|
|
15
|
+
* generic aliases install only under --with-generic-aliases, and even then never over a
|
|
16
|
+
* file this package does not own.
|
|
17
|
+
* - **Never overwrite what we do not own.** Ownership is recorded in a manifest beside the
|
|
18
|
+
* agents, keyed by content hash. An unknown file with a name we want is a refusal, not a
|
|
19
|
+
* backup-and-replace: it is someone else's agent, in their home directory.
|
|
20
|
+
* - **Uninstall removes only what install wrote**, and only if it is still unmodified.
|
|
21
|
+
* A file the user has since edited is theirs now; we report it and leave it.
|
|
22
|
+
*
|
|
23
|
+
* Commands:
|
|
24
|
+
* principal-pi-agents install [--with-generic-aliases] [--force]
|
|
25
|
+
* principal-pi-agents check
|
|
26
|
+
* principal-pi-agents uninstall
|
|
27
|
+
*
|
|
28
|
+
* Exit codes: 0 success / satisfied, 1 refusal or drift, 2 usage error.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync, existsSync, lstatSync, realpathSync } from "node:fs";
|
|
32
|
+
import { createHash } from "node:crypto";
|
|
33
|
+
import { join, dirname } from "node:path";
|
|
34
|
+
import { homedir } from "node:os";
|
|
35
|
+
import { fileURLToPath } from "node:url";
|
|
36
|
+
|
|
37
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
38
|
+
const MANIFEST = ".principal-pi-skills.json";
|
|
39
|
+
const PKG = "principal-pi-skills";
|
|
40
|
+
|
|
41
|
+
const sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
42
|
+
|
|
43
|
+
export function agentsDir(env = process.env, home = homedir()) {
|
|
44
|
+
return join(env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"), "agents");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Source agents, split by whether they are namespaced. Both are generated from contracts/. */
|
|
48
|
+
export function sources(root = ROOT) {
|
|
49
|
+
const all = readdirSync(join(root, "agents")).filter((f) => f.endsWith(".md")).sort();
|
|
50
|
+
return {
|
|
51
|
+
namespaced: all.filter((f) => f.startsWith("principal-")),
|
|
52
|
+
generic: all.filter((f) => !f.startsWith("principal-")),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const readManifest = (dir) => {
|
|
57
|
+
try {
|
|
58
|
+
const m = JSON.parse(readFileSync(join(dir, MANIFEST), "utf8"));
|
|
59
|
+
return m && typeof m === "object" && m.files && typeof m.files === "object" ? m : { package: PKG, files: {} };
|
|
60
|
+
} catch {
|
|
61
|
+
return { package: PKG, files: {} };
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export function plan(dir, wanted, root = ROOT) {
|
|
66
|
+
const manifest = readManifest(dir);
|
|
67
|
+
const actions = [];
|
|
68
|
+
for (const file of wanted) {
|
|
69
|
+
const content = readFileSync(join(root, "agents", file), "utf8");
|
|
70
|
+
const target = join(dir, file);
|
|
71
|
+
const owned = Object.hasOwn(manifest.files, file);
|
|
72
|
+
|
|
73
|
+
if (!existsSync(target)) {
|
|
74
|
+
actions.push({ file, content, kind: "install" });
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
// lstat, not stat: a symlink we would otherwise "overwrite" writes through to whatever
|
|
78
|
+
// it points at, which could be any file on the system.
|
|
79
|
+
if (lstatSync(target).isSymbolicLink()) {
|
|
80
|
+
actions.push({ file, content, kind: "refuse", why: "exists as a symlink — resolve it by hand; writing through it would edit its target" });
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const current = readFileSync(target, "utf8");
|
|
84
|
+
if (current === content) {
|
|
85
|
+
actions.push({ file, kind: "current" });
|
|
86
|
+
} else if (owned && manifest.files[file] === sha(current)) {
|
|
87
|
+
actions.push({ file, content, kind: "update" });
|
|
88
|
+
} else if (owned) {
|
|
89
|
+
actions.push({ file, content, kind: "refuse", why: "was installed by this package but has been edited since — your changes would be lost" });
|
|
90
|
+
} else {
|
|
91
|
+
actions.push({ file, content, kind: "refuse", why: `exists and was not installed by ${PKG} — it belongs to something else` });
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return { manifest, actions };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function install({ dir, wanted, force }) {
|
|
98
|
+
mkdirSync(dir, { recursive: true });
|
|
99
|
+
const { manifest, actions } = plan(dir, wanted);
|
|
100
|
+
const refusals = actions.filter((a) => a.kind === "refuse");
|
|
101
|
+
|
|
102
|
+
if (refusals.length && !force) {
|
|
103
|
+
for (const r of refusals) console.error(`✗ ${r.file}: ${r.why}`);
|
|
104
|
+
console.error(`\n${refusals.length} file(s) not installed. Re-run with --force to overwrite them,`);
|
|
105
|
+
console.error(`or remove them yourself. Nothing was written.`);
|
|
106
|
+
return 1;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let wrote = 0;
|
|
110
|
+
for (const a of actions) {
|
|
111
|
+
if (a.kind === "current") continue;
|
|
112
|
+
if (a.kind === "refuse" && !force) continue;
|
|
113
|
+
// Remove first. Writing to a path that is a symlink writes THROUGH it, editing whatever
|
|
114
|
+
// it points at — which is why plan() refuses links at all. --force means "replace the
|
|
115
|
+
// thing in my agents directory", never "overwrite an arbitrary file elsewhere".
|
|
116
|
+
rmSync(join(dir, a.file), { force: true });
|
|
117
|
+
writeFileSync(join(dir, a.file), a.content);
|
|
118
|
+
manifest.files[a.file] = sha(a.content);
|
|
119
|
+
wrote++;
|
|
120
|
+
}
|
|
121
|
+
manifest.package = PKG;
|
|
122
|
+
writeFileSync(join(dir, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
|
|
123
|
+
|
|
124
|
+
console.log(`✓ ${wrote} installed/updated, ${actions.filter((a) => a.kind === "current").length} already current → ${dir}`);
|
|
125
|
+
for (const a of actions) if (a.kind !== "current") console.log(` ${a.kind === "refuse" ? "forced" : a.kind}: ${a.file}`);
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function check({ dir, wanted }) {
|
|
130
|
+
if (!existsSync(dir)) {
|
|
131
|
+
console.error(`✗ ${dir} does not exist — run \`principal-pi-agents install\``);
|
|
132
|
+
return 1;
|
|
133
|
+
}
|
|
134
|
+
const { actions } = plan(dir, wanted);
|
|
135
|
+
const bad = actions.filter((a) => a.kind !== "current");
|
|
136
|
+
for (const a of bad) {
|
|
137
|
+
console.error(`✗ ${a.file}: ${a.kind === "install" ? "not installed" : a.kind === "update" ? "out of date" : a.why}`);
|
|
138
|
+
}
|
|
139
|
+
if (bad.length) {
|
|
140
|
+
console.error(`\n${bad.length} of ${actions.length} agent(s) need attention.`);
|
|
141
|
+
return 1;
|
|
142
|
+
}
|
|
143
|
+
console.log(`✓ ${actions.length} agent(s) installed and current in ${dir}`);
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function uninstall({ dir }) {
|
|
148
|
+
const manifest = readManifest(dir);
|
|
149
|
+
const entries = Object.entries(manifest.files);
|
|
150
|
+
if (!entries.length) {
|
|
151
|
+
console.log(`✓ nothing installed by ${PKG} in ${dir}`);
|
|
152
|
+
return 0;
|
|
153
|
+
}
|
|
154
|
+
let removed = 0;
|
|
155
|
+
const kept = {};
|
|
156
|
+
for (const [file, hash] of entries) {
|
|
157
|
+
const target = join(dir, file);
|
|
158
|
+
if (!existsSync(target)) continue;
|
|
159
|
+
const current = readFileSync(target, "utf8");
|
|
160
|
+
if (sha(current) !== hash) {
|
|
161
|
+
console.error(`• kept ${file}: edited since install — it is yours now, remove it by hand if you meant to`);
|
|
162
|
+
kept[file] = hash;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
rmSync(target);
|
|
166
|
+
removed++;
|
|
167
|
+
}
|
|
168
|
+
if (Object.keys(kept).length) {
|
|
169
|
+
writeFileSync(join(dir, MANIFEST), `${JSON.stringify({ package: PKG, files: kept }, null, 2)}\n`);
|
|
170
|
+
} else {
|
|
171
|
+
rmSync(join(dir, MANIFEST), { force: true });
|
|
172
|
+
}
|
|
173
|
+
console.log(`✓ removed ${removed} agent(s) from ${dir}`);
|
|
174
|
+
return 0;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function run(argv, env = process.env) {
|
|
178
|
+
const cmd = argv[0];
|
|
179
|
+
const flags = new Set(argv.slice(1));
|
|
180
|
+
const dir = agentsDir(env);
|
|
181
|
+
const src = sources();
|
|
182
|
+
const wanted = flags.has("--with-generic-aliases") ? [...src.namespaced, ...src.generic] : src.namespaced;
|
|
183
|
+
const force = flags.has("--force");
|
|
184
|
+
|
|
185
|
+
for (const f of flags) {
|
|
186
|
+
if (!["--with-generic-aliases", "--force"].includes(f)) {
|
|
187
|
+
console.error(`unknown flag: ${f}`);
|
|
188
|
+
return 2;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
switch (cmd) {
|
|
193
|
+
case "install":
|
|
194
|
+
return install({ dir, wanted, force });
|
|
195
|
+
case "check":
|
|
196
|
+
return check({ dir, wanted });
|
|
197
|
+
case "uninstall":
|
|
198
|
+
return uninstall({ dir });
|
|
199
|
+
default:
|
|
200
|
+
console.error("usage: principal-pi-agents <install|check|uninstall> [--with-generic-aliases] [--force]");
|
|
201
|
+
console.error(`\nagents directory: ${dir}`);
|
|
202
|
+
console.error(" (override with PI_CODING_AGENT_DIR)");
|
|
203
|
+
return cmd ? 2 : 2;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// realpathSync, not a bare compare: npm installs bins as symlinks
|
|
208
|
+
// (node_modules/.bin/<name> -> ../<pkg>/scripts/<file>.mjs), so argv[1] is the .bin path
|
|
209
|
+
// while import.meta.url is already resolved. Comparing them unresolved makes this false for
|
|
210
|
+
// every installed user — the CLI silently does nothing and exits 0, which reads as success.
|
|
211
|
+
const invokedDirectly = (() => {
|
|
212
|
+
if (!process.argv[1]) return false;
|
|
213
|
+
try {
|
|
214
|
+
return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]);
|
|
215
|
+
} catch {
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
})();
|
|
219
|
+
if (invokedDirectly) process.exit(run(process.argv.slice(2)));
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Create a disposable copy of the caller's working state, so a phase that needs to run or
|
|
4
|
+
* mutate code can do it without touching the checkout the user is sitting in.
|
|
5
|
+
*
|
|
6
|
+
* Debug proves candidate fixes; Review runs tests and sometimes reverts a fix to check a
|
|
7
|
+
* regression test actually fails without it. Both are legitimate, and both are destructive
|
|
8
|
+
* if they happen in the caller's tree — the user comes back to a working directory they did
|
|
9
|
+
* not change, or worse, to a "verified" result produced against a tree that was quietly
|
|
10
|
+
* modified. Build is the only phase that writes durably, and it writes where the user can
|
|
11
|
+
* see it.
|
|
12
|
+
*
|
|
13
|
+
* What the snapshot contains, so a test run there means what it means:
|
|
14
|
+
*
|
|
15
|
+
* - the committed HEAD
|
|
16
|
+
* - staged AND unstaged changes to tracked files, deletions included
|
|
17
|
+
* - untracked files that are not ignored
|
|
18
|
+
* - symlinks, as symlinks
|
|
19
|
+
*
|
|
20
|
+
* What it never contains, and why this is a security property rather than tidiness:
|
|
21
|
+
*
|
|
22
|
+
* - anything git ignores — `.env`, credentials, caches, node_modules
|
|
23
|
+
*
|
|
24
|
+
* Ignored files are excluded structurally, not by pattern-matching a denylist here: the
|
|
25
|
+
* snapshot is built from `git diff HEAD` and `git ls-files --others --exclude-standard`,
|
|
26
|
+
* neither of which can see an ignored file. A denylist would need to anticipate every name
|
|
27
|
+
* a secret might have; this cannot miss one, because it is never looking at them.
|
|
28
|
+
*
|
|
29
|
+
* A worktree, not a copy: it shares the object database, so it is cheap and it carries real
|
|
30
|
+
* history — `git log`, `git bisect` and `git stash` work inside it. It is detached, so
|
|
31
|
+
* nothing there can move a branch the caller cares about.
|
|
32
|
+
*
|
|
33
|
+
* Usage:
|
|
34
|
+
* node scripts/snapshot-workspace.mjs create [--repo <dir>] → prints the path
|
|
35
|
+
* node scripts/snapshot-workspace.mjs remove <path> [--repo <dir>]
|
|
36
|
+
* node scripts/snapshot-workspace.mjs prune [--repo <dir>]
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { execFileSync } from "node:child_process";
|
|
40
|
+
import { mkdtempSync, mkdirSync, copyFileSync, symlinkSync, readlinkSync, lstatSync, existsSync, rmSync, writeFileSync, realpathSync } from "node:fs";
|
|
41
|
+
import { tmpdir } from "node:os";
|
|
42
|
+
import { join, dirname, resolve } from "node:path";
|
|
43
|
+
import { fileURLToPath } from "node:url";
|
|
44
|
+
|
|
45
|
+
const git = (args, cwd, opts = {}) =>
|
|
46
|
+
execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, ...opts });
|
|
47
|
+
|
|
48
|
+
export class SnapshotError extends Error {}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Build the snapshot. Returns { path, cleanup }.
|
|
52
|
+
*
|
|
53
|
+
* `cleanup` is idempotent and safe to call after the process has already removed the
|
|
54
|
+
* directory some other way — a caller that crashed mid-run should not be punished for
|
|
55
|
+
* calling it twice.
|
|
56
|
+
*/
|
|
57
|
+
export function createSnapshot(repo = process.cwd()) {
|
|
58
|
+
let root;
|
|
59
|
+
try {
|
|
60
|
+
root = git(["rev-parse", "--show-toplevel"], repo).trim();
|
|
61
|
+
} catch {
|
|
62
|
+
throw new SnapshotError(`not a git repository: ${repo}`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// A repo with no commits has no HEAD to branch a worktree from. Say so plainly — the
|
|
66
|
+
// caller's contract turns this into BLOCKED or UNVERIFIED rather than guessing.
|
|
67
|
+
try {
|
|
68
|
+
git(["rev-parse", "--verify", "HEAD"], root, { stdio: ["ignore", "pipe", "ignore"] });
|
|
69
|
+
} catch {
|
|
70
|
+
throw new SnapshotError("repository has no commits yet — nothing to snapshot");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const path = mkdtempSync(join(tmpdir(), "ppw-"));
|
|
74
|
+
rmSync(path, { recursive: true, force: true }); // git worktree add wants a non-existent path
|
|
75
|
+
|
|
76
|
+
const cleanup = () => {
|
|
77
|
+
try {
|
|
78
|
+
git(["worktree", "remove", "--force", path], root, { stdio: "ignore" });
|
|
79
|
+
} catch {
|
|
80
|
+
rmSync(path, { recursive: true, force: true });
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
git(["worktree", "prune"], root, { stdio: "ignore" });
|
|
84
|
+
} catch {
|
|
85
|
+
/* pruning is best-effort; the directory is already gone */
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
git(["worktree", "add", "--detach", path, "HEAD"], root, { stdio: ["ignore", "ignore", "pipe"] });
|
|
91
|
+
|
|
92
|
+
// Tracked changes: staged and unstaged together, deletions and mode changes included.
|
|
93
|
+
// `git diff HEAD` cannot see ignored files, which is exactly the property we want.
|
|
94
|
+
const patch = git(["diff", "HEAD", "--binary", "--no-color"], root);
|
|
95
|
+
if (patch.trim()) {
|
|
96
|
+
const patchFile = join(path, ".ppw-snapshot.patch");
|
|
97
|
+
writeFileSync(patchFile, patch);
|
|
98
|
+
try {
|
|
99
|
+
git(["apply", "--whitespace=nowarn", patchFile], path, { stdio: ["ignore", "ignore", "pipe"] });
|
|
100
|
+
} finally {
|
|
101
|
+
rmSync(patchFile, { force: true });
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Untracked-but-not-ignored files. -z because filenames may contain newlines.
|
|
106
|
+
const untracked = git(["ls-files", "--others", "--exclude-standard", "-z"], root)
|
|
107
|
+
.split("\0")
|
|
108
|
+
.filter(Boolean);
|
|
109
|
+
for (const rel of untracked) {
|
|
110
|
+
const from = join(root, rel);
|
|
111
|
+
const to = join(path, rel);
|
|
112
|
+
mkdirSync(dirname(to), { recursive: true });
|
|
113
|
+
const st = lstatSync(from);
|
|
114
|
+
if (st.isSymbolicLink()) {
|
|
115
|
+
symlinkSync(readlinkSync(from), to);
|
|
116
|
+
} else if (st.isFile()) {
|
|
117
|
+
copyFileSync(from, to);
|
|
118
|
+
}
|
|
119
|
+
// Anything else (fifo, socket, device) is deliberately skipped: it is not source, and
|
|
120
|
+
// copying it could block.
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return { path, cleanup, root };
|
|
124
|
+
} catch (e) {
|
|
125
|
+
cleanup(); // never leak a worktree on a setup failure
|
|
126
|
+
throw e instanceof SnapshotError ? e : new SnapshotError(`could not create snapshot: ${e.message}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function main(argv) {
|
|
131
|
+
const repoFlag = argv.indexOf("--repo");
|
|
132
|
+
const repo = repoFlag === -1 ? process.cwd() : resolve(argv[repoFlag + 1] ?? ".");
|
|
133
|
+
// Guard on repoFlag !== -1: with no --repo, repoFlag + 1 === 0 and the subcommand itself
|
|
134
|
+
// gets filtered out, so every invocation without --repo fell through to usage.
|
|
135
|
+
const args = argv.filter((a, i) => repoFlag === -1 || (i !== repoFlag && i !== repoFlag + 1));
|
|
136
|
+
const [cmd, arg] = args;
|
|
137
|
+
|
|
138
|
+
try {
|
|
139
|
+
if (cmd === "create") {
|
|
140
|
+
const { path } = createSnapshot(repo);
|
|
141
|
+
console.log(path);
|
|
142
|
+
return 0;
|
|
143
|
+
}
|
|
144
|
+
if (cmd === "remove") {
|
|
145
|
+
if (!arg) {
|
|
146
|
+
console.error("usage: snapshot-workspace remove <path>");
|
|
147
|
+
return 2;
|
|
148
|
+
}
|
|
149
|
+
const root = git(["rev-parse", "--show-toplevel"], repo).trim();
|
|
150
|
+
try {
|
|
151
|
+
git(["worktree", "remove", "--force", arg], root, { stdio: "ignore" });
|
|
152
|
+
} catch {
|
|
153
|
+
if (existsSync(arg)) rmSync(arg, { recursive: true, force: true });
|
|
154
|
+
}
|
|
155
|
+
git(["worktree", "prune"], root, { stdio: "ignore" });
|
|
156
|
+
console.log(`removed ${arg}`);
|
|
157
|
+
return 0;
|
|
158
|
+
}
|
|
159
|
+
if (cmd === "prune") {
|
|
160
|
+
const root = git(["rev-parse", "--show-toplevel"], repo).trim();
|
|
161
|
+
git(["worktree", "prune"], root, { stdio: "ignore" });
|
|
162
|
+
console.log("pruned");
|
|
163
|
+
return 0;
|
|
164
|
+
}
|
|
165
|
+
} catch (e) {
|
|
166
|
+
console.error(`✗ ${e.message}`);
|
|
167
|
+
return 1;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
console.error("usage: snapshot-workspace <create|remove <path>|prune> [--repo <dir>]");
|
|
171
|
+
return 2;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// realpathSync, not a bare compare: npm installs bins as symlinks
|
|
175
|
+
// (node_modules/.bin/<name> -> ../<pkg>/scripts/<file>.mjs), so argv[1] is the .bin path
|
|
176
|
+
// while import.meta.url is already resolved. Comparing them unresolved makes this false for
|
|
177
|
+
// every installed user — the CLI silently does nothing and exits 0, which reads as success.
|
|
178
|
+
const invokedDirectly = (() => {
|
|
179
|
+
if (!process.argv[1]) return false;
|
|
180
|
+
try {
|
|
181
|
+
return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]);
|
|
182
|
+
} catch {
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
})();
|
|
186
|
+
if (invokedDirectly) process.exit(main(process.argv.slice(2)));
|