pi-odd-worktree 3.1.1 → 3.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.
@@ -1,27 +1,43 @@
1
1
  'use strict';
2
- // The `## ODD worktrees` section of the primary session's system prompt (S7).
2
+ // The `## ODD worktrees` section of the primary session's system prompt (S7), and
3
+ // (T3, S5) the one short block a CHILD that writes gets.
3
4
  //
4
5
  // It is appended to `systemPromptOptions.appendSystemPrompt` and nowhere else:
5
6
  // a handler-returned `systemPrompt` is dropped by pi-claude-bridge, and
6
7
  // replacing the option would erase the harness's own text. The block is only
7
8
  // ever added after the existing text, is skipped when it is already there, and
8
- // reaches a primary session only — a named agent or a `GENTLE_PI_AGENTS_CHILD`
9
- // worker is left untouched. `ODD_WORKTREE_PROMPT=0` turns it off.
9
+ // reaches a primary session only — a named agent gets the primary text of its
10
+ // own session, never this one.
11
+ //
12
+ // S5: a `GENTLE_PI_AGENTS_CHILD` session is not skipped any more. A child that
13
+ // WRITES — `gentle-ai-worker`, `jd-fix-agent`, and any child whose agent name the
14
+ // argv cannot name, which is the generic child — gets one short line telling it to
15
+ // work in its workspace root's worktree and to stop and report on the primary. The
16
+ // children that only look or judge (explore, verify, the two judges, every
17
+ // `review-*`) get nothing, exactly as before. The agent name comes from
18
+ // `lib/codegraph-rules.js` (`agentNameFromArgv`), which already reads it from the
19
+ // child's own argv; the argv parsing is never duplicated here.
20
+ //
21
+ // `ODD_WORKTREE_PROMPT=0` turns both blocks off.
10
22
 
11
23
  const fs = require('node:fs');
12
24
  const path = require('node:path');
25
+ const { agentNameFromArgv, variantFor } = require('./codegraph-rules.js');
13
26
 
14
27
  // The heading is the identity of the block, so an already-injected section is
15
28
  // never added twice.
16
29
  const SECTION_MARKER = '## ODD worktrees';
17
30
 
18
31
  // The section text lives in its own Markdown file so it can be read, reviewed
19
- // and edited as prose: `lib/odd-prompt/odd-worktrees.md`. A missing or empty
20
- // file falls back to the heading alone: the block still injects, never crashes
21
- // the session, and the idempotency marker still works.
32
+ // and edited as prose: `lib/odd-prompt/odd-worktrees.md`, and — one short line for a
33
+ // child that writes — `lib/odd-prompt/odd-worktrees-child.md`. A missing or empty
34
+ // file falls back to the heading alone: the block still injects, never crashes the
35
+ // session, and the idempotency marker still works.
22
36
  const PROMPT_DIR = path.join(__dirname, 'odd-prompt');
23
37
  const PROMPT_FILE = path.join(PROMPT_DIR, 'odd-worktrees.md');
38
+ const CHILD_PROMPT_FILE = path.join(PROMPT_DIR, 'odd-worktrees-child.md');
24
39
  const FALLBACK = `${SECTION_MARKER}\n\nEach ODD feature has its own worktree.`;
40
+ const CHILD_FALLBACK = `${SECTION_MARKER}\n`;
25
41
 
26
42
  function readPromptFile(file) {
27
43
  try {
@@ -32,7 +48,31 @@ function readPromptFile(file) {
32
48
  }
33
49
  }
34
50
 
35
- const SECTION = readPromptFile(PROMPT_FILE) || FALLBACK;
51
+ // The block one file contributes, or the fallback when the file cannot be used.
52
+ function sectionFromFile(file, fallback) {
53
+ return readPromptFile(file) || fallback;
54
+ }
55
+
56
+ const SECTION = sectionFromFile(PROMPT_FILE, FALLBACK);
57
+ const CHILD_SECTION = sectionFromFile(CHILD_PROMPT_FILE, CHILD_FALLBACK);
58
+
59
+ // S5: the children that WRITE, by the name `agentNameFromArgv` reports for them.
60
+ const CHILD_WRITER_AGENTS = new Set(['gentle-ai-worker', 'jd-fix-agent']);
61
+ const REVIEWER_PREFIX = 'review-';
62
+
63
+ /**
64
+ * S5: whether this child gets the block. A worker or the fix agent does; a child whose
65
+ * name cannot be read is the generic one and does too; a child that only looks or
66
+ * judges — explore, verify, the judges, every `review-*` — never does. An unknown but
67
+ * READ name is generic exactly as `lib/codegraph-rules.js` decides it, so the two
68
+ * blocks can never call the same child two different things.
69
+ */
70
+ function childGetsSection(agent) {
71
+ if (typeof agent !== 'string' || agent.length === 0) return true;
72
+ if (CHILD_WRITER_AGENTS.has(agent)) return true;
73
+ if (agent.startsWith(REVIEWER_PREFIX)) return false;
74
+ return variantFor({ child: true, agent }) === 'generic';
75
+ }
36
76
 
37
77
  // The names a named-agent event may carry. `agent` itself is listed because a
38
78
  // plain string there is a named agent too; an object is read through `.name`.
@@ -57,26 +97,35 @@ function separatorFor(existing) {
57
97
  return '\n\n';
58
98
  }
59
99
 
60
- // Append the section to `event.systemPromptOptions.appendSystemPrompt`.
61
- // Returns nothing: the mutation is the whole contract, so a host that awaits
62
- // the handler receives no replacement prompt.
100
+ // Append the section for this session to
101
+ // `event.systemPromptOptions.appendSystemPrompt`. Returns nothing: the mutation
102
+ // is the whole contract, so a host that awaits the handler receives no
103
+ // replacement prompt. `deps.env` and `deps.argv` are the seams: the environment the
104
+ // session runs with, and the argv a child's agent name is read from.
63
105
  function appendOddWorktreesSection(event, deps = {}) {
64
106
  try {
65
107
  const effectiveDeps = deps || {};
66
108
  const env = effectiveDeps.env || process.env;
67
109
  if (env.ODD_WORKTREE_PROMPT === '0') return;
68
- if (env.GENTLE_PI_AGENTS_CHILD === '1') return;
69
- if (namedAgentOf(event) !== null) return;
110
+
111
+ // S5: a child is judged by the agent name its own argv carries, and gets the child
112
+ // block only when it writes. A primary session keeps the one section it always had,
113
+ // and a named-agent event still gets none of it.
114
+ const child = env.GENTLE_PI_AGENTS_CHILD === '1';
115
+ if (child) {
116
+ if (!childGetsSection(agentNameFromArgv(effectiveDeps.argv || process.argv))) return;
117
+ } else if (namedAgentOf(event) !== null) return;
70
118
 
71
119
  const options = event && event.systemPromptOptions;
72
120
  if (!options || typeof options !== 'object') return;
73
121
 
122
+ const section = child ? CHILD_SECTION : SECTION;
74
123
  const existing = typeof options.appendSystemPrompt === 'string' ? options.appendSystemPrompt : '';
75
124
  if (existing.includes(SECTION_MARKER)) return;
76
125
  // Append-only: every existing byte stays the prefix of the new value.
77
126
  options.appendSystemPrompt = existing.length === 0
78
- ? SECTION
79
- : `${existing}${separatorFor(existing)}${SECTION}`;
127
+ ? section
128
+ : `${existing}${separatorFor(existing)}${section}`;
80
129
  } catch {
81
130
  // The prompt block must never break session start.
82
131
  }
@@ -84,5 +133,10 @@ function appendOddWorktreesSection(event, deps = {}) {
84
133
 
85
134
  module.exports = {
86
135
  appendOddWorktreesSection,
136
+ childGetsSection,
137
+ readPromptFile,
138
+ sectionFromFile,
87
139
  SECTION,
140
+ CHILD_SECTION,
141
+ CHILD_FALLBACK,
88
142
  };
@@ -0,0 +1,397 @@
1
+ 'use strict';
2
+ // invariant 22 (the `bash` guards read text, fail open and add no surface): the
3
+ // skill-read guard, decided from one `bash` command string.
4
+ //
5
+ // A skill file is read with `read`. A reader typed into `bash` — `cat`, `sed -n`, … —
6
+ // prints the file into the transcript instead, so the guard refuses, before the
7
+ // command runs, the call that reads one.
8
+ //
9
+ // The rule, exactly as implemented: the command is split by the package's ONE
10
+ // segmenter (`shellCommandSegments`, `lib/bash-activity.js`), which never splits
11
+ // inside quotes and keeps a heredoc body in the segment that opened it. Per segment
12
+ // the command position names the program — leading `VAR=value` assignments and the
13
+ // `env`/`time`/`nice` wrappers come before it — and only a program that PRINTS a
14
+ // file's text is judged: `cat`, `head`, `tail`, `less`, `more`, `bat`, `batcat`, `nl`,
15
+ // `awk`, and `sed` without `-i`/`--in-place`, which writes and so is not a read.
16
+ // `grep` and `rg` are absent on purpose: searching a file is not reading it, and the
17
+ // rule stays narrow. A `cd` needs no handling here — the segmenter already ends the
18
+ // segment it appears in.
19
+ //
20
+ // Every non-option argument word of such a program is a path, and the path is a
21
+ // SKILL file when `fileCardIdentity` (`lib/skill-odd-card.js`) says so: that module
22
+ // decides on the FOLDERS alone, so a path below a `skills` component is a skill
23
+ // (`~/.agents/skills/x/SKILL.md`, `…/skills/x/references/y.md`) while `docs/SKILL.md`
24
+ // and `notes/SKILL.md` are ordinary files, and a path whose closest marker is `odd` is
25
+ // an ODD artifact. That identity needs no absolute path, so a leading `~` is judged
26
+ // exactly as written and nothing is expanded, resolved or read.
27
+ //
28
+ // What is NOT a path: a redirection operator and its target (the shell hands neither
29
+ // to the program, so `cat > skills/x/SKILL.md` writes and names no file to read); a
30
+ // heredoc header and everything after it (its body is data, never an argument); the
31
+ // single word `-` (stdin); and `$VAR`, a backtick, or a glob (`*`, `?`, `[…]`, `{…}`),
32
+ // which name a file this reader cannot know. The value an option takes is skipped with
33
+ // the option (`sed -e 's/a/b/'`, `head -n 20`), and so is the inline program of
34
+ // `sed`/`awk` (`sed -n '/skills/p' README.md` reads README.md), so a script is never
35
+ // mistaken for a path. A word with no separator at all can be no skill either — the
36
+ // identity always needs the `skills` folder above the file — so it is dropped before
37
+ // the identity is asked.
38
+ //
39
+ // One occurrence refuses the WHOLE call, and the reason names the FIRST offending path:
40
+ // a command that mixes a skill read with other work is refused as a whole, so the model
41
+ // re-issues the other work and reads the skill with `read`.
42
+ //
43
+ // Nothing here spawns a child, reads a file or caches anything: the decision is a pure
44
+ // function over the command TEXT, and it never throws, because a throwing `tool_call`
45
+ // handler blocks the tool fail-safe (invariant 22). `ODD_WORKTREE_GUARD=0` — the
46
+ // worktree guard's own switch — turns it off, and the guard registers no command, no
47
+ // tool, no option and no setting of its own (invariant 3).
48
+
49
+ const path = require('node:path');
50
+ const { shellCommandSegments } = require('./bash-activity.js');
51
+ const { FILE_CARD_IDENTITY, fileCardIdentity } = require('./skill-odd-card.js');
52
+
53
+ /** The readers that print a file's text, so their argument words name files they read. */
54
+ const READ_PROGRAMS = new Set(['cat', 'head', 'tail', 'less', 'more', 'bat', 'batcat', 'nl', 'awk', 'sed']);
55
+
56
+ /** The wrappers that run another program: the program position is the word after them. */
57
+ const WRAPPERS = new Set(['env', 'time', 'nice', 'timeout', 'sudo', 'command', 'exec', 'nohup']);
58
+
59
+ /** The words a script's control flow puts before the command it runs: `then cat …`, `do head …`. */
60
+ const LEADING_KEYWORDS = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', '{']);
61
+
62
+ /** The shells whose `-c` argument is a command line of its own. */
63
+ const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash']);
64
+
65
+ /** A wrapper option that takes its value as the NEXT word (`nice -n 5`, `env -u HOME`). */
66
+ const WRAPPER_VALUE_OPTIONS = {
67
+ env: new Set(['-u', '-C', '-S']),
68
+ nice: new Set(['-n']),
69
+ time: new Set(['-f', '-o']),
70
+ timeout: new Set(['-s', '-k']),
71
+ sudo: new Set(['-u', '-g', '-h', '-p', '-C', '-r', '-t', '-U', '-D']),
72
+ command: new Set(),
73
+ exec: new Set(['-a']),
74
+ nohup: new Set(),
75
+ };
76
+
77
+ /** An environment assignment at the command position: `SKILL_DIR=… cat …`. */
78
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
79
+
80
+ /** A word the shell resolves first, so this reader cannot know which file it names. */
81
+ const UNRESOLVED = /[$`\u0000]/;
82
+
83
+ /** `sed -i`, `-i.bak`, `-ni` and `--in-place[=SUFFIX]` write the file: a write is not a read. */
84
+ const IN_PLACE = /^(?:--in-place(?:=|$)|-[A-Za-z]*i)/;
85
+
86
+ /**
87
+ * The options that take their value as a SEPARATE word, per reader, so a value that
88
+ * happens to contain a slash (`sed -e 's/a/b/'`) is never read as a file name. A
89
+ * `--flag=value` token carries its own value and therefore consumes no next word, and a
90
+ * short option with its value glued on (`-n5`, `-i.bak`) consumes none either.
91
+ */
92
+ const VALUE_OPTIONS = new Map([
93
+ ['head', { longs: new Set(['--lines', '--bytes']), shorts: new Set(['n', 'c']) }],
94
+ ['tail', { longs: new Set(['--lines', '--bytes', '--sleep-interval', '--pid']), shorts: new Set(['n', 'c', 's']) }],
95
+ ['nl', {
96
+ longs: new Set([
97
+ '--body-numbering', '--section-delimiter', '--footer-numbering', '--header-numbering',
98
+ '--line-increment', '--join-blank-lines', '--number-format', '--number-separator',
99
+ '--starting-line-number', '--number-width',
100
+ ]),
101
+ shorts: new Set(['b', 'd', 'f', 'h', 'i', 'l', 'n', 's', 'v', 'w']),
102
+ }],
103
+ ['awk', { longs: new Set(['--file', '--field-separator', '--assign', '--include', '--load']), shorts: new Set(['f', 'F', 'v']) }],
104
+ ['sed', { longs: new Set(['--expression', '--file', '--line-length']), shorts: new Set(['e', 'f', 'l']) }],
105
+ ['bat', {
106
+ longs: new Set([
107
+ '--language', '--theme', '--line-range', '--tabs', '--terminal-width', '--style',
108
+ '--map-syntax', '--highlight-line', '--diff-context',
109
+ ]),
110
+ shorts: new Set(['l', 'r', 'H']),
111
+ }],
112
+ ['less', {
113
+ longs: new Set(['--tabs', '--shift', '--window', '--buffers', '--max-line-length', '--pattern', '--prompt']),
114
+ shorts: new Set(['x', 'b', 'h', 'j', 'o', 'O', 'p', 'P', 't', 'T', 'y', 'z', 'D']),
115
+ }],
116
+ ]);
117
+
118
+ /**
119
+ * `sed` and `awk` take their PROGRAM as the first non-option word unless a flag named
120
+ * one, so that word is a script and never a file: `sed -n '/skills/p' README.md` reads
121
+ * README.md, while `sed -n '1,80p' …/skills/x/SKILL.md` still names the skill.
122
+ */
123
+ const SCRIPT_FLAGS = new Map([
124
+ ['sed', { longs: new Set(['--expression', '--file']), shorts: new Set(['e', 'f']) }],
125
+ ['awk', { longs: new Set(['--file']), shorts: new Set(['f']) }],
126
+ ]);
127
+
128
+ const NO_OPTIONS = { longs: new Set(), shorts: new Set() };
129
+
130
+ /** The last component of a word path, so `/usr/bin/cat` is the program `cat`. */
131
+ function baseName(word) {
132
+ const slash = word.lastIndexOf('/');
133
+ return slash < 0 ? word : word.slice(slash + 1);
134
+ }
135
+
136
+ /** A `--flag=value` token's own name, or the token itself when it names no value. */
137
+ function longName(word) {
138
+ const equals = word.indexOf('=');
139
+ return equals < 0 ? word : word.slice(0, equals);
140
+ }
141
+
142
+ /** The letters of a short option cluster (`-ne` is `n`,`e`); empty for anything else. */
143
+ function shortLetters(word) {
144
+ // Up to the first character that is not a letter: `-ne1p` is `n`,`e` and a glued value.
145
+ const cluster = /^-([A-Za-z]+)/.exec(word);
146
+ return cluster === null ? [] : cluster[1].split('');
147
+ }
148
+
149
+ /** Whether this option token takes its value as the next word. */
150
+ function takesValue(word, options) {
151
+ if (word.startsWith('--')) return !word.includes('=') && options.longs.has(word);
152
+ if (!/^-[A-Za-z0-9]/.test(word)) return false;
153
+ const chars = word.slice(1).split('');
154
+ for (let at = 0; at < chars.length; at += 1) {
155
+ // The first value-taking letter ends the cluster: what follows it IS its value (`-ne1p`),
156
+ // and only when nothing follows does the value come as the next word.
157
+ if (options.shorts.has(chars[at])) return at === chars.length - 1;
158
+ }
159
+ return false;
160
+ }
161
+
162
+ /**
163
+ * One segment read as the words a program receives, with every quote span resolved and
164
+ * every redirection dropped.
165
+ *
166
+ * A redirection is not an argument: the operator, the file descriptor glued to it
167
+ * (`2>`, `>&1`) and the target word that follows are all dropped, so `cat > skills/x/SKILL.md`
168
+ * names no file at all while `cat notes/a.md > out.md` still names `notes/a.md`. A
169
+ * heredoc STOPS the read: the body the segmenter kept in this segment is data the
170
+ * command reads, never more arguments. Never throws.
171
+ */
172
+ function segmentWords(segment) {
173
+ const words = [];
174
+ let word = null;
175
+ let drop = false;
176
+ let bodyFollows = false;
177
+ const flush = () => {
178
+ // A redirection's target is still to come: an empty word keeps the drop in force.
179
+ if (word === null) return;
180
+ if (drop !== true) words.push(word);
181
+ word = null;
182
+ drop = false;
183
+ };
184
+ let index = 0;
185
+ while (index < segment.length) {
186
+ const char = segment[index];
187
+ if (char === ' ' || char === '\t' || char === '\n' || char === '\r') {
188
+ // The first newline after a heredoc header opens its body: data, never arguments.
189
+ if (char === '\n' && bodyFollows) break;
190
+ flush();
191
+ index += 1;
192
+ continue;
193
+ }
194
+ if (char === "'" || char === '"') {
195
+ // The segmenter already agreed not to split inside a quote; here the quotes come
196
+ // off, so `cat "skills/x/SKILL.md"` names the same path as the bare spelling.
197
+ const end = segment.indexOf(char, index + 1);
198
+ const inner = end < 0 ? segment.slice(index + 1) : segment.slice(index + 1, end);
199
+ word = (word === null ? '' : word) + inner;
200
+ index = end < 0 ? segment.length : end + 1;
201
+ continue;
202
+ }
203
+ if (char === '\\') {
204
+ const next = segment[index + 1];
205
+ if (next !== undefined) word = (word === null ? '' : word) + next;
206
+ index += next === undefined ? 1 : 2;
207
+ continue;
208
+ }
209
+ // A heredoc: its header (`<<'EOF'`) names no file; what follows it on the same line is still
210
+ // the command's own words, and the body that starts on the next line is data.
211
+ if (char === '<' && segment[index + 1] === '<' && segment[index + 2] !== '<') {
212
+ flush();
213
+ index += 2;
214
+ if (segment[index] === '-') index += 1;
215
+ while (segment[index] === ' ' || segment[index] === '\t') index += 1;
216
+ while (index < segment.length && !/[\s;|&<>]/.test(segment[index])) {
217
+ if (segment[index] === "'" || segment[index] === '"') {
218
+ const end = segment.indexOf(segment[index], index + 1);
219
+ index = end < 0 ? segment.length : end + 1;
220
+ } else index += 1;
221
+ }
222
+ bodyFollows = true;
223
+ continue;
224
+ }
225
+ if (char === '>' || char === '<') {
226
+ // A word glued to the operator is a real argument (`cat a.md>out.md`) unless it is
227
+ // only digits, which is the file descriptor the operator applies to.
228
+ if (word !== null && /^\d+$/.test(word)) word = null;
229
+ else flush();
230
+ index += 1;
231
+ while (index < segment.length && (segment[index] === '>' || segment[index] === '<' || segment[index] === '&')) index += 1;
232
+ // `>&1`, `2>&-`: the descriptor is glued on, so no target word follows.
233
+ let glued = false;
234
+ if (index < segment.length && /[0-9-]/.test(segment[index])) {
235
+ while (index < segment.length && /[0-9-]/.test(segment[index])) index += 1;
236
+ glued = true;
237
+ }
238
+ // An output target is not an argument; an input target (`cat < file`) is a file read.
239
+ drop = char === '>' && glued !== true;
240
+ continue;
241
+ }
242
+ word = (word === null ? '' : word) + char;
243
+ // An UNQUOTED glob character leaves a mark: a quoted or escaped one is a literal name.
244
+ if (/[*?[\]{}]/.test(char)) word += '\u0000';
245
+ index += 1;
246
+ }
247
+ flush();
248
+ return words;
249
+ }
250
+
251
+ /** The index of the word the shell runs, or undefined when this segment names no command. */
252
+ function programIndex(words) {
253
+ let index = 0;
254
+ while (index < words.length) {
255
+ const word = words[index];
256
+ if (ASSIGNMENT.test(word) || LEADING_KEYWORDS.has(word)) {
257
+ index += 1;
258
+ continue;
259
+ }
260
+ if (WRAPPERS.has(baseName(word))) {
261
+ // The wrapper's own options, then any assignment it takes, then the program:
262
+ // `env -u HOME SKILL_DIR=1 cat …` still names `cat`.
263
+ const wrapper = baseName(word);
264
+ index += 1;
265
+ while (index < words.length && words[index].length > 1 && words[index].startsWith('-')) {
266
+ index += WRAPPER_VALUE_OPTIONS[wrapper].has(words[index]) ? 2 : 1;
267
+ }
268
+ // `timeout` takes its duration before the command it bounds.
269
+ if (wrapper === 'timeout') index += 1;
270
+ continue;
271
+ }
272
+ return index;
273
+ }
274
+ return undefined;
275
+ }
276
+
277
+ /**
278
+ * One reader's argument list: the words that name a file it reads, and whether it edits
279
+ * in place. Options are skipped together with the value they take, `--` ends them, and
280
+ * the inline program of `sed`/`awk` is skipped as a script.
281
+ */
282
+ function fileWords(program, words, from) {
283
+ const options = VALUE_OPTIONS.get(program === 'batcat' ? 'bat' : program) || NO_OPTIONS;
284
+ const script = SCRIPT_FLAGS.get(program);
285
+ const files = [];
286
+ let scriptGiven = script === undefined;
287
+ let optionsEnded = false;
288
+ let inPlace = false;
289
+ let index = from;
290
+ while (index < words.length) {
291
+ const word = words[index];
292
+ if (!optionsEnded && word === '--') {
293
+ optionsEnded = true;
294
+ index += 1;
295
+ continue;
296
+ }
297
+ // `less +/pattern file` runs a command or a search first: it is an option, not a file.
298
+ if (!optionsEnded && program === 'less' && word.length > 1 && word.startsWith('+')) {
299
+ index += 1;
300
+ continue;
301
+ }
302
+ if (!optionsEnded && word.length > 1 && word.startsWith('-')) {
303
+ if (program === 'sed' && IN_PLACE.test(word)) inPlace = true;
304
+ if (script !== undefined
305
+ && (script.longs.has(longName(word)) || shortLetters(word).some((letter) => script.shorts.has(letter)))) {
306
+ scriptGiven = true;
307
+ }
308
+ index += takesValue(word, options) ? 2 : 1;
309
+ continue;
310
+ }
311
+ // The inline script comes first when the reader runs one: it is a program, never a path.
312
+ if (!scriptGiven) {
313
+ scriptGiven = true;
314
+ index += 1;
315
+ continue;
316
+ }
317
+ files.push(word);
318
+ index += 1;
319
+ }
320
+ return { files, inPlace };
321
+ }
322
+
323
+ /**
324
+ * Whether this argument word names a skill file. A word the shell resolves, a bare `-`,
325
+ * and a word with no separator (a skill always sits BELOW its `skills` folder) are not
326
+ * paths at all; the rest is judged by the folders `fileCardIdentity` reads.
327
+ */
328
+ function isSkillFile(word) {
329
+ if (typeof word !== 'string' || word.length === 0) return false;
330
+ if (word === '-') return false;
331
+ if (UNRESOLVED.test(word)) return false;
332
+ const normal = path.posix.normalize(word);
333
+ if (!/[\\/]/.test(normal)) return false;
334
+ // Judged as written: the identity is decided by the folders, so `~` needs no expansion
335
+ // and no file is touched to answer.
336
+ const card = fileCardIdentity(normal);
337
+ return card !== undefined && card.identity === FILE_CARD_IDENTITY.SKILL;
338
+ }
339
+
340
+ /** The first skill file this one segment reads, or undefined. */
341
+ function skillReadPath(segment, depth = 0) {
342
+ const words = segmentWords(segment);
343
+ const at = programIndex(words);
344
+ if (at === undefined) return undefined;
345
+ const program = baseName(words[at]);
346
+ // A shell handed a command line reads it as commands of its own, two levels deep at most.
347
+ if (SHELLS.has(program) && words[at + 1] === '-c' && words[at + 2] !== undefined) {
348
+ if (depth >= 2) return undefined;
349
+ for (const inner of shellCommandSegments(words[at + 2])) {
350
+ const found = skillReadPath(inner, depth + 1);
351
+ if (found !== undefined) return found;
352
+ }
353
+ return undefined;
354
+ }
355
+ if (!READ_PROGRAMS.has(program)) return undefined;
356
+ // A usage or version request prints text and reads no file.
357
+ if (words.slice(at + 1).some((word) => word === '--help' || word === '--version')) return undefined;
358
+ const { files, inPlace } = fileWords(program, words, at + 1);
359
+ // `sed -i` writes the file: it is not a read, whatever it names.
360
+ if (inPlace) return undefined;
361
+ for (const word of files) {
362
+ if (isSkillFile(word)) return word;
363
+ }
364
+ return undefined;
365
+ }
366
+
367
+ /** The one sentence a refused call shows: what did not run, the path, and the one tool. */
368
+ function skillReadRefusal(skillPath) {
369
+ return `This bash call was not run: it reads the skill file ${skillPath} — read skill files with the \`read\` tool instead.`;
370
+ }
371
+
372
+ /**
373
+ * Decide one `bash` command: `{block: true, reason}` for the first segment that reads a
374
+ * skill file with a reader, and undefined when nothing does. Input is the command TEXT
375
+ * only — nothing is run, resolved or read — and it never throws.
376
+ */
377
+ function decideSkillReadGuard(command) {
378
+ try {
379
+ if (typeof command !== 'string' || command.length === 0) return undefined;
380
+ const segments = shellCommandSegments(command);
381
+ if (!Array.isArray(segments)) return undefined;
382
+ for (const segment of segments) {
383
+ if (typeof segment !== 'string') continue;
384
+ const skillPath = skillReadPath(segment);
385
+ if (skillPath !== undefined) return { block: true, reason: skillReadRefusal(skillPath) };
386
+ }
387
+ return undefined;
388
+ } catch {
389
+ // invariant 22: a command this reader cannot judge simply passes.
390
+ return undefined;
391
+ }
392
+ }
393
+
394
+ module.exports = {
395
+ skillReadRefusal,
396
+ decideSkillReadGuard,
397
+ };