repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

Iteration 12: Hardened wrapper scripts by replacing os.execute/string command construction with pandoc.pipe argv-list calls in batch-convert, md-to-pdf, web-to-md, and docx-to-md. Fixed batch pattern bug and changed web-to-md to preserve H1 instead of silently shifting it into metadata. Verified filenames with spaces, docx→md with spaces, web H1 preservation, 0 os.execute in scripts, 9/9 filters pass.

6a0ae4c8954f02dc292fd1fe9717ca61fd3c947e

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Result: {"status":"keep","skill_quality":31}

Changed files (8)

.pi/autoresearch/session.jsonl

Modified
1 1 {"run":10,"commit":"4d2e499","metric":29,"metrics":{},"status":"keep","description":"Iteration 10: Added Programmatic Lua API subsection under Lua Filters covering pandoc.read/write, building Pandoc docs from scratch, file→transform→write pipelines, format conversion in Lua, and metadata access. Verified all programmatic examples with pandoc lua. Fixed expected HTML output for manual Header (no auto id). 9/9 filters pass.","timestamp":1780157777826,"segment":0,"confidence":null,"asi":{"hypothesis":"Add programmatic Lua API coverage for agents that need document processing in code, not shell; fix example accuracy against actual pandoc output","new_coverage":"pandoc.read, pandoc.write, build AST from scratch, doc:walk transform, file read/write, metadata access","examples_verified":"4 programmatic examples passed via pandoc lua","accuracy_fix":"manual Header output has no id unless attr set; corrected expected output","filters":"9/9 pass"}}
2 +{"run":11,"commit":"df7626a","metric":30,"metrics":{},"status":"keep","description":"Iteration 11: Added pandoc-doctor.lua cross-platform diagnostics script and Decision Guide entry. Doctor reports pandoc/API version, OS/arch, reader/writer counts, key format support, common PDF engine availability, executable version, and markdown→html smoke test. Verified output, SKILL.md references, section refs, and 9/9 filters. Scripts: 6.","timestamp":1780157854132,"segment":0,"confidence":null,"asi":{"hypothesis":"Add environment diagnostics for agents debugging PDF engine/format/support failures; reduces troubleshooting friction without bloating main docs","doctor_checks":"version, API, OS/arch, readers/writers, important formats, PDF engines, executable, smoke test","validation":"doctor runs, key diagnostics present, no missing Decision Guide refs, 9/9 filters pass","scripts":6}}

extensions/super/__tests__/super.test.ts

Added
new file mode 100644
1 +import assert from "node:assert";
3 +import { describe, it } from "node:test";
5 +import {
6 + SessionManager,
7 + type ExtensionAPI,
8 + type ExtensionCommandContext,
9 + type Theme,
10 +} from "@earendil-works/pi-coding-agent";
12 +import registerTaskCommands, {
13 + createPushTaskTool,
14 + createStartTaskCommand,
15 + createFinishTaskCommand,
16 + createAbortTaskCommand,
17 + createDiscardTaskCommand,
18 + createAutoCommand,
19 +} from "../index.ts";
21 +const path: PathFn = (name, fn, ...children) => ({ name, fn, children });
24 +pathSuite("manual workflow", (path) => {
25 + return [
26 + path("push AAA", async (h) => {
27 + h.appendUserMessage("main work");
28 + h.appendAssistantMessage("working...");
29 + await h.runPushTask("Task AAA");
30 + assert.strictEqual(h.getStatus(), "pending task: task-aaa");
31 + assert.ok(!h.isLlmTriggered());
32 + h.assertBranchHistory(
33 + user("main work"),
34 + assistant("working..."),
35 + task("Task AAA"),
36 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
37 + );
38 + },
39 + path("discard AAA", async (h) => {
40 + await h.runDiscardTask();
41 + assert.strictEqual(h.getStatus(), undefined);
42 + assert.ok(!h.isLlmTriggered());
43 + h.assertBranchHistory(
44 + user("main work"),
45 + assistant("working..."),
46 + task("Task AAA"),
47 + notification("Task discarded."),
48 + );
49 + }),
50 + path("start AAA", async (h) => {
51 + await h.runStartTask();
52 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
53 + assert.ok(h.isLlmTriggered());
54 + h.assertBranchHistory(
55 + user("Task AAA"),
56 + );
57 + },
58 + path("finish AAA", async (h) => {
59 + h.appendAssistantMessage("Done.");
60 + await h.runFinishTask();
61 + assert.strictEqual(h.getStatus(), undefined);
62 + assert.ok(h.isLlmTriggered());
63 + h.assertBranchHistory(
64 + user("main work"),
65 + assistant("working..."),
66 + task("Task AAA"),
67 + taskResult("task-aaa", "Done."),
68 + notification("Task finished. Last response attached."),
69 + );
70 + },
71 + path("start AAA [no task]", async (h) => {
72 + await h.runStartTask();
73 + assert.strictEqual(h.getStatus(), undefined);
74 + assert.ok(h.isLlmTriggered());
75 + h.assertBranchHistory(
76 + user("main work"),
77 + assistant("working..."),
78 + task("Task AAA"),
79 + taskResult("task-aaa", "Done."),
80 + notification("No pending task. Use push-task first."),
81 + );
82 + }),
83 + path("discard AAA [no task]", async (h) => {
84 + await h.runDiscardTask();
85 + assert.strictEqual(h.getStatus(), undefined);
86 + assert.ok(h.isLlmTriggered());
87 + h.assertBranchHistory(
88 + user("main work"),
89 + assistant("working..."),
90 + task("Task AAA"),
91 + taskResult("task-aaa", "Done."),
92 + notification("No pending task to discard."),
93 + );
94 + }),
95 + path("finish AAA [no task]", async (h) => {
96 + await h.runFinishTask();
97 + assert.strictEqual(h.getStatus(), undefined);
98 + assert.ok(h.isLlmTriggered());
99 + h.assertBranchHistory(
100 + user("main work"),
101 + assistant("working..."),
102 + task("Task AAA"),
103 + taskResult("task-aaa", "Done."),
104 + notification("Not inside task, nothing to finish."),
105 + );
106 + }),
107 + path("abort AAA [no task]", async (h) => {
108 + await h.runAbortTask();
109 + assert.strictEqual(h.getStatus(), undefined);
110 + assert.ok(h.isLlmTriggered());
111 + h.assertBranchHistory(
112 + user("main work"),
113 + assistant("working..."),
114 + task("Task AAA"),
115 + taskResult("task-aaa", "Done."),
116 + notification("Not inside task, nothing to abort."),
117 + );
118 + }),
119 + ),
120 + path("abort AAA", async (h) => {
121 + h.appendAssistantMessage("Partial...");
122 + await h.runAbortTask();
123 + assert.strictEqual(h.getStatus(), "pending task: task-aaa");
124 + assert.ok(!h.isLlmTriggered());
125 + h.assertBranchHistory(
126 + user("main work"),
127 + assistant("working..."),
128 + task("Task AAA"),
129 + notification("Task aborted. Branch abandoned without summary."),
130 + );
131 + },
132 + path("start AAA", async (h) => {
133 + await h.runStartTask();
134 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
135 + assert.ok(h.isLlmTriggered());
136 + h.assertBranchHistory(
137 + user("Task AAA"),
138 + );
139 + },
140 + path("finish AAA", async (h) => {
141 + h.appendAssistantMessage("Done.");
142 + await h.runFinishTask();
143 + assert.strictEqual(h.getStatus(), undefined);
144 + assert.ok(h.isLlmTriggered());
145 + h.assertBranchHistory(
146 + user("main work"),
147 + assistant("working..."),
148 + task("Task AAA"),
149 + taskResult("task-aaa", "Done."),
150 + notification("Task finished. Last response attached."),
151 + );
152 + }),
153 + ),
154 + ),
155 + path("push BBB", async (h) => {
156 + h.appendAssistantMessage("some more work");
157 + await h.runPushTask("Task BBB");
158 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
159 + assert.ok(!h.isLlmTriggered());
160 + h.assertBranchHistory(
161 + user("Task AAA"),
162 + assistant("some more work"),
163 + task("Task BBB"),
164 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
165 + );
166 + },
167 + path("discard BBB", async (h) => {
168 + await h.runDiscardTask();
169 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
170 + assert.ok(!h.isLlmTriggered());
171 + h.assertBranchHistory(
172 + user("Task AAA"),
173 + assistant("some more work"),
174 + task("Task BBB"),
175 + notification("Task discarded."),
176 + );
177 + },
178 + path("finish AAA", async (h) => {
179 + h.appendAssistantMessage("Done.");
180 + await h.runFinishTask();
181 + assert.strictEqual(h.getStatus(), undefined);
182 + assert.ok(h.isLlmTriggered());
183 + h.assertBranchHistory(
184 + user("main work"),
185 + assistant("working..."),
186 + task("Task AAA"),
187 + taskResult("task-aaa", "Done."),
188 + notification("Task finished. Last response attached."),
189 + );
190 + }),
191 + ),
192 + path("start BBB", async (h) => {
193 + await h.runStartTask();
194 + assert.strictEqual(h.getStatus(), "current task: task-bbb");
195 + assert.ok(h.isLlmTriggered());
196 + h.assertBranchHistory(
197 + user("Task BBB"),
198 + );
199 + },
200 + path("finish BBB", async (h) => {
201 + h.appendAssistantMessage("inner done");
202 + await h.runFinishTask();
203 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
204 + assert.ok(h.isLlmTriggered());
205 + h.assertBranchHistory(
206 + user("Task AAA"),
207 + assistant("some more work"),
208 + task("Task BBB"),
209 + taskResult("task-bbb", "inner done"),
210 + notification("Task finished. Last response attached."),
211 + );
212 + },
213 + path("finish AAA", async (h) => {
214 + h.appendAssistantMessage("Done.");
215 + await h.runFinishTask();
216 + assert.strictEqual(h.getStatus(), undefined);
217 + assert.ok(h.isLlmTriggered());
218 + h.assertBranchHistory(
219 + user("main work"),
220 + assistant("working..."),
221 + task("Task AAA"),
222 + taskResult("task-aaa", "Done."),
223 + notification("Task finished. Last response attached."),
224 + );
225 + }),
226 + ),
227 + path("abort BBB", async (h) => {
228 + h.appendAssistantMessage("partial inner");
229 + await h.runAbortTask();
230 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
231 + assert.ok(!h.isLlmTriggered());
232 + h.assertBranchHistory(
233 + user("Task AAA"),
234 + assistant("some more work"),
235 + task("Task BBB"),
236 + notification("Task aborted. Branch abandoned without summary."),
237 + );
238 + },
239 + path("finish AAA", async (h) => {
240 + h.appendAssistantMessage("Done.");
241 + await h.runFinishTask();
242 + assert.strictEqual(h.getStatus(), undefined);
243 + assert.ok(h.isLlmTriggered());
244 + h.assertBranchHistory(
245 + user("main work"),
246 + assistant("working..."),
247 + task("Task AAA"),
248 + taskResult("task-aaa", "Done."),
249 + notification("Task finished. Last response attached."),
250 + );
251 + }),
252 + ),
253 + ),
254 + ),
255 + path("push BBB [inherit]", async (h) => {
256 + h.appendAssistantMessage("some more work");
257 + await h.runPushTask("Task BBB", true);
258 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
259 + assert.ok(!h.isLlmTriggered());
260 + h.assertBranchHistory(
261 + user("Task AAA"),
262 + assistant("some more work"),
263 + task("Task BBB", true),
264 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
265 + );
266 + },
267 + path("discard BBB [inherit]", async (h) => {
268 + await h.runDiscardTask();
269 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
270 + assert.ok(!h.isLlmTriggered());
271 + h.assertBranchHistory(
272 + user("Task AAA"),
273 + assistant("some more work"),
274 + task("Task BBB", true),
275 + notification("Task discarded."),
276 + );
277 + },
278 + path("finish AAA", async (h) => {
279 + h.appendAssistantMessage("Done.");
280 + await h.runFinishTask();
281 + assert.strictEqual(h.getStatus(), undefined);
282 + assert.ok(h.isLlmTriggered());
283 + h.assertBranchHistory(
284 + user("main work"),
285 + assistant("working..."),
286 + task("Task AAA"),
287 + taskResult("task-aaa", "Done."),
288 + notification("Task finished. Last response attached."),
289 + );
290 + }),
291 + ),
292 + path("start BBB [inherit]", async (h) => {
293 + await h.runStartTask();
294 + assert.strictEqual(h.getStatus(), "current task: task-bbb");
295 + assert.ok(h.isLlmTriggered());
296 + h.assertBranchHistory(
297 + user("Task AAA"),
298 + assistant("some more work"),
299 + task("Task BBB", true),
300 + user("Task BBB"),
301 + );
302 + },
303 + path("finish BBB [inherit]", async (h) => {
304 + h.appendAssistantMessage("inner done");
305 + await h.runFinishTask();
306 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
307 + assert.ok(h.isLlmTriggered());
308 + h.assertBranchHistory(
309 + user("Task AAA"),
310 + assistant("some more work"),
311 + task("Task BBB", true),
312 + taskResult("task-bbb", "inner done"),
313 + notification("Task finished. Last response attached."),
314 + );
315 + },
316 + path("finish AAA", async (h) => {
317 + h.appendAssistantMessage("Done.");
318 + await h.runFinishTask();
319 + assert.strictEqual(h.getStatus(), undefined);
320 + assert.ok(h.isLlmTriggered());
321 + h.assertBranchHistory(
322 + user("main work"),
323 + assistant("working..."),
324 + task("Task AAA"),
325 + taskResult("task-aaa", "Done."),
326 + notification("Task finished. Last response attached."),
327 + );
328 + }),
329 + ),
330 + path("abort BBB [inherit]", async (h) => {
331 + h.appendAssistantMessage("partial inner");
332 + await h.runAbortTask();
333 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
334 + assert.ok(!h.isLlmTriggered());
335 + h.assertBranchHistory(
336 + user("Task AAA"),
337 + assistant("some more work"),
338 + task("Task BBB", true),
339 + notification("Task aborted. Branch abandoned without summary."),
340 + );
341 + },
342 + path("finish AAA", async (h) => {
343 + h.appendAssistantMessage("Done.");
344 + await h.runFinishTask();
345 + assert.strictEqual(h.getStatus(), undefined);
346 + assert.ok(h.isLlmTriggered());
347 + h.assertBranchHistory(
348 + user("main work"),
349 + assistant("working..."),
350 + task("Task AAA"),
351 + taskResult("task-aaa", "Done."),
352 + notification("Task finished. Last response attached."),
353 + );
354 + }),
355 + ),
356 + ),
357 + ),
358 + ),
359 + ),
360 + path("push AAA [inherit]", async (h) => {
361 + h.appendUserMessage("main work");
362 + h.appendAssistantMessage("working...");
363 + await h.runPushTask("Task AAA", true);
364 + assert.strictEqual(h.getStatus(), "pending task: task-aaa");
365 + assert.ok(!h.isLlmTriggered());
366 + h.assertBranchHistory(
367 + user("main work"),
368 + assistant("working..."),
369 + task("Task AAA", true),
370 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
371 + );
372 + },
373 + path("discard AAA", async (h) => {
374 + await h.runDiscardTask();
375 + assert.strictEqual(h.getStatus(), undefined);
376 + assert.ok(!h.isLlmTriggered());
377 + h.assertBranchHistory(
378 + user("main work"),
379 + assistant("working..."),
380 + task("Task AAA", true),
381 + notification("Task discarded."),
382 + );
383 + }),
384 + path("start AAA", async (h) => {
385 + await h.runStartTask();
386 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
387 + assert.ok(h.isLlmTriggered());
388 + h.assertBranchHistory(
389 + user("main work"),
390 + assistant("working..."),
391 + task("Task AAA", true),
392 + user("Task AAA"),
393 + );
394 + },
395 + path("finish AAA", async (h) => {
396 + h.appendAssistantMessage("Done.");
397 + await h.runFinishTask();
398 + assert.strictEqual(h.getStatus(), undefined);
399 + assert.ok(h.isLlmTriggered());
400 + h.assertBranchHistory(
401 + user("main work"),
402 + assistant("working..."),
403 + task("Task AAA", true),
404 + taskResult("task-aaa", "Done."),
405 + notification("Task finished. Last response attached."),
406 + );
407 + },
408 + path("start AAA [no task]", async (h) => {
409 + await h.runStartTask();
410 + assert.strictEqual(h.getStatus(), undefined);
411 + assert.ok(h.isLlmTriggered());
412 + h.assertBranchHistory(
413 + user("main work"),
414 + assistant("working..."),
415 + task("Task AAA", true),
416 + taskResult("task-aaa", "Done."),
417 + notification("No pending task. Use push-task first."),
418 + );
419 + }),
420 + path("discard AAA [no task]", async (h) => {
421 + await h.runDiscardTask();
422 + assert.strictEqual(h.getStatus(), undefined);
423 + assert.ok(h.isLlmTriggered());
424 + h.assertBranchHistory(
425 + user("main work"),
426 + assistant("working..."),
427 + task("Task AAA", true),
428 + taskResult("task-aaa", "Done."),
429 + notification("No pending task to discard."),
430 + );
431 + }),
432 + path("finish AAA [no task]", async (h) => {
433 + await h.runFinishTask();
434 + assert.strictEqual(h.getStatus(), undefined);
435 + assert.ok(h.isLlmTriggered());
436 + h.assertBranchHistory(
437 + user("main work"),
438 + assistant("working..."),
439 + task("Task AAA", true),
440 + taskResult("task-aaa", "Done."),
441 + notification("Not inside task, nothing to finish."),
442 + );
443 + }),
444 + path("abort AAA [no task]", async (h) => {
445 + await h.runAbortTask();
446 + assert.strictEqual(h.getStatus(), undefined);
447 + assert.ok(h.isLlmTriggered());
448 + h.assertBranchHistory(
449 + user("main work"),
450 + assistant("working..."),
451 + task("Task AAA", true),
452 + taskResult("task-aaa", "Done."),
453 + notification("Not inside task, nothing to abort."),
454 + );
455 + }),
456 + ),
457 + path("abort AAA", async (h) => {
458 + h.appendAssistantMessage("Partial...");
459 + await h.runAbortTask();
460 + assert.strictEqual(h.getStatus(), "pending task: task-aaa");
461 + assert.ok(!h.isLlmTriggered());
462 + h.assertBranchHistory(
463 + user("main work"),
464 + assistant("working..."),
465 + task("Task AAA", true),
466 + notification("Task aborted. Branch abandoned without summary."),
467 + );
468 + },
469 + path("start AAA", async (h) => {
470 + await h.runStartTask();
471 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
472 + assert.ok(h.isLlmTriggered());
473 + h.assertBranchHistory(
474 + user("main work"),
475 + assistant("working..."),
476 + task("Task AAA", true),
477 + user("Task AAA"),
478 + );
479 + },
480 + path("finish AAA", async (h) => {
481 + h.appendAssistantMessage("Done.");
482 + await h.runFinishTask();
483 + assert.strictEqual(h.getStatus(), undefined);
484 + assert.ok(h.isLlmTriggered());
485 + h.assertBranchHistory(
486 + user("main work"),
487 + assistant("working..."),
488 + task("Task AAA", true),
489 + taskResult("task-aaa", "Done."),
490 + notification("Task finished. Last response attached."),
491 + );
492 + }),
493 + ),
494 + ),
495 + path("push BBB", async (h) => {
496 + h.appendAssistantMessage("some more work");
497 + await h.runPushTask("Task BBB");
498 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
499 + assert.ok(!h.isLlmTriggered());
500 + h.assertBranchHistory(
501 + user("main work"),
502 + assistant("working..."),
503 + task("Task AAA", true),
504 + user("Task AAA"),
505 + assistant("some more work"),
506 + task("Task BBB"),
507 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
508 + );
509 + },
510 + path("discard BBB", async (h) => {
511 + await h.runDiscardTask();
512 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
513 + assert.ok(!h.isLlmTriggered());
514 + h.assertBranchHistory(
515 + user("main work"),
516 + assistant("working..."),
517 + task("Task AAA", true),
518 + user("Task AAA"),
519 + assistant("some more work"),
520 + task("Task BBB"),
521 + notification("Task discarded."),
522 + );
523 + },
524 + path("finish AAA", async (h) => {
525 + h.appendAssistantMessage("Done.");
526 + await h.runFinishTask();
527 + assert.strictEqual(h.getStatus(), undefined);
528 + assert.ok(h.isLlmTriggered());
529 + h.assertBranchHistory(
530 + user("main work"),
531 + assistant("working..."),
532 + task("Task AAA", true),
533 + taskResult("task-aaa", "Done."),
534 + notification("Task finished. Last response attached."),
535 + );
536 + }),
537 + ),
538 + path("start BBB", async (h) => {
539 + await h.runStartTask();
540 + assert.strictEqual(h.getStatus(), "current task: task-bbb");
541 + assert.ok(h.isLlmTriggered());
542 + h.assertBranchHistory(
543 + user("Task BBB"),
544 + );
545 + },
546 + path("finish BBB", async (h) => {
547 + h.appendAssistantMessage("inner done");
548 + await h.runFinishTask();
549 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
550 + assert.ok(h.isLlmTriggered());
551 + h.assertBranchHistory(
552 + user("main work"),
553 + assistant("working..."),
554 + task("Task AAA", true),
555 + user("Task AAA"),
556 + assistant("some more work"),
557 + task("Task BBB"),
558 + taskResult("task-bbb", "inner done"),
559 + notification("Task finished. Last response attached."),
560 + );
561 + },
562 + path("finish AAA", async (h) => {
563 + h.appendAssistantMessage("Done.");
564 + await h.runFinishTask();
565 + assert.strictEqual(h.getStatus(), undefined);
566 + assert.ok(h.isLlmTriggered());
567 + h.assertBranchHistory(
568 + user("main work"),
569 + assistant("working..."),
570 + task("Task AAA", true),
571 + taskResult("task-aaa", "Done."),
572 + notification("Task finished. Last response attached."),
573 + );
574 + }),
575 + ),
576 + path("abort BBB", async (h) => {
577 + h.appendAssistantMessage("partial inner");
578 + await h.runAbortTask();
579 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
580 + assert.ok(!h.isLlmTriggered());
581 + h.assertBranchHistory(
582 + user("main work"),
583 + assistant("working..."),
584 + task("Task AAA", true),
585 + user("Task AAA"),
586 + assistant("some more work"),
587 + task("Task BBB"),
588 + notification("Task aborted. Branch abandoned without summary."),
589 + );
590 + },
591 + path("finish AAA", async (h) => {
592 + h.appendAssistantMessage("Done.");
593 + await h.runFinishTask();
594 + assert.strictEqual(h.getStatus(), undefined);
595 + assert.ok(h.isLlmTriggered());
596 + h.assertBranchHistory(
597 + user("main work"),
598 + assistant("working..."),
599 + task("Task AAA", true),
600 + taskResult("task-aaa", "Done."),
601 + notification("Task finished. Last response attached."),
602 + );
603 + }),
604 + ),
605 + ),
606 + ),
607 + path("push BBB [inherit]", async (h) => {
608 + h.appendAssistantMessage("some more work");
609 + await h.runPushTask("Task BBB", true);
610 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
611 + assert.ok(!h.isLlmTriggered());
612 + h.assertBranchHistory(
613 + user("main work"),
614 + assistant("working..."),
615 + task("Task AAA", true),
616 + user("Task AAA"),
617 + assistant("some more work"),
618 + task("Task BBB", true),
619 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
620 + );
621 + },
622 + path("discard BBB [inherit]", async (h) => {
623 + await h.runDiscardTask();
624 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
625 + assert.ok(!h.isLlmTriggered());
626 + h.assertBranchHistory(
627 + user("main work"),
628 + assistant("working..."),
629 + task("Task AAA", true),
630 + user("Task AAA"),
631 + assistant("some more work"),
632 + task("Task BBB", true),
633 + notification("Task discarded."),
634 + );
635 + },
636 + path("finish AAA", async (h) => {
637 + h.appendAssistantMessage("Done.");
638 + await h.runFinishTask();
639 + assert.strictEqual(h.getStatus(), undefined);
640 + assert.ok(h.isLlmTriggered());
641 + h.assertBranchHistory(
642 + user("main work"),
643 + assistant("working..."),
644 + task("Task AAA", true),
645 + taskResult("task-aaa", "Done."),
646 + notification("Task finished. Last response attached."),
647 + );
648 + }),
649 + ),
650 + path("start BBB [inherit]", async (h) => {
651 + await h.runStartTask();
652 + assert.strictEqual(h.getStatus(), "current task: task-bbb");
653 + assert.ok(h.isLlmTriggered());
654 + h.assertBranchHistory(
655 + user("main work"),
656 + assistant("working..."),
657 + task("Task AAA", true),
658 + user("Task AAA"),
659 + assistant("some more work"),
660 + task("Task BBB", true),
661 + user("Task BBB"),
662 + );
663 + },
664 + path("finish BBB [inherit]", async (h) => {
665 + h.appendAssistantMessage("inner done");
666 + await h.runFinishTask();
667 + assert.strictEqual(h.getStatus(), "current task: task-aaa");
668 + assert.ok(h.isLlmTriggered());
669 + h.assertBranchHistory(
670 + user("main work"),
671 + assistant("working..."),
672 + task("Task AAA", true),
673 + user("Task AAA"),
674 + assistant("some more work"),
675 + task("Task BBB", true),
676 + taskResult("task-bbb", "inner done"),
677 + notification("Task finished. Last response attached."),
678 + );
679 + },
680 + path("finish AAA", async (h) => {
681 + h.appendAssistantMessage("Done.");
682 + await h.runFinishTask();
683 + assert.strictEqual(h.getStatus(), undefined);
684 + assert.ok(h.isLlmTriggered());
685 + h.assertBranchHistory(
686 + user("main work"),
687 + assistant("working..."),
688 + task("Task AAA", true),
689 + taskResult("task-aaa", "Done."),
690 + notification("Task finished. Last response attached."),
691 + );
692 + }),
693 + ),
694 + path("abort BBB [inherit]", async (h) => {
695 + h.appendAssistantMessage("partial inner");
696 + await h.runAbortTask();
697 + assert.strictEqual(h.getStatus(), "pending task: task-bbb");
698 + assert.ok(!h.isLlmTriggered());
699 + h.assertBranchHistory(
700 + user("main work"),
701 + assistant("working..."),
702 + task("Task AAA", true),
703 + user("Task AAA"),
704 + assistant("some more work"),
705 + task("Task BBB", true),
706 + notification("Task aborted. Branch abandoned without summary."),
707 + );
708 + },
709 + path("finish AAA", async (h) => {
710 + h.appendAssistantMessage("Done.");
711 + await h.runFinishTask();
712 + assert.strictEqual(h.getStatus(), undefined);
713 + assert.ok(h.isLlmTriggered());
714 + h.assertBranchHistory(
715 + user("main work"),
716 + assistant("working..."),
717 + task("Task AAA", true),
718 + taskResult("task-aaa", "Done."),
719 + notification("Task finished. Last response attached."),
720 + );
721 + }),
722 + ),
723 + ),
724 + ),
725 + ),
726 + ),
727 + path("start AAA [no task]", async (h) => {
728 + h.appendUserMessage("main work");
729 + h.appendAssistantMessage("working...");
730 + await h.runStartTask();
731 + assert.strictEqual(h.getStatus(), undefined);
732 + assert.ok(!h.isLlmTriggered());
733 + h.assertBranchHistory(
734 + user("main work"),
735 + assistant("working..."),
736 + notification("No pending task. Use push-task first."),
737 + );
738 + }),
739 + path("discard AAA [no task]", async (h) => {
740 + h.appendUserMessage("main work");
741 + h.appendAssistantMessage("working...");
742 + await h.runDiscardTask();
743 + assert.strictEqual(h.getStatus(), undefined);
744 + assert.ok(!h.isLlmTriggered());
745 + h.assertBranchHistory(
746 + user("main work"),
747 + assistant("working..."),
748 + notification("No pending task to discard."),
749 + );
750 + }),
751 + path("finish AAA [no task]", async (h) => {
752 + h.appendUserMessage("main work");
753 + h.appendAssistantMessage("working...");
754 + await h.runFinishTask();
755 + assert.strictEqual(h.getStatus(), undefined);
756 + assert.ok(!h.isLlmTriggered());
757 + h.assertBranchHistory(
758 + user("main work"),
759 + assistant("working..."),
760 + notification("Not inside task, nothing to finish."),
761 + );
762 + }),
763 + path("abort AAA [no task]", async (h) => {
764 + h.appendUserMessage("main work");
765 + h.appendAssistantMessage("working...");
766 + await h.runAbortTask();
767 + assert.strictEqual(h.getStatus(), undefined);
768 + assert.ok(!h.isLlmTriggered());
769 + h.assertBranchHistory(
770 + user("main work"),
771 + assistant("working..."),
772 + notification("Not inside task, nothing to abort."),
773 + );
774 + }),
775 + ];
776 +});
778 +describe("automated workflow", () => {
779 + it("completes push-task -> /auto -> finish-task and injects the branch result", async () => {
780 + const { appendUserMessage, appendAssistantMessage, assertBranchHistory, isLlmTriggered, getStatus, releaseNextIdle, flushMicrotasks, runPushTask, runAuto } =
781 + makeHarness();
783 + appendUserMessage("main work");
784 + appendAssistantMessage("working on main...");
785 + await runPushTask("Analyze performance.");
786 + assert.strictEqual(getStatus(), "pending task: analyze-performance");
787 + assertBranchHistory(
788 + user("main work"),
789 + assistant("working on main..."),
790 + task("Analyze performance."),
791 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
792 + );
794 + const running = runAuto();
796 + await flushMicrotasks();
797 + await releaseNextIdle();
798 + // Auto started the task (fresh context)
799 + assertBranchHistory(
800 + user("Analyze performance."),
801 + );
803 + appendAssistantMessage("Found 3 bottlenecks: ...");
805 + await releaseNextIdle();
806 + await releaseNextIdle();
807 + await running;
808 + assertBranchHistory(
809 + user("main work"),
810 + assistant("working on main..."),
811 + task("Analyze performance."),
812 + taskResult("analyze-performance", "Found 3 bottlenecks: ..."),
813 + notification("Task finished. Last response attached."),
814 + );
815 + assert.ok(isLlmTriggered());
816 + });
818 + it("returns the branch result to the original leaf for branch-context tasks", async () => {
819 + const { appendUserMessage, appendAssistantMessage, assertBranchHistory, isLlmTriggered, getStatus, releaseNextIdle, flushMicrotasks, runPushTask, runAuto } =
820 + makeHarness();
822 + appendUserMessage("main work");
823 + appendAssistantMessage("working...");
824 + await runPushTask("Quick fix.", true);
825 + assert.strictEqual(getStatus(), "pending task: quick-fix");
826 + assertBranchHistory(
827 + user("main work"),
828 + assistant("working..."),
829 + task("Quick fix.", true),
830 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
831 + );
833 + const running = runAuto();
835 + await flushMicrotasks();
836 + await releaseNextIdle();
837 + // Auto started the task (branch context, inherit_context=true)
838 + assertBranchHistory(
839 + user("main work"),
840 + assistant("working..."),
841 + task("Quick fix.", true),
842 + user("Quick fix."),
843 + );
845 + appendAssistantMessage("Fixed the bug.");
847 + await releaseNextIdle();
848 + await releaseNextIdle();
849 + await running;
850 + assertBranchHistory(
851 + user("main work"),
852 + assistant("working..."),
853 + task("Quick fix.", true),
854 + taskResult("quick-fix", "Fixed the bug."),
855 + notification("Task finished. Last response attached."),
856 + );
857 + assert.ok(isLlmTriggered());
858 + });
860 + it("stops when navigation is cancelled and does not mark the task done", async () => {
861 + const { appendUserMessage, assertBranchHistory, isLlmTriggered, setCancelNextNav, releaseNextIdle, flushMicrotasks, runPushTask, runAuto } =
862 + makeHarness();
864 + appendUserMessage("main work");
865 + await runPushTask("Analyze performance.");
867 + setCancelNextNav(true);
869 + const running = runAuto();
871 + await flushMicrotasks();
872 + await releaseNextIdle();
873 + await running;
874 + assert.ok(!isLlmTriggered());
875 + // Navigation was cancelled, so no task-start was added
876 + assertBranchHistory(
877 + user("main work"),
878 + task("Analyze performance."),
879 + notification("Task stored. Use `/start-task` or `/auto` to start it."),
880 + );
881 + });
883 + it("notifies and exits when started with no pending tasks", async () => {
884 + const { assertBranchHistory, releaseNextIdle, flushMicrotasks, runAuto } =
885 + makeHarness();
887 + const running = runAuto();
889 + await flushMicrotasks();
890 + await releaseNextIdle();
891 + await running;
892 + // Should have exited without looping forever
893 + assertBranchHistory(
894 + notification("No pending tasks to run."),
895 + );
896 + });
898 + it("warns and returns when /auto is already running", async () => {
899 + const { assertBranchHistory, releaseNextIdle, flushMicrotasks, emitSessionShutdown, runAuto } =
900 + makeHarness();
902 + const firstRun = runAuto();
903 + await flushMicrotasks();
905 + await runAuto();
906 + assertBranchHistory(notification("Auto is already running."));
908 + await emitSessionShutdown();
909 + await releaseNextIdle();
910 + await firstRun;
911 + });
913 + it("stops when the last assistant message was aborted", async () => {
914 + const { appendUserMessage, appendAssistantMessage, isLlmTriggered, releaseNextIdle, flushMicrotasks, runPushTask, runStartTask, runAuto } =
915 + makeHarness();
917 + appendUserMessage("start");
918 + await runPushTask("Implement phase 1.", true);
920 + await runStartTask();
922 + appendAssistantMessage("Stopped by user.", "aborted");
924 + const running = runAuto();
926 + await flushMicrotasks();
927 + await releaseNextIdle();
928 + await running;
929 + assert.ok(!isLlmTriggered());
930 + });
932 + it("keeps waiting while follow-up work is pending after finishTask", async () => {
933 + const { appendUserMessage, appendAssistantMessage, isLlmTriggered, setPendingMessages, releaseNextIdle, flushMicrotasks, runPushTask, runStartTask, runAuto } =
934 + makeHarness();
936 + appendUserMessage("start");
937 + await runPushTask("Quick fix.", true);
939 + await runStartTask();
941 + appendAssistantMessage("Fixed the bug.");
943 + let resolved = false;
944 + const running = runAuto().then(() => {
945 + resolved = true;
946 + });
948 + await flushMicrotasks();
949 + setPendingMessages(true);
950 + await releaseNextIdle();
951 + await releaseNextIdle();
952 + assert.ok(isLlmTriggered());
953 + assert.strictEqual(resolved, false);
955 + setPendingMessages(false);
956 + await releaseNextIdle();
957 + await running;
958 + assert.strictEqual(resolved, true);
959 + });
960 +});
962 +// ── Registration ─────────────────────────────────────────────────
964 +describe("registration", () => {
965 + it("registers the push-task tool and all five task commands", () => {
966 + const registered: Array<{ type: string; name: string; description?: string }> = [];
967 + const pi = {
968 + registerTool: (tool: { name: string; label: string; description: string }) =>
969 + registered.push({ type: "tool", name: tool.name, description: tool.description }),
970 + registerCommand: (name: string, opts: { description: string }) =>
971 + registered.push({ type: "command", name, description: opts.description }),
972 + registerMessageRenderer: () => {},
973 + on: () => {},
974 + } as unknown as ExtensionAPI;
976 + registerTaskCommands(pi);
978 + assert.deepStrictEqual(registered, [
979 + { type: "tool", name: "push-task", description: "Store a task prompt for a user-started navigation branch." },
980 + { type: "command", name: "start-task", description: "Navigate to a fresh context and inject the active task prompt" },
981 + { type: "command", name: "discard-task", description: "Discard the active task without executing it" },
982 + { type: "command", name: "finish-task", description: "Finish the current task and return to the task start point" },
983 + { type: "command", name: "abort-task", description: "Abort the current task without finishing" },
984 + { type: "command", name: "auto", description: "Automatically run pushed task branches" },
985 + ]);
986 + });
987 +});
989 +const assistant = (content: string) => ({
990 + type: "message" as const,
991 + message: { role: "assistant" as const, content: [{ type: "text" as const, text: content }] }
992 +}) as unknown as Partial<BranchEntry>;
994 +const user = (content: string) => ({
995 + type: "message" as const,
996 + message: { role: "user" as const, content: [{ type: "text", text: content }] }
997 +}) as unknown as Partial<BranchEntry>;
999 +const task = (prompt: string, inherit_context = false) => ({
1000 + type: "custom" as const,
1001 + customType: "task",
1002 + data: { prompt, inherit_context }
1003 +}) as unknown as Partial<BranchEntry>;
1005 +const taskResult = (slug: string, content?: string) => ({
1006 + type: "custom_message" as const,
1007 + customType: "task-result",
1008 + details: { slug },
1009 + ...(content !== undefined ? { content: [{ type: "text" as const, text: content }] } : {}),
1010 +}) as unknown as Partial<BranchEntry>;
1012 +// ── Test harness ─────────────────────────────────────────────────
1014 +function makeHarness() {
1015 + const sm = SessionManager.inMemory();
1016 + // Seed a non-visible root entry so findFreshTargetId can escape past user messages.
1017 + // Pi always inserts thinking_level_change at session creation (main.js:471).
1018 + sm.appendThinkingLevelChange("off");
1019 + const idleWaiters: Array<() => void> = [];
1020 + const sessionShutdownHandlers: Array<() => unknown> = [];
1021 + const triggeredCustomMessages = new Set<string>();
1022 + const triggeredUserMessages = new Set<string>();
1024 + const trackedHints: Array<{ text: string; afterEntryId: string | null }> = [];
1025 + let cancelNextNav = false;
1026 + let pendingMessages = false;
1027 + let taskStatus: string | undefined;
1030 + const pi = {
1031 + appendEntry(customType: string, data?: unknown) {
1032 + sm.appendCustomEntry(customType, data);
1033 + },
1034 + sendUserMessage(content: string | Array<{ type: string; text: string }>) {
1035 + const text = typeof content === "string" ? content : content.map((b) => b.text).join("");
1036 + sm.appendMessage({ role: "user", content: [{ type: "text", text }], timestamp: Date.now() });
1037 + const branch = sm.getBranch();
1038 + const last = branch[branch.length - 1];
1039 + if (last) triggeredUserMessages.add(last.id);
1040 + },
1041 + sendMessage(
1042 + message: { customType: string; content: unknown; display?: boolean; details?: unknown },
1043 + options?: { triggerTurn?: boolean },
1044 + ) {
1045 + sm.appendCustomMessageEntry(
1046 + message.customType,
1047 + message.content as string,
1048 + message.display ?? true,
1049 + message.details,
1050 + );
1052 + if (options?.triggerTurn) {
1053 + const branch = sm.getBranch();
1054 + const last = branch[branch.length - 1];
1055 + if (last) triggeredCustomMessages.add(last.id);
1057 + },
1058 + on(eventName: string, handler: () => unknown) {
1059 + if (eventName === "session_shutdown") sessionShutdownHandlers.push(handler);
1060 + },
1061 + registerMessageRenderer() {},
1062 + registerTool() {},
1063 + registerCommand() {},
1064 + } as unknown as ExtensionAPI;
1066 + const ctx = {
1067 + hasUI: true,
1068 + waitForIdle: async () => {
1069 + await new Promise<void>((resolve) => {
1070 + idleWaiters.push(resolve);
1071 + });
1072 + },
1073 + hasPendingMessages: () => pendingMessages,
1074 + sessionManager: sm,
1075 + ui: {
1076 + notify(message: string) {
1077 + trackedHints.push({ text: message, afterEntryId: sm.getLeafId() });
1078 + },
1079 + setStatus(key: string, value: string | undefined) {
1080 + if (key === "task") taskStatus = value;
1081 + },
1082 + theme: {
1083 + fg: (_key: string, text: string) => text,
1084 + bg: (_key: string, text: string) => text,
1085 + bold: (text: string) => text,
1086 + } as unknown as Theme,
1087 + },
1088 + navigateTree: async (targetId: string) => {
1089 + if (cancelNextNav) {
1090 + cancelNextNav = false;
1091 + return { cancelled: true };
1093 + sm.branch(targetId);
1094 + return { cancelled: false };
1095 + },
1096 + } as unknown as ExtensionCommandContext & { sessionManager: SessionManager };
1098 + // ── Plumbing helpers ──────────────────────────────────────────
1100 + function isLlmTriggered(): boolean {
1101 + const branch = sm.getBranch();
1102 + if (branch.length === 0) return false;
1103 + // Walk backwards past "custom" entries (data-only bookkeeping, invisible to LLM)
1104 + for (let i = branch.length - 1; i >= 0; i--) {
1105 + const entry = branch[i];
1106 + if (entry.type === "custom") continue;
1107 + if (entry.type === "message" && entry.message.role === "user") return triggeredUserMessages.has(entry.id);
1108 + if (entry.type === "message" && entry.message.role === "assistant") return false;
1109 + if (entry.type === "custom_message") return triggeredCustomMessages.has(entry.id);
1110 + return false;
1112 + return false;
1115 + function appendUserMessage(text: string): void {
1116 + sm.appendMessage({ role: "user", content: [{ type: "text", text }], timestamp: 0 });
1119 + function appendAssistantMessage(text: string, stopReason?: string): void {
1120 + sm.appendMessage({
1121 + role: "assistant",
1122 + content: [{ type: "text", text }],
1123 + timestamp: 0,
1124 + model: "test",
1125 + provider: "test",
1126 + ...(stopReason ? { stopReason } : {}),
1127 + } as Parameters<typeof sm.appendMessage>[0]);
1130 + function assertBranchHistory(...expected: Partial<BranchEntry>[]) {
1131 + const entries = sm.getBranch();
1132 + const actual: Partial<BranchEntry>[] = [];
1133 + const consumedHints = new Set<number>();
1135 + for (const entry of entries) {
1136 + // Skip entries invisible to both the user and LLM context.
1137 + const HIDDEN_TYPES = new Set(["thinking_level_change", "model_change", "session_info", "label"]);
1138 + const isSkipped =
1139 + HIDDEN_TYPES.has(entry.type) ||
1140 + (entry.type === "custom" && (entry.customType === "task-done" || entry.customType === "task-start"));
1142 + if (!isSkipped) {
1143 + // Strip IDs, internal fields, display, and content for comparison
1144 + const { id: _id, parentId: _pid, timestamp: _ts, display: _dp, data: rawData, details: rawDetails, ...restEntry } = entry as unknown as Record<string, unknown>;
1146 + // Build stripped version excluding fields we always strip
1147 + const stripped: Record<string, unknown> = { ...restEntry };
1149 + // Clean nested message fields
1150 + if (stripped.message && typeof stripped.message === "object") {
1151 + const { timestamp: _mt, model: _mp, provider: _pp, stopReason: _sr, ...msgRest } = stripped.message as Record<string, unknown>;
1152 + stripped.message = msgRest;
1155 + // Process data: only include non-dynamic keys
1156 + if (rawData && typeof rawData === "object") {
1157 + const cleaned: Record<string, unknown> = {};
1158 + for (const [k, v] of Object.entries(rawData as Record<string, unknown>)) {
1159 + if (typeof v !== "string" || !/^[a-f0-9]{8}$/.test(v)) {
1160 + cleaned[k] = v;
1163 + if (Object.keys(cleaned).length > 0) stripped.data = cleaned;
1166 + // Process details: only include non-dynamic keys
1167 + if (rawDetails && typeof rawDetails === "object") {
1168 + const cleaned: Record<string, unknown> = {};
1169 + for (const [k, v] of Object.entries(rawDetails as Record<string, unknown>)) {
1170 + if (typeof v !== "string" || !/^[a-f0-9]{8}$/.test(v)) {
1171 + cleaned[k] = v;
1174 + if (Object.keys(cleaned).length > 0) stripped.details = cleaned;
1177 + actual.push(stripped as Partial<BranchEntry>);
1180 + // Insert tracked hints with matching afterEntryId after the entry
1181 + for (let i = 0; i < trackedHints.length; i++) {
1182 + if (trackedHints[i].afterEntryId === entry.id) {
1183 + actual.push(notification(trackedHints[i].text));
1184 + consumedHints.add(i);
1189 + // Unclassified hints (afterEntryId === null) go at start
1190 + for (let i = 0; i < trackedHints.length; i++) {
1191 + if (!consumedHints.has(i) && trackedHints[i].afterEntryId === null) {
1192 + actual.unshift(notification(trackedHints[i].text));
1193 + consumedHints.add(i);
1197 + // Remove consumed hints so they don"t leak across calls.
1198 + // Also discard orphaned hints (non-null afterEntryId from a different branch).
1199 + const remaining: Array<{ text: string; afterEntryId: string | null }> = [];
1200 + for (let i = 0; i < trackedHints.length; i++) {
1201 + if (!consumedHints.has(i) && trackedHints[i].afterEntryId === null) {
1202 + remaining.push(trackedHints[i]);
1205 + trackedHints.length = 0;
1206 + trackedHints.push(...remaining);
1208 + assert.deepStrictEqual(actual, expected);
1213 + async function releaseNextIdle() {
1214 + const next = idleWaiters.shift();
1215 + assert.ok(next, "Expected a pending waitForIdle call.");
1216 + next();
1217 + // Drain microtasks so anything awaiting the released idle can proceed.
1218 + for (let i = 0; i < 10; i++) {
1219 + await Promise.resolve();
1223 + async function flushMicrotasks() {
1224 + await Promise.resolve();
1225 + await Promise.resolve();
1228 + async function emitSessionShutdown() {
1229 + for (const handler of sessionShutdownHandlers) {
1230 + await handler();
1234 + function setPendingMessages(value: boolean) {
1235 + pendingMessages = value;
1238 + function setCancelNextNav(v: boolean) {
1239 + cancelNextNav = v;
1242 + // ── Convenience wrappers (pre-bound to pi / ctx) ───────────────
1244 + async function runPushTask(prompt: string, inherit_context?: boolean) {
1245 + const tool = createPushTaskTool(pi);
1246 + await tool.execute("call-1", { prompt, inherit_context }, undefined, undefined, ctx);
1249 + async function runTaskCommand(command: { handler: (args: string, ctx: ExtensionCommandContext) => Promise<unknown> }) {
1250 + const handlerP = command.handler("", ctx);
1251 + await releaseNextIdle();
1252 + await handlerP;
1255 + const runStartTask = () => runTaskCommand(createStartTaskCommand(pi));
1256 + const runFinishTask = () => runTaskCommand(createFinishTaskCommand(pi));
1257 + const runDiscardTask = () => runTaskCommand(createDiscardTaskCommand(pi));
1258 + const runAbortTask = () => runTaskCommand(createAbortTaskCommand());
1260 + // Auto-register commands so the shutdown handler is set up
1261 + registerTaskCommands(pi);
1263 + function runAuto(): Promise<void> {
1264 + return createAutoCommand(pi).handler("", ctx) as Promise<void>;
1267 + function getStatus(): string | undefined {
1268 + return taskStatus;
1271 + return {
1272 + assertBranchHistory,
1273 + isLlmTriggered,
1274 + getStatus,
1275 + appendUserMessage,
1276 + appendAssistantMessage,
1277 + releaseNextIdle,
1278 + flushMicrotasks,
1279 + emitSessionShutdown,
1280 + setPendingMessages,
1281 + setCancelNextNav,
1282 + runPushTask,
1283 + runStartTask,
1284 + runFinishTask,
1285 + runDiscardTask,
1286 + runAbortTask,
1287 + runAuto,
1288 + };
1292 +const notification = (text: string) => ({
1293 + type: "notification" as const,
1294 + text,
1295 + afterEntryId: null as string | null
1296 +}) as unknown as Partial<BranchEntry>;
1298 +type BranchEntry = import("@earendil-works/pi-coding-agent").SessionEntry | NotificationEntry;
1300 +// ── Branch history helpers ──────────────────────────────────────
1302 +type NotificationEntry = {
1303 + type: "notification";
1304 + text: string;
1305 + afterEntryId: string | null;
1308 +// ── pathSuite test helper ───────────────────────────────────────
1310 +interface PathNode {
1311 + name: string;
1312 + fn?: (h: ReturnType<typeof makeHarness>) => Promise<void> | void;
1313 + children: PathNode[];
1316 +type PathFn = (
1317 + name: string,
1318 + fn?: (h: ReturnType<typeof makeHarness>) => Promise<void> | void,
1319 + ...children: PathNode[]
1320 +) => PathNode;
1322 +function pathSuite(
1323 + description: string,
1324 + fn: (path: PathFn) => PathNode | PathNode[],
1325 +): void {
1326 + describe(description, () => {
1327 + const roots = fn(path);
1328 + const rootsArray = Array.isArray(roots) ? roots : [roots];
1330 + function registerTests(node: PathNode, ancestors: PathNode[]): void {
1331 + const chain = [...ancestors, node];
1332 + const name = chain.map(n => n.name).join(" → ");
1334 + it(name, async () => {
1335 + const h = makeHarness();
1336 + for (const ancestor of chain) {
1337 + if (ancestor.fn) {
1338 + await ancestor.fn(h);
1341 + });
1343 + for (const child of node.children) {
1344 + registerTests(child, chain);
1348 + for (const root of rootsArray) {
1349 + registerTests(root, []);
1351 + });

skills/pandoc/SKILL.md

Modified
1101 1101 ## 18. Helper Scripts (Cross-Platform)
1103 -All scripts are written in Lua and run via `pandoc lua` — works on Linux, macOS, and Windows.
1103 +All scripts are written in Lua and run via `pandoc lua` — works on Linux, macOS, and Windows. They call pandoc with argv lists via `pandoc.pipe` (no shell quoting or `os.execute`).
1105 1105 ```bash
1106 1106 # Batch convert all .md files in current directory to .html

skills/pandoc/ideas.md

Modified
31 31 - 20 sections, 9 filters, 6 scripts, 2 defaults — comprehensive but focused
32 32 - All scripts cross-platform via `pandoc lua`
33 33 - No shell-only patterns remain anywhere
34 +- Wrapper scripts use `pandoc.pipe` argv lists (no `os.execute`, safer filenames with spaces)

skills/pandoc/scripts/pandoc-batch-convert.lua

Modified
5 5 -- Cross-platform: works on Linux, macOS, Windows (requires pandoc 3.x)
7 7 local system = require 'pandoc.system'
8 -local path = require 'pandoc.path'
10 9 local args = arg
11 10 if #args < 2 then
53 52 local base = f:gsub("%." .. in_ext .. "$", "")
54 53 local out = base .. "." .. out_ext
56 - -- Build pandoc command
57 - local cmd = string.format('pandoc "%s" -o "%s"', f, out)
55 + local pandoc_args = {f, "-o", out}
58 56 for _, a in ipairs(extra) do
59 - cmd = cmd .. ' "' .. a .. '"'
57 + pandoc_args[#pandoc_args + 1] = a
62 60 io.stdout:write("Converting: " .. f .. " -> " .. out .. "\n")
63 - local ret = os.execute(cmd)
61 + local ok, result = pcall(pandoc.pipe, "pandoc", pandoc_args, "")
65 - local success = (ret == true) or (ret == 0)
66 - if success then
63 + if ok then
67 64 count = count + 1
68 65 else
69 66 io.stderr:write(" FAILED: " .. f .. "\n")
67 + io.stderr:write(" " .. tostring(result):match("([^\r\n]+)") .. "\n")
70 68 failed = failed + 1

skills/pandoc/scripts/pandoc-docx-to-md.lua

Modified
7 7 -- - Track changes acceptance (default)
8 8 -- - Clean Markdown output with no wrapping
10 -local system = require 'pandoc.system'
11 -local path = require 'pandoc.path'
10 +local path = require 'pandoc.path'
13 12 local args = arg
14 13 if #args < 1 then
31 30 local out_dir = path.directory(output) or "."
32 31 local media_dir = path.join({out_dir, "media"})
34 --- Build pandoc command
35 -local cmd = string.format(
36 - 'pandoc "%s" -f docx -t markdown --wrap=none --track-changes=accept --extract-media="%s" -o "%s"',
37 - input, media_dir, output
38 -)
33 +local pandoc_args = {
34 + input,
35 + "-f", "docx",
36 + "-t", "markdown",
37 + "--wrap=none",
38 + "--track-changes=accept",
39 + "--extract-media=" .. media_dir,
40 + "-o", output,
40 43 io.stdout:write(string.format("Extracting: %s -> %s\n", input, output))
41 44 io.stdout:write(string.format("Media dir: %s\n", media_dir))
43 -local ret = os.execute(cmd)
44 -local success = (ret == true) or (ret == 0)
45 -if success then
46 +local ok, result = pcall(pandoc.pipe, "pandoc", pandoc_args, "")
47 +if ok then
46 48 io.stdout:write("Done.\n")
47 49 else
48 50 io.stderr:write("FAILED\n")
51 + io.stderr:write(tostring(result) .. "\n")
49 52 os.exit(1)

skills/pandoc/scripts/pandoc-md-to-pdf.lua

Modified
1 1 -- pandoc-md-to-pdf.lua — Markdown to polished PDF with sensible defaults
2 2 -- Usage: pandoc lua scripts/pandoc-md-to-pdf.lua <input.md> [output.pdf] [--draft|--final]
3 3 -- Cross-platform: works on Linux, macOS, Windows (requires pandoc 3.x)
4 --- Requires: xelatex (or set PANDOC_PDF_ENGINE env var)
4 +-- Requires: xelatex (or set PANDOC_PDF_ENGINE)
6 6 local args = arg
7 7 if #args < 1 then
33 33 -- PDF engine: env var override or default to xelatex
34 34 local engine = os.getenv("PANDOC_PDF_ENGINE") or "xelatex"
36 --- Build pandoc arguments
37 -local cmd_parts = {
38 - string.format('pandoc "%s" -o "%s"', input, output),
39 - string.format('--pdf-engine=%s', engine),
40 - '-V geometry:margin=1in',
41 - '-V colorlinks=true',
42 - '-V linkcolor=blue',
43 - '-V urlcolor=blue',
44 - '--toc',
45 - '--toc-depth=3',
46 - '-N',
47 - '--highlight-style=kate',
36 +local pandoc_args = {
37 + input,
38 + "-o", output,
39 + "--pdf-engine=" .. engine,
40 + "-V", "geometry:margin=1in",
41 + "-V", "colorlinks=true",
42 + "-V", "linkcolor=blue",
43 + "-V", "urlcolor=blue",
44 + "--toc",
45 + "--toc-depth=3",
46 + "-N",
47 + "--highlight-style=kate",
50 50 if mode == "draft" then
51 - cmd_parts[#cmd_parts + 1] = '-V fontsize=12pt'
52 - cmd_parts[#cmd_parts + 1] = '-V linestretch=1.5'
51 + pandoc_args[#pandoc_args + 1] = "-V"
52 + pandoc_args[#pandoc_args + 1] = "fontsize=12pt"
53 + pandoc_args[#pandoc_args + 1] = "-V"
54 + pandoc_args[#pandoc_args + 1] = "linestretch=1.5"
53 55 else
54 - cmd_parts[#cmd_parts + 1] = '-V fontsize=11pt'
56 + pandoc_args[#pandoc_args + 1] = "-V"
57 + pandoc_args[#pandoc_args + 1] = "fontsize=11pt"
57 -local cmd = table.concat(cmd_parts, " ")
59 60 io.stdout:write(string.format("Converting: %s -> %s (engine=%s, mode=%s)\n",
60 61 input, output, engine, mode))
62 -local ret = os.execute(cmd)
63 -local success = (ret == true) or (ret == 0) or (ret == 0x0)
64 -if success then
63 +local ok, result = pcall(pandoc.pipe, "pandoc", pandoc_args, "")
64 +if ok then
65 65 io.stdout:write("Done: " .. output .. "\n")
66 66 else
67 67 io.stderr:write("FAILED\n")
68 + io.stderr:write(tostring(result) .. "\n")
68 69 os.exit(1)

skills/pandoc/scripts/pandoc-web-to-md.lua

Modified
12 12 local url = args[1]
13 13 local output = args[2] or "-" -- default to stdout
15 --- Build command
16 -local cmd
17 -if output == "-" then
18 - cmd = string.format(
19 - 'pandoc -f html -t markdown --wrap=none --shift-heading-level-by=-1 "%s"',
20 - url
21 - )
22 -else
23 - cmd = string.format(
24 - 'pandoc -f html -t markdown --wrap=none --shift-heading-level-by=-1 "%s" -o "%s"',
25 - url, output
26 - )
15 +local pandoc_args = {
16 + "-f", "html",
17 + "-t", "markdown",
18 + "--wrap=none",
19 + url,
22 +if output ~= "-" then
23 + pandoc_args[#pandoc_args + 1] = "-o"
24 + pandoc_args[#pandoc_args + 1] = output
29 -local ret = os.execute(cmd)
30 -local success = (ret == true) or (ret == 0) or (ret == 0x0)
31 -if not success then
27 +local ok, result = pcall(pandoc.pipe, "pandoc", pandoc_args, "")
28 +if ok then
29 + if output == "-" then
30 + io.stdout:write(result)
31 + end
32 +else
32 33 io.stderr:write("FAILED to fetch/convert: " .. url .. "\n")
34 + io.stderr:write(tostring(result) .. "\n")
33 35 os.exit(1)