pi-odd-worktree 3.8.1 → 3.9.1

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.
@@ -4,11 +4,22 @@
4
4
  // conversation's card style never reaches them. While the bridge's `Card activity` line answers
5
5
  // `activity` for the tool being drawn, this package draws them on its own card substrate
6
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.
7
+ // absence of an answer — draws what Pi draws for a tool with no renderer, inside the card that
8
+ // was already mounted.
9
+ //
10
+ // The answer is read on EVERY paint, inside the component the host already mounted, because Pi
11
+ // resolves a tool's renderers once (`interactive-mode.js`: `getRegisteredToolDefinition` goes
12
+ // into `ToolExecutionComponent` at construction) and never asks again. That is what makes a
13
+ // flipped `Card activity` line repaint the cards already on screen, exactly as it does for
14
+ // `bash`, and the cases below drive it that way: one mounted component, repainted.
8
15
  //
9
16
  // Every case goes through the public surface: the resolver, the slots it returns and the
10
17
  // rows a component draws for a width. The text seam and the themes are the fakes
11
18
  // `tools/file-card.test.js` uses; the bridge is the published object a process-wide slot holds.
19
+ //
20
+ // The rows the card hands back while the line says anything else are compared byte for byte
21
+ // with Pi's own drawing, reproduced here from the host's source (`tool-execution.js`,
22
+ // `render-utils.js`) and independently of this package's implementation.
12
23
  const assert = require('node:assert/strict');
13
24
  const { after, afterEach, beforeEach, test } = require('node:test');
14
25
 
@@ -115,9 +126,91 @@ function assertFramed(rows, width) {
115
126
  for (const row of rows) assert.equal(metrics.visibleWidth(unpaint(row)), width, `"${unpaint(row)}" is not ${width} wide`);
116
127
  }
117
128
 
129
+ // ---- Pi's own drawing for a tool with a definition and no renderer ----
130
+ //
131
+ // Reproduced from the host's source and independently of this package: `contentBox` is
132
+ // `new Box(1, 1, bgFn)` with the `outputPad` columns of horizontal padding, `addChild`s
133
+ // `createCallFallback()` — `formatToolCallWithArgs(toolName, args, theme, expanded)` — and,
134
+ // once the result exists, `createResultFallback()`; `Box.render` draws one painted blank row
135
+ // above, the children at `width - pad * 2` padded to the full width, and one blank below.
136
+ const hostTheme = {
137
+ fg: (role, value) => `<${role}>${value}</${role}>`,
138
+ bg: (role, value) => `<${role}>${value}</${role}>`,
139
+ bold: (value) => `<bold>${value}</bold>`,
140
+ };
141
+
142
+ /** `formatToolCallWithArgs`: the bold name, then `key=value` pairs — or one `key: value` row each. */
143
+ function piCallText(tool, args, expanded) {
144
+ const header = hostTheme.fg('toolTitle', hostTheme.bold(tool));
145
+ if (args === null || args === undefined) return header;
146
+ const entries = typeof args === 'object' && !Array.isArray(args) ? Object.entries(args) : [['args', args]];
147
+ if (entries.length === 0) return header;
148
+ if (expanded) {
149
+ const lines = entries.map(([key, value]) => {
150
+ const text = typeof value === 'string' ? value : JSON.stringify(value, null, 2) ?? String(value);
151
+ return ` ${key}: ${text.replace(/\t/g, ' ').replace(/\r/g, '').split('\n').join('\n ')}`;
152
+ });
153
+ return `${header}\n${hostTheme.fg('muted', lines.join('\n'))}`;
154
+ }
155
+ const pairs = entries.map(([key, value]) => `${key}=${JSON.stringify(value) ?? String(value)}`).join(' ');
156
+ const preview = pairs.length > 100 ? `${pairs.slice(0, 97)}...` : pairs;
157
+ return `${header} ${hostTheme.fg('muted', preview)}`;
158
+ }
159
+
160
+ // The host's own readers for a result's text (`dist/utils/ansi.js`: `stripAnsi`;
161
+ // `dist/utils/shell.js`: `sanitizeBinaryOutput`; then `\r` goes), transcribed from the host's
162
+ // source so the fallback rows can be compared byte for byte. Note what the host KEEPS: DEL
163
+ // (U+007F) is not in its list, and U+FFF9–U+FFFB are removed like binary controls.
164
+ const PI_ANSI = /(?:\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C))|(?:(?:\u001B\[|\u009B)[<=>]|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?)[\dA-PR-TZcf-nq-uy=><~]/g;
165
+ const PI_BINARY = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFF9-\uFFFB]/g;
166
+ const piText = (value) => value.replace(PI_ANSI, '').replace(PI_BINARY, '').replace(/\r/g, '');
167
+
168
+ /** `createResultFallback`: the result's text, ten rows collapsed, and the host's own expand hint. */
169
+ function piResultText(result, context) {
170
+ const output = result.content.filter((part) => part.type === 'text').map((part) => piText(part.text || '')).join('\n');
171
+ if (output === '') return undefined;
172
+ const lines = output.split('\n');
173
+ const shown = context.expanded === true ? lines : lines.slice(0, 10);
174
+ const remaining = lines.length - shown.length;
175
+ const text = shown.map((line) => hostTheme.fg('toolOutput', line)).join('\n');
176
+ if (remaining <= 0) return text;
177
+ return `${text}${hostTheme.fg('muted', `\n... (${remaining} more lines,`)} ${context.keyHint('app.tools.expand', 'to expand')}${hostTheme.fg('muted', ')')}`;
178
+ }
179
+
180
+ /** `Text(text, 0, 0).render(width)`: tabs are three spaces, wrapped, every row padded to the width. */
181
+ function piTextRows(text, width) {
182
+ if (text.trim() === '') return [];
183
+ return metrics.wrapTextWithAnsi(text.replace(/\t/g, ' '), Math.max(1, width))
184
+ .map((row) => row + ' '.repeat(Math.max(0, width - metrics.visibleWidth(row))));
185
+ }
186
+
187
+ /** The host's box around the given children, exactly as `Box.render` draws it for this state. */
188
+ function piBox(childTexts, width, context) {
189
+ const pad = context.outputPad ?? 1;
190
+ const role = context.isPartial !== false ? 'toolPendingBg' : context.isError === true ? 'toolErrorBg' : 'toolSuccessBg';
191
+ const contentWidth = Math.max(1, width - pad * 2);
192
+ const rows = childTexts.flatMap((text) => piTextRows(text, contentWidth));
193
+ if (rows.length === 0) return [];
194
+ const painted = (line) => hostTheme.bg(role, line + ' '.repeat(Math.max(0, width - metrics.visibleWidth(line))));
195
+ return [painted(''), ...rows.map((row) => painted(' '.repeat(pad) + row)), painted('')];
196
+ }
197
+
198
+ /** The key hint the host paints into a fallback result, the same seam the cards read. */
199
+ const keyHint = (_id, text) => `[${text}]`;
200
+ const settled = { isPartial: false, expanded: false, outputPad: 1, keyHint };
201
+
202
+ /** What Pi draws for one settled job card: the call's fallback and the result's, in one box. */
203
+ function piSettledRows(tool, args, text, context, width) {
204
+ const result = { content: [{ type: 'text', text }], details: {} };
205
+ const children = [piCallText(tool, args, context.expanded === true)];
206
+ const fallback = piResultText(result, context);
207
+ if (fallback !== undefined) children.push(fallback);
208
+ return piBox(children, width, context);
209
+ }
210
+
118
211
  // ---- the one switch ----
119
212
 
120
- test('the card is drawn only while the Card activity line answers activity; every other answer leaves Pi\'s own drawing', () => {
213
+ test('every answer but activity draws what Pi draws for a tool with no renderer, byte for byte', () => {
121
214
  const answers = [
122
215
  ['no bridge published', undefined],
123
216
  ['the bridge\'s native answer', { kind: 'native' }],
@@ -126,30 +219,133 @@ test('the card is drawn only while the Card activity line answers activity; ever
126
219
  ['another plugin\'s design', { kind: 'design', design: { id: 'acme.tools' } }],
127
220
  ['an answer nothing can read', 'garbage'],
128
221
  ];
222
+ const args = { command: COMMAND, label: LABEL };
129
223
  for (const [name, answer] of answers) {
130
224
  if (answer !== undefined) publishBridge(answer);
131
- for (const tool of JOB_TOOLS) assert.equal(slots(jobsResolver(), tool), PI_DEFAULT, `${name}: ${tool}`);
225
+ for (const tool of JOB_TOOLS) {
226
+ const callArgs = tool === 'job_stop' ? { job_id: 'job-2' } : tool === 'job_list' ? {} : args;
227
+ const resolver = jobsResolver();
228
+ const call = slots(resolver, tool).renderCall(callArgs, hostTheme, { args: callArgs, ...settled }).render(70);
229
+ const result = slots(resolver, tool)
230
+ .renderResult({ content: [{ type: 'text', text: STARTED }], details: {} }, settled, hostTheme, { args: callArgs, state: {}, ...settled })
231
+ .render(70);
232
+ assert.deepEqual([...call, ...result], piSettledRows(tool, callArgs, STARTED, settled, 70), `${name}: ${tool}`);
233
+ }
132
234
  delete globalThis[BRIDGE_API_SLOT];
133
235
  }
134
236
  // A bridge too old to carry the reader, and one whose reader throws, are no answer either.
135
237
  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);
238
+ assert.deepEqual(
239
+ [...callRows(jobsResolver(), 'bash_background', args, hostTheme, 70, settled), ...resultRows(jobsResolver(), 'bash_background', args, STARTED, settled, hostTheme, 70, settled)],
240
+ piSettledRows('bash_background', args, STARTED, settled, 70),
241
+ 'a bridge older than the reader',
242
+ );
137
243
  publishBridge(() => { throw new Error('boom'); });
138
- assert.equal(slots(jobsResolver(), 'bash_background'), PI_DEFAULT);
244
+ assert.deepEqual(
245
+ [...callRows(jobsResolver(), 'bash_background', args, hostTheme, 70, settled), ...resultRows(jobsResolver(), 'bash_background', args, STARTED, settled, hostTheme, 70, settled)],
246
+ piSettledRows('bash_background', args, STARTED, settled, 70),
247
+ 'a reader that throws',
248
+ );
249
+ });
250
+
251
+ test('a call still running keeps the host\'s box closed below it, because no result follows yet', () => {
252
+ publishBridge({ kind: 'native' });
253
+ const args = { command: COMMAND };
254
+ const running = callRows(jobsResolver(), 'bash_background', args, hostTheme, 60, { isPartial: true, outputPad: 1 });
255
+ assert.deepEqual(running, piBox([piCallText('bash_background', args, false)], 60, { isPartial: true, outputPad: 1 }));
256
+ assert.equal(metrics.visibleWidth(unpaint(running[0])), 60, 'the box paints its blank rows to the whole width');
139
257
  });
140
258
 
141
- test('while activity is selected the four job tools get a self-framed card and the bridge is asked per tool', () => {
259
+ test('a result that states nothing leaves the host\'s box closed, with no row of its own', () => {
260
+ publishBridge({ kind: 'native' });
261
+ const args = { job_id: 'job-2' };
262
+ const resolver = jobsResolver();
263
+ const call = callRows(resolver, 'job_stop', args, hostTheme, 50, settled);
264
+ const result = resultRows(resolver, 'job_stop', args, '', settled, hostTheme, 50, settled);
265
+ assert.deepEqual([...call, ...result], piSettledRows('job_stop', args, '', settled, 50), 'the host draws the box around the call alone');
266
+ assert.deepEqual(result, [piBox([piCallText('job_stop', args, false)], 50, settled).at(-1)], 'the result half is that box\'s closing row');
267
+ });
268
+
269
+ /**
270
+ * One pass of Pi's own component: the result half is BUILT when its update arrives (before the
271
+ * pass), then the pass renders the call and the result inside the one box. The card is driven in
272
+ * that same order, so a mark made while painting cannot hide behind the next frame.
273
+ */
274
+ function piPass(resolver, tool, args, text, context, width) {
275
+ const state = {};
276
+ const options = { isPartial: context.isPartial === true, expanded: context.expanded === true };
277
+ const result = slots(resolver, tool).renderResult({ content: [{ type: 'text', text }], details: {} }, options, hostTheme, { args, state, ...context });
278
+ const call = slots(resolver, tool).renderCall(args, hostTheme, { args, state, ...context });
279
+ return [...call.render(width), ...result.render(width)];
280
+ }
281
+
282
+ test('a PARTIAL result closes the host\'s box once, exactly as the host draws it', () => {
283
+ publishBridge({ kind: 'native' });
284
+ const partial = { isPartial: true, expanded: false, outputPad: 2, keyHint };
285
+ const args = { command: 'tail -f app.log', label: 'app log' };
286
+ const resolver = jobsResolver();
287
+ assert.deepEqual(piPass(resolver, 'monitor', args, STARTED, partial, 84), piSettledRows('monitor', args, STARTED, partial, 84), 'the call waits while its result streams');
288
+ // An empty partial result is no child at all: the box is the one around the call.
289
+ assert.deepEqual(piPass(resolver, 'monitor', args, '', partial, 84), piSettledRows('monitor', args, '', partial, 84));
290
+ });
291
+
292
+ test('the host\'s own reader sanitizes a result, byte for byte', () => {
293
+ publishBridge({ kind: 'native' });
294
+ // A CSI colour, a BEL, the interlinear annotations the host strips, a CR and a DEL — which
295
+ // the host's own list does NOT remove (`sanitizeBinaryOutput`).
296
+ const raw = 'first \u001B[31mred\u001B[0m\uFFFB row\u0007\r\nsecond\u007F row';
297
+ const args = { command: COMMAND };
298
+ const resolver = jobsResolver();
299
+ assert.deepEqual(piPass(resolver, 'bash_background', args, raw, settled, 70), piSettledRows('bash_background', args, raw, settled, 70));
300
+ const drawn = piPass(resolver, 'bash_background', args, raw, settled, 70).join('\n');
301
+ assert.doesNotMatch(unpaint(drawn), /\u001B|\uFFFB|\u0007/u, 'the host strips these');
302
+ assert.match(unpaint(drawn), /second\u007F row/u, 'and the host keeps DEL, so the card keeps it too');
303
+ });
304
+
305
+ test('the four job tools are always the card\'s, and the line is read on every paint, never at build time', () => {
142
306
  const asked = [];
143
307
  publishBridge(ACTIVITY, asked);
144
308
  const resolver = jobsResolver();
145
- for (const tool of JOB_TOOLS) {
146
- const drawn = slots(resolver, tool);
309
+ const slots_ = JOB_TOOLS.map((tool) => slots(resolver, tool));
310
+ assert.deepEqual(asked, [], 'building the card asks nothing: Pi would never ask again');
311
+ for (const [index, tool] of JOB_TOOLS.entries()) {
312
+ const drawn = slots_[index];
147
313
  assert.notEqual(drawn, PI_DEFAULT, tool);
148
314
  assert.equal(drawn.renderShell, 'self', `${tool} frames itself`);
149
315
  assert.equal(typeof drawn.renderCall, 'function');
150
316
  assert.equal(typeof drawn.renderResult, 'function');
151
317
  }
152
- assert.deepEqual(asked, [...JOB_TOOLS]);
318
+ for (const [index, tool] of JOB_TOOLS.entries()) {
319
+ const args = tool === 'job_stop' ? { job_id: 'job-2' } : tool === 'job_list' ? {} : { command: COMMAND };
320
+ slots_[index].renderCall(args, plainTheme, { args, ...settled }).render(70);
321
+ assert.deepEqual(asked.at(-1), tool, `${tool} is asked on its own name`);
322
+ slots_[index].renderResult({ content: [{ type: 'text', text: STARTED }], details: {} }, settled, plainTheme, { args, state: {}, ...settled }).render(70);
323
+ assert.deepEqual(asked.at(-1), tool, `${tool}'s result asks the same question`);
324
+ }
325
+ assert.equal(asked.length, JOB_TOOLS.length * 2, 'one question per painted slot, and no other');
326
+ });
327
+
328
+ test('a mounted card repaints when the line flips, in both directions', () => {
329
+ const asked = [];
330
+ publishBridge(ACTIVITY, asked);
331
+ const resolver = jobsResolver();
332
+ const args = { command: COMMAND, label: LABEL };
333
+ // ONE card, mounted: the components the host built before any of this changed.
334
+ const call = slots(resolver, 'bash_background').renderCall(args, hostTheme, { args, ...settled });
335
+ const result = slots(resolver, 'bash_background')
336
+ .renderResult({ content: [{ type: 'text', text: STARTED }], details: {} }, settled, hostTheme, { args, state: {}, ...settled });
337
+ const on = { call: call.render(70), result: result.render(70) };
338
+ assert.match(unpaint(on.call[0]), /⧗ bash background · Release runs/u, 'the card is drawn while the line says activity');
339
+ // The line is turned off, and the SAME mounted components are repainted.
340
+ publishBridge({ kind: 'native' });
341
+ const off = { call: call.render(70), result: result.render(70) };
342
+ assert.deepEqual([...off.call, ...off.result], piSettledRows('bash_background', args, STARTED, settled, 70), 'flipped off, the rows are the host\'s own');
343
+ assert.doesNotMatch(unpaint(off.call.join('\n')), /⧗/u, 'the card\'s mark is gone');
344
+ // And back on, from the same two components.
345
+ publishBridge(ACTIVITY, asked);
346
+ assert.deepEqual(call.render(70), on.call, 'flipped back on, the card is drawn again, unchanged');
347
+ assert.deepEqual(result.render(70), on.result, 'the result half too');
348
+ assert.equal(asked.length, 4, 'each paint of each half asked the line once: two paints on, and two back on');
153
349
  });
154
350
 
155
351
  test('no other tool is ever claimed: bash, the file tools and an unknown tool come back as the chain resolved them', () => {
@@ -270,6 +270,37 @@ test('a live flip repaints the message and turns it off again, with no re-regist
270
270
  assert.ok(wire.bridge.resolutions >= 4, 'the follow was read on every pass');
271
271
  });
272
272
 
273
+ /**
274
+ * One MOUNTED message component: the rows the bridge answers for this message, read again on
275
+ * every paint. Mounted once, like the component Pi builds for a custom message — nothing here
276
+ * is rebuilt between the flips below, which is exactly the claim (S5).
277
+ */
278
+ function mountMessage(state, customType, lines, width = 70) {
279
+ const hostRows = [...lines];
280
+ return {
281
+ render() {
282
+ return renderMessage(state, customType, hostRows, width);
283
+ },
284
+ };
285
+ }
286
+
287
+ test('a mounted message card repaints when Card activity flips, in both directions', () => {
288
+ // S5: the message designs are FOLLOWED per pass by the bridge, so a mounted message
289
+ // (Pi builds one per message and never asks its renderer again) repaints when the line
290
+ // moves — the one claim this card has to make good on, and the reason it owns no switch.
291
+ const wire = registered({ toolLine: ACTIVITY });
292
+ const input = plainBody(EXPLORATION, STARTED);
293
+ const mounted = mountMessage(wire.bridge, EXPLORATION, input);
294
+ const on = mounted.render();
295
+ assert.equal(unpaint(on[0]), headOf(EXPLORATION_HEADING, 70), 'the card is drawn while the line says activity');
296
+ wire.bridge.toolLine = 'native';
297
+ assert.deepEqual(mounted.render(), input, 'flipped off, the very same component draws Pi\'s own rows, byte for byte');
298
+ wire.bridge.toolLine = ACTIVITY;
299
+ assert.deepEqual(mounted.render(), on, 'flipped back on, the card is drawn again, unchanged');
300
+ assert.equal(wire.bridge.calls.length, 1, 'no re-registration: one design, asked again on every pass');
301
+ assert.equal(wire.bridge.resolutions, 3, 'the follow was read on each of the three passes');
302
+ });
303
+
273
304
  test('registration needs no store, so no seed is written for a switch that already exists', () => {
274
305
  // The fake publishes no `createStore`: a module that seeded anything would have to throw here.
275
306
  const outcome = registered();
@@ -3,12 +3,29 @@
3
3
  // switches. The switches are read ONCE, when the extension registers, from the bridge's
4
4
  // store, and a missing document keeps everything on — so every other suite in this package
5
5
  // loads the whole thing.
6
- const { test, describe, afterEach } = require('node:test');
6
+ const { test, describe, after, afterEach } = require('node:test');
7
7
  const assert = require('node:assert/strict');
8
8
  const os = require('node:os');
9
9
 
10
10
  const { BRIDGE_SLOT, defaultBridge, loadExtension } = require('./fixtures/load-extension.js');
11
11
 
12
+ // The prompt assertions below read the extension's own `before_agent_start`, which honors these
13
+ // two switches from the ambient environment: a suite that ran inside a subagent child (or under
14
+ // `ODD_WORKTREE_PROMPT=0`) would otherwise assert against a prompt the extension was told to keep
15
+ // empty. They are cleared once here, so the cases are the same in every environment.
16
+ const savedPromptEnv = {
17
+ child: process.env.GENTLE_PI_AGENTS_CHILD,
18
+ prompt: process.env.ODD_WORKTREE_PROMPT,
19
+ };
20
+ delete process.env.GENTLE_PI_AGENTS_CHILD;
21
+ delete process.env.ODD_WORKTREE_PROMPT;
22
+ after(() => {
23
+ for (const [key, value] of [['GENTLE_PI_AGENTS_CHILD', savedPromptEnv.child], ['ODD_WORKTREE_PROMPT', savedPromptEnv.prompt]]) {
24
+ if (value === undefined) delete process.env[key];
25
+ else process.env[key] = value;
26
+ }
27
+ });
28
+
12
29
  const saved = globalThis[BRIDGE_SLOT];
13
30
  afterEach(() => {
14
31
  if (saved === undefined) delete globalThis[BRIDGE_SLOT];
@@ -75,9 +92,12 @@ describe('Worktrees+', () => {
75
92
  assert.equal(off.commands.has('warp'), false);
76
93
  assert.equal(off.messageRenderers.has('worktree-warp'), false);
77
94
  assert.doesNotMatch(await promptOf(off, []), /## ODD worktrees/);
78
- // the naming handler, the bash guard and the write guard go; the skill-read guard stays
79
- assert.equal(toolCallHandlers(on) - toolCallHandlers(off), 3);
80
- assert.ok(toolCallHandlers(off) >= 1, 'the skill-read guard is transversal');
95
+ // the naming handler, the bash guard, the write guard, the skill-read bash guard and the
96
+ // whole-read rule go: every ``tool_call`` observation of the worktree half
97
+ assert.equal(toolCallHandlers(on) - toolCallHandlers(off), 5);
98
+ // The CodeGraph wiring adds ONE `tool_call` observation of its own, and only where its CLI is
99
+ // installed — so a host without it leaves zero, and neither answer is this half's.
100
+ assert.ok(toolCallHandlers(off) <= 1, `at most the CodeGraph observation is left, got ${toolCallHandlers(off)}`);
81
101
  for (const name of ['odd', 'files']) assert.ok(off.commands.has(name), `${name} stays`);
82
102
  assert.equal(off.hooks.some(([hook]) => hook === 'agent_settled'), false, 'the warp settle tick goes');
83
103
  });
@@ -105,21 +125,45 @@ describe('Codegraph+', () => {
105
125
  });
106
126
 
107
127
  describe('the CodeGraph card', () => {
108
- const cardResolvers = async (modules, selection) => {
128
+ // The card claims `codegraph` on EVERY answer, because Pi resolves a tool's renderers once,
129
+ // when it mounts the card, and never asks again: the `Card activity` line is read inside the
130
+ // component, on every paint, and a flipped line repaints the card already on screen. What this
131
+ // file can observe is the ROWS — with any answer but `activity`, and with no reader at all, the
132
+ // chain's own renderer keeps them untouched — and that the card is still the one answering,
133
+ // which is what a flip depends on. (This load injects no text seam, so the card itself degrades
134
+ // to the host's drawing here; tools/codegraph-card.test.js proves the card's own rows.)
135
+ const CHAIN = {
136
+ renderShell: 'self',
137
+ renderCall: () => ({ render: () => ['the chain drew this'], invalidate() {} }),
138
+ renderResult: () => ({ render: () => ['the chain drew this too'], invalidate() {} }),
139
+ };
140
+
141
+ /** The CodeGraph card's own answer on this load, as the call rows it draws — or [] when none claims. */
142
+ const cardRows = async (modules, selection) => {
109
143
  const resolvers = [];
110
144
  await load(modules, { selection, host: { registerToolRenderer: (resolver) => resolvers.push(resolver) } });
111
- return resolvers.filter((resolver) => resolver('codegraph', () => undefined) !== undefined).length;
145
+ return resolvers
146
+ .map((resolver) => resolver('codegraph', () => CHAIN))
147
+ .filter((slot) => slot !== CHAIN && slot?.renderShell === 'self' && typeof slot.renderCall === 'function')
148
+ .map((slot) => slot.renderCall({ operation: 'status' }, undefined, { isPartial: false }).render(24));
112
149
  };
113
150
 
114
- test('is a design of the `Card activity` line: activity on paints it, and Codegraph+ off keeps it', async () => {
115
- assert.equal(await cardResolvers(undefined, ACTIVITY), 1, 'activity on, both modules on');
116
- assert.equal(await cardResolvers({ codegraph: false }, ACTIVITY), 1, 'Codegraph+ off does not take the card away');
151
+ test('is a design of the `Card activity` line: activity on answers it, and Codegraph+ off keeps it', async () => {
152
+ for (const modules of [undefined, { codegraph: false }]) {
153
+ assert.deepEqual(await cardRows(modules, ACTIVITY), [['the chain drew this']], `the card answers whatever the line says (${JSON.stringify(modules)})`);
154
+ }
117
155
  });
118
156
 
119
- test('is not a module surface: native leaves every row to the chain', async () => {
120
- assert.equal(await cardResolvers(undefined, () => ({ kind: 'native' })), 0);
121
- assert.equal(await cardResolvers({ codegraph: false }, () => ({ kind: 'native' })), 0);
122
- assert.equal(await cardResolvers(undefined, undefined), 0, 'no reader, no switch, no card');
157
+ test('is not a module surface: native, another answer and no reader hand every row back to the chain', async () => {
158
+ for (const [name, selection] of [
159
+ ['native', () => ({ kind: 'native' })],
160
+ ['another plugin\'s design', () => ({ kind: 'design', design: { id: 'acme.tools' } })],
161
+ ['no reader at all', undefined],
162
+ ]) {
163
+ for (const modules of [undefined, { codegraph: false }]) {
164
+ assert.deepEqual(await cardRows(modules, selection), [['the chain drew this']], `${name} (${JSON.stringify(modules)}): the rows are the chain's`);
165
+ }
166
+ }
123
167
  });
124
168
  });
125
169
 
@@ -137,13 +137,14 @@ 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.
140
+ test('the skill rules are two more hooks and add no name (invariant 22)', async () => {
141
+ // invariant 22 (S5 of skill-read-full): the `tool_call` hooks are the naming handler, the
142
+ // worktree bash and write guards, the skill-read bash guard and the whole-read rule, all of
143
+ // them under `Worktrees+` — a sixth would be a surface nobody asked for.
144
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');
145
+ assert.equal(source.split('pi.on("tool_call"').length - 1, 5, 'the naming handler, the two worktree guards, the skill-read guard and the whole-read rule');
146
146
  assert.ok(source.includes('libRequire("skill-read-guard.js")'), 'the decision comes from lib/skill-read-guard.js');
147
+ assert.ok(source.includes('libRequire("artifact-read-full.js")'), 'the whole-read decision comes from lib/artifact-read-full.js');
147
148
  const { commands, tools } = await loadExtension({});
148
149
  for (const gone of ['skill-read', 'skill_read', 'skill-read-guard']) {
149
150
  assert.equal(commands.has(gone), false, `the guard adds no /${gone} command`);
@@ -0,0 +1,156 @@
1
+ 'use strict';
2
+ // S1-S5 (skill-read-full): a skill's or an ODD's Markdown is read whole, the decision the
3
+ // extension's `tool_call` handler makes is a mutation of the host's own input, and the rule
4
+ // follows the `Worktrees+` module switch.
5
+ //
6
+ // The pure half is exercised directly; the wiring half loads the extension and drives
7
+ // the registered handlers with the event the host sends, which is the only way to prove
8
+ // the mutation reaches the tool.
9
+ const { test, describe } = require('node:test');
10
+ const assert = require('node:assert/strict');
11
+ const os = require('node:os');
12
+
13
+ const { isArtifactMarkdown, keepArtifactReadWhole } = require('../lib/artifact-read-full.js');
14
+ const { BRIDGE_SLOT, defaultBridge, loadExtension } = require('./fixtures/load-extension.js');
15
+
16
+ // S5: the module switch is read from the bridge's own store when the extension registers, so a
17
+ // suite that turns `Worktrees+` off publishes the document first and restores the slot after.
18
+ const savedBridge = globalThis[BRIDGE_SLOT];
19
+ async function loadWithModules(modules) {
20
+ const bridge = defaultBridge();
21
+ bridge.api.createStore = () => ({
22
+ get: (key, fallback) => (key === 'modules' && modules !== undefined ? modules : fallback),
23
+ set: () => {},
24
+ delete: () => {},
25
+ });
26
+ globalThis[BRIDGE_SLOT] = bridge.api;
27
+ try {
28
+ return await loadExtension({});
29
+ } finally {
30
+ if (savedBridge === undefined) delete globalThis[BRIDGE_SLOT];
31
+ else globalThis[BRIDGE_SLOT] = savedBridge;
32
+ }
33
+ }
34
+
35
+ const SKILL = '/home/me/project/skills/release/SKILL.md';
36
+
37
+ describe('what counts as an artifact\'s Markdown', () => {
38
+ test('a .md below a skills or an odd folder, at any depth', () => {
39
+ for (const path of [
40
+ SKILL,
41
+ 'skills/release/SKILL.md',
42
+ '/a/b/skills/x/references/notes.md',
43
+ 'C:\\repo\\skills\\x\\SKILL.MD',
44
+ 'odd/tasks/a.md',
45
+ '/home/me/project/odd/tasks/section-placement.md',
46
+ ]) {
47
+ assert.equal(isArtifactMarkdown(path), true, path);
48
+ }
49
+ });
50
+
51
+ test('everything else is not: other folders, a non-Markdown file, a sibling name, no path', () => {
52
+ for (const path of [
53
+ 'lib/skillset/notes.md',
54
+ 'docs/oddity.md',
55
+ 'skills/release/scripts/run.js',
56
+ 'skills/release/SKILL',
57
+ undefined,
58
+ null,
59
+ 42,
60
+ '',
61
+ ]) {
62
+ assert.equal(isArtifactMarkdown(path), false, String(path));
63
+ }
64
+ });
65
+ });
66
+
67
+ describe('the patch', () => {
68
+ test('offset and limit are dropped, and both are reported', () => {
69
+ const input = { path: SKILL, offset: 1, limit: 90 };
70
+ assert.deepEqual(keepArtifactReadWhole('read', input), { patched: true, dropped: ['offset', 'limit'] });
71
+ assert.deepEqual(input, { path: SKILL }, 'the host executes a whole read');
72
+ });
73
+
74
+ test('one field alone is dropped alone', () => {
75
+ const onlyOffset = { path: SKILL, offset: 12 };
76
+ assert.deepEqual(keepArtifactReadWhole('read', onlyOffset), { patched: true, dropped: ['offset'] });
77
+ assert.deepEqual(onlyOffset, { path: SKILL });
78
+ const onlyLimit = { path: SKILL, limit: 5 };
79
+ assert.deepEqual(keepArtifactReadWhole('read', onlyLimit), { patched: true, dropped: ['limit'] });
80
+ assert.deepEqual(onlyLimit, { path: SKILL });
81
+ });
82
+
83
+ test('a whole read, another tool and a non-skill path are untouched', () => {
84
+ const whole = { path: SKILL };
85
+ assert.deepEqual(keepArtifactReadWhole('read', whole), { patched: false, dropped: [] });
86
+ assert.deepEqual(whole, { path: SKILL });
87
+
88
+ const other = { path: 'lib/odd-worktree-worktrees/x.md', offset: 1, limit: 2, extra: 'kept' };
89
+ assert.deepEqual(keepArtifactReadWhole('read', other), { patched: false, dropped: [] });
90
+ assert.deepEqual(other, { path: 'lib/odd-worktree-worktrees/x.md', offset: 1, limit: 2, extra: 'kept' });
91
+
92
+ const edit = { path: SKILL, offset: 1, limit: 2 };
93
+ assert.deepEqual(keepArtifactReadWhole('edit', edit), { patched: false, dropped: [] });
94
+ assert.deepEqual(edit, { path: SKILL, offset: 1, limit: 2 });
95
+ });
96
+
97
+ test('a hostile input never throws', () => {
98
+ for (const value of [null, undefined, 42, 'path', []]) {
99
+ assert.doesNotThrow(() => keepArtifactReadWhole('read', value));
100
+ assert.deepEqual(keepArtifactReadWhole('read', value), { patched: false, dropped: [] });
101
+ }
102
+ const hostile = { get path() { throw new Error('boom'); }, offset: 1 };
103
+ assert.deepEqual(keepArtifactReadWhole('read', hostile), { patched: false, dropped: [] });
104
+ });
105
+ });
106
+
107
+ describe('the extension wiring', () => {
108
+ const readEvent = (input) => ({ type: 'tool_call', toolName: 'read', toolCallId: 'call-1', input });
109
+
110
+ const runToolCall = async (loaded, event, ctx = { cwd: os.tmpdir() }) => {
111
+ let answer;
112
+ for (const [name, handler] of loaded.hooks) {
113
+ if (name !== 'tool_call') continue;
114
+ const result = await handler(event, ctx);
115
+ if (result !== undefined) answer = result;
116
+ }
117
+ return answer;
118
+ };
119
+
120
+ test('a skill read with a range is executed whole, and the call is not blocked', async () => {
121
+ const loaded = await loadExtension({});
122
+ const event = readEvent({ path: SKILL, offset: 1, limit: 90 });
123
+ const answer = await runToolCall(loaded, event);
124
+ assert.equal(answer, undefined, 'nothing is blocked: the call still runs');
125
+ assert.deepEqual(event.input, { path: SKILL }, 'the host executes a whole read');
126
+ });
127
+
128
+ test('an ordinary read keeps its range, byte for byte', async () => {
129
+ const loaded = await loadExtension({});
130
+ const event = readEvent({ path: 'lib/skill-read-full.js', offset: 3, limit: 40 });
131
+ await runToolCall(loaded, event);
132
+ assert.deepEqual(event.input, { path: 'lib/skill-read-full.js', offset: 3, limit: 40 });
133
+ });
134
+
135
+ test('S5: worktrees+ off leaves the read exactly as the host proposed it', async () => {
136
+ const loaded = await loadWithModules({ worktrees: false });
137
+ const event = readEvent({ path: SKILL, offset: 1, limit: 90 });
138
+ await runToolCall(loaded, event);
139
+ assert.deepEqual(event.input, { path: SKILL, offset: 1, limit: 90 });
140
+ });
141
+
142
+ test('an odd artifact read with a range is executed whole too', async () => {
143
+ const loaded = await loadExtension({});
144
+ const event = readEvent({ path: 'odd/tasks/x.md', offset: 40, limit: 10 });
145
+ await runToolCall(loaded, event);
146
+ assert.deepEqual(event.input, { path: 'odd/tasks/x.md' });
147
+ });
148
+
149
+ test('the old bash guard still refuses a skill printed with a reader', async () => {
150
+ const loaded = await loadExtension({});
151
+ const event = { type: 'tool_call', toolName: 'bash', toolCallId: 'call-2', input: { command: `cat ${SKILL}` } };
152
+ const answer = await runToolCall(loaded, event);
153
+ assert.equal(answer?.block, true, 'the bash reader is still refused');
154
+ assert.match(answer.reason, /read/);
155
+ });
156
+ });