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.
- package/README.md +9 -6
- package/assets/agents/gentle-ai-verify.md +4 -0
- package/assets/agents/gentle-ai-worker.md +1 -0
- package/assets/migrations/agent-body-history.json +147 -0
- package/assets/orchestrator-delegation-reference.md +3 -3
- package/assets/orchestrator-delegation.md +2 -2
- package/assets/orchestrator-verification.md +10 -6
- package/assets/orchestrator.md +8 -8
- package/bin/gentle-shell.mjs +61 -26
- package/docs/ci-performance.md +11 -0
- package/docs/delegated-verification.md +6 -0
- package/docs/fast-mode.md +15 -0
- package/docs/gentle-agents-activity.md +8 -0
- package/docs/gentle-music.md +6 -3
- package/docs/gentle-shell.md +70 -20
- package/docs/install-wizard.md +1 -1
- package/docs/mcp-status.md +52 -0
- package/docs/prompt-budget.md +28 -0
- package/docs/readme-reference.md +82 -21
- package/docs/session-profile-format.md +20 -5
- package/docs/sound-notifications.md +1 -1
- package/docs/star-prompt.md +32 -0
- package/docs/work-continuity.md +46 -0
- package/extensions/ask-user-question.ts +1 -0
- package/extensions/codegraph-tools.ts +38 -4
- package/extensions/gentle-agents.ts +477 -50
- package/extensions/gentle-ai.ts +1046 -191
- package/extensions/gentle-fast.ts +61 -0
- package/extensions/gentle-guide.ts +174 -0
- package/extensions/gentle-herdr-activity.ts +21 -1
- package/extensions/gentle-herdr-agent.ts +144 -0
- package/extensions/gentle-music.ts +10 -0
- package/extensions/gentle-program-identity.ts +61 -0
- package/extensions/gentle-shell.ts +642 -97
- package/extensions/gentle-star-prompt.ts +334 -0
- package/extensions/gentle-stats.ts +5 -5
- package/extensions/gentle-todo.ts +42 -22
- package/extensions/history/store.ts +18 -12
- package/extensions/skill-registry.ts +35 -3
- package/extensions/startup-banner.ts +39 -7
- package/lib/agent-assets.ts +74 -17
- package/lib/agent-profiles.ts +1 -1
- package/lib/agents-config.ts +12 -3
- package/lib/agents-keys.ts +8 -16
- package/lib/agents-protocol.ts +80 -4
- package/lib/agents-runner.ts +105 -4
- package/lib/agents-view.ts +6 -1
- package/lib/agents-widget.ts +132 -9
- package/lib/bridge-cost.ts +28 -0
- package/lib/codemode-renderer.ts +16 -0
- package/lib/command-palette-catalog.ts +1 -0
- package/lib/command-palette.ts +21 -8
- package/lib/exploration-budget.ts +62 -0
- package/lib/gentle-guide.ts +201 -0
- package/lib/gentle-shell-launcher.ts +4 -0
- package/lib/herdr-activity.ts +9 -3
- package/lib/herdr-task-summary-policy.ts +85 -0
- package/lib/inprocess-reviewer.ts +33 -13
- package/lib/jobs-sidebar-state.ts +5 -6
- package/lib/jobs-widget.ts +16 -52
- package/lib/keymaps-customize.ts +81 -0
- package/lib/keymaps.ts +291 -0
- package/lib/model-fallback-notice.ts +61 -0
- package/lib/model-fallback-policy.ts +141 -0
- package/lib/model-fallback-store.ts +143 -0
- package/lib/model-routing-authority.ts +10 -2
- package/lib/nan-provider.ts +3 -2
- package/lib/native-review-cli.ts +7 -2
- package/lib/notification-customize.ts +48 -51
- package/lib/openai-fast-tier.ts +22 -0
- package/lib/orchestrator-discovery.ts +5 -1
- package/lib/orchestrator-fallback.ts +75 -0
- package/lib/pasted-image-paths.ts +113 -0
- package/lib/questionnaire/questionnaire-view.ts +121 -7
- package/lib/review-candidate-view-owner.ts +4 -0
- package/lib/review-candidate-view.ts +10 -7
- package/lib/review-host-relay.ts +5 -1
- package/lib/review-integration-v2.ts +22 -7
- package/lib/review-repository.ts +5 -0
- package/lib/session-profile-append-controller.ts +21 -6
- package/lib/session-profile-authority.ts +119 -0
- package/lib/session-profile-binding.ts +54 -5
- package/lib/session-profile-freeze.ts +105 -9
- package/lib/session-profile-integration.ts +313 -0
- package/lib/session-profile-persistence.ts +63 -9
- package/lib/shell-bar.ts +171 -56
- package/lib/shell-card.ts +26 -6
- package/lib/shell-page.ts +120 -0
- package/lib/shell-panel.ts +149 -0
- package/lib/shell-prompt.ts +53 -1
- package/lib/shell-sidebar-layout.ts +98 -25
- package/lib/shell-sidebar.ts +54 -1
- package/lib/shell-stats.ts +123 -0
- package/lib/shell-todo.ts +71 -0
- package/lib/shell-usage.ts +12 -2
- package/lib/star-prompt.ts +197 -0
- package/lib/verifier-admission.ts +18 -8
- package/lib/verifier-settle-reminder.ts +64 -0
- package/lib/vim-editor-adapter.ts +6 -1
- package/lib/visual-customization-policy.ts +41 -6
- package/lib/visual-customize-view.ts +164 -26
- package/lib/visual-layout-preview.ts +43 -0
- package/lib/yolo-session-policy.ts +28 -1
- package/package.json +1 -1
- package/runtime/gentle-shell-launcher.mjs +4 -0
- package/runtime/native-review-cli.mjs +7 -2
- package/runtime/review-integration-v2.mjs +22 -7
- package/runtime/windows-session-transport.ps1 +60 -3
- package/scripts/bootstrap.sh +4 -1
- package/scripts/installer-preflight.mjs +1 -1
- package/scripts/pi-update.mjs +113 -3
- package/scripts/run-test-suite.mjs +17 -1
- package/scripts/shell-snapshot.mjs +340 -0
- package/scripts/test-packed-runner.mjs +1 -1
- package/scripts/update-agent-body-history.mjs +41 -0
- package/scripts/verify-installer-tap.mjs +45 -0
- package/scripts/verify-package-files.mjs +2 -0
- package/skills/gentle-ai/SKILL.md +2 -2
- package/skills/tui-design/NOTICE.md +5 -0
- package/skills/tui-design/SKILL.md +56 -0
- package/skills/tui-design/references/commands.md +75 -0
- package/skills/tui-design/references/critique.md +48 -0
- package/skills/tui-design/references/design-doc.md +44 -0
- package/skills/tui-design/references/terminal-craft.md +64 -0
- package/skills/tui-design/references/visual-loop.md +32 -0
- package/tests/agents-protocol.test.ts +53 -1
- package/tests/agents-runner.test.ts +168 -3
- package/tests/agents-view.test.ts +27 -0
- package/tests/agents-widget.test.ts +312 -10
- package/tests/bounded-scan-contract.test.ts +39 -0
- package/tests/bridge-cost.test.ts +32 -0
- package/tests/bundled-install.test.ts +6 -4
- package/tests/ci-concurrency.test.ts +11 -0
- package/tests/ci-merge-base-identity.test.ts +114 -0
- package/tests/codegraph-tools.test.ts +69 -0
- package/tests/codemode-rendering.test.ts +22 -2
- package/tests/command-palette.test.ts +16 -2
- package/tests/commit-slice-signal.test.ts +11 -9
- package/tests/delegate-for-reason-contract.test.ts +5 -4
- package/tests/design-canvas-server.test.ts +6 -2
- package/tests/exploration-budget.test.ts +128 -0
- package/tests/fixtures/agent-assets/gentle-ai-worker.strict-tdd-era.md +122 -0
- package/tests/fixtures/measure-orchestrator-prompt.mjs +2 -1
- package/tests/fixtures/primary-session-prompt/gentleman.golden.md +18 -10
- package/tests/fixtures/session-profile-v1/replay.ts +125 -0
- package/tests/fixtures/session-profile-v1/session-profile-authority.ts +113 -0
- package/tests/fixtures/session-profile-v1/session-profile-binding.ts +83 -0
- package/tests/fixtures/session-profile-v1/session-profile-disk-reader.ts +182 -0
- package/tests/fixtures/session-profile-v1/session-profile-freeze.ts +290 -0
- package/tests/fixtures/session-profile-v1/session-profile-persistence.ts +195 -0
- package/tests/fixtures/session-profile-v1/v1-inputs.ts +16 -0
- package/tests/fixtures/windows-pipe-availability.ps1 +26 -0
- package/tests/fixtures/windows-session-bootstrap.ps1 +6 -2
- package/tests/gentle-agents.test.ts +416 -21
- package/tests/gentle-ai-exploration-budget.test.ts +135 -0
- package/tests/gentle-ai.test.ts +1011 -37
- package/tests/gentle-fast.test.ts +73 -0
- package/tests/gentle-guide.test.ts +208 -0
- package/tests/gentle-herdr-activity.test.ts +76 -2
- package/tests/gentle-herdr-agent.test.ts +111 -0
- package/tests/gentle-music.test.ts +36 -1
- package/tests/gentle-program-identity.test.ts +197 -0
- package/tests/gentle-shell-bin.test.ts +49 -26
- package/tests/gentle-shell-launcher.test.ts +18 -2
- package/tests/gentle-shell.test.ts +1068 -37
- package/tests/gentle-stats.test.ts +15 -2
- package/tests/gentle-todo.test.ts +50 -4
- package/tests/herdr-task-summary-policy.test.ts +128 -0
- package/tests/history-store-private-mode.test.ts +40 -0
- package/tests/image-paste-chips.test.ts +42 -0
- package/tests/inprocess-reviewer.test.ts +122 -0
- package/tests/installer-posix-bootstrap.test.ts +67 -5
- package/tests/installer-server.test.ts +2 -2
- package/tests/installer-windows-diagnostics.test.ts +4 -5
- package/tests/isolated-config-home.ts +28 -0
- package/tests/jobs-widget.test.ts +25 -37
- package/tests/keymaps-customize.test.ts +114 -0
- package/tests/keymaps.test.ts +103 -0
- package/tests/maintainer/mcp-status.maintest.ts +88 -0
- package/tests/maintainer/pi-update-source.maintest.ts +116 -0
- package/tests/model-fallback-notice.test.ts +45 -0
- package/tests/model-fallback-policy.test.ts +83 -0
- package/tests/model-fallback-store.test.ts +111 -0
- package/tests/nan-provider.test.ts +4 -4
- package/tests/no-self-pause-contract.test.ts +19 -0
- package/tests/notification-customize.test.ts +58 -34
- package/tests/odd-routing-canonical-ratchet.test.ts +3 -3
- package/tests/odd-routing-contract.test.ts +1 -1
- package/tests/orchestrator-fallback.test.ts +82 -0
- package/tests/orchestrator-prompt-budget.test.ts +131 -0
- package/tests/package-manifest.test.ts +160 -7
- package/tests/pasted-image-paths.test.ts +118 -0
- package/tests/persona-reply-language.test.ts +61 -0
- package/tests/pi-update-launcher.test.ts +32 -8
- package/tests/pi-update-source.test.ts +162 -0
- package/tests/profile-fast-tier.test.ts +311 -0
- package/tests/profile-tier-footer.test.ts +79 -0
- package/tests/questionnaire-view.test.ts +150 -0
- package/tests/review-candidate-owner-sweep.test.ts +93 -0
- package/tests/review-candidate-view.test.ts +51 -0
- package/tests/review-controller-native-routing.test.ts +120 -6
- package/tests/review-gate.test.ts +24 -0
- package/tests/review-inspect-preflight.test.ts +197 -0
- package/tests/review-integration-v2-forward.test.ts +59 -0
- package/tests/review-repository.test.ts +52 -1
- package/tests/review-sidebar-state.test.ts +5 -5
- package/tests/run-test-suite.test.ts +61 -5
- package/tests/sensitive-path-tools.test.ts +74 -0
- package/tests/session-profile-append-controller.test.ts +63 -0
- package/tests/session-profile-authority.test.ts +259 -0
- package/tests/session-profile-binding.test.ts +15 -0
- package/tests/session-profile-extension.test.ts +615 -0
- package/tests/session-profile-freeze.test.ts +110 -2
- package/tests/session-profile-integration.test.ts +857 -0
- package/tests/session-profile-persistence.test.ts +57 -0
- package/tests/session-profile-v1-compat.test.ts +221 -0
- package/tests/shell-bar.test.ts +113 -55
- package/tests/shell-card.test.ts +13 -1
- package/tests/shell-page.test.ts +108 -0
- package/tests/shell-panel.test.ts +332 -0
- package/tests/shell-prompt.test.ts +54 -0
- package/tests/shell-render-cache.test.ts +5 -0
- package/tests/shell-sidebar-fullscreen.test.ts +12 -0
- package/tests/shell-sidebar-layout.test.ts +159 -27
- package/tests/shell-stats.test.ts +90 -0
- package/tests/shell-usage.test.ts +14 -0
- package/tests/skill-registry.test.ts +68 -1
- package/tests/star-prompt.test.ts +470 -0
- package/tests/startup-banner.test.ts +57 -1
- package/tests/task-size-routing-contract.test.ts +45 -1
- package/tests/verifier-settle-reminder.test.ts +281 -0
- package/tests/verify-first-launch-contract.test.ts +56 -5
- package/tests/verify-installer-tap.test.ts +57 -0
- package/tests/vim-editor-adapter.test.ts +2 -2
- package/tests/visual-customization-policy.test.ts +61 -7
- package/tests/visual-customize-view.test.ts +253 -8
- package/tests/visual-layout-preview.test.ts +28 -0
- package/tests/windows-session-bootstrap.test.ts +105 -2
- package/tests/work-continuity-contract.test.ts +86 -0
- package/tests/writer-surfaces.test.ts +12 -10
- package/tests/yolo-customize.test.ts +30 -11
- package/tests/yolo-mode-runtime.test.ts +4 -2
- package/tests/yolo-mode.test.ts +16 -2
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
-
import test
|
|
2
|
+
import test from "node:test";
|
|
3
3
|
import { visibleWidth } from "@earendil-works/pi-tui";
|
|
4
|
-
import { JOBS_GLYPH,
|
|
5
|
-
import { CARD_STYLE, cardStyle, setCardStyle } from "../lib/shell-card.ts";
|
|
4
|
+
import { JOBS_GLYPH, renderJobsSection, widgetJobs } from "../lib/jobs-widget.ts";
|
|
6
5
|
import { stripAnsi } from "../lib/terminal-theme.ts";
|
|
7
6
|
|
|
8
|
-
// The Jobs
|
|
9
|
-
//
|
|
10
|
-
//
|
|
7
|
+
// The Jobs rail section (a panel section, see lib/shell-panel.ts). Rendering is
|
|
8
|
+
// pure, so it verifies without a TUI: newest job first, one row per job with
|
|
9
|
+
// its elapsed time, collapsible like Agents and Todos.
|
|
11
10
|
|
|
12
11
|
// Width math counts every painted character, so these assertions use a plain
|
|
13
12
|
// theme; colored roles are covered by the widget's paint calls, not here.
|
|
@@ -25,46 +24,35 @@ const jobs = [
|
|
|
25
24
|
{ id: "job-1", label: "Build runtime", startedAt: 10_000 },
|
|
26
25
|
];
|
|
27
26
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const initialCardStyle = cardStyle();
|
|
31
|
-
before(() => setCardStyle(CARD_STYLE.NEON));
|
|
32
|
-
after(() => setCardStyle(initialCardStyle));
|
|
33
|
-
|
|
34
|
-
test("the jobs card lists running jobs newest first with elapsed time", () => {
|
|
35
|
-
const lines = renderJobsCard(jobs, plainTheme, 50, 100_000, { collapsed: false, collapseControl: true });
|
|
27
|
+
test("the jobs section lists running jobs newest first with elapsed time", () => {
|
|
28
|
+
const lines = renderJobsSection(jobs, plainTheme, 50, 100_000, { collapsed: false });
|
|
36
29
|
const text = lines.join("\n");
|
|
37
|
-
assert.match(
|
|
38
|
-
assert.match(text,
|
|
30
|
+
assert.match(lines[0]!, /^▾ JOBS +2 running$/);
|
|
31
|
+
assert.match(text, new RegExp(`${JOBS_GLYPH} job-2 Watcher CI ronda 2`));
|
|
39
32
|
const watcher = text.indexOf("Watcher CI ronda 2");
|
|
40
33
|
const build = text.indexOf("Build runtime");
|
|
41
34
|
assert.ok(watcher >= 0, "the newest job paints");
|
|
42
35
|
assert.ok(build > watcher, "newest first, matching the /gentle:jobs running group");
|
|
43
36
|
assert.match(text, /1m 0s/, "the 60s job shows its elapsed time");
|
|
44
37
|
assert.match(text, /1m 30s/, "the 90s job shows its elapsed time");
|
|
45
|
-
assert.
|
|
46
|
-
for (const line of lines) assert.ok(visibleWidth(stripAnsi(line)) <= 50, `row fits: ${stripAnsi(line)}`);
|
|
38
|
+
for (const line of lines) assert.equal(visibleWidth(stripAnsi(line)), 50, `row fills the section: ${stripAnsi(line)}`);
|
|
47
39
|
});
|
|
48
40
|
|
|
49
41
|
test("an empty job list paints nothing", () => {
|
|
50
|
-
assert.deepEqual(
|
|
42
|
+
assert.deepEqual(renderJobsSection([], plainTheme, 50, 100_000, { collapsed: false }), []);
|
|
51
43
|
});
|
|
52
44
|
|
|
53
|
-
test("a collapsed jobs
|
|
54
|
-
|
|
55
|
-
const lines = renderJobsCard(jobs, plainTheme, 64, 100_000, { collapsed: true, collapseKey: "ctrl+shift+j", collapseControl: true });
|
|
45
|
+
test("a collapsed jobs section keeps the newest job and folds the rest", () => {
|
|
46
|
+
const lines = renderJobsSection(jobs, plainTheme, 64, 100_000, { collapsed: true });
|
|
56
47
|
const text = lines.join("\n");
|
|
48
|
+
assert.match(lines[0]!, /^▸ JOBS/);
|
|
57
49
|
assert.match(text, /Watcher CI ronda 2/);
|
|
58
50
|
assert.doesNotMatch(text, /Build runtime/);
|
|
59
51
|
assert.match(text, /… 1 more/);
|
|
60
|
-
assert.match(text, /ctrl\+shift\+j expand/);
|
|
61
|
-
assert.match(text, /▸ Expand/);
|
|
62
52
|
});
|
|
63
53
|
|
|
64
|
-
test("the
|
|
54
|
+
test("the sort never mutates the snapshot", () => {
|
|
65
55
|
const snapshot = [{ id: "job-1", label: "Build runtime", startedAt: 10_000 }];
|
|
66
|
-
const lines = renderJobsCard(snapshot, plainTheme, 50, 100_000, { collapsed: false });
|
|
67
|
-
assert.doesNotMatch(lines.join("\n"), /Collapse|Expand/);
|
|
68
56
|
const sorted = widgetJobs(snapshot, 100_000);
|
|
69
57
|
assert.deepEqual(snapshot, [{ id: "job-1", label: "Build runtime", startedAt: 10_000 }]);
|
|
70
58
|
assert.equal(sorted[0]?.id, "job-1");
|
|
@@ -80,36 +68,36 @@ function finishedJobs(): Array<typeof exitedJob> {
|
|
|
80
68
|
}
|
|
81
69
|
|
|
82
70
|
test("a finished job lingers with a ✓ row and its elapsed frozen at the end", () => {
|
|
83
|
-
const lines =
|
|
71
|
+
const lines = renderJobsSection([exitedJob], plainTheme, 50, 100_000, { collapsed: false });
|
|
84
72
|
const text = lines.join("\n");
|
|
85
|
-
assert.match(text,
|
|
73
|
+
assert.match(text, /✓ job-1 Build runtime/);
|
|
86
74
|
assert.match(text, /1m 0s/, "elapsed freezes at endedAt instead of ticking to 1m 30s");
|
|
87
75
|
assert.match(text, /1 finished/);
|
|
88
76
|
for (const line of lines) assert.ok(visibleWidth(stripAnsi(line)) <= 50, `row fits: ${stripAnsi(line)}`);
|
|
89
77
|
});
|
|
90
78
|
|
|
91
79
|
test("a nonzero exit paints ✗ and a stopped job paints –", () => {
|
|
92
|
-
const lines =
|
|
80
|
+
const lines = renderJobsSection([
|
|
93
81
|
{ ...exitedJob, exitCode: 1 },
|
|
94
82
|
{ id: "job-2", label: "Watcher CI", startedAt: 5_000, status: "stopped", endedAt: 60_000 },
|
|
95
83
|
], plainTheme, 50, 100_000, { collapsed: false });
|
|
96
84
|
const text = lines.join("\n");
|
|
97
|
-
assert.match(text,
|
|
98
|
-
assert.match(text,
|
|
85
|
+
assert.match(text, /✗ job-1 Build runtime/);
|
|
86
|
+
assert.match(text, /– job-2 Watcher CI/);
|
|
99
87
|
assert.match(text, /2 finished/);
|
|
100
88
|
});
|
|
101
89
|
|
|
102
90
|
test("a failed job rides the tail with the ✗ glyph", () => {
|
|
103
|
-
const lines =
|
|
91
|
+
const lines = renderJobsSection([{ ...exitedJob, status: "failed" as const }], plainTheme, 50, 100_000, { collapsed: false });
|
|
104
92
|
const text = lines.join("\n");
|
|
105
|
-
assert.match(text,
|
|
93
|
+
assert.match(text, /✗ job-1 Build runtime/);
|
|
106
94
|
assert.match(text, /1m 0s/, "elapsed freezes at endedAt like the other outcomes");
|
|
107
95
|
assert.match(text, /1 finished/);
|
|
108
96
|
});
|
|
109
97
|
|
|
110
98
|
test("finished jobs past the TTL paint nothing", () => {
|
|
111
99
|
// now - endedAt lands exactly on the TTL: not fresh anymore.
|
|
112
|
-
assert.deepEqual(
|
|
100
|
+
assert.deepEqual(renderJobsSection([{ ...exitedJob, endedAt: 40_000 }], plainTheme, 50, 100_000, { collapsed: false }), []);
|
|
113
101
|
});
|
|
114
102
|
|
|
115
103
|
test("at most the three newest finished jobs survive", () => {
|
|
@@ -129,8 +117,8 @@ test("running entries sort before the finished tail and never expire", () => {
|
|
|
129
117
|
assert.deepEqual(shown.map((job) => job.id), ["new", "old", "done"]);
|
|
130
118
|
});
|
|
131
119
|
|
|
132
|
-
test("the
|
|
133
|
-
const lines =
|
|
120
|
+
test("the header count mixes running and finished jobs", () => {
|
|
121
|
+
const lines = renderJobsSection([
|
|
134
122
|
{ id: "job-1", label: "New run", startedAt: 50_000 },
|
|
135
123
|
{ id: "job-2", label: "Watcher CI", startedAt: 5_000, status: "stopped", endedAt: 60_000 },
|
|
136
124
|
], plainTheme, 50, 100_000, { collapsed: false });
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test, { after } from "node:test";
|
|
3
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { buildKeymapRows, type KeymapRowsOptions } from "../lib/keymaps-customize.ts";
|
|
7
|
+
import type { CustomizeInline, CustomizeRow } from "../lib/visual-customize-view.ts";
|
|
8
|
+
import type { PiKeybindings } from "../lib/keymaps.ts";
|
|
9
|
+
|
|
10
|
+
// The Keymaps category of /gentle:customize: one row per action and palette
|
|
11
|
+
// command; Enter captures the next key, ⌫ disables, r restores the default.
|
|
12
|
+
|
|
13
|
+
const homes: string[] = [];
|
|
14
|
+
after(() => { for (const home of homes) rmSync(home, { recursive: true, force: true }); });
|
|
15
|
+
|
|
16
|
+
const PI_KEYS: PiKeybindings = {
|
|
17
|
+
getKeys: (binding) => binding === "tui.editor.deleteToLineEnd" ? ["ctrl+k"] : [],
|
|
18
|
+
getResolvedBindings: () => ({ "tui.editor.deleteToLineEnd": "ctrl+k" }),
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function setup(env: NodeJS.ProcessEnv = {}) {
|
|
22
|
+
const configHome = mkdtempSync(join(tmpdir(), "gentle-keymaps-customize-"));
|
|
23
|
+
homes.push(configHome);
|
|
24
|
+
const notices: Array<{ message: string; type: string }> = [];
|
|
25
|
+
let reloads = 0;
|
|
26
|
+
const options: KeymapRowsOptions = {
|
|
27
|
+
env, configHome, keybindings: () => PI_KEYS,
|
|
28
|
+
commands: [{ command: "gentle:changes", label: "Browse changes" }, { command: "gentle:design", label: "Design · HTML artboards" }],
|
|
29
|
+
notify: (message, type) => notices.push({ message, type }),
|
|
30
|
+
reload: () => { reloads += 1; },
|
|
31
|
+
};
|
|
32
|
+
const rows = buildKeymapRows(options);
|
|
33
|
+
const row = (prefix: string) => rows.find((candidate) => label(candidate).startsWith(prefix))!;
|
|
34
|
+
const saved = () => existsSync(join(configHome, "keymaps.json")) ? JSON.parse(readFileSync(join(configHome, "keymaps.json"), "utf8")).bindings : undefined;
|
|
35
|
+
return { rows, row, notices, saved, configHome, reloads: () => reloads };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function label(row: CustomizeRow): string {
|
|
39
|
+
return typeof row.label === "function" ? row.label() : row.label;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** An inline bridge whose capture answers with `key` and whose confirm answers `yes`. */
|
|
43
|
+
function inline(key: string | undefined, yes = true, asked: string[] = []): CustomizeInline {
|
|
44
|
+
return { capture: async () => key, confirm: async (message) => { asked.push(message); return yes; }, input: async () => undefined, disposed: false };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
test("every action and palette command has a Keymaps row with its current key, plus a reload row", () => {
|
|
48
|
+
const { rows } = setup({ GENTLE_PI_AGENTS_VIEW_KEY: "alt+w" });
|
|
49
|
+
assert.ok(rows.every((row) => row.category === "Keymaps"));
|
|
50
|
+
assert.deepEqual(rows.map(label), [
|
|
51
|
+
"Command palette: alt+k", "Browse changes: alt+g", "Subscription usage: alt+u", "Cycle visual preset: alt+l",
|
|
52
|
+
"Subagents overlay: alt+w (GENTLE_PI_AGENTS_VIEW_KEY)", "Stop active subagents: alt+s", "Collapse the agents card: ctrl+shift+a",
|
|
53
|
+
"Collapse the jobs card: ctrl+shift+j", "Collapse the todo list: ctrl+shift+t", "Usage stats: none",
|
|
54
|
+
"/gentle:design · Design · HTML artboards: none", "Reload now to apply keymap changes",
|
|
55
|
+
]);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("Enter captures a key, saves it, and tells the user to reload", async () => {
|
|
59
|
+
const { row, notices, saved } = setup();
|
|
60
|
+
await row("Command palette").action(inline("\x1bj"));
|
|
61
|
+
assert.deepEqual(saved(), { commands: "alt+j" });
|
|
62
|
+
assert.equal(label(row("Command palette")), "Command palette: alt+j");
|
|
63
|
+
assert.deepEqual(notices.at(-1), { message: "Command palette: alt+j. Run /reload to apply it.", type: "info" });
|
|
64
|
+
await row("/gentle:design").action(inline("\x1bd"));
|
|
65
|
+
assert.deepEqual(saved(), { commands: "alt+j", "command:gentle:design": "alt+d" });
|
|
66
|
+
await row("Usage stats").action(inline(undefined));
|
|
67
|
+
assert.deepEqual(saved(), { commands: "alt+j", "command:gentle:design": "alt+d" }, "a cancelled capture saves nothing");
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("a reserved key, a typing key or an environment-controlled action is refused and saves nothing", async () => {
|
|
71
|
+
const { row, notices, saved } = setup({ GENTLE_PI_AGENTS_VIEW_KEY: "alt+w" });
|
|
72
|
+
await row("Command palette").action(inline("\x0b"));
|
|
73
|
+
assert.deepEqual(notices.at(-1), { message: "ctrl+k is reserved by Pi (tui.editor.deleteToLineEnd); choose another key.", type: "warning" });
|
|
74
|
+
await row("Command palette").action(inline("a"));
|
|
75
|
+
assert.match(notices.at(-1)!.message, /a is needed for typing/);
|
|
76
|
+
await row("Subagents overlay").action(inline("\x1bv"));
|
|
77
|
+
assert.deepEqual(notices.at(-1), { message: "Subagents overlay is set by GENTLE_PI_AGENTS_VIEW_KEY; unset it to change the key here.", type: "warning" });
|
|
78
|
+
assert.equal(saved(), undefined);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test("a key used by another action moves only after confirmation", async () => {
|
|
82
|
+
const { row, saved } = setup();
|
|
83
|
+
const asked: string[] = [];
|
|
84
|
+
await row("Command palette").action(inline("\x1bg", false, asked));
|
|
85
|
+
assert.deepEqual(asked, ["alt+g is used by Browse changes. Move it to Command palette?"]);
|
|
86
|
+
assert.equal(saved(), undefined);
|
|
87
|
+
await row("Command palette").action(inline("\x1bg", true));
|
|
88
|
+
assert.deepEqual(saved(), { commands: "alt+g", changes: null });
|
|
89
|
+
assert.equal(label(row("Browse changes")), "Browse changes: none");
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
test("⌫ disables a key, r restores the default, and the reload row reloads", async () => {
|
|
93
|
+
const { row, saved, notices, reloads } = setup();
|
|
94
|
+
const bridge = inline(undefined);
|
|
95
|
+
assert.equal(row("Browse changes").key!("\x7f", bridge), true);
|
|
96
|
+
assert.deepEqual(saved(), { changes: null });
|
|
97
|
+
assert.deepEqual(notices.at(-1), { message: "Browse changes: none. Run /reload to apply it.", type: "info" });
|
|
98
|
+
assert.equal(row("Browse changes").key!("r", bridge), true);
|
|
99
|
+
assert.deepEqual(saved(), {});
|
|
100
|
+
assert.equal(label(row("Browse changes")), "Browse changes: alt+g");
|
|
101
|
+
assert.equal(row("Browse changes").key!("x", bridge), false, "other keys stay with the card");
|
|
102
|
+
await row("Reload now").action(bridge);
|
|
103
|
+
assert.equal(reloads(), 1);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test("a malformed keymaps.json is never overwritten", async () => {
|
|
107
|
+
const { row, notices, configHome } = setup();
|
|
108
|
+
writeFileSync(join(configHome, "keymaps.json"), "{");
|
|
109
|
+
await row("Command palette").action(inline("\x1bj"));
|
|
110
|
+
assert.equal(readFileSync(join(configHome, "keymaps.json"), "utf8"), "{");
|
|
111
|
+
assert.deepEqual(notices.at(-1), { message: `Keymaps: ${join(configHome, "keymaps.json")} is unreadable or malformed; fix or delete it to change keys.`, type: "error" });
|
|
112
|
+
assert.equal(row("Browse changes").key!("\x7f", inline(undefined)), true);
|
|
113
|
+
assert.equal(readFileSync(join(configHome, "keymaps.json"), "utf8"), "{");
|
|
114
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
assignKeymap, checkKeymap, commandKeymapId, commandKeymapIds, effectiveKey, keyFromInput, KEYMAP_ACTIONS,
|
|
8
|
+
keymapCommand, keymapSource, normalizeKeyId, readKeymaps, resetKeymap, writeKeymaps, type PiKeybindings,
|
|
9
|
+
} from "../lib/keymaps.ts";
|
|
10
|
+
|
|
11
|
+
// The keymap registry every Gentle shortcut reads: environment variable
|
|
12
|
+
// first (unchanged behavior), then the saved keymaps.json, then the default.
|
|
13
|
+
|
|
14
|
+
const DEFAULTS: Record<string, string | undefined> = {
|
|
15
|
+
commands: "alt+k", changes: "alt+g", usage: "alt+u", preset: "alt+l", "agents.view": "alt+a",
|
|
16
|
+
"agents.stop": "alt+s", "agents.collapse": "ctrl+shift+a", "jobs.collapse": "ctrl+shift+j", "todo.collapse": "ctrl+shift+t", "stats.view": undefined,
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
function scratch(): string {
|
|
20
|
+
return mkdtempSync(join(tmpdir(), "gentle-keymaps-"));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Pi's default bindings for the few ids the checks look at. */
|
|
24
|
+
const PI_KEYS: PiKeybindings = {
|
|
25
|
+
getKeys: (binding) => ({ "tui.editor.deleteToLineEnd": ["ctrl+k"], "app.clear": ["ctrl+c"], "app.model.cycleBackward": ["shift+ctrl+p"] } as Record<string, string[]>)[binding] ?? [],
|
|
26
|
+
getResolvedBindings: () => ({ "tui.editor.deleteToLineEnd": "ctrl+k", "app.clear": "ctrl+c", "tui.editor.cursorWordLeft": ["alt+left", "ctrl+left"] }),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
test("with no file and no environment every action keeps its default key", () => {
|
|
30
|
+
for (const action of KEYMAP_ACTIONS) assert.equal(effectiveKey(action.id, {}, {}), DEFAULTS[action.id], action.id);
|
|
31
|
+
assert.deepEqual(KEYMAP_ACTIONS.map((action) => action.id).sort(), Object.keys(DEFAULTS).sort());
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
test("a saved key replaces the default, null disables it, and the environment still wins", () => {
|
|
35
|
+
const bindings = { commands: "alt+j", changes: null };
|
|
36
|
+
assert.equal(effectiveKey("commands", {}, bindings), "alt+j");
|
|
37
|
+
assert.equal(keymapSource("commands", {}, bindings), "saved");
|
|
38
|
+
assert.equal(effectiveKey("changes", {}, bindings), undefined);
|
|
39
|
+
assert.equal(effectiveKey("commands", { GENTLE_PI_COMMANDS_KEY: "alt+x" }, bindings), "alt+x");
|
|
40
|
+
assert.equal(keymapSource("commands", { GENTLE_PI_COMMANDS_KEY: "alt+x" }, bindings), "env");
|
|
41
|
+
assert.equal(effectiveKey("commands", { GENTLE_PI_COMMANDS_KEY: "off" }, bindings), undefined);
|
|
42
|
+
assert.equal(effectiveKey("commands", { GENTLE_PI_COMMANDS_KEY: "" }, bindings), undefined);
|
|
43
|
+
assert.equal(keymapSource("usage", {}, bindings), "default");
|
|
44
|
+
assert.equal(keymapSource("stats.view", {}, bindings), "none");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("any palette command gets a command keymap id, built-in commands reuse their action", () => {
|
|
48
|
+
assert.equal(commandKeymapId("gentle:changes"), "changes");
|
|
49
|
+
assert.equal(commandKeymapId("gentle:design"), "command:gentle:design");
|
|
50
|
+
assert.equal(keymapCommand("command:gentle:design"), "gentle:design");
|
|
51
|
+
assert.equal(keymapCommand("changes"), undefined);
|
|
52
|
+
const bindings = { "command:gentle:design": "alt+d", "command:gentle:vim": null };
|
|
53
|
+
assert.equal(effectiveKey("command:gentle:design", {}, bindings), "alt+d");
|
|
54
|
+
assert.deepEqual(commandKeymapIds(bindings), ["command:gentle:design"]);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
test("key ids are normalized and only modified keys or function keys can be assigned", () => {
|
|
58
|
+
assert.equal(normalizeKeyId("Shift+Ctrl+A"), "ctrl+shift+a");
|
|
59
|
+
assert.equal(normalizeKeyId("hyper+a"), undefined);
|
|
60
|
+
assert.deepEqual(keyFromInput("\x1bj"), { key: "alt+j" });
|
|
61
|
+
assert.deepEqual(keyFromInput("\x1b[97;6u"), { key: "ctrl+shift+a" });
|
|
62
|
+
assert.deepEqual(keyFromInput("\x1bOP"), { key: "f1" });
|
|
63
|
+
assert.match((keyFromInput("a") as { error: string }).error, /needed for typing/);
|
|
64
|
+
assert.match((keyFromInput("\r") as { error: string }).error, /needed for typing/);
|
|
65
|
+
assert.match((keyFromInput("\x1bK") as { error: string }).error, /not recognized/);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test("checks block Pi's reserved keys and environment-controlled actions, and confirm a moved key", () => {
|
|
69
|
+
assert.deepEqual(checkKeymap("commands", "ctrl+k", {}, {}, PI_KEYS), { kind: "blocked", message: "ctrl+k is reserved by Pi (tui.editor.deleteToLineEnd); choose another key." });
|
|
70
|
+
assert.equal(checkKeymap("commands", "ctrl+shift+p", {}, {}, PI_KEYS).kind, "blocked");
|
|
71
|
+
assert.deepEqual(checkKeymap("commands", "alt+j", { GENTLE_PI_COMMANDS_KEY: "alt+k" }, {}, PI_KEYS), { kind: "blocked", message: "Command palette is set by GENTLE_PI_COMMANDS_KEY; unset it to change the key here." });
|
|
72
|
+
assert.deepEqual(checkKeymap("commands", "alt+g", {}, {}, PI_KEYS), { kind: "confirm", message: "alt+g is used by Browse changes. Move it to Command palette?", displaces: "changes" });
|
|
73
|
+
assert.equal(checkKeymap("command:gentle:design", "alt+d", {}, { "command:gentle:vim": "alt+d" }, PI_KEYS).kind, "confirm");
|
|
74
|
+
assert.deepEqual(checkKeymap("commands", "alt+left", {}, {}, PI_KEYS), { kind: "confirm", message: "alt+left is Pi's tui.editor.cursorWordLeft. Use it for Command palette instead?" });
|
|
75
|
+
assert.deepEqual(checkKeymap("commands", "alt+j", {}, {}, PI_KEYS), { kind: "ok" });
|
|
76
|
+
assert.deepEqual(checkKeymap("commands", "alt+k", {}, {}, PI_KEYS), { kind: "ok" }, "its own key is not a conflict");
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
test("assigning moves a key off the displaced action, and reset restores the default", () => {
|
|
80
|
+
const moved = assignKeymap({}, "commands", "alt+g", "changes");
|
|
81
|
+
assert.deepEqual(moved, { commands: "alt+g", changes: null });
|
|
82
|
+
assert.deepEqual(assignKeymap({}, "commands", "Shift+Ctrl+X"), { commands: "ctrl+shift+x" });
|
|
83
|
+
assert.deepEqual(resetKeymap(moved, "changes"), { commands: "alt+g" });
|
|
84
|
+
assert.equal(effectiveKey("changes", {}, resetKeymap(moved, "changes")), "alt+g");
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("keymaps.json round-trips atomically and a malformed file is reported, not used", () => {
|
|
88
|
+
const home = scratch();
|
|
89
|
+
try {
|
|
90
|
+
assert.deepEqual(readKeymaps(home), { bindings: {}, path: join(home, "keymaps.json"), malformed: false });
|
|
91
|
+
const path = writeKeymaps(home, { commands: "alt+j", changes: null });
|
|
92
|
+
assert.deepEqual(JSON.parse(readFileSync(path, "utf8")), { schema: 1, bindings: { commands: "alt+j", changes: null } });
|
|
93
|
+
assert.deepEqual(readKeymaps(home).bindings, { commands: "alt+j", changes: null });
|
|
94
|
+
assert.deepEqual(readdirSync(home), ["keymaps.json"], "no temporary file is left behind");
|
|
95
|
+
for (const bad of ["{", "[]", '{"schema":2,"bindings":{}}', '{"schema":1,"bindings":{"commands":3}}', '{"schema":1,"bindings":{"commands":"hyper+a"}}']) {
|
|
96
|
+
writeFileSync(path, bad);
|
|
97
|
+
assert.deepEqual(readKeymaps(home), { bindings: {}, path, malformed: true }, bad);
|
|
98
|
+
assert.equal(readFileSync(path, "utf8"), bad, "reading never rewrites the file");
|
|
99
|
+
}
|
|
100
|
+
} finally {
|
|
101
|
+
rmSync(home, { recursive: true, force: true });
|
|
102
|
+
}
|
|
103
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { buildPiInvocation } from "../../lib/gentle-shell-launcher.ts";
|
|
9
|
+
|
|
10
|
+
const piRoot = process.env.GENTLE_MCP_STATUS_PI_ROOT;
|
|
11
|
+
const packageRoot = fileURLToPath(new URL("../..", import.meta.url));
|
|
12
|
+
|
|
13
|
+
test("Shell child invocation receives native sanitized MCP snapshots and events", {
|
|
14
|
+
skip: !piRoot && "Set GENTLE_MCP_STATUS_PI_ROOT to a built Pi coding-agent package with the status API",
|
|
15
|
+
}, () => {
|
|
16
|
+
if (!piRoot) throw new Error("Pi status runtime was not selected");
|
|
17
|
+
const root = mkdtempSync(join(tmpdir(), "shell-mcp-status-"));
|
|
18
|
+
try {
|
|
19
|
+
const home = join(root, "agent");
|
|
20
|
+
const userHome = join(root, "home");
|
|
21
|
+
const temporary = join(root, "tmp");
|
|
22
|
+
for (const path of [home, userHome, temporary]) mkdirSync(path);
|
|
23
|
+
writeFileSync(join(home, "mcp.json"), JSON.stringify({ mcpServers: {
|
|
24
|
+
"dev-docs": { command: "never-start", enabled: false, env: { FIXTURE: "fixture-not-public" } },
|
|
25
|
+
} }));
|
|
26
|
+
const extension = join(root, "probe.mjs");
|
|
27
|
+
writeFileSync(extension, `
|
|
28
|
+
export default function (pi) {
|
|
29
|
+
const initial = pi.getMcpStatus();
|
|
30
|
+
const events = [];
|
|
31
|
+
const subscription = pi.onMcpStatusChanged((all) => events.push(all));
|
|
32
|
+
pi.registerProvider("mcp-status-fixture", {
|
|
33
|
+
api: "openai-completions", apiKey: "fixture", baseUrl: "http://unused.invalid",
|
|
34
|
+
models: [{
|
|
35
|
+
id: "fixture", name: "Fixture", reasoning: false, input: ["text"],
|
|
36
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 1024, maxTokens: 16,
|
|
37
|
+
}],
|
|
38
|
+
streamSimple() { throw new Error("A status probe must not call a model"); },
|
|
39
|
+
});
|
|
40
|
+
pi.registerCommand("mcp-status-probe", {
|
|
41
|
+
description: "Report native status for an isolated integration probe",
|
|
42
|
+
async handler() {
|
|
43
|
+
subscription.dispose();
|
|
44
|
+
subscription.dispose();
|
|
45
|
+
process.stdout.write(JSON.stringify({ initial, snapshot: pi.getMcpStatus(), events }) + "\\n");
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
pi.on("session_shutdown", () => subscription.dispose());
|
|
49
|
+
}
|
|
50
|
+
`);
|
|
51
|
+
const invocation = buildPiInvocation({
|
|
52
|
+
runtime: { kind: "path", command: process.execPath, args: [resolve(piRoot, "dist/cli.js")] },
|
|
53
|
+
home: { mode: "path", dir: home, source: "flag" },
|
|
54
|
+
packageRoot,
|
|
55
|
+
// Exercise the normal declared-package route, without loading unrelated harness extensions.
|
|
56
|
+
declaration: { kind: "npm" }, takeOver: false, otherPackagePaths: [],
|
|
57
|
+
passthrough: [
|
|
58
|
+
"--no-extensions", "-e", "builtin:mcp", "-e", extension,
|
|
59
|
+
"--no-session", "--provider", "mcp-status-fixture", "--model", "fixture",
|
|
60
|
+
"--print", "/mcp-status-probe",
|
|
61
|
+
],
|
|
62
|
+
baseEnv: {
|
|
63
|
+
PATH: process.env.PATH, HOME: userHome, USERPROFILE: userHome,
|
|
64
|
+
TMPDIR: temporary, TMP: temporary, TEMP: temporary,
|
|
65
|
+
PI_OFFLINE: "1", PI_NO_LOCAL_LLM: "1", NO_COLOR: "1",
|
|
66
|
+
GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null",
|
|
67
|
+
GIT_CONFIG_NOSYSTEM: "1", GIT_TERMINAL_PROMPT: "0",
|
|
68
|
+
},
|
|
69
|
+
homedir: userHome, cwd: root,
|
|
70
|
+
});
|
|
71
|
+
const child = spawnSync(invocation.command, invocation.args, {
|
|
72
|
+
cwd: root, env: invocation.env, encoding: "utf8", timeout: 15000,
|
|
73
|
+
});
|
|
74
|
+
assert.ifError(child.error);
|
|
75
|
+
assert.equal(child.status, 0, child.stderr);
|
|
76
|
+
// Pi reserves print-mode stdout for model output and redirects extension writes to stderr.
|
|
77
|
+
assert.equal(child.stdout, "");
|
|
78
|
+
const report = JSON.parse(child.stderr) as { snapshot: Array<{ since: number }> };
|
|
79
|
+
assert.equal(child.stderr, JSON.stringify(report) + "\n");
|
|
80
|
+
const since = report.snapshot[0]?.since;
|
|
81
|
+
assert.equal(typeof since, "number");
|
|
82
|
+
const snapshot = [{ name: "dev_docs", state: "disabled", since }];
|
|
83
|
+
assert.deepEqual(report, { initial: [], snapshot, events: [snapshot] });
|
|
84
|
+
assert.ok(!child.stderr.includes("fixture-not-public"));
|
|
85
|
+
} finally {
|
|
86
|
+
rmSync(root, { recursive: true, force: true });
|
|
87
|
+
}
|
|
88
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Real managers, private HOME/cache and a loopback-only registry; no live installation is touched.
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import * as fs from 'node:fs/promises';
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { test } from 'node:test';
|
|
11
|
+
import { updateSelectedPi } from '../../scripts/pi-update.mjs';
|
|
12
|
+
|
|
13
|
+
const exec = promisify(execFile);
|
|
14
|
+
const PI = '@earendil-works/pi-coding-agent';
|
|
15
|
+
for (const manager of ['npm', 'pnpm']) test(`real ${manager} source update preserves ranges, unrelated pins, Shell link and lifecycle safety`, {skip: process.platform === 'win32'}, async t => {
|
|
16
|
+
const temp = await fs.realpath(await fs.mkdtemp(join(tmpdir(), 'pi-real-')));
|
|
17
|
+
t.after(() => fs.rm(temp, {recursive:true, force:true}));
|
|
18
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(npm_config_|pnpm_config_|git_)/i.test(key)));
|
|
19
|
+
Object.assign(env, {HOME:temp, USERPROFILE:temp, XDG_CONFIG_HOME:temp, XDG_CACHE_HOME:join(temp,'cache'), npm_config_cache:join(temp,'cache'), npm_config_userconfig:join(temp,'user.npmrc'), npm_config_globalconfig:join(temp,'global.npmrc'), npm_config_update_notifier:'false', COREPACK_ENABLE_PROJECT_SPEC:'0', COREPACK_ENABLE_NETWORK:'0', COREPACK_HOME:join(temp,'corepack'), PNPM_HOME:join(temp,'pnpm-home')});
|
|
20
|
+
await fs.writeFile(env.npm_config_userconfig!, '');
|
|
21
|
+
await fs.writeFile(env.npm_config_globalconfig!, '');
|
|
22
|
+
const command = (await exec('which', [manager], {env})).stdout.trim();
|
|
23
|
+
const version = (await exec(command, ['--version'], {cwd:temp, env})).stdout.trim();
|
|
24
|
+
const files = new Map<string, Buffer>();
|
|
25
|
+
const manifests: Record<string, any> = {};
|
|
26
|
+
let updated = false;
|
|
27
|
+
let registry = '';
|
|
28
|
+
const registryRequests: {path: string, phase: string}[] = [];
|
|
29
|
+
const managerRuns: {args: string[], stdout: string, stderr: string}[] = [];
|
|
30
|
+
const server = createServer((req, res) => {
|
|
31
|
+
const path = decodeURIComponent(req.url!.split('?')[0]);
|
|
32
|
+
registryRequests.push({path, phase:updated ? 'update' : 'install'});
|
|
33
|
+
const tar = files.get(path);
|
|
34
|
+
if (tar) {res.end(tar); return;}
|
|
35
|
+
const name = path.slice(1);
|
|
36
|
+
if (!manifests[name]) {res.statusCode = 404; res.end('{}'); return;}
|
|
37
|
+
res.setHeader('content-type', 'application/json');
|
|
38
|
+
res.end(JSON.stringify({name, 'dist-tags':{latest:updated ? '1.1.0' : '1.0.0'}, time:{'1.0.0':'2020-01-01T00:00:00Z','1.1.0':'2020-01-02T00:00:00Z'}, versions:updated ? manifests[name] : {'1.0.0':manifests[name]['1.0.0']}}));
|
|
39
|
+
});
|
|
40
|
+
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
|
|
41
|
+
t.after(() => new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())));
|
|
42
|
+
registry = `http://127.0.0.1:${(server.address() as any).port}`;
|
|
43
|
+
env.npm_config_registry = registry;
|
|
44
|
+
env.npm_config_store_dir = join(temp, 'store');
|
|
45
|
+
Object.assign(env, {HTTP_PROXY:'http://127.0.0.1:9', HTTPS_PROXY:'http://127.0.0.1:9', NO_PROXY:'127.0.0.1,localhost'});
|
|
46
|
+
// pnpm 11 does not honor npm's registry environment variable. Bind both
|
|
47
|
+
// install and update explicitly to the fixture registry and private store.
|
|
48
|
+
const registryFlags = ['--registry', registry, ...(manager === 'pnpm' ? ['--store-dir', join(temp,'store'), '--config.update-notifier=false'] : [])];
|
|
49
|
+
for (const name of [PI, 'unrelated-fixture']) {
|
|
50
|
+
manifests[name] = {};
|
|
51
|
+
for (const version of ['1.0.0', '1.1.0']) {
|
|
52
|
+
const pack = join(temp, `pack-${name === PI ? 'pi' : 'other'}-${version}`);
|
|
53
|
+
await fs.mkdir(join(pack, 'package', 'dist', 'bundle'), {recursive:true});
|
|
54
|
+
const manifest = {name, version, bin:name === PI ? {pi:'dist/bundle/cli.js'} : undefined, scripts:{postinstall:'node -e "require(\'fs\').writeFileSync(\'LIFECYCLE_RAN\', \'bad\')"'}};
|
|
55
|
+
await fs.writeFile(join(pack, 'package', 'package.json'), JSON.stringify(manifest));
|
|
56
|
+
await fs.writeFile(join(pack, 'package', 'dist', 'bundle', 'cli.js'), `console.log('${version}');`);
|
|
57
|
+
const archive = join(pack, 'p.tgz');
|
|
58
|
+
await exec('tar', ['-czf', archive, '-C', pack, 'package'], {env});
|
|
59
|
+
const bytes = await fs.readFile(archive);
|
|
60
|
+
const path = `/tar/${name === PI ? 'pi' : 'other'}-${version}.tgz`;
|
|
61
|
+
files.set(path, bytes);
|
|
62
|
+
manifests[name][version] = {...manifest, dist:{tarball:registry + path, shasum:createHash('sha1').update(bytes).digest('hex')}};
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const root = join(temp, 'checkout');
|
|
66
|
+
await fs.mkdir(join(root, '.git'), {recursive:true});
|
|
67
|
+
const declaredVersion = manager === 'pnpm' ? '11.1.1' : version;
|
|
68
|
+
t.diagnostic(`${manager} runtime ${version}; project declaration ${declaredVersion}`);
|
|
69
|
+
const manifest = JSON.stringify({name:'gentle-pi', version:'4.4.0', packageManager:`${manager}@${declaredVersion}`, devDependencies:{[PI]:'^1.0.0', 'unrelated-fixture':'^1.0.0'}});
|
|
70
|
+
await fs.writeFile(join(root, 'package.json'), manifest);
|
|
71
|
+
const policy = 'minimumReleaseAge: 4320\n';
|
|
72
|
+
if (manager === 'pnpm') await fs.writeFile(join(root,'pnpm-workspace.yaml'), policy);
|
|
73
|
+
const common = ['--ignore-scripts', '--global=false', ...(manager === 'pnpm' ? ['--ignore-pnpmfile', '--pm-on-fail=ignore'] : ['--no-audit', '--no-fund'])];
|
|
74
|
+
await exec(command, ['install', ...common, ...registryFlags], {cwd:root, env, maxBuffer:1024*1024});
|
|
75
|
+
const lockPath = join(root, manager === 'pnpm' ? 'pnpm-lock.yaml' : 'package-lock.json');
|
|
76
|
+
const oldLock = await fs.readFile(lockPath, 'utf8');
|
|
77
|
+
const link = join(temp, 'global', 'node_modules', 'gentle-pi');
|
|
78
|
+
await fs.mkdir(join(temp, 'global', 'node_modules'), {recursive:true});
|
|
79
|
+
await fs.symlink(root, link, 'junction');
|
|
80
|
+
const selected = await fs.realpath(join(root, 'node_modules', PI, 'dist', 'bundle', 'cli.js'));
|
|
81
|
+
updated = true;
|
|
82
|
+
const output: string[] = [];
|
|
83
|
+
const mutations: string[][] = [];
|
|
84
|
+
assert.equal(await updateSelectedPi({runtime:{kind:'bundled', command:process.execPath, args:[selected]}, packageRoot:link, cwd:temp, home:temp, env, currentVersion:'1.0.0', out:(s: string) => output.push(s), adapters:{
|
|
85
|
+
fs,
|
|
86
|
+
which:async (name: string) => name === manager || name === 'npm' ? command : null,
|
|
87
|
+
run:async (_cmd: string, args: string[], options: {cwd?: string,env?: Record<string,string>}) => {
|
|
88
|
+
if (args.includes('list') && args.includes('-g')) return {code:0, stdout:JSON.stringify([{path:temp, dependencies:{}}])};
|
|
89
|
+
if (args.includes('ls') && args.includes('-g')) return {code:0, stdout:JSON.stringify({path:temp, dependencies:{'gentle-pi':{path:link, resolved:'file:../../checkout'}}})};
|
|
90
|
+
if (args[0] === 'update') mutations.push(args);
|
|
91
|
+
// The second phase models an already-published release, not a newly
|
|
92
|
+
// backdated version hidden behind install's fresh metadata-age cache.
|
|
93
|
+
const selectedEnv = options.env ?? env;
|
|
94
|
+
const runEnv = manager === 'pnpm' && args[0] === 'update' ? {...selectedEnv, XDG_CACHE_HOME:join(temp,'update-cache')} : selectedEnv;
|
|
95
|
+
try {const result = await exec(command, args[0] === 'update' ? [...args, ...registryFlags] : args, {cwd:options.cwd, env:runEnv, maxBuffer:1024*1024}); managerRuns.push({args, stdout:result.stdout, stderr:result.stderr}); return {code:0, stdout:result.stdout, stderrTail:result.stderr};}
|
|
96
|
+
catch (error: any) {return {code:error.code, stdout:error.stdout, stderrTail:error.stderr};}
|
|
97
|
+
},
|
|
98
|
+
}}), 0);
|
|
99
|
+
assert.equal(mutations.length, 1);
|
|
100
|
+
assert.ok(mutations[0].includes(PI));
|
|
101
|
+
assert.ok(registryRequests.some(request => request.phase === 'update' && request.path === `/${PI}`), JSON.stringify(registryRequests));
|
|
102
|
+
assert.ok(!mutations[0].includes('-g'));
|
|
103
|
+
assert.equal(await fs.realpath(link), root);
|
|
104
|
+
assert.equal(await fs.readFile(join(root, 'package.json'), 'utf8'), manifest);
|
|
105
|
+
if (manager === 'pnpm') {
|
|
106
|
+
assert.equal(await fs.readFile(join(root,'pnpm-workspace.yaml'),'utf8'), policy);
|
|
107
|
+
assert.ok(managerRuns.filter(run => run.args.includes('config') || run.args.includes('--recursive') || run.args[0] === 'update').every(run => run.args.includes('--pm-on-fail=ignore')));
|
|
108
|
+
assert.ok(!registryRequests.some(request => request.path === '/pnpm' || request.path.startsWith('/@pnpm/')), 'no project-pinned manager acquired');
|
|
109
|
+
}
|
|
110
|
+
assert.notEqual(await fs.readFile(lockPath, 'utf8'), oldLock, JSON.stringify({output, installed:JSON.parse(await fs.readFile(join(root,'node_modules',PI,'package.json'),'utf8')).version, managerRuns, registryRequests}));
|
|
111
|
+
assert.equal(JSON.parse(await fs.readFile(join(root,'node_modules',PI,'package.json'),'utf8')).version, '1.1.0');
|
|
112
|
+
assert.equal(JSON.parse(await fs.readFile(join(root,'node_modules','unrelated-fixture','package.json'),'utf8')).version, '1.0.0');
|
|
113
|
+
await assert.rejects(fs.access(join(root,'node_modules',PI,'LIFECYCLE_RAN')));
|
|
114
|
+
assert.equal(output.length, 1);
|
|
115
|
+
assert.match(output[0], /the selected Pi is now 1\.1\.0 \(was 1\.0\.0\)/);
|
|
116
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test from "node:test";
|
|
6
|
+
import { TERMINAL_ERROR_CATEGORY as C } from "../lib/agents-protocol.ts";
|
|
7
|
+
import { fallbackNotice, MODEL_FALLBACK_ENTRY, profileFallbackChain } from "../lib/model-fallback-notice.ts";
|
|
8
|
+
import { emptyFallbacksFile, fallbacksFilePath, setChain, writeFallbacksFile } from "../lib/model-fallback-store.ts";
|
|
9
|
+
|
|
10
|
+
const prices: Record<string, { input: number; output: number; cacheRead: number; cacheWrite: number }> = {
|
|
11
|
+
"a/cheap": { input: 1, output: 4, cacheRead: 0, cacheWrite: 0 },
|
|
12
|
+
"b/pricey": { input: 5, output: 20, cacheRead: 0, cacheWrite: 0 },
|
|
13
|
+
};
|
|
14
|
+
const lookup = (model: { provider: string | undefined; id: string }) => prices[`${model.provider}/${model.id}`];
|
|
15
|
+
|
|
16
|
+
test("the notice names the agent, why it moved, where it went, and when that costs more", () => {
|
|
17
|
+
assert.equal(MODEL_FALLBACK_ENTRY, "gentle-pi.model-fallback/v1");
|
|
18
|
+
assert.equal(fallbackNotice({ agent: "explore", from: "a/cheap", to: "b/pricey", category: C.QUOTA }, lookup),
|
|
19
|
+
"explore: a/cheap hit its usage limit; continuing on b/pricey (5.0x the price).");
|
|
20
|
+
assert.equal(fallbackNotice({ agent: "orchestrator", from: "b/pricey", to: "a/cheap", category: C.RATE_LIMIT }, lookup),
|
|
21
|
+
"orchestrator: b/pricey hit a rate limit; continuing on a/cheap.");
|
|
22
|
+
assert.equal(fallbackNotice({ agent: "worker", from: "a/cheap", to: "x/unknown", category: C.NETWORK }, lookup),
|
|
23
|
+
"worker: a/cheap hit a network error; continuing on x/unknown (price unknown).");
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
test("the chain comes from the launch's profile, else the active profile; a broken file gives none", () => {
|
|
27
|
+
const home = mkdtempSync(join(tmpdir(), "fallback-notice-"));
|
|
28
|
+
try {
|
|
29
|
+
assert.deepEqual(profileFallbackChain(home, "work", "explore"), [], "no file, no chain");
|
|
30
|
+
writeFallbacksFile(fallbacksFilePath(home), setChain(setChain(emptyFallbacksFile(), "work", "explore", [{ model: "b/pricey" }]), "home", "*", [{ model: "a/cheap" }]));
|
|
31
|
+
assert.deepEqual(profileFallbackChain(home, "work", "explore"), [{ model: "b/pricey" }]);
|
|
32
|
+
assert.deepEqual(profileFallbackChain(home, undefined, "explore"), [], "no profile and no active profile");
|
|
33
|
+
writeFileSync(join(home, "profiles.json"), JSON.stringify({ kind: "gentle-pi.agent_model_profiles", version: 1, active: "home", profiles: { home: {}, work: {} } }));
|
|
34
|
+
assert.deepEqual(profileFallbackChain(home, undefined, "explore"), [{ model: "a/cheap" }], "the active profile when the launch names none");
|
|
35
|
+
writeFileSync(fallbacksFilePath(home), "{ broken");
|
|
36
|
+
assert.deepEqual(profileFallbackChain(home, "work", "explore"), []);
|
|
37
|
+
} finally {
|
|
38
|
+
rmSync(home, { recursive: true, force: true });
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
test("a launch that starts on a fallback says the primary is still cooling down", () => {
|
|
43
|
+
assert.equal(fallbackNotice({ agent: "explore", from: "a/cheap", to: "b/pricey", category: C.QUOTA, launch: true }, lookup),
|
|
44
|
+
"explore: a/cheap is still cooling down after its usage limit; starting on b/pricey (5.0x the price).");
|
|
45
|
+
});
|