gentle-pi 4.5.0 → 4.6.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.
Files changed (243) hide show
  1. package/README.md +9 -6
  2. package/assets/agents/gentle-ai-verify.md +4 -0
  3. package/assets/agents/gentle-ai-worker.md +1 -0
  4. package/assets/migrations/agent-body-history.json +147 -0
  5. package/assets/orchestrator-delegation-reference.md +3 -3
  6. package/assets/orchestrator-delegation.md +2 -2
  7. package/assets/orchestrator-verification.md +10 -6
  8. package/assets/orchestrator.md +8 -8
  9. package/bin/gentle-shell.mjs +61 -26
  10. package/docs/ci-performance.md +11 -0
  11. package/docs/delegated-verification.md +6 -0
  12. package/docs/fast-mode.md +15 -0
  13. package/docs/gentle-agents-activity.md +8 -0
  14. package/docs/gentle-music.md +6 -3
  15. package/docs/gentle-shell.md +70 -20
  16. package/docs/install-wizard.md +1 -1
  17. package/docs/mcp-status.md +52 -0
  18. package/docs/prompt-budget.md +28 -0
  19. package/docs/readme-reference.md +82 -21
  20. package/docs/session-profile-format.md +20 -5
  21. package/docs/sound-notifications.md +1 -1
  22. package/docs/star-prompt.md +32 -0
  23. package/docs/work-continuity.md +46 -0
  24. package/extensions/ask-user-question.ts +1 -0
  25. package/extensions/codegraph-tools.ts +38 -4
  26. package/extensions/gentle-agents.ts +477 -50
  27. package/extensions/gentle-ai.ts +1046 -191
  28. package/extensions/gentle-fast.ts +61 -0
  29. package/extensions/gentle-guide.ts +174 -0
  30. package/extensions/gentle-herdr-activity.ts +21 -1
  31. package/extensions/gentle-herdr-agent.ts +144 -0
  32. package/extensions/gentle-music.ts +10 -0
  33. package/extensions/gentle-program-identity.ts +61 -0
  34. package/extensions/gentle-shell.ts +642 -97
  35. package/extensions/gentle-star-prompt.ts +334 -0
  36. package/extensions/gentle-stats.ts +5 -5
  37. package/extensions/gentle-todo.ts +42 -22
  38. package/extensions/history/store.ts +18 -12
  39. package/extensions/skill-registry.ts +35 -3
  40. package/extensions/startup-banner.ts +39 -7
  41. package/lib/agent-assets.ts +74 -17
  42. package/lib/agent-profiles.ts +1 -1
  43. package/lib/agents-config.ts +12 -3
  44. package/lib/agents-keys.ts +8 -16
  45. package/lib/agents-protocol.ts +80 -4
  46. package/lib/agents-runner.ts +105 -4
  47. package/lib/agents-view.ts +6 -1
  48. package/lib/agents-widget.ts +132 -9
  49. package/lib/bridge-cost.ts +28 -0
  50. package/lib/codemode-renderer.ts +16 -0
  51. package/lib/command-palette-catalog.ts +1 -0
  52. package/lib/command-palette.ts +21 -8
  53. package/lib/exploration-budget.ts +62 -0
  54. package/lib/gentle-guide.ts +201 -0
  55. package/lib/gentle-shell-launcher.ts +4 -0
  56. package/lib/herdr-activity.ts +9 -3
  57. package/lib/herdr-task-summary-policy.ts +85 -0
  58. package/lib/inprocess-reviewer.ts +33 -13
  59. package/lib/jobs-sidebar-state.ts +5 -6
  60. package/lib/jobs-widget.ts +16 -52
  61. package/lib/keymaps-customize.ts +81 -0
  62. package/lib/keymaps.ts +291 -0
  63. package/lib/model-fallback-notice.ts +61 -0
  64. package/lib/model-fallback-policy.ts +141 -0
  65. package/lib/model-fallback-store.ts +143 -0
  66. package/lib/model-routing-authority.ts +10 -2
  67. package/lib/nan-provider.ts +3 -2
  68. package/lib/native-review-cli.ts +7 -2
  69. package/lib/notification-customize.ts +48 -51
  70. package/lib/openai-fast-tier.ts +22 -0
  71. package/lib/orchestrator-discovery.ts +5 -1
  72. package/lib/orchestrator-fallback.ts +75 -0
  73. package/lib/pasted-image-paths.ts +113 -0
  74. package/lib/questionnaire/questionnaire-view.ts +121 -7
  75. package/lib/review-candidate-view-owner.ts +4 -0
  76. package/lib/review-candidate-view.ts +10 -7
  77. package/lib/review-host-relay.ts +5 -1
  78. package/lib/review-integration-v2.ts +22 -7
  79. package/lib/review-repository.ts +5 -0
  80. package/lib/session-profile-append-controller.ts +21 -6
  81. package/lib/session-profile-authority.ts +119 -0
  82. package/lib/session-profile-binding.ts +54 -5
  83. package/lib/session-profile-freeze.ts +105 -9
  84. package/lib/session-profile-integration.ts +313 -0
  85. package/lib/session-profile-persistence.ts +63 -9
  86. package/lib/shell-bar.ts +171 -56
  87. package/lib/shell-card.ts +26 -6
  88. package/lib/shell-page.ts +120 -0
  89. package/lib/shell-panel.ts +149 -0
  90. package/lib/shell-prompt.ts +53 -1
  91. package/lib/shell-sidebar-layout.ts +98 -25
  92. package/lib/shell-sidebar.ts +54 -1
  93. package/lib/shell-stats.ts +123 -0
  94. package/lib/shell-todo.ts +71 -0
  95. package/lib/shell-usage.ts +12 -2
  96. package/lib/star-prompt.ts +197 -0
  97. package/lib/verifier-admission.ts +18 -8
  98. package/lib/verifier-settle-reminder.ts +64 -0
  99. package/lib/vim-editor-adapter.ts +6 -1
  100. package/lib/visual-customization-policy.ts +41 -6
  101. package/lib/visual-customize-view.ts +164 -26
  102. package/lib/visual-layout-preview.ts +43 -0
  103. package/lib/yolo-session-policy.ts +28 -1
  104. package/package.json +1 -1
  105. package/runtime/gentle-shell-launcher.mjs +4 -0
  106. package/runtime/native-review-cli.mjs +7 -2
  107. package/runtime/review-integration-v2.mjs +22 -7
  108. package/runtime/windows-session-transport.ps1 +60 -3
  109. package/scripts/bootstrap.sh +4 -1
  110. package/scripts/installer-preflight.mjs +1 -1
  111. package/scripts/pi-update.mjs +113 -3
  112. package/scripts/run-test-suite.mjs +17 -1
  113. package/scripts/shell-snapshot.mjs +340 -0
  114. package/scripts/test-packed-runner.mjs +1 -1
  115. package/scripts/update-agent-body-history.mjs +41 -0
  116. package/scripts/verify-installer-tap.mjs +45 -0
  117. package/scripts/verify-package-files.mjs +2 -0
  118. package/skills/gentle-ai/SKILL.md +2 -2
  119. package/skills/tui-design/NOTICE.md +5 -0
  120. package/skills/tui-design/SKILL.md +56 -0
  121. package/skills/tui-design/references/commands.md +75 -0
  122. package/skills/tui-design/references/critique.md +48 -0
  123. package/skills/tui-design/references/design-doc.md +44 -0
  124. package/skills/tui-design/references/terminal-craft.md +64 -0
  125. package/skills/tui-design/references/visual-loop.md +32 -0
  126. package/tests/agents-protocol.test.ts +53 -1
  127. package/tests/agents-runner.test.ts +168 -3
  128. package/tests/agents-view.test.ts +27 -0
  129. package/tests/agents-widget.test.ts +312 -10
  130. package/tests/bounded-scan-contract.test.ts +39 -0
  131. package/tests/bridge-cost.test.ts +32 -0
  132. package/tests/bundled-install.test.ts +6 -4
  133. package/tests/ci-concurrency.test.ts +11 -0
  134. package/tests/ci-merge-base-identity.test.ts +114 -0
  135. package/tests/codegraph-tools.test.ts +69 -0
  136. package/tests/codemode-rendering.test.ts +22 -2
  137. package/tests/command-palette.test.ts +16 -2
  138. package/tests/commit-slice-signal.test.ts +11 -9
  139. package/tests/delegate-for-reason-contract.test.ts +5 -4
  140. package/tests/design-canvas-server.test.ts +6 -2
  141. package/tests/exploration-budget.test.ts +128 -0
  142. package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
  143. package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
  144. package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
  145. package/tests/fixtures/session-profile-v1/replay.ts +125 -0
  146. package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
  147. package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
  148. package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
  149. package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
  150. package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
  151. package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
  152. package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
  153. package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
  154. package/tests/gentle-agents.test.ts +416 -21
  155. package/tests/gentle-ai-exploration-budget.test.ts +135 -0
  156. package/tests/gentle-ai.test.ts +1011 -37
  157. package/tests/gentle-fast.test.ts +73 -0
  158. package/tests/gentle-guide.test.ts +208 -0
  159. package/tests/gentle-herdr-activity.test.ts +76 -2
  160. package/tests/gentle-herdr-agent.test.ts +111 -0
  161. package/tests/gentle-music.test.ts +36 -1
  162. package/tests/gentle-program-identity.test.ts +197 -0
  163. package/tests/gentle-shell-bin.test.ts +49 -26
  164. package/tests/gentle-shell-launcher.test.ts +18 -2
  165. package/tests/gentle-shell.test.ts +1068 -37
  166. package/tests/gentle-stats.test.ts +15 -2
  167. package/tests/gentle-todo.test.ts +50 -4
  168. package/tests/herdr-task-summary-policy.test.ts +128 -0
  169. package/tests/history-store-private-mode.test.ts +40 -0
  170. package/tests/image-paste-chips.test.ts +42 -0
  171. package/tests/inprocess-reviewer.test.ts +122 -0
  172. package/tests/installer-posix-bootstrap.test.ts +67 -5
  173. package/tests/installer-server.test.ts +2 -2
  174. package/tests/installer-windows-diagnostics.test.ts +4 -5
  175. package/tests/isolated-config-home.ts +28 -0
  176. package/tests/jobs-widget.test.ts +25 -37
  177. package/tests/keymaps-customize.test.ts +114 -0
  178. package/tests/keymaps.test.ts +103 -0
  179. package/tests/maintainer/mcp-status.maintest.ts +88 -0
  180. package/tests/maintainer/pi-update-source.maintest.ts +116 -0
  181. package/tests/model-fallback-notice.test.ts +45 -0
  182. package/tests/model-fallback-policy.test.ts +83 -0
  183. package/tests/model-fallback-store.test.ts +111 -0
  184. package/tests/nan-provider.test.ts +4 -4
  185. package/tests/no-self-pause-contract.test.ts +19 -0
  186. package/tests/notification-customize.test.ts +58 -34
  187. package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
  188. package/tests/odd-routing-contract.test.ts +1 -1
  189. package/tests/orchestrator-fallback.test.ts +82 -0
  190. package/tests/orchestrator-prompt-budget.test.ts +131 -0
  191. package/tests/package-manifest.test.ts +160 -7
  192. package/tests/pasted-image-paths.test.ts +118 -0
  193. package/tests/persona-reply-language.test.ts +61 -0
  194. package/tests/pi-update-launcher.test.ts +32 -8
  195. package/tests/pi-update-source.test.ts +162 -0
  196. package/tests/profile-fast-tier.test.ts +311 -0
  197. package/tests/profile-tier-footer.test.ts +79 -0
  198. package/tests/questionnaire-view.test.ts +150 -0
  199. package/tests/review-candidate-owner-sweep.test.ts +93 -0
  200. package/tests/review-candidate-view.test.ts +51 -0
  201. package/tests/review-controller-native-routing.test.ts +120 -6
  202. package/tests/review-gate.test.ts +24 -0
  203. package/tests/review-inspect-preflight.test.ts +197 -0
  204. package/tests/review-integration-v2-forward.test.ts +59 -0
  205. package/tests/review-repository.test.ts +52 -1
  206. package/tests/review-sidebar-state.test.ts +5 -5
  207. package/tests/run-test-suite.test.ts +61 -5
  208. package/tests/sensitive-path-tools.test.ts +74 -0
  209. package/tests/session-profile-append-controller.test.ts +63 -0
  210. package/tests/session-profile-authority.test.ts +259 -0
  211. package/tests/session-profile-binding.test.ts +15 -0
  212. package/tests/session-profile-extension.test.ts +615 -0
  213. package/tests/session-profile-freeze.test.ts +110 -2
  214. package/tests/session-profile-integration.test.ts +857 -0
  215. package/tests/session-profile-persistence.test.ts +57 -0
  216. package/tests/session-profile-v1-compat.test.ts +221 -0
  217. package/tests/shell-bar.test.ts +113 -55
  218. package/tests/shell-card.test.ts +13 -1
  219. package/tests/shell-page.test.ts +108 -0
  220. package/tests/shell-panel.test.ts +332 -0
  221. package/tests/shell-prompt.test.ts +54 -0
  222. package/tests/shell-render-cache.test.ts +5 -0
  223. package/tests/shell-sidebar-fullscreen.test.ts +12 -0
  224. package/tests/shell-sidebar-layout.test.ts +159 -27
  225. package/tests/shell-stats.test.ts +90 -0
  226. package/tests/shell-usage.test.ts +14 -0
  227. package/tests/skill-registry.test.ts +68 -1
  228. package/tests/star-prompt.test.ts +470 -0
  229. package/tests/startup-banner.test.ts +57 -1
  230. package/tests/task-size-routing-contract.test.ts +45 -1
  231. package/tests/verifier-settle-reminder.test.ts +281 -0
  232. package/tests/verify-first-launch-contract.test.ts +56 -5
  233. package/tests/verify-installer-tap.test.ts +57 -0
  234. package/tests/vim-editor-adapter.test.ts +2 -2
  235. package/tests/visual-customization-policy.test.ts +61 -7
  236. package/tests/visual-customize-view.test.ts +253 -8
  237. package/tests/visual-layout-preview.test.ts +28 -0
  238. package/tests/windows-session-bootstrap.test.ts +105 -2
  239. package/tests/work-continuity-contract.test.ts +86 -0
  240. package/tests/writer-surfaces.test.ts +12 -10
  241. package/tests/yolo-customize.test.ts +30 -11
  242. package/tests/yolo-mode-runtime.test.ts +4 -2
  243. package/tests/yolo-mode.test.ts +16 -2
@@ -0,0 +1,131 @@
1
+ import assert from "node:assert/strict";
2
+ import { createHash } from "node:crypto";
3
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath, pathToFileURL } from "node:url";
7
+ import test, { after } from "node:test";
8
+ import {
9
+ createBashToolDefinition, createEditToolDefinition, createReadToolDefinition, createWriteToolDefinition,
10
+ getDocsPath, getExamplesPath, getReadmePath, loadSkillsFromDir,
11
+ } from "@earendil-works/pi-coding-agent";
12
+ import gentleAgents from "../extensions/gentle-agents.ts";
13
+ import { __testing } from "../extensions/gentle-ai.ts";
14
+ import { BACKGROUND_SUBAGENTS_FILE, BACKGROUND_SUBAGENTS_SCHEMA } from "../lib/background-subagents-policy.ts";
15
+ import { appendSystemPromptOnce } from "../lib/append-system-prompt.ts";
16
+
17
+ const root = join(import.meta.dirname, "..");
18
+ const assets = join(root, "assets");
19
+ const fixture = mkdtempSync(join(tmpdir(), "prompt-budget-"));
20
+ const policyDirectory = join(fixture, ".pi", "gentle-ai");
21
+ mkdirSync(policyDirectory, { recursive: true });
22
+ writeFileSync(join(policyDirectory, BACKGROUND_SUBAGENTS_FILE), JSON.stringify({ schema: BACKGROUND_SUBAGENTS_SCHEMA, policy: "off" }));
23
+ after(() => rmSync(fixture, { recursive: true, force: true }));
24
+ const core = __testing.renderOrchestratorPrompt(assets).replaceAll(assets, "/fixture/assets");
25
+
26
+ type Declaration = { name: string; description: string; parameters: unknown; promptSnippet?: string; promptGuidelines?: string[] };
27
+ const tools = new Map<string, Declaration>();
28
+ const pi = {
29
+ on() {}, registerCommand() {}, registerShortcut() {}, registerMessageRenderer() {}, registerEntryRenderer() {},
30
+ events: { on() {}, emit() {} },
31
+ registerTool(tool: Declaration) { tools.set(tool.name, tool); },
32
+ };
33
+ gentleAgents(pi as never, { GENTLE_PI_CONFIG_HOME: fixture }, { home: fixture, agentHome: fixture });
34
+ const names = ["orchestrator_session_id", "orchestrator_list", "subagent_run"];
35
+ const selected = names.map(name => {
36
+ const tool = tools.get(name);
37
+ assert.ok(tool, `missing registered tool ${name}`);
38
+ return { name: tool.name, description: tool.description, parameters: tool.parameters };
39
+ });
40
+ const declarationBytes = Buffer.byteLength(JSON.stringify(selected), "utf8");
41
+
42
+ function withoutDescriptions(value: unknown): unknown {
43
+ if (Array.isArray(value)) return value.map(withoutDescriptions);
44
+ if (value && typeof value === "object") {
45
+ return Object.fromEntries(Object.entries(value).filter(([key]) => key !== "description")
46
+ .map(([key, entry]) => [key, withoutDescriptions(entry)]));
47
+ }
48
+ return value;
49
+ }
50
+
51
+ test("rendered orchestrator core and selected declarations fit the byte budget", t => {
52
+ const prompt = Buffer.byteLength(core, "utf8");
53
+ const total = prompt + declarationBytes;
54
+ t.diagnostic(`rendered core ${prompt} B + declarations ${declarationBytes} B = ${total} B`);
55
+ assert.ok(total <= 16600, `rendered core ${prompt} B + declarations ${declarationBytes} B = ${total} B`);
56
+ });
57
+
58
+ // Pi 1.4 does not export its pure system assembler from the package root.
59
+ // Deliberately use its installed internal module for this test; a missing or
60
+ // changed seam must fail rather than silently falling back to a proxy.
61
+ test("fixed primary host system assembly fits the byte budget", async t => {
62
+ const dist = dirname(fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent")));
63
+ const assembler = await import(pathToFileURL(join(dist, "core", "system-prompt.js")).href);
64
+ assert.equal(typeof assembler.buildSystemPrompt, "function", "Pi system assembler unavailable");
65
+ const activeTools = ["read", "bash", "edit", "write", ...names];
66
+ const harness = __testing.buildGentlePrompt("gentleman", fixture, activeTools, undefined, "tui");
67
+ assert.match(harness, /Background subagent policy: off/);
68
+ assert.match(harness, /Receipt-driven development: unknown \(native status unavailable\)/);
69
+ const review = __testing.readMirroredReviewContractFragment();
70
+ assert.ok(review, "verified mirrored review fragment must be present");
71
+ const { skills, diagnostics } = loadSkillsFromDir({ dir: join(root, "skills", "work-unit-commits"), source: "fixture" });
72
+ assert.equal(diagnostics.length, 0);
73
+ assert.equal(skills.length, 1);
74
+ const builtins = [createReadToolDefinition(fixture), createBashToolDefinition(fixture), createEditToolDefinition(fixture), createWriteToolDefinition(fixture)];
75
+ const registered = [...builtins, ...names.map(name => tools.get(name)!)];
76
+ const toolSnippets = Object.fromEntries(registered.filter(tool => tool.promptSnippet).map(tool => [tool.name, tool.promptSnippet]));
77
+ const toolGuidelines = Object.fromEntries(registered.filter(tool => tool.promptGuidelines).map(tool => [tool.name, tool.promptGuidelines]));
78
+ const options = { appendSystemPrompt: "" };
79
+ appendSystemPromptOnce(options, `\n\n${harness}`);
80
+ appendSystemPromptOnce(options, `\n\n${review}`);
81
+ const system: string = assembler.buildSystemPrompt({
82
+ cwd: fixture, selectedTools: activeTools, toolSnippets, toolGuidelines,
83
+ ...options, skills,
84
+ });
85
+ for (const [label, fragment] of [["harness", harness], ["review contract", review]]) {
86
+ assert.equal(system.split(fragment.replace(/^\n+/, "")).length - 1, 1, `complete ${label} must appear exactly once`);
87
+ }
88
+ const replacements: Array<[string, string]> = [
89
+ [getReadmePath(), "/fixture/pi/README.md"], [getDocsPath(), "/fixture/pi/docs"],
90
+ [getExamplesPath(), "/fixture/pi/examples"], [assets, "/fixture/assets"],
91
+ [join(root, "skills"), "/fixture/skills"], [fixture, "/fixture/cwd"],
92
+ [dirname(dist), "/fixture/pi"],
93
+ ];
94
+ let normalized = system;
95
+ for (const [path, replacement] of replacements) {
96
+ normalized = normalized.replaceAll(path, replacement).replaceAll(path.replaceAll("\\", "/"), replacement);
97
+ }
98
+ const bytes = Buffer.byteLength(normalized, "utf8");
99
+ t.diagnostic(`assembled system ${bytes} B; selected declarations ${declarationBytes} B`);
100
+ assert.ok(bytes <= 40000, `assembled system: ${bytes} B`);
101
+ });
102
+
103
+ test("fixed harness is independent of ambient background policy", () => {
104
+ const previous = process.env.GENTLE_PI_BACKGROUND_SUBAGENTS;
105
+ const activeTools = ["read", "bash", "edit", "write", ...names];
106
+ const rendered: string[] = [];
107
+ try {
108
+ for (const policy of ["off", "on"]) {
109
+ process.env.GENTLE_PI_BACKGROUND_SUBAGENTS = policy;
110
+ const harness = __testing.buildGentlePrompt("gentleman", fixture, activeTools, undefined, "tui");
111
+ assert.match(harness, /Background subagent policy: off/);
112
+ rendered.push(harness);
113
+ }
114
+ assert.equal(rendered[0], rendered[1]);
115
+ } finally {
116
+ if (previous === undefined) delete process.env.GENTLE_PI_BACKGROUND_SUBAGENTS;
117
+ else process.env.GENTLE_PI_BACKGROUND_SUBAGENTS = previous;
118
+ }
119
+ });
120
+
121
+ const schemaDigests: Record<string, string> = {
122
+ orchestrator_session_id: "5fb49381808a8dc1146d89409ba6237380b62c871282a99104770b24902589e0",
123
+ orchestrator_list: "fe50d306a023bfaf20fddeb8696a3e62b84534b02efb6d699f9991b129a709fa",
124
+ subagent_run: "02e15acc80fde692b0e7ceab434c248b733f33783b176606119969952cd16036",
125
+ };
126
+ for (const tool of selected) {
127
+ test(`${tool.name} schema retains its non-description contract`, () => {
128
+ const digest = createHash("sha256").update(JSON.stringify(withoutDescriptions(tool.parameters))).digest("hex");
129
+ assert.equal(digest, schemaDigests[tool.name]);
130
+ });
131
+ }
@@ -1,6 +1,5 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { parseNpmPackResult } from "../scripts/npm-pack-result.mjs";
3
- import { execFileSync } from "node:child_process";
4
3
  import { createHash } from "node:crypto";
5
4
  import {
6
5
  existsSync,
@@ -18,9 +17,10 @@ import ts from "typescript";
18
17
  import { fileURLToPath } from "node:url";
19
18
  import { applyModelConfig } from "../extensions/gentle-ai.ts";
20
19
  import { resolveGentlePiAgentHome } from "../lib/agent-home.ts";
21
- import { getPackageAssetOwner, installPackageAssets, type PackageAssetOwner } from "../lib/agent-assets.ts";
20
+ import { agentBody, getPackageAssetOwner, installPackageAssets, readAgentBodyHistory, type PackageAssetOwner } from "../lib/agent-assets.ts";
21
+ import { discoverAgents } from "../lib/agents-config.ts";
22
22
  import { AUDITED_PI_EDITOR_VERSIONS } from "../lib/vim-editor-adapter.ts";
23
- import { resolveProjectPiSdkVersion } from "../scripts/test-packed-runner.mjs";
23
+ import { resolveProjectPiSdkVersion, runNpmWithEnv } from "../scripts/test-packed-runner.mjs";
24
24
  // Package installation is owned by lib/agent-assets.ts, not the retired SDD preflight.
25
25
 
26
26
  const PACKAGE_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -630,7 +630,7 @@ test("packaged agents use YAML list syntax for tool allowlists", () => {
630
630
  assert.doesNotMatch(
631
631
  frontmatter,
632
632
  /^tools:\s*[^\n,]+(?:,\s*[^\n,]+)+$/m,
633
- `${file} must not use comma-separated inline tools; pi-subagents expects a YAML list`,
633
+ `${file} must not use comma-separated inline tools; the agent runtime expects a YAML list`,
634
634
  );
635
635
  assert.match(
636
636
  frontmatter,
@@ -667,6 +667,46 @@ test("packaged agents declare only tool names a Pi child session can resolve", (
667
667
  }
668
668
  });
669
669
 
670
+ // The tool-allowlist marker that denies everything else. An allowlist already
671
+ // denies unlisted tools, so the runtime tolerates this entry by design: it is
672
+ // not a tool name and Pi drops it from --tools.
673
+ const DENY_ALL_TOOLS_MARKER = '"*": false';
674
+
675
+ // gentle-shell#62: the declared YAML list once collapsed into one malformed
676
+ // token on its way to the child, which then started without its filesystem
677
+ // tools. This walks the real path every packaged agent takes at runtime:
678
+ // install into an agent home, then discover and parse with the agent runtime,
679
+ // and compares what the runtime yields against what the file declares.
680
+ test("packaged agents reach the agent runtime with their declared tool allowlists", () => {
681
+ const agentsDir = join(PACKAGE_ROOT, "assets", "agents");
682
+ const agentFiles = readdirSync(agentsDir).flatMap((entry) =>
683
+ entry.endsWith(".md") ? [join(agentsDir, entry)] : [],
684
+ );
685
+ assert.ok(agentFiles.length > 0, "gentle-pi must ship packaged agents");
686
+
687
+ withIsolatedAssetHome((agentHome) => {
688
+ installPackageAssets(agentHome, false);
689
+ const empty = mkdtempSync(join(tmpdir(), "gentle-agent-roots-"));
690
+ try {
691
+ const { agents, errors } = discoverAgents({ cwd: empty, home: empty, agentHome });
692
+ assert.deepEqual(errors, [], "every packaged agent must parse through the agent runtime");
693
+ for (const file of agentFiles) {
694
+ const { name, tools: declared } = readAgentDefinition(file);
695
+ const agent = agents.find((candidate) => candidate.name === name);
696
+ assert.ok(agent, `${file} must be discovered by the agent runtime after installation`);
697
+ assert.deepEqual(
698
+ agent.tools.filter((tool) => tool !== DENY_ALL_TOOLS_MARKER),
699
+ declared,
700
+ `${file} must reach the runtime with exactly its declared tool allowlist`,
701
+ );
702
+ assert.ok(agent.tools.includes("read"), `${file} must keep read so the child can inspect files`);
703
+ }
704
+ } finally {
705
+ rmSync(empty, { recursive: true, force: true });
706
+ }
707
+ });
708
+ });
709
+
670
710
  function withIsolatedAssetHome(run: (agentHome: string) => void): void {
671
711
  const temporary = mkdtempSync(join(tmpdir(), "gentle-asset-owners-"));
672
712
  const previous = process.env.GENTLE_PI_AGENT_HOME;
@@ -704,6 +744,102 @@ test("ODD delegation assets retain applicable test-first checks and independent
704
744
  assert.match(worker, /review lifecycle.*parent/i);
705
745
  });
706
746
 
747
+ // A package agent whose frontmatter another tool rewrote (inline tools, model
748
+ // routing) once fell out of the manifest and froze on an outdated contract,
749
+ // such as the retired Strict TDD mode prompt.
750
+ test("forced refresh updates a frozen package agent with a shipped body and keeps its routing", () => {
751
+ withIsolatedAssetHome((agentHome) => {
752
+ const key = "agents/gentle-ai-worker.md";
753
+ const installedPath = join(agentHome, key);
754
+ const packaged = readFileSync(join(PACKAGE_ROOT, "assets", key), "utf8");
755
+ const stale = readFileSync(join(PACKAGE_ROOT, "tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md"), "utf8");
756
+ const foreignFrontmatter = "---\nname: gentle-ai-worker\ndescription: Old description.\nmodel: openai/test-model\nthinking: max\ntools: read, grep, find, edit, write, bash, mem_save, mcp";
757
+ installPackageAssets(agentHome, false, ["delegation"]);
758
+ writeFileSync(installedPath, `${foreignFrontmatter}${agentBody(stale)}`);
759
+ const manifestPath = join(agentHome, "gentle-ai", "managed-assets.json");
760
+ const manifest = installedAssetManifest(agentHome);
761
+ delete manifest.assets[key];
762
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
763
+
764
+ installPackageAssets(agentHome, true, ["delegation"]);
765
+ const refreshed = readFileSync(installedPath, "utf8");
766
+ assert.doesNotMatch(refreshed, /effective TDD mode/);
767
+ assert.equal(
768
+ refreshed,
769
+ packaged.replace(/^(description:.*)$/m, "$1\nmodel: openai/test-model\nthinking: max"),
770
+ );
771
+ assert.equal(installedAssetManifest(agentHome).assets[key], undefined, "a locally routed copy stays unmanaged");
772
+
773
+ installPackageAssets(agentHome, true, ["delegation"]);
774
+ assert.equal(readFileSync(installedPath, "utf8"), refreshed, "a second refresh must keep the routing");
775
+ });
776
+ });
777
+
778
+ test("forced refresh restores an old shipped agent without routing to the managed copy", () => {
779
+ withIsolatedAssetHome((agentHome) => {
780
+ const key = "agents/gentle-ai-worker.md";
781
+ const installedPath = join(agentHome, key);
782
+ const packaged = readFileSync(join(PACKAGE_ROOT, "assets", key), "utf8");
783
+ const stale = readFileSync(join(PACKAGE_ROOT, "tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md"), "utf8");
784
+ installPackageAssets(agentHome, false, ["delegation"]);
785
+ writeFileSync(installedPath, stale.replace(/\ntools:\n(?: - .*\n)+/, "\ntools: read, grep, find, edit, write, bash, mem_save\n"));
786
+ const manifestPath = join(agentHome, "gentle-ai", "managed-assets.json");
787
+ const manifest = installedAssetManifest(agentHome);
788
+ manifest.assets[key] = sha256("stale");
789
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
790
+
791
+ const result = installPackageAssets(agentHome, true, ["delegation"]);
792
+ assert.equal(readFileSync(installedPath, "utf8"), packaged);
793
+ assert.equal(installedAssetManifest(agentHome).assets[key], sha256(packaged));
794
+ assert.equal(result.skipped, 0);
795
+ });
796
+ });
797
+
798
+ // Only outdated instructions are refreshed: a frontmatter edit on the current
799
+ // agent (here a restricted tool allowlist) stays a user override.
800
+ test("forced refresh keeps a frontmatter edit on an agent with current instructions", () => {
801
+ withIsolatedAssetHome((agentHome) => {
802
+ const key = "agents/gentle-ai-worker.md";
803
+ const installedPath = join(agentHome, key);
804
+ installPackageAssets(agentHome, false, ["delegation"]);
805
+ const restricted = readFileSync(installedPath, "utf8").replace(" - bash\n", "");
806
+ writeFileSync(installedPath, restricted);
807
+
808
+ const result = installPackageAssets(agentHome, true, ["delegation"]);
809
+ assert.equal(readFileSync(installedPath, "utf8"), restricted);
810
+ assert.equal(installedAssetManifest(agentHome).assets[key], undefined);
811
+ assert.equal(result.skipped, 1);
812
+ });
813
+ });
814
+
815
+ test("agent body history records the body of every packaged agent", () => {
816
+ const history = readAgentBodyHistory();
817
+ const agentsDir = join(PACKAGE_ROOT, "assets", "agents");
818
+ for (const file of readdirSync(agentsDir).filter((name) => name.endsWith(".md"))) {
819
+ assert.ok(
820
+ history[`agents/${file}`]?.includes(sha256(agentBody(readFileSync(join(agentsDir, file), "utf8")))),
821
+ `assets/agents/${file} changed: run node scripts/update-agent-body-history.mjs`,
822
+ );
823
+ }
824
+ });
825
+
826
+ test("forced refresh still leaves agents with user-edited bodies in place", () => {
827
+ withIsolatedAssetHome((agentHome) => {
828
+ const key = "agents/gentle-ai-worker.md";
829
+ const installedPath = join(agentHome, key);
830
+ installPackageAssets(agentHome, false, ["delegation"]);
831
+ const edited = readFileSync(installedPath, "utf8")
832
+ .replace(/^(description:.*)$/m, "$1\nmodel: openai/test-model")
833
+ .concat("\nUser-authored instruction.\n");
834
+ writeFileSync(installedPath, edited);
835
+
836
+ const result = installPackageAssets(agentHome, true, ["delegation"]);
837
+ assert.equal(readFileSync(installedPath, "utf8"), edited);
838
+ assert.equal(installedAssetManifest(agentHome).assets[key], undefined);
839
+ assert.equal(result.skipped, 1);
840
+ });
841
+ });
842
+
707
843
  test("delegation installation retains strict TDD support without installing SDD assets", () => {
708
844
  withIsolatedAssetHome((agentHome) => {
709
845
  installPackageAssets(agentHome, false, ["delegation"]);
@@ -903,12 +1039,29 @@ test("native windows audio ships an owned encoded-command adapter without script
903
1039
  assert.doesNotMatch(source, /postinstall|installer|download/i, path);
904
1040
  });
905
1041
 
1042
+ test("shell-free npm helper preserves packed tarball arguments and options", () => {
1043
+ const source = readFileSync(join(PACKAGE_ROOT, "tests", "package-manifest.test.ts"), "utf8");
1044
+ const runner = readFileSync(join(PACKAGE_ROOT, "scripts", "test-packed-runner.mjs"), "utf8");
1045
+ const tarball = source.split('\ntest("packed tarball excludes retired workflow paths')[1]?.split('\n});')[0] ?? "";
1046
+ assert.match(source, /import \{[^}]*runNpmWithEnv[^}]*\} from "\.\.\/scripts\/test-packed-runner\.mjs"/);
1047
+ assert.match(tarball, /runNpmWithEnv\(\["pack", "--ignore-scripts", "--offline", "--json", "--pack-destination", destination\], process\.env, \{/);
1048
+ assert.match(tarball, /cwd: PACKAGE_ROOT/);
1049
+ assert.match(tarball, /encoding: "utf8"/);
1050
+ assert.match(tarball, /maxBuffer: 8 \* 1024 \* 1024/);
1051
+ assert.doesNotMatch(tarball, /execFileSync|shell\s*:\s*true/);
1052
+ assert.match(runner, /export function runNpmWithEnv\(/);
1053
+ const helper = readNamedFunction(runner, "runNpmWithEnv");
1054
+ assert.match(helper, /process\.platform === "win32" \? windowsNpmInvocation\(\) : \{ file: "npm", prefix: \[\] \}/);
1055
+ assert.match(helper, /execFileSync\(invocation\.file, \[\.\.\.invocation\.prefix, \.\.\.arguments_\], \{ \.\.\.options, env \}\)/);
1056
+ assert.doesNotMatch(helper, /shell\s*:\s*true|cmd\.exe|npm\.cmd/);
1057
+ });
1058
+
906
1059
  test("packed tarball excludes retired workflow paths while source retains legacy migration proof", () => {
907
1060
  const fixture = "tests/fixtures/legacy/sdd-research-v2.5.0.md";
908
1061
  assert.ok(existsSync(join(PACKAGE_ROOT, fixture)), "the historical source fixture must remain available to migration tests");
909
1062
  const destination = mkdtempSync(join(tmpdir(), "gentle-pi-pack-manifest-"));
910
1063
  try {
911
- const output = execFileSync("npm", ["pack", "--ignore-scripts", "--offline", "--json", "--pack-destination", destination], {
1064
+ const output = runNpmWithEnv(["pack", "--ignore-scripts", "--offline", "--json", "--pack-destination", destination], process.env, {
912
1065
  cwd: PACKAGE_ROOT,
913
1066
  encoding: "utf8",
914
1067
  maxBuffer: 8 * 1024 * 1024,
@@ -1793,9 +1946,9 @@ test("pi-pretty wrapper uses cached ESM loading for compiled and pnpm symlink in
1793
1946
  assert.match(wrapper, /quietToolsEnabled/);
1794
1947
  });
1795
1948
 
1796
- test("Gentle Shell v4.5.0 package manifest declares the release version", () => {
1949
+ test("Gentle Shell v4.6.0 package manifest declares the release version", () => {
1797
1950
  const packageJson = readPackageJson();
1798
- assert.equal(packageJson.version, "4.5.0", "the release manifest must be explicitly pinned to v4.5.0");
1951
+ assert.equal(packageJson.version, "4.6.0", "the release manifest must be explicitly pinned to v4.6.0");
1799
1952
  assert.equal(packageJson.scripts?.test, "node scripts/run-test-suite.mjs");
1800
1953
  assert.ok(packageJson.files?.includes("assets/"));
1801
1954
  assert.ok(packageJson.files?.includes("contracts/"));
@@ -0,0 +1,118 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { mkdtempSync, rmSync, truncateSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { parsePathTokens, readPastedImagePaths } from "../lib/pasted-image-paths.ts";
7
+
8
+ // Herdr hands a clipboard image to a terminal on another machine as a temp-file
9
+ // path, and dropped or file-manager-copied images arrive as quoted paths. Those
10
+ // pastes must become chips instead of text.
11
+
12
+ const PNG_2X1 = new Uint8Array([
13
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
14
+ 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
15
+ 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01,
16
+ 0x08, 0x06, 0x00, 0x00, 0x00,
17
+ ]);
18
+ const JPEG = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]);
19
+ const GIF = new Uint8Array([0x47, 0x49, 0x46, 0x38, 0x39, 0x61]);
20
+ const WEBP = new Uint8Array([0x52, 0x49, 0x46, 0x46, 0x20, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50]);
21
+
22
+ type Files = Record<string, Uint8Array>;
23
+
24
+ function filesystem(files: Files, home = "/home/devel") {
25
+ return {
26
+ home,
27
+ readFile: (path: string) => {
28
+ const bytes = files[path];
29
+ if (!bytes) throw new Error(`ENOENT: ${path}`);
30
+ return bytes;
31
+ },
32
+ isFile: (path: string) => path in files,
33
+ };
34
+ }
35
+
36
+ test("a bare image path from Herdr's clipboard bridge becomes an image", () => {
37
+ const options = filesystem({ "/tmp/client-1-clipboard-99.png": PNG_2X1 });
38
+ assert.deepEqual(
39
+ readPastedImagePaths("/tmp/client-1-clipboard-99.png", options).map((image) => image.mimeType),
40
+ ["image/png"],
41
+ );
42
+ });
43
+
44
+ test("Herdr's quoted paths keep spaces and become one chip per file", () => {
45
+ const options = filesystem({
46
+ "/tmp/herdr paste/a.png": PNG_2X1,
47
+ "/tmp/herdr paste/b.jpg": JPEG,
48
+ });
49
+ const images = readPastedImagePaths("'/tmp/herdr paste/a.png' '/tmp/herdr paste/b.jpg' ", options);
50
+ assert.deepEqual(images.map((image) => image.mimeType), ["image/png", "image/jpeg"]);
51
+ });
52
+
53
+ test("an escaped quote inside a quoted path stays part of the name", () => {
54
+ const options = filesystem({ "/tmp/it's/one.gif": GIF });
55
+ assert.deepEqual(readPastedImagePaths("'/tmp/it'\\''s/one.gif'", options).map((image) => image.mimeType), ["image/gif"]);
56
+ });
57
+
58
+ test("newline-separated paths, ~ and file:// URLs resolve", () => {
59
+ const options = filesystem({
60
+ "/home/devel/shot.webp": WEBP,
61
+ "/tmp/other.png": PNG_2X1,
62
+ });
63
+ const pasted = `${"/tmp/other.png"}\n~/shot.webp`;
64
+ assert.deepEqual(readPastedImagePaths(pasted, options).map((image) => image.mimeType), ["image/png", "image/webp"]);
65
+ assert.deepEqual(
66
+ readPastedImagePaths("file:///tmp/other.png", options).map((image) => image.mimeType),
67
+ ["image/png"],
68
+ );
69
+ });
70
+
71
+ test("text, a sentence mentioning a path, or a mix with it stays Pi's paste", () => {
72
+ const options = filesystem({ "/tmp/shot.png": PNG_2X1 });
73
+ assert.deepEqual(readPastedImagePaths("", options), []);
74
+ assert.deepEqual(readPastedImagePaths("look at /tmp/shot.png please", options), []);
75
+ assert.deepEqual(readPastedImagePaths("/tmp/shot.png and more", options), []);
76
+ assert.deepEqual(readPastedImagePaths("/tmp/shot.png\n/tmp/missing.png", options), []);
77
+ });
78
+
79
+ test("missing files, non-image extensions and foreign bytes are not images", () => {
80
+ const notAnImage = new Uint8Array([0x00, 0x01, 0x02, 0x03]);
81
+ const options = filesystem({
82
+ "/tmp/missing.png": PNG_2X1,
83
+ "/tmp/notes.txt": PNG_2X1,
84
+ "/tmp/fake.png": notAnImage,
85
+ "relative/shot.png": PNG_2X1,
86
+ });
87
+ assert.deepEqual(readPastedImagePaths("/tmp/absent.png", options), []);
88
+ assert.deepEqual(readPastedImagePaths("/tmp/notes.txt", options), []);
89
+ assert.deepEqual(readPastedImagePaths("/tmp/fake.png", options), []);
90
+ assert.deepEqual(readPastedImagePaths("relative/shot.png", options), []);
91
+ });
92
+
93
+ test("a paste of more than eight paths stays Pi's paste", () => {
94
+ const files: Files = {};
95
+ const tokens: string[] = [];
96
+ for (let index = 0; index < 9; index += 1) {
97
+ files[`/tmp/${index}.png`] = PNG_2X1;
98
+ tokens.push(`/tmp/${index}.png`);
99
+ }
100
+ assert.deepEqual(readPastedImagePaths(tokens.join(" "), filesystem(files)), []);
101
+ assert.equal(readPastedImagePaths(tokens.slice(0, 8).join(" "), filesystem(files)).length, 8);
102
+ });
103
+
104
+ test("token parsing handles single quotes, double quotes, escapes and newlines", () => {
105
+ assert.deepEqual(parsePathTokens("'a b.png' \"c d.png\" e\\ f.png"), ["a b.png", "c d.png", "e f.png"]);
106
+ assert.deepEqual(parsePathTokens("\n/tmp/a.png\n\n/tmp/b.png\r\n"), ["/tmp/a.png", "/tmp/b.png"]);
107
+ assert.deepEqual(parsePathTokens("'/tmp/it'\\''s.png'"), ["/tmp/it's.png"]);
108
+ });
109
+
110
+ test("an oversized file is rejected before its bytes are read", () => {
111
+ // A sparse file keeps this cheap while still exceeding the 64 MiB cap.
112
+ const directory = mkdtempSync(join(tmpdir(), "gentle-pasted-path-"));
113
+ const path = join(directory, "huge.png");
114
+ writeFileSync(path, PNG_2X1);
115
+ truncateSync(path, 64 * 1024 * 1024 + 1);
116
+ assert.deepEqual(readPastedImagePaths(path, {}), []);
117
+ rmSync(directory, { recursive: true, force: true });
118
+ });
@@ -0,0 +1,61 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { __testing } from "../extensions/gentle-ai.ts";
4
+
5
+ // gentle-shell #55 / #57 / #125 / #2348: the reply language is inferred every
6
+ // turn,
7
+ // never stored, so the persona prompt itself must say how to infer it. The
8
+ // rule lives on the single existing language-match bullet (the concept-level
9
+ // duplication guard allows exactly one), so these tests read the rendered
10
+ // prompt rather than a second rule.
11
+
12
+ for (const persona of ["gentleman", "neutral"] as const) {
13
+ test(`[${persona}] the reply language follows the user's latest message, never a Spanish default (#125, #57)`, () => {
14
+ const prompt = __testing.buildGentlePrompt(persona);
15
+ assert.match(prompt, /Always respond in the same language the user writes in\./);
16
+ assert.match(
17
+ prompt,
18
+ /latest message, never by earlier context or a compaction summary/,
19
+ `${persona} prompt must judge the reply language by the user's latest message, so a compaction summary cannot flip it (#57)`,
20
+ );
21
+ assert.match(
22
+ prompt,
23
+ /never default to Spanish: a message in English gets a reply in English/,
24
+ `${persona} prompt must forbid a Spanish default, so an English message never gets a Spanish reply (#125)`,
25
+ );
26
+ });
27
+ test(`[${persona}] harness-generated turns are never a language signal (#2348)`, () => {
28
+ const prompt = __testing.buildGentlePrompt(persona);
29
+ assert.match(
30
+ prompt,
31
+ /Only a message written by the human can select or change the reply language/,
32
+ `${persona} prompt must let only a human-authored message change the reply language (#2348)`,
33
+ );
34
+ assert.match(
35
+ prompt,
36
+ /subagent completion and progress notifications, background job notices, todo and system reminders, tool output, skill bodies, and injected memory never count as a language signal, even when delivered with the user role/,
37
+ `${persona} prompt must exclude harness-generated user-role turns, so an English subagent or background notification cannot flip the session to English (#2348)`,
38
+ );
39
+ assert.match(
40
+ prompt,
41
+ /Translate relayed subagent findings into the selected reply language/,
42
+ `${persona} prompt must require translating relayed subagent findings (#2348)`,
43
+ );
44
+ });
45
+ }
46
+
47
+ test("[neutral] the voseo prohibition covers regular and irregular forms, not only four irregular verbs (#55)", () => {
48
+ const prompt = __testing.buildGentlePrompt("neutral");
49
+ assert.match(prompt, /Do NOT use voseo/);
50
+ assert.match(prompt, /regular or irregular: use tú or usted forms, never vos forms/);
51
+ for (const pair of ["ajustas, not ajustás", "vives, not vivís", "mira, not mirá", "haz, not hacé"]) {
52
+ assert.ok(prompt.includes(pair), `neutral prompt must name the voseo replacement "${pair}"`);
53
+ }
54
+ });
55
+
56
+ test("[gentleman] Spanish replies keep Rioplatense voseo and get no neutral-only rule", () => {
57
+ const prompt = __testing.buildGentlePrompt("gentleman");
58
+ assert.match(prompt, /When the user writes Spanish, answer in natural Rioplatense Spanish with voseo\./);
59
+ assert.match(prompt, /Language: natural Rioplatense Spanish with voseo when the user writes Spanish\./);
60
+ assert.doesNotMatch(prompt, /never vos forms/, "gentleman prompt must not inherit the neutral voseo prohibition");
61
+ });
@@ -6,15 +6,16 @@ const PI = '@earendil-works/pi-coding-agent';
6
6
  // A virtual symlink filesystem: listed global links point into a pnpm store.
7
7
  // The store's adjacent peer is a sibling, not Shell/node_modules/Pi.
8
8
  function launch(args: string[], scenario = 'owned', piVersion = '1.2.0') {
9
- const adjacent = scenario.startsWith('adjacent');
10
- const npm = scenario.startsWith('npm-');
9
+ const source = scenario === 'source';
10
+ const adjacent = source || scenario.startsWith('adjacent');
11
+ const npm = source || scenario.startsWith('npm-');
11
12
  const nodeModules = '/global/v11/selected/node_modules';
12
13
  const shellRoot = '/store/shell-peer/node_modules/gentle-pi';
13
14
  const piRoot = adjacent ? '/store/shell-peer/node_modules/' + PI : '/store/pi/node_modules/' + PI;
14
15
  const target = adjacent ? 'gentle-pi' : PI;
15
16
  const dependencies: Record<string, object> = {[target]:{path: `${nodeModules}/${target}`,
16
17
  ...(scenario === 'npm-link' ? {link:true} : {}),
17
- ...(scenario === 'npm-file' ? {resolved:'file:/source/pi'} : {})}};
18
+ ...(scenario === 'npm-file' || source ? {resolved:'file:/source/pi'} : {})}};
18
19
  if (scenario.endsWith('shared')) dependencies['unrelated'] = {path:`${nodeModules}/unrelated`};
19
20
  if (scenario === 'separate') dependencies['unrelated'] = {path:'/global/v11/other/node_modules/unrelated'};
20
21
  const groups = [{path:'/global/v11',dependencies}, ...(scenario === 'ambiguous' ? [{path:'/global/other',dependencies}] : [])];
@@ -22,7 +23,11 @@ function launch(args: string[], scenario = 'owned', piVersion = '1.2.0') {
22
23
  // pnpm links only the top-level package into the global group; the peer
23
24
  // is reachable solely as the Shell package's store sibling.
24
25
  const links = {[`${nodeModules}/${target}`]:adjacent ? shellRoot : piRoot};
25
- const roots = [nodeModules, '/global/v11/other/node_modules', shellRoot, piRoot, `${piRoot}/dist/bundle/cli.js`];
26
+ if (source) {
27
+ links[`${shellRoot}/node_modules/${PI}`] = piRoot;
28
+ links[`${shellRoot}/node_modules/${PI}/dist/bundle/cli.js`] = `${piRoot}/dist/bundle/cli.js`;
29
+ }
30
+ const roots = [nodeModules, '/global/v11/other/node_modules', shellRoot, piRoot, `${piRoot}/dist/bundle/cli.js`, `${shellRoot}/.git`, `${shellRoot}/package.json`, `${shellRoot}/package-lock.json`];
26
31
  const bootstrap = `import { registerHooks } from 'node:module';
27
32
  const original = ${JSON.stringify(new URL('../bin/gentle-shell.mjs', import.meta.url).href)};
28
33
  registerHooks({load(url, context, next) {
@@ -40,12 +45,13 @@ function launch(args: string[], scenario = 'owned', piVersion = '1.2.0') {
40
45
  }});
41
46
  const links = ${JSON.stringify(links)}, roots = ${JSON.stringify(roots)};
42
47
  globalThis.fakeAdapters = {
43
- fs: { realpath: async p => { if (links[p]) return links[p]; if (roots.includes(p)) return p; throw new Error('ENOENT ' + p); },
44
- readFile: async p => { if (p === '${shellRoot}/package.json') return JSON.stringify({name:'gentle-pi',version:'4.1.0'}); if(p === '${piRoot}/package.json') return JSON.stringify({name:'${PI}',version:'1.2.0',bin:{pi:'dist/bundle/cli.js'}}); throw new Error('ENOENT ' + p); } },
48
+ fs: { realpath: async p => { if (links[p]) return links[p]; if (roots.includes(p)) return p; throw Object.assign(new Error('ENOENT ' + p), {code:'ENOENT'}); },
49
+ readFile: async p => { if (p === '${shellRoot}/package.json') return JSON.stringify({name:'gentle-pi',version:'4.1.0', ...(${source} ? {packageManager:'npm@11.1.1',devDependencies:{'${PI}':'^1.2.0'}} : {})}); if(p === '${piRoot}/package.json') return JSON.stringify({name:'${PI}',version:'1.2.0',bin:{pi:'dist/bundle/cli.js'}}); if (${source} && p === '${shellRoot}/package-lock.json') return '{}'; throw Object.assign(new Error('ENOENT ' + p), {code:'ENOENT'}); } },
45
50
  which: async n => n === '${npm ? 'npm' : 'pnpm'}' ? '/fake/' + n : null,
46
- run: async (cmd, args) => {
51
+ run: async (cmd, args, options) => {
47
52
  if(args.includes('list') || args.includes('ls')) return {code:0,stdout:${JSON.stringify(listing)}};
48
- console.log('MUTATION ' + JSON.stringify(args)); return {code:0};
53
+ if(args.includes('--version')) return {code:0,stdout:'11.1.1'};
54
+ console.log('MUTATION ' + JSON.stringify(args)); if (${source}) console.log('CWD ' + options.cwd); return {code:0};
49
55
  }
50
56
  };
51
57
  await import(original);`;
@@ -63,6 +69,24 @@ for (const scenario of ['owned','adjacent','separate']) test(`public linked-stor
63
69
  assert.equal(result.stderr, '');
64
70
  });
65
71
 
72
+ for (const all of [false, true]) test(`public source-linked update uses the checkout and preserves extension forwarding (all: ${all})`, () => {
73
+ const result = launch(all ? ['update', '--all'] : ['update'], 'source');
74
+ assert.equal(result.status, 0, result.stderr);
75
+ assert.equal(result.stderr, '');
76
+ assert.match(result.stdout, /MUTATION \["update","@earendil-works\/pi-coding-agent","--no-save","--ignore-scripts","--global=false","--prefix","\/store\/shell-peer\/node_modules\/gentle-pi","--workspaces=false","--no-audit","--no-fund"\]/);
77
+ assert.match(result.stdout, /CWD \/store\/shell-peer\/node_modules\/gentle-pi/);
78
+ assert.doesNotMatch(result.stdout, /"-g"|@latest/);
79
+ assert.equal(result.stdout.includes('FORWARD ["update","--extensions"]'), all);
80
+ });
81
+
82
+ test('source-linked --latest preserves the ordinary local, range-respecting plan', () => {
83
+ const normal = launch(['update'], 'source');
84
+ const latest = launch(['update', '--latest'], 'source');
85
+ assert.equal(latest.status, 0, latest.stderr);
86
+ assert.deepEqual({status:latest.status, stdout:latest.stdout, stderr:latest.stderr}, {status:normal.status, stdout:normal.stdout, stderr:normal.stderr});
87
+ assert.doesNotMatch(latest.stdout, /"--latest"|"-g"|@latest/);
88
+ });
89
+
66
90
  test('public all updates only its owner and then forwards extension updates', () => {
67
91
  const result = launch(['update', '--all']);
68
92
  assert.equal(result.status, 0, result.stderr);