pi-odd-worktree 3.2.0 → 3.4.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.
@@ -0,0 +1,292 @@
1
+ 'use strict';
2
+ // The jobs card: `bash_background`, `monitor`, `job_stop` and `job_list` are registered by
3
+ // Gentle Shell with no renderer of their own, so Pi draws its plain default box and the
4
+ // conversation's card style never reaches them. While the bridge's `Card tags` line answers
5
+ // `activity` for the tool being drawn, this package draws them on its own card substrate
6
+ // (`lib/shell-card.js`), in whichever style the shell has chosen. Any other answer — and the
7
+ // absence of an answer — leaves Pi's own drawing exactly as it was.
8
+ //
9
+ // Every case goes through the public surface: the resolver, the slots it returns and the
10
+ // rows a component draws for a width. The text seam and the themes are the fakes
11
+ // `tools/file-card.test.js` uses; the bridge is the published object a process-wide slot holds.
12
+ const assert = require('node:assert/strict');
13
+ const { after, afterEach, beforeEach, test } = require('node:test');
14
+
15
+ const { JOB_TOOLS } = require('../lib/jobs-card.js');
16
+ const { createJobsCardResolver, registerJobsCard } = require('../lib/jobs-card-resolver.js');
17
+ const { applyBashActivityHeading, toolsActivityDesign } = require('../lib/bash-design.js');
18
+ const { CARD_CONTENT, CARD_CONTENT_SLOT } = require('../lib/card-content.js');
19
+ const { CARD_STYLE, CARD_STYLE_SLOT } = require('../lib/card-style.js');
20
+
21
+ const ANSI = /\x1b\[[0-9;]*m/g;
22
+ const stripAnsi = (value) => value.replace(ANSI, '');
23
+ const chars = (value) => [...stripAnsi(value)];
24
+
25
+ const metrics = {
26
+ visibleWidth: (value) => chars(value).length,
27
+ truncateToWidth(value, width, ellipsis = '') {
28
+ if (width <= 0) return '';
29
+ if (this.visibleWidth(value) <= width) return value;
30
+ const tail = ellipsis ?? '';
31
+ return chars(value).slice(0, Math.max(0, width - [...tail].length)).join('') + tail;
32
+ },
33
+ wrapTextWithAnsi(value, width) {
34
+ const text = stripAnsi(value);
35
+ if (width <= 0) return [text];
36
+ return text.split('\n').flatMap((line) => {
37
+ const lines = [];
38
+ let current = '';
39
+ for (const word of line.split(' ')) {
40
+ const candidate = current === '' ? word : `${current} ${word}`;
41
+ if ([...candidate].length <= width) { current = candidate; continue; }
42
+ if (current !== '') { lines.push(current); current = ''; }
43
+ const rest = [...word];
44
+ while (rest.length > width) lines.push(rest.splice(0, width).join(''));
45
+ current = rest.join('');
46
+ }
47
+ lines.push(current);
48
+ return lines;
49
+ });
50
+ },
51
+ };
52
+
53
+ const plainTheme = { fg: (_role, value) => value };
54
+ const taggedTheme = { fg: (role, value) => `<${role}>${value}</${role}>` };
55
+ const bandTheme = { fg: (_role, value) => value, bg: (_role, value) => `\x1b[48;5;240m${value}\x1b[49m` };
56
+ const unpaint = (value) => stripAnsi(value).replace(/<\/?[a-zA-Z][a-zA-Z0-9]*>/g, '');
57
+
58
+ const BRIDGE_API_SLOT = Symbol.for('gentle-shell-bridge/api/v1');
59
+ const ACTIVITY = Object.freeze({ kind: 'design', design: { id: 'odd-worktree.bash-activity' } });
60
+
61
+ beforeEach(() => {
62
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
63
+ delete globalThis[CARD_CONTENT_SLOT];
64
+ delete globalThis[BRIDGE_API_SLOT];
65
+ });
66
+ afterEach(() => { delete globalThis[BRIDGE_API_SLOT]; });
67
+ after(() => {
68
+ delete globalThis[CARD_STYLE_SLOT];
69
+ delete globalThis[CARD_CONTENT_SLOT];
70
+ delete globalThis[BRIDGE_API_SLOT];
71
+ });
72
+
73
+ function publishBridge(selection, asked) {
74
+ const api = {
75
+ schema: 'gentle-shell-bridge/api',
76
+ version: 1,
77
+ VERSION: '0.10.0',
78
+ registerToolDesign: () => () => {},
79
+ resolveToolDesignSelection(tool) {
80
+ if (asked !== undefined) asked.push(tool);
81
+ if (typeof selection === 'function') return selection(tool);
82
+ return selection;
83
+ },
84
+ };
85
+ globalThis[BRIDGE_API_SLOT] = api;
86
+ return api;
87
+ }
88
+
89
+ function jobsResolver(options) {
90
+ const registered = [];
91
+ const cards = createJobsCardResolver({ metrics, theme: plainTheme, registerToolRenderer: (resolver) => registered.push(resolver), ...options });
92
+ assert.equal(cards.registered, true);
93
+ assert.equal(registered.length, 1);
94
+ return registered[0];
95
+ }
96
+
97
+ // What Pi would have drawn for a tool with no renderer of its own: whatever `next()` says.
98
+ const PI_DEFAULT = Object.freeze({ marker: 'pi default' });
99
+
100
+ const COMMAND = 'sleep 20; until [ "$(gh run list --repo acme/api)" ]; do sleep 1; done';
101
+ const LABEL = 'Release runs for 1.9.1';
102
+ const STARTED = [
103
+ 'Started background job job-2 ("Release runs for 1.9.1").',
104
+ 'Output: /tmp/gentle-jobs-1018kZ/job-2.log',
105
+ 'You will be notified once when it exits; keep working or end your turn. Stop it with job_stop.',
106
+ ].join('\n');
107
+
108
+ const slots = (resolver, tool) => resolver(tool, () => PI_DEFAULT);
109
+ const callRows = (resolver, tool, args, theme, width = 70, context = { isPartial: false }) =>
110
+ slots(resolver, tool).renderCall(args, theme, { args, ...context }).render(width);
111
+ const resultRows = (resolver, tool, args, text, options = { isPartial: false }, theme = plainTheme, width = 70, context = {}) =>
112
+ slots(resolver, tool).renderResult({ content: [{ type: 'text', text }], details: {} }, options, theme, { args, state: {}, ...context }).render(width);
113
+
114
+ function assertFramed(rows, width) {
115
+ for (const row of rows) assert.equal(metrics.visibleWidth(unpaint(row)), width, `"${unpaint(row)}" is not ${width} wide`);
116
+ }
117
+
118
+ // ---- the one switch ----
119
+
120
+ test('the card is drawn only while the Card tags line answers activity; every other answer leaves Pi\'s own drawing', () => {
121
+ const answers = [
122
+ ['no bridge published', undefined],
123
+ ['the bridge\'s native answer', { kind: 'native' }],
124
+ ['a tool the line does not cover', { kind: 'not-covered' }],
125
+ ['a design that has left the line', { kind: 'missing' }],
126
+ ['another plugin\'s design', { kind: 'design', design: { id: 'acme.tools' } }],
127
+ ['an answer nothing can read', 'garbage'],
128
+ ];
129
+ for (const [name, answer] of answers) {
130
+ if (answer !== undefined) publishBridge(answer);
131
+ for (const tool of JOB_TOOLS) assert.equal(slots(jobsResolver(), tool), PI_DEFAULT, `${name}: ${tool}`);
132
+ delete globalThis[BRIDGE_API_SLOT];
133
+ }
134
+ // A bridge too old to carry the reader, and one whose reader throws, are no answer either.
135
+ globalThis[BRIDGE_API_SLOT] = { schema: 'gentle-shell-bridge/api', version: 1, VERSION: '0.6.0', registerToolDesign: () => () => {} };
136
+ assert.equal(slots(jobsResolver(), 'bash_background'), PI_DEFAULT);
137
+ publishBridge(() => { throw new Error('boom'); });
138
+ assert.equal(slots(jobsResolver(), 'bash_background'), PI_DEFAULT);
139
+ });
140
+
141
+ test('while activity is selected the four job tools get a self-framed card and the bridge is asked per tool', () => {
142
+ const asked = [];
143
+ publishBridge(ACTIVITY, asked);
144
+ const resolver = jobsResolver();
145
+ for (const tool of JOB_TOOLS) {
146
+ const drawn = slots(resolver, tool);
147
+ assert.notEqual(drawn, PI_DEFAULT, tool);
148
+ assert.equal(drawn.renderShell, 'self', `${tool} frames itself`);
149
+ assert.equal(typeof drawn.renderCall, 'function');
150
+ assert.equal(typeof drawn.renderResult, 'function');
151
+ }
152
+ assert.deepEqual(asked, [...JOB_TOOLS]);
153
+ });
154
+
155
+ test('no other tool is ever claimed: bash, the file tools and an unknown tool come back as the chain resolved them', () => {
156
+ publishBridge(ACTIVITY);
157
+ const resolver = jobsResolver();
158
+ for (const tool of ['bash', 'read', 'write', 'edit', 'grep', 'codemode', 'job_unknown']) {
159
+ assert.equal(slots(resolver, tool), PI_DEFAULT, tool);
160
+ }
161
+ });
162
+
163
+ // ---- the call ----
164
+
165
+ test('a background job heads with its mark, its label and nothing it did not state', () => {
166
+ publishBridge(ACTIVITY);
167
+ const rows = callRows(jobsResolver(), 'bash_background', { command: COMMAND, label: LABEL }, taggedTheme);
168
+ assert.equal(rows.length, 1, 'collapsed, a finished call is one rule');
169
+ const text = unpaint(rows[0]);
170
+ assert.match(text, /^╭─ ⧗ background · Release runs for 1\.9\.1 /u, text);
171
+ assert.match(text, /╮$/u);
172
+ assert.ok(rows[0].includes('<bashMode>⧗</bashMode>'), 'the mark wears the identity role');
173
+ assert.doesNotMatch(text, /sleep 20/u, 'the command waits for the expanded view');
174
+ assertFramed(rows, 70);
175
+ });
176
+
177
+ test('without a label the first line of the command names the job; the other tools name their target', () => {
178
+ publishBridge(ACTIVITY);
179
+ const resolver = jobsResolver();
180
+ assert.match(unpaint(callRows(resolver, 'bash_background', { command: '\n npm test --silent\nnpm run lint' }, plainTheme)[0]), /⧗ background · npm test --silent/u);
181
+ assert.match(unpaint(callRows(resolver, 'monitor', { command: 'tail -f app.log', label: 'app log', timeout_seconds: 60 }, plainTheme)[0]), /◉ monitor · app log/u);
182
+ assert.match(unpaint(callRows(resolver, 'job_stop', { job_id: 'job-2' }, plainTheme)[0]), /■ stop · job-2/u);
183
+ assert.match(unpaint(callRows(resolver, 'job_list', {}, plainTheme)[0]), /≡ jobs · this session/u);
184
+ });
185
+
186
+ test('expanded, the whole command is stated below the heading, every line of it', () => {
187
+ publishBridge(ACTIVITY);
188
+ const rows = callRows(jobsResolver(), 'bash_background', { command: 'sleep 20\n\ngh run list --repo acme/api', label: LABEL }, plainTheme, 70, { isPartial: false, expanded: true }).map(unpaint);
189
+ const joined = rows.join('\n');
190
+ assert.match(joined, /Release runs for 1\.9\.1/u);
191
+ assert.match(joined, /│ sleep 20 +│/u);
192
+ assert.match(joined, /│ gh run list --repo acme\/api +│/u);
193
+ assertFramed(rows, 70);
194
+ });
195
+
196
+ test('a call still waiting for its result closes its own frame; once the result exists the result closes it', () => {
197
+ publishBridge(ACTIVITY);
198
+ const resolver = jobsResolver();
199
+ const state = {};
200
+ const running = slots(resolver, 'bash_background').renderCall({ command: COMMAND }, plainTheme, { isPartial: true, state }).render(70).map(unpaint);
201
+ assert.match(running.join('\n'), /running/iu);
202
+ assert.match(running.at(-1), /^╰/u, 'the running call closes itself');
203
+ const settled = callRows(resolver, 'bash_background', { command: COMMAND }, plainTheme, 70, { isPartial: false }).map(unpaint);
204
+ assert.doesNotMatch(settled.join('\n'), /^╰/mu, 'the result owns the closing rule');
205
+ });
206
+
207
+ // ---- the result ----
208
+
209
+ test('the result previews the first rows collapsed, everything expanded, and always closes the frame', () => {
210
+ publishBridge(ACTIVITY);
211
+ const resolver = jobsResolver();
212
+ const collapsed = resultRows(resolver, 'bash_background', { command: COMMAND }, `${STARTED}\nextra line four`).map(unpaint);
213
+ assert.match(collapsed.join('\n'), /Started background job job-2/u);
214
+ assert.doesNotMatch(collapsed.join('\n'), /extra line four/u, 'only the preview budget is drawn collapsed');
215
+ assert.match(collapsed.at(-1), /^╰/u);
216
+ const expanded = resultRows(resolver, 'bash_background', { command: COMMAND }, `${STARTED}\nextra line four`, { isPartial: false, expanded: true }).map(unpaint);
217
+ assert.match(expanded.join('\n'), /extra line four/u);
218
+ assert.match(expanded.at(-1), /^╰/u);
219
+ });
220
+
221
+ test('the minimal card content level draws the call alone, but a failure still says why', () => {
222
+ publishBridge(ACTIVITY);
223
+ globalThis[CARD_CONTENT_SLOT] = CARD_CONTENT.MINIMAL;
224
+ const resolver = jobsResolver();
225
+ const quiet = resultRows(resolver, 'bash_background', { command: COMMAND }, STARTED).map(unpaint);
226
+ assert.doesNotMatch(quiet.join('\n'), /Started background job/u);
227
+ assert.match(quiet.at(-1), /^╰/u, 'the frame still closes');
228
+ const failed = resultRows(resolver, 'job_stop', { job_id: 'job-9' }, 'No background job job-9 in this session.', { isPartial: false }, plainTheme, 70, { isError: true }).map(unpaint);
229
+ assert.match(failed.join('\n'), /No background job job-9 in this session\./u);
230
+ });
231
+
232
+ // ---- the style and the width ----
233
+
234
+ test('neon draws the outlined frame and float the borderless rail, whichever tool is drawn', () => {
235
+ publishBridge(ACTIVITY);
236
+ const resolver = jobsResolver();
237
+ for (const tool of JOB_TOOLS) {
238
+ const args = tool === 'job_stop' ? { job_id: 'job-2' } : tool === 'job_list' ? {} : { command: COMMAND, label: LABEL };
239
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.NEON;
240
+ const neon = [...callRows(resolver, tool, args, bandTheme), ...resultRows(resolver, tool, args, STARTED, { isPartial: false }, bandTheme)].map(unpaint);
241
+ assert.match(neon[0], /^╭/u, `${tool} neon`);
242
+ assert.match(neon.at(-1), /^╰/u);
243
+ globalThis[CARD_STYLE_SLOT] = CARD_STYLE.FLOAT;
244
+ const float = [...callRows(resolver, tool, args, bandTheme), ...resultRows(resolver, tool, args, STARTED, { isPartial: false }, bandTheme)].map(unpaint);
245
+ assert.doesNotMatch(float.join('\n'), /[╭╮╰╯]/u, `${tool} float draws no box`);
246
+ assert.match(float.join('\n'), /▎/u);
247
+ }
248
+ });
249
+
250
+ test('every row fits the width the host asked for, at narrow and wide terminals', () => {
251
+ publishBridge(ACTIVITY);
252
+ const resolver = jobsResolver();
253
+ for (const style of [CARD_STYLE.NEON, CARD_STYLE.FLOAT]) {
254
+ globalThis[CARD_STYLE_SLOT] = style;
255
+ for (const width of [24, 40, 70, 120]) {
256
+ const rows = [
257
+ ...callRows(resolver, 'bash_background', { command: COMMAND, label: LABEL }, bandTheme, width),
258
+ ...callRows(resolver, 'bash_background', { command: COMMAND, label: LABEL }, bandTheme, width, { isPartial: false, expanded: true }),
259
+ ...resultRows(resolver, 'bash_background', { command: COMMAND }, STARTED, { isPartial: false, expanded: true }, bandTheme, width),
260
+ ];
261
+ assertFramed(rows, width);
262
+ }
263
+ }
264
+ });
265
+
266
+ // ---- the wiring ----
267
+
268
+ test('registerJobsCard hands one resolver to the host hook and reports a host that has none', () => {
269
+ const handed = [];
270
+ const outcome = registerJobsCard({ registerToolRenderer: (resolver) => handed.push(resolver) }, { metrics });
271
+ assert.equal(outcome.registered, true);
272
+ assert.equal(handed.length, 1);
273
+ assert.deepEqual(registerJobsCard({}, { metrics }), { registered: false, resolver: undefined });
274
+ });
275
+
276
+ test('the Card tags line covers the four job tools, so the bridge can answer for them', () => {
277
+ for (const scopes of [true, false]) {
278
+ const design = toolsActivityDesign({ scopes });
279
+ for (const tool of JOB_TOOLS) assert.ok(design.tools.includes(tool), `${tool} (scopes: ${scopes})`);
280
+ for (const tool of ['bash', 'grep', 'find', 'ls', 'read', 'write']) assert.ok(design.tools.includes(tool), `${tool} stays covered`);
281
+ }
282
+ });
283
+
284
+ test('declaring the job tools on the line changes nothing the activity design draws: their rows come back exactly as given', () => {
285
+ const rows = ['\x1b[2m bash_background command="sleep 20" \x1b[22m', ' Started background job job-2. '];
286
+ for (const tool of JOB_TOOLS) {
287
+ for (const part of ['call', 'result']) {
288
+ const drawn = applyBashActivityHeading(rows, { width: 60, tool, theme: plainTheme, part, render: { args: { command: 'sleep 20' }, isPartial: false } });
289
+ assert.deepEqual(drawn, rows, `${tool} ${part}`);
290
+ }
291
+ }
292
+ });
@@ -73,7 +73,7 @@ describe('manifest', () => {
73
73
  // their own four modules — a classifier, the card, its resolver and the document
74
74
  // body Pi's Markdown draws — and own no preference at all (S1): they are gated by
75
75
  // the bridge's `Card tags` line, which is the bridge's, not ours.
76
- for (const kept of ['gh-issues.js', 'issue-preview.js', 'issues-view.js', 'warp-selector-view.js', 'odd-view.js', 'worktree-git.js', 'worktree-registry.js', 'worktree-session-guard.js', 'bash-activity.js', 'bash-design.js', 'bash-frame.js', 'diff-design.js', 'skill-odd-card.js', 'file-card.js', 'file-card-resolver.js', 'file-card-markdown.js']) {
76
+ for (const kept of ['gh-issues.js', 'issue-preview.js', 'issues-view.js', 'warp-selector-view.js', 'odd-view.js', 'worktree-git.js', 'worktree-registry.js', 'worktree-session-guard.js', 'skill-read-guard.js', 'bash-activity.js', 'bash-inline-script.js', 'bash-design.js', 'bash-frame.js', 'diff-design.js', 'skill-odd-card.js', 'file-card.js', 'file-card-resolver.js', 'file-card-markdown.js']) {
77
77
  assert.ok(shipped.includes(kept), `lib/${kept} is shipped`);
78
78
  }
79
79
  for (const gone of ['card-files-mode.js', 'cards-customize.js']) {
@@ -137,6 +137,20 @@ describe('registration', () => {
137
137
  }
138
138
  });
139
139
 
140
+ test('the skill-read guard is one more bash hook and adds no name (invariant 22)', async () => {
141
+ // invariant 22: the skill-read guard is one more `bash` observation, so the `tool_call`
142
+ // hooks stay the naming handler, the worktree bash and write guards and this one — a
143
+ // fifth would be a surface nobody asked for.
144
+ const source = stubbedSource();
145
+ assert.equal(source.split('pi.on("tool_call"').length - 1, 4, 'the naming handler, the worktree bash and write guards and the skill-read guard');
146
+ assert.ok(source.includes('libRequire("skill-read-guard.js")'), 'the decision comes from lib/skill-read-guard.js');
147
+ const { commands, tools } = await loadExtension({});
148
+ for (const gone of ['skill-read', 'skill_read', 'skill-read-guard']) {
149
+ assert.equal(commands.has(gone), false, `the guard adds no /${gone} command`);
150
+ assert.equal(tools.has(gone), false, `the guard adds no ${gone} tool`);
151
+ }
152
+ });
153
+
140
154
  test('both Card rows are registered once each, observed through the bridge\'s own object', async () => {
141
155
  // S2/S6: what a caller observes is the REGISTRATION, not a spelling in the source. A bridge
142
156
  // that publishes the release both lines need sees one design per line, each with its own id and
@@ -0,0 +1,316 @@
1
+ 'use strict';
2
+ // invariant 22 (T1, T2): the skill-read guard — the reader a `bash` call must not use
3
+ // on a skill file, and the sentence that says so.
4
+ //
5
+ // The guarded forms are one table: every refused and every allowed spelling, through
6
+ // the module's one entry point and, for the extension half, through the `tool_call`
7
+ // handler the host actually receives. The commands are INPUT TEXT only — the guard
8
+ // reads the string and never runs it — so no row below spawns anything, and the only
9
+ // scratch this file creates is the throwaway cwd the handler is called with, removed
10
+ // in teardown.
11
+ //
12
+ // Public behavior only: what `decideSkillReadGuard(command)` returns and what the
13
+ // handler the extension registered returns.
14
+
15
+ const { test, describe, before, after } = require('node:test');
16
+ const assert = require('node:assert/strict');
17
+ const fs = require('node:fs');
18
+ const os = require('node:os');
19
+ const path = require('node:path');
20
+ const { decideSkillReadGuard } = require('../lib/skill-read-guard.js');
21
+ const { loadExtension } = require('./fixtures/load-extension.js');
22
+
23
+ // The refusal, written out: a reworded sentence fails here. It says the call did not
24
+ // run, names the path it read and the ONE tool that replaces the command.
25
+ const refusalFor = (skillPath) => `This bash call was not run: it reads the skill file ${skillPath} — read skill files with the \`read\` tool instead.`;
26
+
27
+ const SKILL_PATH = '/home/dev/.agents/skills/release/SKILL.md';
28
+ const REFERENCE_PATH = '/home/dev/.agents/skills/release/references/commands.md';
29
+
30
+ // The offending call as it was issued, abridged at the end: one skill read mid-chain,
31
+ // among ordinary reading that must keep working.
32
+ const REAL_COMMAND = `cd /home/jona/dev/projects/odd-worktree && sed -n '1,80p' /home/jona/.agents/skills/release/SKILL.md; echo '=== reference: commits/PRs + cut a release ==='; sed -n '/,$p' docs/reference.md | head -60; echo '=== release.yml ==='; cat .github/workflows/release.yml | head -80`;
33
+ const REAL_SKILL_PATH = '/home/jona/.agents/skills/release/SKILL.md';
34
+
35
+ // Every refused spelling, with the path the reason must name.
36
+ const BLOCKED = [
37
+ [`sed -n '1,80p' ${SKILL_PATH}`, SKILL_PATH],
38
+ [`head -80 ${REFERENCE_PATH}`, REFERENCE_PATH],
39
+ ['cat skills/x/SKILL.md', 'skills/x/SKILL.md'],
40
+ ['cat ./skills/x/SKILL.md', './skills/x/SKILL.md'],
41
+ ['cat "skills/x/SKILL.md"', 'skills/x/SKILL.md'],
42
+ ["cat 'skills/my skill/SKILL.md'", 'skills/my skill/SKILL.md'],
43
+ ['cat ../skills/x/references/y.md', '../skills/x/references/y.md'],
44
+ ['cat ~/.agents/skills/gentle-ai/SKILL.md', '~/.agents/skills/gentle-ai/SKILL.md'],
45
+ ['head -n 20 skills/x/SKILL.md', 'skills/x/SKILL.md'],
46
+ ['tail -5 skills/x/SKILL.md', 'skills/x/SKILL.md'],
47
+ ['less skills/x/SKILL.md', 'skills/x/SKILL.md'],
48
+ ['more skills/x/SKILL.md', 'skills/x/SKILL.md'],
49
+ ['bat skills/x/SKILL.md', 'skills/x/SKILL.md'],
50
+ ['batcat skills/x/SKILL.md', 'skills/x/SKILL.md'],
51
+ ['nl skills/x/SKILL.md', 'skills/x/SKILL.md'],
52
+ ["awk '{print}' skills/x/SKILL.md", 'skills/x/SKILL.md'],
53
+ ["sed -e 's/a/b/' skills/x/SKILL.md", 'skills/x/SKILL.md'],
54
+ ["sed -n '/name/p' skills/x/references/commands.md", 'skills/x/references/commands.md'],
55
+ ['cat skills/x/SKILL.md | head -5', 'skills/x/SKILL.md'],
56
+ ['cat skills/x/SKILL.md 2>/dev/null', 'skills/x/SKILL.md'],
57
+ ['cat 2>/dev/null skills/x/SKILL.md', 'skills/x/SKILL.md'],
58
+ // The command position, not the first word: assignments and wrappers come before it.
59
+ ['SKILL_DIR=1 cat skills/x/SKILL.md', 'skills/x/SKILL.md'],
60
+ ['env FOO=1 cat skills/x/SKILL.md', 'skills/x/SKILL.md'],
61
+ ['time cat skills/x/SKILL.md', 'skills/x/SKILL.md'],
62
+ ['nice -n 5 cat skills/x/SKILL.md', 'skills/x/SKILL.md'],
63
+ // A skill read beside ordinary work refuses the whole call.
64
+ ['git status && cat skills/x/SKILL.md', 'skills/x/SKILL.md'],
65
+ ['echo start; sed -n 1p skills/x/SKILL.md', 'skills/x/SKILL.md'],
66
+ [REAL_COMMAND, REAL_SKILL_PATH],
67
+ ];
68
+
69
+ // Every allowed spelling: general Markdown, ODD artifacts, a skill path in argument
70
+ // text, a heredoc body, search, writes and listings.
71
+ const ALLOWED = [
72
+ 'sed -n 1p docs/reference.md',
73
+ 'sed -n 1,80p docs/reference.md',
74
+ "sed -n '/,$p' docs/reference.md | head -60",
75
+ 'cat README.md',
76
+ 'head -60 README.md',
77
+ 'cat .github/workflows/release.yml | head -80',
78
+ 'cat odd/tasks/feature.md',
79
+ 'cat odd/tasks/feature.md | head -20',
80
+ 'git commit -m "touched skills/x/SKILL.md"',
81
+ "echo 'see skills/x/SKILL.md'",
82
+ "echo '=== skills/x/SKILL.md ==='",
83
+ 'grep -n SKILL skills/x/SKILL.md',
84
+ "rg --files-with-matches 'SKILL' skills/",
85
+ 'grep -rn skills .github',
86
+ "sed -i 's/a/b/' skills/x/SKILL.md",
87
+ "sed -i.bak 's/a/b/' skills/x/SKILL.md",
88
+ "sed --in-place 's/a/b/' skills/x/SKILL.md",
89
+ 'cat > skills/x/SKILL.md',
90
+ 'cat >> skills/x/SKILL.md',
91
+ 'cat notes/a.md > skills/x/SKILL.md',
92
+ 'tee skills/x/SKILL.md',
93
+ 'ls skills/',
94
+ 'ls -la skills/x',
95
+ 'cat $HOME/.agents/skills/x/SKILL.md',
96
+ 'cat skills/*/SKILL.md',
97
+ 'cat -',
98
+ 'cat',
99
+ 'cat docs/SKILL.md',
100
+ 'cat notes/SKILL.md',
101
+ "sed -e '/skills/p' README.md",
102
+ "awk '/skills/p' README.md",
103
+ 'git diff docs/reference.md',
104
+ '',
105
+ ];
106
+
107
+ // A heredoc hands its body to the command as data: the skill path in it is never an
108
+ // argument, and the same is true of a body a reader cannot delimit.
109
+ const HEREDOCS = [
110
+ "cat <<'EOF' > notes.md\nsee skills/x/SKILL.md\nEOF",
111
+ 'cat <<EOF\ncat skills/x/SKILL.md\nEOF',
112
+ "git commit -F - <<'MSG'\nmoved skills/x/SKILL.md\nMSG",
113
+ ];
114
+
115
+ const bash = (command) => ({ toolName: 'bash', input: { command } });
116
+
117
+ // ---- the decision itself ----
118
+
119
+ describe('the decision (invariant 22)', () => {
120
+ test('refuses a reader pointed at a skill file, and names that path', () => {
121
+ for (const [command, skillPath] of BLOCKED) {
122
+ assert.deepEqual(decideSkillReadGuard(command), { block: true, reason: refusalFor(skillPath) }, command);
123
+ }
124
+ });
125
+
126
+ test('one call that reads two skills names the first one', () => {
127
+ assert.deepEqual(
128
+ decideSkillReadGuard('cat skills/a/SKILL.md; cat skills/b/SKILL.md'),
129
+ { block: true, reason: refusalFor('skills/a/SKILL.md') },
130
+ );
131
+ });
132
+
133
+ test('the refusal says the call did not run and names one tool', () => {
134
+ const { reason } = decideSkillReadGuard('cat skills/x/SKILL.md');
135
+ assert.equal(reason.includes('!'), false, `no exclamation: ${reason}`);
136
+ assert.equal(/[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u.test(reason), false, `no emoji: ${reason}`);
137
+ assert.match(reason, /was not run:/, `says the command did not run: ${reason}`);
138
+ assert.ok(reason.endsWith('.'), `ends with a period: ${reason}`);
139
+ assert.equal((reason.match(/`[a-z_]+`/g) || []).length, 1, `exactly one tool is named: ${reason}`);
140
+ assert.match(reason, /`read`/, `names read: ${reason}`);
141
+ });
142
+
143
+ test('allows everything that is not a read of a skill file', () => {
144
+ for (const command of [...ALLOWED, ...HEREDOCS]) {
145
+ assert.equal(decideSkillReadGuard(command), undefined, command);
146
+ }
147
+ });
148
+
149
+ test('garbage never throws and always allows', () => {
150
+ const values = [
151
+ undefined,
152
+ null,
153
+ 42,
154
+ {},
155
+ [],
156
+ ['cat'],
157
+ () => 'cat skills/x/SKILL.md',
158
+ "cat 'unterminated",
159
+ "sed -n '1,80p skills/x/SKILL.md",
160
+ 'cat <<EOF\nskills/x/SKILL.md',
161
+ '${cat} skills/x/SKILL.md',
162
+ '\u0000',
163
+ ];
164
+ for (const value of values) {
165
+ assert.equal(decideSkillReadGuard(value), undefined, String(value));
166
+ }
167
+ });
168
+ });
169
+
170
+ // ---- the handler the extension registers ----
171
+
172
+ const roots = [];
173
+
174
+ function track(dir) {
175
+ roots.push(dir);
176
+ return dir;
177
+ }
178
+
179
+ // The host's `tool_call` round trip: every registered handler in turn, and the first
180
+ // block answer is the block the host sees.
181
+ async function callTool(hooks, event, cwd) {
182
+ const handlers = hooks.filter(([name]) => name === 'tool_call').map(([, handler]) => handler);
183
+ for (const handler of handlers) {
184
+ const answer = await handler(event, { cwd });
185
+ if (answer !== undefined) return answer;
186
+ }
187
+ return undefined;
188
+ }
189
+
190
+ describe('the tool_call handler the extension registers', () => {
191
+ let loaded;
192
+ let cwd;
193
+
194
+ before(async () => {
195
+ loaded = await loadExtension({});
196
+ cwd = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-skill-read-guard-')));
197
+ });
198
+
199
+ after(() => {
200
+ for (const dir of roots) {
201
+ try {
202
+ fs.rmSync(dir, { recursive: true, force: true });
203
+ } catch {
204
+ // Best effort: a temp directory that is already gone is fine.
205
+ }
206
+ }
207
+ });
208
+
209
+ test('refuses a bash call that reads a skill file', async () => {
210
+ for (const [command, skillPath] of BLOCKED) {
211
+ assert.deepEqual(
212
+ await callTool(loaded.hooks, bash(command), cwd),
213
+ { block: true, reason: refusalFor(skillPath) },
214
+ command,
215
+ );
216
+ }
217
+ });
218
+
219
+ test('lets every other call through', async () => {
220
+ for (const command of [...ALLOWED, ...HEREDOCS]) {
221
+ assert.equal(await callTool(loaded.hooks, bash(command), cwd), undefined, command);
222
+ }
223
+ });
224
+
225
+ test('leaves every non-bash tool call exactly as the host proposed it', async () => {
226
+ const calls = [
227
+ { toolName: 'read', input: { path: 'skills/x/SKILL.md' } },
228
+ { toolName: 'grep', input: { pattern: 'SKILL', path: 'skills/x' } },
229
+ { toolName: 'edit', input: { path: 'skills/x/SKILL.md' } },
230
+ { toolName: 'worktree_list', input: {} },
231
+ ];
232
+ for (const event of calls) {
233
+ assert.equal(await callTool(loaded.hooks, event, cwd), undefined, JSON.stringify(event));
234
+ }
235
+ });
236
+
237
+ test('ODD_WORKTREE_GUARD=0 turns it off, and only that value', async () => {
238
+ const previous = process.env.ODD_WORKTREE_GUARD;
239
+ const command = 'cat skills/x/SKILL.md';
240
+ const expected = { block: true, reason: refusalFor('skills/x/SKILL.md') };
241
+ try {
242
+ for (const value of ['0', 'false', '', '1']) {
243
+ process.env.ODD_WORKTREE_GUARD = value;
244
+ const answer = await callTool(loaded.hooks, bash(command), cwd);
245
+ if (value === '0') assert.equal(answer, undefined, 'value "0" turns it off');
246
+ else assert.deepEqual(answer, expected, `value ${JSON.stringify(value)}`);
247
+ }
248
+ delete process.env.ODD_WORKTREE_GUARD;
249
+ assert.deepEqual(await callTool(loaded.hooks, bash(command), cwd), expected, 'unset keeps it on');
250
+ } finally {
251
+ if (previous === undefined) delete process.env.ODD_WORKTREE_GUARD;
252
+ else process.env.ODD_WORKTREE_GUARD = previous;
253
+ }
254
+ });
255
+
256
+ test('the worktree guard keeps precedence when one call does both', async () => {
257
+ const answer = await callTool(loaded.hooks, bash('git worktree add ../odd-b && cat skills/x/SKILL.md'), cwd);
258
+ assert.equal(answer.block, true, 'the call is refused');
259
+ assert.match(answer.reason, /`worktree_create`/, `the worktree refusal is the one shown: ${answer.reason}`);
260
+ });
261
+
262
+ test('garbage events never throw and always allow', async () => {
263
+ const events = [
264
+ { toolName: 'bash' },
265
+ { toolName: 'bash', input: {} },
266
+ { toolName: 'bash', input: { command: 42 } },
267
+ { toolName: 'bash', input: { command: {} } },
268
+ { toolName: 'bash', input: { command: "cat 'unterminated" } },
269
+ {},
270
+ null,
271
+ ];
272
+ for (const event of events) {
273
+ assert.equal(await callTool(loaded.hooks, event, cwd), undefined, JSON.stringify(event));
274
+ }
275
+ });
276
+ });
277
+
278
+ // ---- regressions an independent verification found ----
279
+ test('a skill is read through a real argument, not a search pattern or a normalised-away folder', () => {
280
+ const skill = 'skills/x/SKILL.md';
281
+ for (const command of [
282
+ `sed -ne'1p' ${skill}`,
283
+ `cat < ${skill}`,
284
+ `timeout 5s head ${skill}`,
285
+ `sudo cat ${skill}`,
286
+ `cat <<'EOF' | head ${skill}\ntext\nEOF`,
287
+ `cat "skills/x/[draft].md"`,
288
+ ]) {
289
+ const decision = decideSkillReadGuard(command);
290
+ assert.equal(decision && decision.block, true, command);
291
+ }
292
+ for (const command of ['cat skills/../README.md', `less +/${skill} docs/reference.md`, 'cat skills/x/[draft].md']) {
293
+ assert.equal(decideSkillReadGuard(command), undefined, command);
294
+ }
295
+ });
296
+
297
+ test('a skill read in shell syntax is refused, and a mention or a usage request is not', () => {
298
+ const skill = 'skills/x/SKILL.md';
299
+ for (const command of [
300
+ `cat <<'EOF' ${skill}\nhello\nEOF`,
301
+ `command cat ${skill}`,
302
+ `bash -c 'cat ${skill}'`,
303
+ `if true; then cat ${skill}; fi`,
304
+ ]) {
305
+ const decision = decideSkillReadGuard(command);
306
+ assert.equal(decision && decision.block, true, command);
307
+ assert.ok(decision.reason.includes(skill), command);
308
+ }
309
+ for (const command of [
310
+ `cat <<'ONE' <<'TWO'\nfirst\nONE\ncat ${skill}\nTWO`,
311
+ `echo hello # && cat ${skill}`,
312
+ `cat --help ${skill}`,
313
+ ]) {
314
+ assert.equal(decideSkillReadGuard(command), undefined, command);
315
+ }
316
+ });