@rob-c/pi-managed-tools 0.0.0-stage → 0.23.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/src/guard.ts ADDED
@@ -0,0 +1,437 @@
1
+ /**
2
+ * The view-correctness guard: keep the model's picture of a run honest.
3
+ *
4
+ * A stream merge (`2>&1` and friends) inside a command makes the timeline lie — stderr
5
+ * arrives tagged `[out]` — so the reflex is blocked *before* the command runs and the
6
+ * model is asked to rewrite it, rather than being told afterwards that it fooled itself.
7
+ *
8
+ * The scope is deliberately narrow: only the command's **tail** — the last two lines,
9
+ * the last ~24 characters of each — is checked. A `2>&1` deep inside a long heredoc the
10
+ * model authored is first-order scripting, left alone (the override marker exists for
11
+ * the honest tail case anyway). A rule that nags on complex scripts gets disabled by its
12
+ * users; a rule that catches `cmd >log 2>&1 &` at the point of reflex does not.
13
+ */
14
+
15
+ /** Patterns that merge the two streams inside the child, defeating the tags. */
16
+ const MERGE_PATTERNS: { pattern: RegExp; label: string }[] = [
17
+ { pattern: /2>\s*&1/, label: "2>&1" },
18
+ { pattern: /\|&/, label: "|&" },
19
+ { pattern: /(?:^|\s)&>>?/, label: "&>" },
20
+ ];
21
+
22
+ /** Declaring a merge intentional: the marker survives as a comment on any shell. */
23
+ export const OVERRIDE_MARKER = "# pitime-safe";
24
+
25
+ const TAIL_LINES = 2;
26
+ const TAIL_CHARS = 24;
27
+
28
+ /**
29
+ * The only region the guard inspects: the tail of each of the last two lines.
30
+ * `server … 2>&1 &` on the second-to-last line (before an `echo started`) is the other
31
+ * reflex shape the benchmark caught, hence two lines and not one.
32
+ */
33
+ export function tailZone(command: string): string[] {
34
+ const lines = command.replace(/\s+$/, "").split("\n");
35
+ return lines.slice(-TAIL_LINES).map((line) => line.slice(-TAIL_CHARS));
36
+ }
37
+
38
+ export interface MergeHit {
39
+ label: string;
40
+ excerpt: string;
41
+ }
42
+
43
+ /** The merge sitting at the command's tail, if there is one. */
44
+ export function detectTailMerge(command: string): MergeHit | undefined {
45
+ for (const zone of tailZone(command)) {
46
+ for (const { pattern, label } of MERGE_PATTERNS) {
47
+ const match = pattern.exec(zone);
48
+ if (match) return { label, excerpt: zone.trim() };
49
+ }
50
+ }
51
+ return undefined;
52
+ }
53
+
54
+ /** The model's explicit declaration that a merge is intentional. */
55
+ export function hasOverride(command: string): boolean {
56
+ return /(?:^|\s)#\s*pitime-safe\b/.test(command);
57
+ }
58
+
59
+ /** `PI_MANAGED_TOOLS_GUARD=off` disables the block; the notes are not affected. */
60
+ export function guardEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
61
+ const raw = (env.PI_MANAGED_TOOLS_GUARD ?? "").trim().toLowerCase();
62
+ return !(raw === "0" || raw === "off" || raw === "false" || raw === "no");
63
+ }
64
+
65
+ /** The refusal the model receives, so a rewrite — not a retry of the same — follows. */
66
+ export function blockReason(hit: MergeHit): string {
67
+ return [
68
+ `Blocked before running: \`${hit.label}\` at the command's tail (\`${hit.excerpt}\`) merges stderr into stdout inside the child, so the timeline loses the [err] tag — the skills ban it.`,
69
+ "Rewrite instead: silence one stream only (`cmd >/dev/null` keeps stderr tagged), read warnings from the [err] lines or `busybox log <R> --stream stderr --match <literal>`, and log a background server as `cmd >srv.log 2>srv.err &`.",
70
+ `If the merge is genuinely intended and you will not read that output back as evidence, append \`${OVERRIDE_MARKER}\` to the command and say why in a comment.`,
71
+ ].join("\n");
72
+ }
73
+
74
+ /** What the guest shell left behind about how it ended (see `reportTrap` in wrap.ts). */
75
+ export interface RunFacts {
76
+ /** Exit status of every stage of the last pipeline, in order. */
77
+ pipestatus?: number[];
78
+ /** Where the command started and where it was when it exited. */
79
+ cwdStart?: string;
80
+ cwdFinal?: string;
81
+ }
82
+
83
+ export interface NoteOptions {
84
+ /** The whole call ran unwrapped via the `command` prefix. */
85
+ escaped?: boolean;
86
+ /**
87
+ * Notes already given in full this session. A note seen before comes back in a few
88
+ * words: the same two lines on every `| head` call are read once and then skimmed
89
+ * past, which is the opposite of what a caveat is for.
90
+ */
91
+ seen?: Set<string>;
92
+ /** What the run itself reported, when it did: a fact replaces a guess. */
93
+ facts?: RunFacts;
94
+ /** The header's exit code, so a note about a status is only made when it applies. */
95
+ exitCode?: number;
96
+ }
97
+
98
+ /** One line for a pipeline's stage statuses, or undefined when they say nothing new. */
99
+ export function describePipestatus(pipestatus: number[], exitCode?: number): string | undefined {
100
+ if (pipestatus.length < 2) return undefined;
101
+ // The trap sees the *last* pipeline. If the script went on to exit with something
102
+ // else (`a | b; exit 7`), these are not the statuses behind the header's code.
103
+ if (exitCode !== undefined && pipestatus[pipestatus.length - 1] !== exitCode) return undefined;
104
+ // All zero: nothing in the pipeline disagrees with the header.
105
+ if (pipestatus.every((status) => status === 0)) return undefined;
106
+ const earlier = pipestatus.slice(0, -1);
107
+ const parts = [`pipeline stage statuses: ${pipestatus.join(" ")} — the exit_code shown is the last stage's`];
108
+ if (earlier.includes(141)) parts.push("141 is a stage ended by SIGPIPE because the next stage stopped reading, not a failure of its own");
109
+ const failed = earlier.filter((status) => status !== 0 && status !== 141);
110
+ if (failed.length > 0) parts.push(`an earlier stage failed (${failed.join(", ")}) and the header does not show it`);
111
+ return `${parts.join("; ")}.`;
112
+ }
113
+
114
+ /**
115
+ * What the result should state about what the model *cannot* know from it.
116
+ *
117
+ * The timeline says what arrived; it cannot say what was thrown away. A discarded
118
+ * stream, a backgrounded process and a declared merge each leave a hole in the picture,
119
+ * and naming the hole is what makes the remaining view correct.
120
+ *
121
+ * Where the run reported a fact (`options.facts`), the fact is stated instead of the
122
+ * caveat: "pipeline stage statuses: 1 141 0" replaces "its own status is unknown", and a
123
+ * pipeline whose stages all exited 0 gets no note at all.
124
+ */
125
+ export function resultNotes(command: string, options: NoteOptions = {}): string[] {
126
+ const notes: string[] = [];
127
+ const note = (key: string, full: string, short: string) => {
128
+ const isRepeat = options.seen?.has(key) === true;
129
+ options.seen?.add(key);
130
+ notes.push(isRepeat ? short : full);
131
+ };
132
+ if (hasOverride(command)) {
133
+ note(
134
+ "override",
135
+ `\`${OVERRIDE_MARKER}\` declared on this call: stream identity in this output was merged or discarded by design — do not read the [out]/[err] tags as evidence about the program.`,
136
+ `\`${OVERRIDE_MARKER}\` declared: the [out]/[err] tags here are not evidence.`,
137
+ );
138
+ }
139
+ if (/(?:^|[\s;&(])1?>\s*\/dev\/null/.test(command)) {
140
+ note("stdout", "stdout was discarded by this command (`>/dev/null`): its content is unknown to you.", "stdout was discarded (`>/dev/null`): unknown.");
141
+ }
142
+ if (/(?:^|[\s;&(])2>\s*\/dev\/null/.test(command)) {
143
+ note("stderr", "stderr was discarded by this command (`2>/dev/null`): its content is unknown to you.", "stderr was discarded (`2>/dev/null`): unknown.");
144
+ }
145
+ if (/(?:^|[\s;])&\s*(?:#.*)?$/m.test(command) && !/\bwaitfor\b|\bwait\b/.test(command)) {
146
+ note(
147
+ "background",
148
+ "a process was left running in the background; the timeline stops at this call's exit — poll with `waitfor` before assuming it finished.",
149
+ "a process was left in the background: poll with `waitfor`.",
150
+ );
151
+ }
152
+ if (options.escaped) {
153
+ note(
154
+ "escaped",
155
+ "this call ran unwrapped (the `command` prefix): no timeline, no stream tags, no timing — byte-exact is all you got.",
156
+ "ran unwrapped (`command`): no timeline.",
157
+ );
158
+ }
159
+ // The exit code in the header is the *last pipeline stage's* — three stages make it
160
+ // read wrong more often than right. `head` closes the pipe early (the first command
161
+ // dies of SIGPIPE); `grep` makes exit 1 mean "no match"; and `|| true` replaces a
162
+ // failure with success by design.
163
+ const stage = lastPipelineStage(command);
164
+ const stages = options.facts?.pipestatus;
165
+ if (stages !== undefined) {
166
+ // Known: say what each stage returned, and nothing when they all returned 0.
167
+ const fact = describePipestatus(stages, options.exitCode);
168
+ if (fact) notes.push(fact);
169
+ } else if (/^(?:head|tail)\b/.test(stage)) {
170
+ note(
171
+ "head",
172
+ "the pipeline ends in `head`/`tail`: the exit_code shown is theirs, not the command's — the command is killed by SIGPIPE when it closes the pipe, so its own status is unknown.",
173
+ "exit_code is `head`/`tail`'s, not the command's.",
174
+ );
175
+ }
176
+ // Only when it applies: with the header's code known, a `grep` that matched (0) needs
177
+ // no caveat at all.
178
+ if (/^grep\b/.test(stage) && (options.exitCode === undefined || options.exitCode === 1)) {
179
+ note("grep", "the pipeline ends in `grep`: exit_code 1 means no match, not a failed command.", "`grep` exit 1 = no match.");
180
+ }
181
+ if (/\|\|\s*(?:true|:)\b/.test(command)) {
182
+ note(
183
+ "or-true",
184
+ "a segment's failure may be hidden by `|| true`: the exit_code shown is `true`'s, not that command's.",
185
+ "`|| true` may hide a failure.",
186
+ );
187
+ }
188
+ // `cd` is call-local (each bash call starts fresh at the session cwd — measured, and
189
+ // pi's tool schema has no cwd parameter), so files written relative to it must be
190
+ // findable from where the *next* call starts.
191
+ const { cwdStart, cwdFinal } = options.facts ?? {};
192
+ if (cwdStart !== undefined && cwdFinal !== undefined) {
193
+ // Known: name the two directories, and say nothing when it ended where it began.
194
+ if (cwdFinal !== cwdStart) {
195
+ notes.push(`this command ended in ${cwdFinal}; the next bash call starts back in ${cwdStart} — \`cd\` does not carry.`);
196
+ }
197
+ } else {
198
+ // First line only: heredoc bodies and nested `sh -c` strings are not this call's shell.
199
+ const firstLine = command.split("\n")[0] ?? "";
200
+ if (/(?:^|[;&]\s)cd\s/.test(firstLine.trim())) {
201
+ note(
202
+ "cd",
203
+ "`cd` affects this call only; the next bash call starts back at the session cwd — write files where a later call can find them (absolute, or relative to the session cwd).",
204
+ "`cd` does not carry to the next call.",
205
+ );
206
+ }
207
+ }
208
+ return notes;
209
+ }
210
+
211
+ // =============================================================================
212
+ // Commands that cannot end
213
+ // =============================================================================
214
+
215
+ export interface EndlessHit {
216
+ /** What kind of command it is, in a few words. */
217
+ label: string;
218
+ /** The statement that was recognised. */
219
+ excerpt: string;
220
+ /** What to write instead. */
221
+ rewrite: string;
222
+ }
223
+
224
+ /** Words that run the next word as the command: skipped to find the real one. */
225
+ const PREFIX_WORDS = /^(?:sudo|exec|nohup|time|nice|env|stdbuf\s+\S+|[A-Za-z_][A-Za-z0-9_]*=\S*)\s+/;
226
+
227
+ /** Remove heredoc bodies: they are data, not this call's shell (`cat > notes <<EOF … watch the logs … EOF`). */
228
+ function stripHeredocs(command: string): string {
229
+ const out: string[] = [];
230
+ let terminator: string | undefined;
231
+ let stripTabs = false;
232
+ for (const line of command.split("\n")) {
233
+ if (terminator !== undefined) {
234
+ if ((stripTabs ? line.replace(/^\t+/, "") : line) === terminator) terminator = undefined;
235
+ continue;
236
+ }
237
+ out.push(line);
238
+ const start = /<<(-?)\s*(?:'([^']+)'|"([^"]+)"|\\?([A-Za-z_][A-Za-z0-9_]*))/.exec(line);
239
+ if (start) {
240
+ stripTabs = start[1] === "-";
241
+ terminator = start[2] ?? start[3] ?? start[4];
242
+ }
243
+ }
244
+ return out.join("\n");
245
+ }
246
+
247
+ /**
248
+ * Blank out everything inside quotes, keeping the length and the line breaks.
249
+ *
250
+ * What is quoted is an argument, not syntax: a `|`, `;` or `&&` in there separates
251
+ * nothing, and a word in there is not in command position. The state carries across
252
+ * lines, so a multi-line `python3 -c '…'` body is blanked whole. A backslash escapes the
253
+ * next character outside single quotes, as the shell has it.
254
+ */
255
+ export function maskQuotes(command: string): string {
256
+ let out = "";
257
+ let quote: "'" | '"' | undefined;
258
+ for (let i = 0; i < command.length; i++) {
259
+ const char = command[i] as string;
260
+ if (quote === undefined) {
261
+ if (char === "\\" && i + 1 < command.length) {
262
+ out += "__";
263
+ i++;
264
+ } else if (char === "'" || char === '"') {
265
+ quote = char;
266
+ out += "_";
267
+ } else out += char;
268
+ continue;
269
+ }
270
+ if (quote === '"' && char === "\\" && i + 1 < command.length) {
271
+ out += command[i + 1] === "\n" ? "_\n" : "__";
272
+ i++;
273
+ } else if (char === quote) {
274
+ quote = undefined;
275
+ out += "_";
276
+ } else out += char === "\n" ? "\n" : "_";
277
+ }
278
+ return out;
279
+ }
280
+
281
+ const SERVER_HINT =
282
+ "start it with busybox_job (action 'start', `wait_for` its readiness line) and stop it when done; or background it with its output in files (`cmd >srv.log 2>srv.err &`) and poll with `waitfor`";
283
+
284
+ /** The rule for one pipeline stage, given whether it is the pipeline's last. */
285
+ function endlessStage(stage: string, isLast: boolean): Omit<EndlessHit, "excerpt"> | undefined {
286
+ let words = stage.trim();
287
+ while (PREFIX_WORDS.test(words)) words = words.replace(PREFIX_WORDS, "");
288
+ // Bounded by construction.
289
+ if (/^(?:busybox\s+)?timeout\s/.test(words)) return undefined;
290
+ const [name = "", ...rest] = words.split(/\s+/);
291
+ const args = rest.join(" ");
292
+ const has = (pattern: RegExp) => pattern.test(` ${args} `);
293
+ const base = name.replace(/^.*\//, "");
294
+ if (/--(?:help|version)\b/.test(args)) return undefined;
295
+ switch (base) {
296
+ case "watch":
297
+ return { label: "`watch` repeats until interrupted", rewrite: "run the command once; to wait for a condition use `busybox waitfor`" };
298
+ case "vi":
299
+ case "vim":
300
+ case "nvim":
301
+ case "nano":
302
+ case "pico":
303
+ return { label: "an editor waits for keys nobody can press", rewrite: "change files with the edit tool or `busybox replace`, and read them with the read tool" };
304
+ case "emacs":
305
+ if (has(/\s--?batch\s/)) return undefined;
306
+ return { label: "an editor waits for keys nobody can press", rewrite: "change files with the edit tool or `busybox replace`; `emacs --batch` for a script" };
307
+ case "less":
308
+ case "more":
309
+ case "most":
310
+ if (!isLast) return undefined;
311
+ return { label: "a pager waits for keys nobody can press", rewrite: "drop the pager: the output is captured whole (or read the file with the read tool)" };
312
+ case "htop":
313
+ case "btop":
314
+ return { label: "a full-screen monitor never exits", rewrite: "`ps aux` (or `top -l 1` on macOS, `top -b -n 1` on Linux) prints once" };
315
+ case "top":
316
+ if (has(/\s-(?:l|b|n)\b/)) return undefined;
317
+ return { label: "`top` redraws until interrupted", rewrite: "`top -l 1` on macOS or `top -b -n 1` on Linux prints once; `ps aux` also does" };
318
+ case "tail":
319
+ if (!isLast || !has(/\s(?:-[A-Za-z0-9]*[fF]\b|--follow\b)/) || has(/\s--pid\b/)) return undefined;
320
+ return { label: "`tail -f` follows until interrupted", rewrite: "read what is there now (`tail -n 50 FILE`), or wait for a line with `busybox waitfor`; inside a pipeline that ends (`tail -f FILE | grep -m1 ready`) it is fine" };
321
+ case "journalctl":
322
+ if (!isLast || !has(/\s(?:-[A-Za-z]*f\b|--follow\b)/)) return undefined;
323
+ return { label: "`journalctl -f` follows until interrupted", rewrite: "drop `-f` and bound it (`-n 100`, `--since`)" };
324
+ case "yes":
325
+ if (!isLast) return undefined;
326
+ return { label: "`yes` prints for ever", rewrite: "pipe it into the command that needs the answers (`yes | cmd`), or give the answer once (`printf 'y\\n' | cmd`)" };
327
+ case "sleep":
328
+ if (!has(/\s(?:infinity|inf)\s/)) return undefined;
329
+ return { label: "`sleep infinity` never returns", rewrite: "sleep for a number of seconds, or wait for a condition with `busybox waitfor`" };
330
+ case "git":
331
+ if (has(/\srebase\s(?:.*\s)?(?:-i|--interactive)\s/)) {
332
+ return { label: "an interactive rebase opens an editor", rewrite: "`git rebase <base>` without `-i`, or script the todo list with `GIT_SEQUENCE_EDITOR`" };
333
+ }
334
+ if (has(/\sadd\s(?:.*\s)?(?:-i|-p|--interactive|--patch)\s/)) {
335
+ return { label: "`git add -p`/`-i` asks questions nobody can answer", rewrite: "`git add <paths>`, or apply a prepared patch with `git apply --cached`" };
336
+ }
337
+ return undefined;
338
+ case "docker":
339
+ case "podman":
340
+ if (isLast && has(/\slogs\s(?:.*\s)?(?:-[A-Za-z]*f\b|--follow\b)/)) {
341
+ return { label: "`logs -f` follows until interrupted", rewrite: "drop `-f` and bound it (`--tail 100`, `--since 5m`)" };
342
+ }
343
+ if (isLast && has(/\scompose\s(?:.*\s)?up\s/) && !has(/\s(?:-d|--detach|--wait|--abort-on-container-exit|--exit-code-from)\b/)) {
344
+ return { label: "`compose up` stays attached to its containers", rewrite: `\`compose up -d\` (then \`compose logs --tail 50\`), or ${SERVER_HINT}` };
345
+ }
346
+ return undefined;
347
+ case "kubectl":
348
+ if (isLast && has(/\slogs\s(?:.*\s)?(?:-[A-Za-z]*f\b|--follow\b)/)) {
349
+ return { label: "`logs -f` follows until interrupted", rewrite: "drop `-f` and bound it (`--tail=100`, `--since=5m`)" };
350
+ }
351
+ if (isLast && has(/\sport-forward\s/)) return { label: "`port-forward` runs until interrupted", rewrite: SERVER_HINT };
352
+ return undefined;
353
+ case "python":
354
+ case "python3":
355
+ if (isLast && has(/\s-m\s+http\.server\b/)) return { label: "a web server runs until stopped", rewrite: SERVER_HINT };
356
+ return undefined;
357
+ case "php":
358
+ if (isLast && has(/\s-S\s/)) return { label: "a web server runs until stopped", rewrite: SERVER_HINT };
359
+ return undefined;
360
+ case "npm":
361
+ case "yarn":
362
+ case "pnpm":
363
+ case "bun":
364
+ if (isLast && has(/^\s(?:run\s+)?(?:dev|serve|start|watch)\s*$/)) {
365
+ return { label: `\`${base} ${args.trim()}\` starts something that runs until stopped`, rewrite: SERVER_HINT };
366
+ }
367
+ return undefined;
368
+ case "nodemon":
369
+ case "uvicorn":
370
+ case "gunicorn":
371
+ return isLast ? { label: "a server runs until stopped", rewrite: SERVER_HINT } : undefined;
372
+ case "flask":
373
+ case "rails":
374
+ case "hugo":
375
+ case "jekyll":
376
+ case "next":
377
+ case "vite":
378
+ if (isLast && has(/^\s(?:run|s|server|serve|dev)\b/)) return { label: "a development server runs until stopped", rewrite: SERVER_HINT };
379
+ return undefined;
380
+ default:
381
+ return undefined;
382
+ }
383
+ }
384
+
385
+ /**
386
+ * A statement of this command that cannot end on its own here, if there is one.
387
+ *
388
+ * Nobody can press `q`, Ctrl-C or a key at a prompt, so a pager, an editor, `tail -f`, a
389
+ * foreground server all run until the deadline and come back as a TIMEOUT two minutes
390
+ * later — with nothing learned. Refusing first costs nothing and carries the rewrite.
391
+ *
392
+ * Deliberately narrow. Only the first word of a statement or pipeline stage is judged,
393
+ * heredoc bodies are skipped, a backgrounded statement and anything under `timeout` are
394
+ * left alone, and "last stage only" rules let `tail -f log | grep -m1 ready` through.
395
+ * Quoted text is blanked before anything is split: the first real session refused
396
+ * `grep -n "PIPESTATUS\|tail -f /dev/null" notes.md`, because the `|` inside the pattern
397
+ * was read as a pipe and what followed it as a command. `# pitime-safe` overrides it.
398
+ */
399
+ export function detectEndless(command: string): EndlessHit | undefined {
400
+ for (const line of maskQuotes(stripHeredocs(command)).split("\n")) {
401
+ const code = line.replace(/\s+#.*$/, "");
402
+ for (const statement of code.split(/&&|\|\||;/)) {
403
+ const trimmed = statement.trim();
404
+ // Backgrounded: the call returns, whatever the process does.
405
+ if (trimmed === "" || /&\s*$/.test(trimmed)) continue;
406
+ const stages = trimmed.split(/\|(?!\|)/);
407
+ for (const [index, stage] of stages.entries()) {
408
+ const hit = endlessStage(stage, index === stages.length - 1);
409
+ if (hit) return { ...hit, excerpt: trimmed.length > 60 ? `${trimmed.slice(0, 59)}…` : trimmed };
410
+ }
411
+ }
412
+ }
413
+ return undefined;
414
+ }
415
+
416
+ /** The refusal for a command that cannot end, with what to write instead. */
417
+ export function endlessReason(hit: EndlessHit): string {
418
+ return [
419
+ `Blocked before running: \`${hit.excerpt}\` does not end on its own here (${hit.label}), and nobody can press a key or Ctrl-C — it would run until the deadline and come back as a TIMEOUT with nothing learned.`,
420
+ `Instead: ${hit.rewrite}.`,
421
+ `If this one does end by itself, append \`${OVERRIDE_MARKER}\` to the command.`,
422
+ ].join("\n");
423
+ }
424
+
425
+ /**
426
+ * The final pipeline stage of the last line: the stage whose exit status the header shows.
427
+ *
428
+ * A trailing `&` and comment are stripped first; the split is naive about `|` inside
429
+ * quotes, which only ever makes the note fire a little early, never lie about the stage
430
+ * it names.
431
+ */
432
+ function lastPipelineStage(command: string): string {
433
+ const last = command.trimEnd().split("\n").pop() ?? "";
434
+ const stripped = last.replace(/\s*&\s*$/, "").replace(/\s*#.*$/, "");
435
+ const segments = stripped.split("|");
436
+ return (segments[segments.length - 1] ?? "").trim();
437
+ }