gentle-pi 4.7.0 → 4.8.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 +55 -44
- package/assets/agents/gentle-ai-explore.md +3 -3
- package/assets/agents/gentle-ai-verify.md +20 -6
- package/assets/agents/gentle-ai-worker.md +6 -6
- package/assets/agents/jd-judge-a.md +1 -3
- package/assets/agents/jd-judge-b.md +1 -3
- package/assets/agents/review-readability.md +1 -5
- package/assets/agents/review-reliability.md +1 -5
- package/assets/agents/review-resilience.md +1 -5
- package/assets/agents/review-risk.md +1 -5
- package/assets/design-canvas/canvas-api.js +45 -0
- package/assets/design-canvas/canvas-boards.js +456 -0
- package/assets/design-canvas/canvas-boot.js +217 -0
- package/assets/design-canvas/canvas-checks.js +491 -0
- package/assets/design-canvas/canvas-comments.js +315 -0
- package/assets/design-canvas/canvas-compare.js +159 -0
- package/assets/design-canvas/canvas-events.js +75 -0
- package/assets/design-canvas/canvas-export.js +393 -0
- package/assets/design-canvas/canvas-focus.js +203 -0
- package/assets/design-canvas/canvas-handoffs.js +150 -0
- package/assets/design-canvas/canvas-i18n-es.js +392 -0
- package/assets/design-canvas/canvas-i18n.js +108 -0
- package/assets/design-canvas/canvas-layout.js +526 -0
- package/assets/design-canvas/canvas-menu.js +213 -0
- package/assets/design-canvas/canvas-messages.js +86 -0
- package/assets/design-canvas/canvas-minimap.js +163 -0
- package/assets/design-canvas/canvas-parts.js +401 -0
- package/assets/design-canvas/canvas-popover.js +234 -0
- package/assets/design-canvas/canvas-rail.js +348 -0
- package/assets/design-canvas/canvas-sizes.js +524 -0
- package/assets/design-canvas/canvas-store.js +164 -0
- package/assets/design-canvas/canvas-tokens.js +674 -0
- package/assets/design-canvas/canvas-ui.js +24 -0
- package/assets/design-canvas/canvas-view.js +184 -0
- package/assets/design-canvas/canvas.css +746 -15
- package/assets/design-canvas/canvas.js +2 -1506
- package/assets/design-canvas/index.html +117 -36
- package/assets/design-canvas/inspector.js +546 -16
- package/assets/install-wizard/wizard.js +5 -1
- package/assets/migrations/agent-body-history.json +24 -0
- package/assets/orchestrator-delegation-reference.md +8 -14
- package/assets/orchestrator-delegation.md +4 -4
- package/assets/orchestrator-full-delegation-card.md +4 -5
- package/assets/orchestrator-full-delegation.md +8 -8
- package/assets/orchestrator-memory.md +2 -2
- package/assets/orchestrator-prompts.md +1 -1
- package/assets/orchestrator-quota-recovery.md +5 -0
- package/assets/orchestrator-skills.md +13 -12
- package/assets/orchestrator-tracking.md +10 -14
- package/assets/orchestrator-verification.md +10 -8
- package/assets/orchestrator-writer.md +4 -4
- package/assets/orchestrator.md +18 -22
- package/bin/gentle-shell.mjs +128 -9
- package/contracts/review-provider-contract-mirror/provider-contract.lock.json +8 -9
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/manifest.json +3 -3
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/orchestration/pi.md +1 -0
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/routing/pi.md +6 -6
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-capabilities.baseline.json +3 -3
- package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/generated/provider-roles.baseline.json +1 -1
- package/docs/assets/brand/sponsor-banner.svg +60 -0
- package/docs/bundled-install.md +14 -6
- package/docs/delegated-verification.md +18 -2
- package/docs/desktop-rpc.md +1253 -0
- package/docs/gentle-agents-activity.md +26 -0
- package/docs/gentle-shell.md +39 -16
- package/docs/install-wizard.md +30 -21
- package/docs/odd-preparation-continuity.md +24 -0
- package/docs/permission-modes.md +9 -1
- package/docs/prompt-budget.md +12 -0
- package/docs/rdd-odd-friction-triage-2026-11-07.md +57 -0
- package/docs/readme-reference.md +76 -24
- package/docs/review-coordinator.md +29 -9
- package/docs/review-delivery-preflight.md +22 -0
- package/docs/work-continuity.md +11 -1
- package/extensions/ask-user-question.ts +2 -2
- package/extensions/child-context.ts +21 -7
- package/extensions/gentle-agents.ts +234 -33
- package/extensions/gentle-ai.ts +576 -135
- package/extensions/gentle-design.ts +69 -3
- package/extensions/gentle-desktop-rpc.ts +143 -0
- package/extensions/gentle-guide.ts +3 -0
- package/extensions/gentle-shell.ts +105 -52
- package/extensions/gentle-todo.ts +48 -25
- package/extensions/skill-registry.ts +248 -223
- package/lib/agent-assets.ts +30 -6
- package/lib/agent-tool-overlay.ts +117 -0
- package/lib/agents-config.ts +47 -6
- package/lib/agents-message-delivery.ts +17 -0
- package/lib/agents-messaging.ts +8 -2
- package/lib/agents-protocol.ts +15 -0
- package/lib/agents-report-cap.ts +115 -0
- package/lib/agents-runner.ts +91 -6
- package/lib/agents-session-transport.ts +17 -1
- package/lib/background-jobs-tools.ts +9 -4
- package/lib/bounded-writer-admission.ts +184 -31
- package/lib/child-context-files.ts +21 -6
- package/lib/codemode-renderer.ts +1 -0
- package/lib/delivery-conflict-markers.ts +349 -0
- package/lib/design-canvas-assets.ts +36 -0
- package/lib/design-canvas-server.ts +241 -23
- package/lib/design-comments.ts +94 -4
- package/lib/design-handoffs.ts +2 -1
- package/lib/design-layout.ts +125 -0
- package/lib/design-parts.ts +281 -0
- package/lib/design-system-tokens.ts +111 -0
- package/lib/desktop-agents-service.ts +294 -0
- package/lib/desktop-design-service.ts +233 -0
- package/lib/desktop-jobs-service.ts +263 -0
- package/lib/desktop-rpc-agents.ts +294 -0
- package/lib/desktop-rpc-config.ts +731 -0
- package/lib/desktop-rpc-design.ts +138 -0
- package/lib/desktop-rpc-jobs.ts +181 -0
- package/lib/desktop-rpc-permissions.ts +177 -0
- package/lib/desktop-rpc-profiles.ts +196 -0
- package/lib/desktop-rpc-usage.ts +229 -0
- package/lib/desktop-rpc.ts +225 -0
- package/lib/desktop-usage-service.ts +310 -0
- package/lib/destructive-command-guard.ts +188 -13
- package/lib/gentle-ai-renderer.ts +13 -1
- package/lib/gentle-design.ts +201 -14
- package/lib/gentle-shell-bundled.ts +100 -9
- package/lib/hidden-tools.ts +35 -0
- package/lib/inprocess-reviewer.ts +96 -12
- package/lib/model-fallback-policy.ts +9 -0
- package/lib/model-routing-authority.ts +9 -0
- package/lib/nan-provider.ts +42 -28
- package/lib/native-review-cli.ts +79 -4
- package/lib/orchestrator-discovery.ts +39 -2
- package/lib/reply-language-anchor.ts +27 -2
- package/lib/request-context-placement.ts +53 -0
- package/lib/review-candidate-view.ts +11 -1
- package/lib/review-continuation-registry.ts +17 -0
- package/lib/review-coordinator.ts +252 -8
- package/lib/review-delivery-preflight.ts +85 -0
- package/lib/review-host-relay.ts +5 -1
- package/lib/review-integration-v2.ts +56 -3
- package/lib/reviewer-stream.ts +87 -0
- package/lib/shell-prompt.ts +16 -3
- package/lib/shell-usage.ts +10 -0
- package/lib/vim-editor-adapter.ts +9 -2
- package/lib/writer-batch-admission.ts +55 -0
- package/lib/yolo-session-policy.ts +6 -1
- package/package.json +2 -2
- package/prompts/skill-creation.md +1 -10
- package/runtime/design-canvas-assets.mjs +37 -0
- package/runtime/gentle-shell-bundled.mjs +100 -9
- package/runtime/native-review-cli.mjs +79 -4
- package/runtime/review-integration-v2.mjs +56 -3
- package/scripts/bootstrap.cmd +2 -2
- package/scripts/bootstrap.sh +41 -4
- package/scripts/build-full-delegation-card.mjs +4 -0
- package/scripts/build-runtime-modules.mjs +1 -0
- package/scripts/gentle-ai-installer.mjs +10 -10
- package/scripts/gentle-ai-proxy.mjs +1 -1
- package/scripts/installer-downloads.mjs +34 -8
- package/scripts/installer-preflight.mjs +28 -17
- package/scripts/installer-probes.mjs +25 -5
- package/scripts/installer-server.mjs +38 -9
- package/scripts/installer-windows.mjs +2 -2
- package/scripts/pi-update.mjs +166 -27
- package/scripts/prepare-verifier.mjs +107 -0
- package/scripts/update-agent-body-history.mjs +55 -8
- package/scripts/verify-package-files.mjs +40 -19
- package/skills/branch-pr/SKILL.md +16 -16
- package/skills/comment-writer/SKILL.md +1 -1
- package/skills/design/SKILL.md +6 -6
- package/skills/gentle-ai/SKILL.md +5 -5
- package/skills/judgment-day/SKILL.md +2 -2
- package/skills/judgment-day/references/prompts-and-formats.md +1 -1
- package/skills/rdd-defect-workflow/SKILL.md +6 -6
- package/skills/skill-improver/SKILL.md +2 -2
- package/skills/skill-registry/SKILL.md +11 -13
- package/skills/tui-design/SKILL.md +1 -1
- package/skills/work-unit-commits/SKILL.md +5 -5
- package/tests/agent-prompt-diet-contract.test.ts +101 -0
- package/tests/agent-tool-overlay-acceptance.test.ts +158 -0
- package/tests/agent-tool-overlay.test.ts +89 -0
- package/tests/agents-config.test.ts +10 -1
- package/tests/agents-message-delivery.test.ts +36 -0
- package/tests/agents-queries.test.ts +144 -4
- package/tests/agents-report-cap.test.ts +126 -0
- package/tests/agents-runner.test.ts +37 -1
- package/tests/agents-session-transport.test.ts +34 -0
- package/tests/always-on-prompt-verdicts-contract.test.ts +188 -0
- package/tests/append-system-prompt-route.test.ts +10 -2
- package/tests/approved-text-leftovers-contract.test.ts +136 -0
- package/tests/artifact-language.test.ts +1 -1
- package/tests/ask-user-question.test.ts +2 -1
- package/tests/audit-leftovers-contract.test.ts +51 -0
- package/tests/bounded-stop-contract.test.ts +9 -1
- package/tests/branch-pr-skill.test.ts +10 -1
- package/tests/bundled-install.test.ts +1 -1
- package/tests/child-context-files.test.ts +64 -8
- package/tests/child-skills-catalog.test.ts +56 -0
- package/tests/codemode-rendering.test.ts +4 -1
- package/tests/delegate-for-reason-contract.test.ts +30 -8
- package/tests/delivery-conflict-markers.test.ts +348 -0
- package/tests/design-canvas-all-sizes.test.ts +631 -0
- package/tests/design-canvas-allowlist.test.ts +32 -0
- package/tests/design-canvas-assets.test.ts +11 -878
- package/tests/design-canvas-boards.test.ts +77 -0
- package/tests/design-canvas-checks.test.ts +655 -0
- package/tests/design-canvas-compare.test.ts +79 -0
- package/tests/design-canvas-events.test.ts +59 -0
- package/tests/design-canvas-export.test.ts +1168 -0
- package/tests/design-canvas-focus.test.ts +113 -0
- package/tests/design-canvas-handoffs.test.ts +59 -0
- package/tests/design-canvas-i18n-review.test.ts +513 -0
- package/tests/design-canvas-i18n-views.test.ts +259 -0
- package/tests/design-canvas-i18n.test.ts +526 -0
- package/tests/design-canvas-inspector.test.ts +937 -0
- package/tests/design-canvas-layout.test.ts +1222 -0
- package/tests/design-canvas-minimap.test.ts +413 -0
- package/tests/design-canvas-modules.test.ts +90 -0
- package/tests/design-canvas-parts.test.ts +721 -0
- package/tests/design-canvas-rail.test.ts +799 -0
- package/tests/design-canvas-server.test.ts +855 -17
- package/tests/design-canvas-sizes.test.ts +548 -0
- package/tests/design-canvas-store.test.ts +180 -0
- package/tests/design-canvas-tokens.test.ts +965 -0
- package/tests/design-canvas-view.test.ts +299 -0
- package/tests/design-comments.test.ts +201 -1
- package/tests/design-handoffs.test.ts +20 -0
- package/tests/design-layout.test.ts +100 -0
- package/tests/design-parts.test.ts +260 -0
- package/tests/design-system-tokens.test.ts +215 -0
- package/tests/desktop-rpc-agents.test.ts +893 -0
- package/tests/desktop-rpc-config.test.ts +1452 -0
- package/tests/desktop-rpc-design.test.ts +662 -0
- package/tests/desktop-rpc-jobs.test.ts +796 -0
- package/tests/desktop-rpc-permissions.test.ts +311 -0
- package/tests/desktop-rpc-profiles.test.ts +140 -0
- package/tests/desktop-rpc-safety.test.ts +119 -0
- package/tests/desktop-rpc-usage.test.ts +697 -0
- package/tests/desktop-rpc.test.ts +252 -0
- package/tests/devbinary/pi-host-relay.devtest.ts +149 -80
- package/tests/devbinary/review-session-consent.devtest.ts +84 -0
- package/tests/engram-safety.test.ts +111 -0
- package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.captured.json +92 -0
- package/tests/fixtures/devbinary/status-v9-escalated-non-blocking.provenance.md +3 -0
- package/tests/fixtures/primary-session-prompt/gentleman.golden.md +20 -29
- package/tests/fixtures/refusal-identity.probe.mjs +139 -0
- package/tests/full-delegation-closure.test.ts +29 -0
- package/tests/gentle-agents.test.ts +329 -4
- package/tests/gentle-ai-binary.test.ts +1 -1
- package/tests/gentle-ai-child-guards.test.ts +1 -0
- package/tests/gentle-ai-installer.test.ts +52 -51
- package/tests/gentle-ai-renderer.test.ts +36 -2
- package/tests/gentle-ai.test.ts +121 -6
- package/tests/gentle-design.test.ts +365 -1
- package/tests/gentle-shell-bundled.test.ts +91 -5
- package/tests/gentle-shell-launcher.test.ts +1 -1
- package/tests/gentle-shell.test.ts +118 -87
- package/tests/gentle-todo.test.ts +32 -9
- package/tests/hidden-tools.test.ts +188 -0
- package/tests/independent-recovery-delivery.test.ts +19 -5
- package/tests/inprocess-reviewer.test.ts +73 -0
- package/tests/install-wizard.test.ts +27 -1
- package/tests/installer-downloads.test.ts +30 -1
- package/tests/installer-posix-bootstrap.test.ts +114 -13
- package/tests/installer-preflight.test.ts +49 -1
- package/tests/installer-probes.test.ts +146 -0
- package/tests/installer-server.test.ts +203 -4
- package/tests/installer-windows-bootstrap.test.ts +19 -1
- package/tests/judgment-day-severity-admission.test.ts +46 -0
- package/tests/lazy-module-contradictions-contract.test.ts +158 -0
- package/tests/maintainer/desktop-rpc.maintest.ts +632 -0
- package/tests/maintainer/pi-update-source.maintest.ts +48 -18
- package/tests/model-fallback-policy.test.ts +26 -7
- package/tests/nan-provider-runtime.test.ts +17 -3
- package/tests/nan-provider.test.ts +111 -56
- package/tests/native-review-capability-contract.test.ts +11 -1
- package/tests/native-review-cli-nonblocking-findings.test.ts +165 -0
- package/tests/native-review-parity.test.ts +24 -5
- package/tests/native-review-refusal-identity.test.ts +25 -0
- package/tests/no-self-pause-contract.test.ts +11 -3
- package/tests/odd-integration.test.ts +11 -3
- package/tests/odd-routing-contract.test.ts +80 -28
- package/tests/orchestrator-budget.test.ts +30 -5
- package/tests/orchestrator-consultation-sdk.test.ts +32 -6
- package/tests/orchestrator-delegation-mode.test.ts +2 -1
- package/tests/orchestrator-discovery.test.ts +28 -0
- package/tests/orchestrator-prompt-budget.test.ts +11 -2
- package/tests/orchestrator-prompt-diet-contract.test.ts +221 -0
- package/tests/orchestrator-rdd-ownership.test.ts +2 -1
- package/tests/orchestrator-work-search.test.ts +4 -2
- package/tests/package-files.test.ts +25 -1
- package/tests/package-manifest.test.ts +11 -10
- package/tests/parallel-reason-contract.test.ts +6 -3
- package/tests/permission-allowlist.test.ts +200 -30
- package/tests/persona-neutral-voseo.test.ts +4 -4
- package/tests/persona-reply-language.test.ts +1 -1
- package/tests/persona-single-channel.test.ts +13 -5
- package/tests/pi-update-launcher.test.ts +17 -7
- package/tests/pi-update-source.test.ts +113 -6
- package/tests/pi-update.test.ts +294 -19
- package/tests/pnpm-workspace-policy.test.ts +47 -0
- package/tests/primary-context-files.test.ts +233 -0
- package/tests/primary-context-three-files.test.ts +174 -0
- package/tests/provider-defect-handoff.test.ts +9 -2
- package/tests/rdd-aware-verification-contract.test.ts +1 -1
- package/tests/rdd-status-line.test.ts +94 -1
- package/tests/reply-language-anchor-placement.test.ts +184 -0
- package/tests/reply-language-anchor.test.ts +17 -1
- package/tests/request-context-append-only.test.ts +218 -0
- package/tests/request-context-placement.test.ts +148 -0
- package/tests/review-agent-end-preflight.test.ts +79 -1
- package/tests/review-candidate-view.test.ts +65 -0
- package/tests/review-continuation-registry.test.ts +31 -0
- package/tests/review-contract-prompt.test.ts +1 -1
- package/tests/review-controller.test.ts +2 -1
- package/tests/review-coordinator-correction-gate.test.ts +105 -0
- package/tests/review-coordinator-findings.test.ts +206 -0
- package/tests/review-coordinator-nonblocking-scope.test.ts +169 -0
- package/tests/review-coordinator.test.ts +271 -4
- package/tests/review-delivery-preflight.test.ts +462 -0
- package/tests/review-due-compaction.test.ts +31 -0
- package/tests/review-due-public-boundary.test.ts +26 -0
- package/tests/review-integration-nonblocking-findings.test.ts +108 -0
- package/tests/review-json-arguments.test.ts +41 -2
- package/tests/review-ledger-contract.test.ts +19 -40
- package/tests/review-loadout-rdd-off-sdk.test.ts +30 -1
- package/tests/review-one-call-findings.test.ts +131 -0
- package/tests/review-one-call-followups.test.ts +308 -0
- package/tests/review-one-call-reviewer-requests.test.ts +207 -0
- package/tests/review-one-call.test.ts +452 -0
- package/tests/review-relay-transport-agent.test.ts +28 -1
- package/tests/review-reviewer-evidence.test.ts +41 -1
- package/tests/review-risk-assessment.test.ts +52 -5
- package/tests/review-run-statement-guidance-independent.test.ts +54 -0
- package/tests/review-session-standing-permission-controller.test.ts +32 -2
- package/tests/review-tool-prose-budget.test.ts +1 -0
- package/tests/reviewer-stream.test.ts +149 -0
- package/tests/session-profile-extension.test.ts +2 -2
- package/tests/shell-prompt.test.ts +17 -0
- package/tests/shell-usage.test.ts +59 -10
- package/tests/skill-contradictions-contract.test.ts +122 -0
- package/tests/skill-registry-watcher.test.ts +216 -2
- package/tests/skill-registry.test.ts +929 -306
- package/tests/support/design-canvas-dom.ts +369 -0
- package/tests/support/review-coordinator-runtime.ts +212 -17
- package/tests/task-size-routing-contract.test.ts +42 -11
- package/tests/test-strength-contract.test.ts +2 -1
- package/tests/todo-request-append-only.test.ts +214 -0
- package/tests/tool-batching-contract.test.ts +3 -1
- package/tests/update-agent-body-history.test.ts +138 -0
- package/tests/verification-tiers-contract.test.ts +229 -0
- package/tests/verifier-preparation.test.ts +229 -0
- package/tests/verify-agent-contract.test.ts +20 -2
- package/tests/verify-first-launch-contract.test.ts +87 -11
- package/tests/vim-editor-adapter.test.ts +2 -2
- package/tests/work-continuity-contract.test.ts +54 -11
- package/tests/writer-admission-messages.test.ts +232 -0
- package/tests/writer-batch-admission.test.ts +66 -0
- package/tests/writer-edit-surface-scope.test.ts +52 -20
- package/tests/writer-feature-document-admission.test.ts +184 -0
- package/tests/yolo-mode.test.ts +39 -0
- package/skills/_shared/review-ledger-contract.md +0 -106
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/README.md +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/lens.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/refuter.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/schemas/targeted-validator.schema.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/lens.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/refuter.json +0 -0
- /package/contracts/review-provider-contract-mirror/{v1.4.0 → v1.5.0}/bundle/vectors/targeted-validator.json +0 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test, { type TestContext } from "node:test";
|
|
6
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
|
|
8
|
+
import { createGentleAiExtension } from "../extensions/gentle-ai.ts";
|
|
9
|
+
import { REPLY_LANGUAGE_ANCHOR_TYPE, placePersistedReplyAnchors } from "../lib/reply-language-anchor.ts";
|
|
10
|
+
|
|
11
|
+
// cost-speed-painpoints S10/S15 (P1), independent verifier probes (mwb638m6-12-yqki). Pi saves an anchor sent
|
|
12
|
+
// while streaming only when the turn ends, after the reply and its tool results; the saved copy records the
|
|
13
|
+
// message it followed and is moved back there on every later request. These probes pin that placement in the
|
|
14
|
+
// cases a plain session does not reach: a tool loop in progress, consecutive automated messages, compaction,
|
|
15
|
+
// branch switches, anchors saved before placement existed, and a long session.
|
|
16
|
+
|
|
17
|
+
type Message = { role: string; content?: unknown; customType?: string; timestamp?: number; [key: string]: unknown };
|
|
18
|
+
type Handler = (event: unknown, ctx: ExtensionContext) => unknown;
|
|
19
|
+
|
|
20
|
+
const HUMAN = "Che, revisá por qué el writer no arranca y decime qué pasa con la admisión";
|
|
21
|
+
const WAKE = "[System-generated Gentle Agents notification, not written by the user] Subagent output was delivered to this session above. Review it and continue.";
|
|
22
|
+
let clock = 100;
|
|
23
|
+
const sys: Message = { role: "system", content: "prompt", timestamp: 0 };
|
|
24
|
+
const user = (text: string): Message => ({ role: "user", content: [{ type: "text", text }], timestamp: ++clock });
|
|
25
|
+
const assistant = (call?: string): Message => ({ role: "assistant", content: call ? [{ type: "toolCall", id: call, name: "read", arguments: {} }] : [{ type: "text", text: "ok" }], timestamp: ++clock });
|
|
26
|
+
const toolResult = (id: string): Message => ({ role: "toolResult", toolCallId: id, toolName: "read", content: [{ type: "text", text: "r" }], isError: false, timestamp: ++clock });
|
|
27
|
+
const result = (): Message => ({ role: "custom", customType: "gentle-agents.result", content: "Subagent finished.", display: true, timestamp: ++clock });
|
|
28
|
+
const compactionSummary = (): Message => ({ role: "compactionSummary", summary: "s", tokensBefore: 1, timestamp: ++clock });
|
|
29
|
+
|
|
30
|
+
function fixture(t: TestContext) {
|
|
31
|
+
const cwd = mkdtempSync(join(tmpdir(), "anchor-placement-"));
|
|
32
|
+
t.after(() => rmSync(cwd, { recursive: true, force: true }));
|
|
33
|
+
const handlers = new Map<string, Handler[]>();
|
|
34
|
+
const sent: Message[] = [];
|
|
35
|
+
const api = {
|
|
36
|
+
on(name: string, handler: Handler) { handlers.set(name, [...(handlers.get(name) ?? []), handler]); },
|
|
37
|
+
events: { on() {}, emit() {} }, registerCommand() {}, registerTool() {}, registerShortcut() {}, registerMessageRenderer() {},
|
|
38
|
+
getActiveTools: () => ["read", "todo"], getFlag: () => undefined,
|
|
39
|
+
// Pi stamps the saved copy itself, later than the request that carried it.
|
|
40
|
+
sendMessage(message: Message, options: unknown) { sent.push({ ...message, role: "custom", timestamp: ++clock, _options: options }); },
|
|
41
|
+
} as unknown as ExtensionAPI;
|
|
42
|
+
createGentleAiExtension({
|
|
43
|
+
nativeReviewCli: null,
|
|
44
|
+
processEnv: { GENTLE_PI_CONFIG_HOME: join(cwd, "config"), GENTLE_PI_AGENTS_CHILD: "0" },
|
|
45
|
+
resolveTelemetryTriggerBinary: () => "/usr/bin/true", telemetryTriggerSpawn: (() => undefined) as never,
|
|
46
|
+
})(api);
|
|
47
|
+
const ctx = {
|
|
48
|
+
cwd, hasUI: false, mode: "interactive", ui: { notify() {}, setWidget() {}, setStatus() {} },
|
|
49
|
+
sessionManager: { getSessionId: () => "anchor-placement", getCwd: () => cwd, getBranch: () => [] },
|
|
50
|
+
getContextUsage: () => undefined, isIdle: () => false,
|
|
51
|
+
} as unknown as ExtensionContext;
|
|
52
|
+
const fire = async (name: string, event: unknown) => {
|
|
53
|
+
let last: unknown;
|
|
54
|
+
for (const handler of handlers.get(name) ?? []) last = await handler(event, ctx);
|
|
55
|
+
return last;
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
sent,
|
|
59
|
+
input: (text: string) => fire("input", { type: "input", text, source: "interactive" }),
|
|
60
|
+
/** Pi 1.5.2 order: `context` handlers (no system messages), then `context_with_system` (full transcript). */
|
|
61
|
+
request: async (messages: Message[]): Promise<Message[]> => {
|
|
62
|
+
let current = structuredClone(messages);
|
|
63
|
+
for (const handler of handlers.get("context") ?? []) {
|
|
64
|
+
const visible = current.filter((message) => message.role !== "system");
|
|
65
|
+
const returned = await handler({ type: "context", messages: visible }, ctx) as { messages?: Message[] } | undefined;
|
|
66
|
+
if (returned?.messages) current = [...current.filter((message) => message.role === "system"), ...returned.messages];
|
|
67
|
+
}
|
|
68
|
+
for (const handler of handlers.get("context_with_system") ?? []) {
|
|
69
|
+
const returned = await handler({ type: "context_with_system", messages: current }, ctx) as { messages?: Message[] } | undefined;
|
|
70
|
+
current = returned?.messages ?? current;
|
|
71
|
+
}
|
|
72
|
+
return current;
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The saved copies as Pi would hold them in the session, without the fixture's bookkeeping. */
|
|
78
|
+
const saved = (messages: Message[]): Message[] => messages.map(({ _options, ...rest }) => rest);
|
|
79
|
+
const isAnchor = (message: Message | undefined) => message?.customType === REPLY_LANGUAGE_ANCHOR_TYPE;
|
|
80
|
+
/** System head first, no leading assistant, and every toolCall immediately answered by its toolResult. */
|
|
81
|
+
function protocolOk(list: Message[]): boolean {
|
|
82
|
+
if (list[0]?.role !== "system") return false;
|
|
83
|
+
if (list.find((message) => message.role !== "system")?.role === "assistant") return false;
|
|
84
|
+
return list.every((message, index) => message.role !== "assistant"
|
|
85
|
+
|| (message.content as Array<{ type: string; id?: string }>).filter((part) => part.type === "toolCall")
|
|
86
|
+
.every((part, offset) => list[index + 1 + offset]?.role === "toolResult" && list[index + 1 + offset]!.toolCallId === part.id));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
test("P1 placement: during a tool loop the saved anchor returns behind the automated result, never between a toolCall and its toolResult, and is not added again", async (t) => {
|
|
90
|
+
const f = fixture(t);
|
|
91
|
+
await f.input(HUMAN);
|
|
92
|
+
const base = [sys, user(HUMAN), assistant(), result()];
|
|
93
|
+
const k = await f.request(base);
|
|
94
|
+
assert.ok(isAnchor(k.at(-1)));
|
|
95
|
+
assert.equal(f.sent.length, 1);
|
|
96
|
+
const k1 = await f.request([...base, assistant("c1"), toolResult("c1"), ...saved(f.sent)]);
|
|
97
|
+
assert.deepEqual(k1.slice(0, k.length), k, "request k+1 extends request k");
|
|
98
|
+
assert.ok(protocolOk(k1));
|
|
99
|
+
assert.equal(f.sent.length, 1, "no second anchor mid loop");
|
|
100
|
+
assert.ok(!isAnchor(k1.at(-1)));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
test("P1 placement: after two automated messages in a row the anchor follows the second and the next request extends it", async (t) => {
|
|
104
|
+
const f = fixture(t);
|
|
105
|
+
await f.input(HUMAN);
|
|
106
|
+
const base = [sys, user(HUMAN), assistant(), result(), user(WAKE)];
|
|
107
|
+
const k = await f.request(base);
|
|
108
|
+
const k1 = await f.request([...base, assistant(), ...saved(f.sent)]);
|
|
109
|
+
assert.deepEqual(k1.slice(0, k.length), k);
|
|
110
|
+
assert.ok(protocolOk(k1));
|
|
111
|
+
assert.equal(f.sent.length, 1);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("P1 placement: when compaction removed the anchor's predecessor, the anchor stays put and requests are stable", async (t) => {
|
|
115
|
+
const f = fixture(t);
|
|
116
|
+
await f.input(HUMAN);
|
|
117
|
+
await f.request([sys, user(HUMAN), assistant(), result()]);
|
|
118
|
+
const compacted = [sys, compactionSummary(), assistant(), saved(f.sent)[0]!, user("seguí")];
|
|
119
|
+
assert.equal(placePersistedReplyAnchors(compacted), undefined);
|
|
120
|
+
const first = await f.request(compacted);
|
|
121
|
+
const second = await f.request(compacted);
|
|
122
|
+
assert.deepEqual(first, second);
|
|
123
|
+
assert.deepEqual(first, compacted);
|
|
124
|
+
assert.ok(protocolOk(first));
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("P1 placement: with a compaction summary at the head, an automated message is anchored right after it", async (t) => {
|
|
128
|
+
const f = fixture(t);
|
|
129
|
+
await f.input(HUMAN);
|
|
130
|
+
const k = await f.request([sys, compactionSummary(), result()]);
|
|
131
|
+
assert.ok(isAnchor(k.at(-1)));
|
|
132
|
+
assert.ok(protocolOk(k));
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("P1 placement: after a branch switch replaced the anchor's predecessor, the anchor stays put; another message never matches its identity", async (t) => {
|
|
136
|
+
const f = fixture(t);
|
|
137
|
+
await f.input(HUMAN);
|
|
138
|
+
await f.request([sys, user(HUMAN), assistant(), result()]);
|
|
139
|
+
const other = [sys, user("otra rama"), assistant(), result(), assistant(), saved(f.sent)[0]!];
|
|
140
|
+
assert.equal(placePersistedReplyAnchors(other), undefined);
|
|
141
|
+
assert.ok(protocolOk(await f.request(other)));
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test("P1 placement: anchors saved without placement stay where they are while new ones move, and placement is idempotent", async (t) => {
|
|
145
|
+
const f = fixture(t);
|
|
146
|
+
await f.input(HUMAN);
|
|
147
|
+
const legacy: Message = { role: "custom", customType: REPLY_LANGUAGE_ANCHOR_TYPE, content: "legacy", display: false, timestamp: ++clock };
|
|
148
|
+
const head = [sys, user(HUMAN), assistant(), result(), assistant(), legacy, user("sigo"), assistant(), result()];
|
|
149
|
+
const k = await f.request(head);
|
|
150
|
+
const next = [...head, assistant(), ...saved(f.sent)];
|
|
151
|
+
const k1 = await f.request(next);
|
|
152
|
+
assert.deepEqual(k1.slice(0, k.length), k);
|
|
153
|
+
assert.equal(k1.findIndex((message) => message.content === "legacy"), 5);
|
|
154
|
+
const placed = placePersistedReplyAnchors(next)!;
|
|
155
|
+
assert.equal(placePersistedReplyAnchors(placed), undefined);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("P1 placement: a long session with 50 anchors stays append-only and placement is cheap and idempotent", async (t) => {
|
|
159
|
+
const f = fixture(t);
|
|
160
|
+
await f.input(HUMAN);
|
|
161
|
+
const persisted: Message[] = [sys, user(HUMAN), assistant()];
|
|
162
|
+
const snapshots: Message[][] = [];
|
|
163
|
+
for (let i = 0; i < 50; i++) {
|
|
164
|
+
persisted.push(result());
|
|
165
|
+
snapshots.push(await f.request(persisted));
|
|
166
|
+
for (let j = 0; j < 8; j++) {
|
|
167
|
+
persisted.push(assistant(`c${i}_${j}`), toolResult(`c${i}_${j}`));
|
|
168
|
+
if (j === 0) persisted.push(saved([f.sent[i]!])[0]!);
|
|
169
|
+
snapshots.push(await f.request(persisted));
|
|
170
|
+
}
|
|
171
|
+
persisted.push(assistant());
|
|
172
|
+
}
|
|
173
|
+
assert.equal(f.sent.length, 50);
|
|
174
|
+
const started = performance.now();
|
|
175
|
+
let placed: Message[] | undefined;
|
|
176
|
+
for (let n = 0; n < 200; n++) placed = placePersistedReplyAnchors(persisted);
|
|
177
|
+
const perCall = (performance.now() - started) / 200;
|
|
178
|
+
assert.ok(perCall < 5, `placement costs ${perCall.toFixed(3)} ms per call over ${persisted.length} messages`);
|
|
179
|
+
assert.ok(placed);
|
|
180
|
+
assert.equal(placePersistedReplyAnchors(placed), undefined, "second call: nothing moves");
|
|
181
|
+
assert.ok(protocolOk(placed));
|
|
182
|
+
for (let k = 1; k < snapshots.length; k++) assert.deepEqual(snapshots[k]!.slice(0, snapshots[k - 1]!.length), snapshots[k - 1], `request ${k + 1} extends request ${k}`);
|
|
183
|
+
assert.deepEqual(await f.request(persisted), placed);
|
|
184
|
+
});
|
|
@@ -10,7 +10,9 @@ import {
|
|
|
10
10
|
REPLY_LANGUAGE_ANCHOR_TYPE,
|
|
11
11
|
humanLanguageExcerpt,
|
|
12
12
|
isHumanInput,
|
|
13
|
+
placePersistedReplyAnchors,
|
|
13
14
|
replyLanguageAnchor,
|
|
15
|
+
replyLanguageAnchorPosition,
|
|
14
16
|
} from "../lib/reply-language-anchor.ts";
|
|
15
17
|
|
|
16
18
|
// ---------------------------------------------------------------------------
|
|
@@ -110,7 +112,8 @@ function hookFixture(t: TestContext, child = false) {
|
|
|
110
112
|
return {
|
|
111
113
|
sent,
|
|
112
114
|
input: (text: string, source = "interactive") => handlers.get("input")!({ type: "input", text, source }, ctx),
|
|
113
|
-
|
|
115
|
+
// P1: the anchor runs in `context_with_system`, so a changed list never folds Pi's system messages.
|
|
116
|
+
context: (messages: unknown[]) => handlers.get("context_with_system")?.({ type: "context_with_system", messages }, ctx) as { messages?: unknown[] } | undefined,
|
|
114
117
|
};
|
|
115
118
|
}
|
|
116
119
|
|
|
@@ -171,3 +174,16 @@ test("S9: the anchor Pi flushes at turn_end, after the tool round, is not re-add
|
|
|
171
174
|
assert.equal(replyLanguageAnchor(flushed as never, HUMAN), undefined);
|
|
172
175
|
});
|
|
173
176
|
|
|
177
|
+
|
|
178
|
+
// P1 (cost-speed-painpoints S10): Pi saves the anchor after the reply, so each saved copy records where its request
|
|
179
|
+
// carried it and is moved back there; one whose predecessor is gone, or saved without a placement, stays put.
|
|
180
|
+
test("P1: a saved anchor is moved back after the message it followed, with its request's timestamp", () => {
|
|
181
|
+
const anchor = (details?: unknown) => ({ role: "custom", customType: REPLY_LANGUAGE_ANCHOR_TYPE, content: "a", display: false, details, timestamp: 50 });
|
|
182
|
+
const tail = custom("gentle-agents.result");
|
|
183
|
+
const saved = anchor({ after: replyLanguageAnchorPosition(tail), at: 7 });
|
|
184
|
+
const placed = placePersistedReplyAnchors([user(HUMAN), tail, assistant(), toolResult(), saved]);
|
|
185
|
+
assert.deepEqual(placed, [user(HUMAN), tail, { ...saved, timestamp: 7 }, assistant(), toolResult()]);
|
|
186
|
+
assert.equal(placePersistedReplyAnchors(placed!), undefined, "an anchor already in place is left alone");
|
|
187
|
+
assert.equal(placePersistedReplyAnchors([user(HUMAN), assistant(), saved]), undefined, "its predecessor compacted away: it stays put");
|
|
188
|
+
assert.equal(placePersistedReplyAnchors([user(HUMAN), tail, assistant(), anchor()]), undefined, "saved by an earlier version: it stays put");
|
|
189
|
+
});
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import test, { type TestContext } from "node:test";
|
|
6
|
+
import { getCurrentSystemMessage } from "@earendil-works/pi-ai";
|
|
7
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
|
|
9
|
+
import { createGentleAiExtension } from "../extensions/gentle-ai.ts";
|
|
10
|
+
import installGentleTodo from "../extensions/gentle-todo.ts";
|
|
11
|
+
import { REPLY_LANGUAGE_ANCHOR_TYPE, humanLanguageExcerpt } from "../lib/reply-language-anchor.ts";
|
|
12
|
+
|
|
13
|
+
// cost-speed-painpoints S10/S15 (P1). pi-claude-bridge warned that an extension adds a
|
|
14
|
+
// message to every request without saving it, so every request rewrote the whole prompt
|
|
15
|
+
// cache. Invariant: across consecutive requests of one session, the message list sent to
|
|
16
|
+
// the provider is append-only — request k+1 starts with exactly the messages of request k.
|
|
17
|
+
//
|
|
18
|
+
// The loop below drives the real gentle-ai and gentle-todo hooks the way Pi 1.5.2 does:
|
|
19
|
+
// `context` handlers see the conversation without system messages (a changed list gets the
|
|
20
|
+
// replayed system head, runner.js restoreSystemMessages), then `context_with_system`
|
|
21
|
+
// handlers see the full transcript and their output is sent as returned. A custom message
|
|
22
|
+
// sent with `triggerTurn: false` while streaming is appended once the current turn ends,
|
|
23
|
+
// after its assistant message and tool results (agent-session.js sendCustomMessage).
|
|
24
|
+
|
|
25
|
+
type Message = { role: string; content?: unknown; customType?: string; display?: boolean; details?: unknown; timestamp?: number; [key: string]: unknown };
|
|
26
|
+
type Handler = (event: unknown, ctx: ExtensionContext) => unknown;
|
|
27
|
+
|
|
28
|
+
const HUMAN_1 = "Che, revisá por qué el writer no arranca y decime qué pasa con la admisión";
|
|
29
|
+
const HUMAN_2 = "Bien, ahora armá la lista de tareas y seguí con el arreglo";
|
|
30
|
+
const WAKE = "[System-generated Gentle Agents notification, not written by the user] Subagent output was delivered to this session above. Review it and continue.";
|
|
31
|
+
|
|
32
|
+
function session(t: TestContext, options: { child?: boolean } = {}) {
|
|
33
|
+
const cwd = mkdtempSync(join(tmpdir(), "append-only-"));
|
|
34
|
+
t.after(() => rmSync(cwd, { recursive: true, force: true }));
|
|
35
|
+
const handlers = new Map<string, Handler[]>();
|
|
36
|
+
const tools = new Map<string, { execute: (...args: unknown[]) => Promise<unknown> }>();
|
|
37
|
+
const pending: Message[] = [];
|
|
38
|
+
let clock = 1_000;
|
|
39
|
+
const now = () => ++clock;
|
|
40
|
+
const sendMessage = (message: { customType: string; content: unknown; display?: boolean; details?: unknown }, sendOptions?: { triggerTurn?: boolean }) => {
|
|
41
|
+
assert.equal(sendOptions?.triggerTurn, false, "a harness message never starts a turn");
|
|
42
|
+
pending.push({ role: "custom", customType: message.customType, content: message.content, display: message.display, details: message.details, timestamp: now() });
|
|
43
|
+
};
|
|
44
|
+
const api = (extension: string) => ({
|
|
45
|
+
on(name: string, handler: Handler) { handlers.set(name, [...(handlers.get(name) ?? []), handler]); void extension; },
|
|
46
|
+
events: { on() {}, emit() {} }, registerCommand() {}, registerShortcut() {}, registerMessageRenderer() {},
|
|
47
|
+
registerTool(tool: { name: string; execute: (...args: unknown[]) => Promise<unknown> }) { tools.set(tool.name, tool); },
|
|
48
|
+
getActiveTools: () => ["read", "todo"], getFlag: () => undefined,
|
|
49
|
+
sendMessage,
|
|
50
|
+
}) as unknown as ExtensionAPI;
|
|
51
|
+
createGentleAiExtension({
|
|
52
|
+
nativeReviewCli: null,
|
|
53
|
+
processEnv: { GENTLE_PI_CONFIG_HOME: join(cwd, "config"), GENTLE_PI_AGENTS_CHILD: options.child ? "1" : "0" },
|
|
54
|
+
resolveTelemetryTriggerBinary: () => "/usr/bin/true", telemetryTriggerSpawn: (() => undefined) as never,
|
|
55
|
+
})(api("gentle-ai"));
|
|
56
|
+
installGentleTodo(api("gentle-todo"), {});
|
|
57
|
+
|
|
58
|
+
const transcript: Message[] = [{ role: "system", content: "You are the harness under test.", timestamp: 0 }];
|
|
59
|
+
const ctx = {
|
|
60
|
+
cwd, hasUI: false, mode: "interactive", ui: { notify() {}, setWidget() {}, setStatus() {} },
|
|
61
|
+
sessionManager: { getSessionId: () => "append-only", getCwd: () => cwd, getBranch: () => transcript.map((message) => ({ type: "message", message })) },
|
|
62
|
+
getContextUsage: () => undefined, isIdle: () => false,
|
|
63
|
+
} as unknown as ExtensionContext;
|
|
64
|
+
const fire = async (name: string, event: unknown) => {
|
|
65
|
+
let last: unknown;
|
|
66
|
+
for (const handler of handlers.get(name) ?? []) last = await handler(event, ctx);
|
|
67
|
+
return last;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const requests: Message[][] = [];
|
|
71
|
+
/** One model request, built the way Pi's ExtensionRunner.emitContext builds it. */
|
|
72
|
+
const request = async (): Promise<Message[]> => {
|
|
73
|
+
let current = structuredClone(transcript);
|
|
74
|
+
for (const handler of handlers.get("context") ?? []) {
|
|
75
|
+
const visible = current.filter((message) => message.role !== "system");
|
|
76
|
+
const snapshot = visible.slice();
|
|
77
|
+
const result = await handler({ type: "context", messages: visible }, ctx) as { messages?: Message[] } | undefined;
|
|
78
|
+
const returned = result?.messages ?? (visible.every((message, index) => message === snapshot[index]) ? undefined : visible);
|
|
79
|
+
if (!returned || (returned.length === snapshot.length && returned.every((message, index) => message === snapshot[index]))) continue;
|
|
80
|
+
const head = getCurrentSystemMessage(current as never) as Message | undefined;
|
|
81
|
+
current = head ? [head, ...returned] : returned;
|
|
82
|
+
}
|
|
83
|
+
for (const handler of handlers.get("context_with_system") ?? []) {
|
|
84
|
+
const result = await handler({ type: "context_with_system", messages: current }, ctx) as { messages?: Message[] } | undefined;
|
|
85
|
+
current = result?.messages ?? current;
|
|
86
|
+
}
|
|
87
|
+
const sent = structuredClone(current);
|
|
88
|
+
requests.push(sent);
|
|
89
|
+
return sent;
|
|
90
|
+
};
|
|
91
|
+
/** One assistant turn: request, reply, tool results, turn_end, then Pi flushes queued custom messages. */
|
|
92
|
+
const turn = async (reply: Message, toolResults: Message[] = []) => {
|
|
93
|
+
const sent = await request();
|
|
94
|
+
transcript.push(reply);
|
|
95
|
+
transcript.push(...toolResults);
|
|
96
|
+
await fire("turn_end", { type: "turn_end", message: reply, toolResults });
|
|
97
|
+
transcript.push(...pending.splice(0));
|
|
98
|
+
return sent;
|
|
99
|
+
};
|
|
100
|
+
const say = (text: string): Message => ({ role: "assistant", content: [{ type: "text", text }], timestamp: now() });
|
|
101
|
+
/** A run started by text the human typed. */
|
|
102
|
+
const human = async (text: string) => {
|
|
103
|
+
await fire("input", { type: "input", text, source: "interactive" });
|
|
104
|
+
transcript.push({ role: "user", content: [{ type: "text", text }], timestamp: now() });
|
|
105
|
+
return turn(say("Listo."));
|
|
106
|
+
};
|
|
107
|
+
/** A run started by an automated wake: Gentle Agents sends it as an extension-sourced user message. */
|
|
108
|
+
const wake = async () => {
|
|
109
|
+
await fire("input", { type: "input", text: WAKE, source: "extension" });
|
|
110
|
+
transcript.push({ role: "user", content: [{ type: "text", text: WAKE }], timestamp: now() });
|
|
111
|
+
return turn(say("Revisé el resultado."));
|
|
112
|
+
};
|
|
113
|
+
/** A run started by an automated custom message, as a subagent result sent with triggerTurn while idle. */
|
|
114
|
+
const automated = async (customType = "gentle-agents.result") => {
|
|
115
|
+
transcript.push({ role: "custom", customType, content: "Subagent gentle-ai-worker (task x) finished. All checks pass.", display: true, timestamp: now() });
|
|
116
|
+
return turn(say("El worker terminó."));
|
|
117
|
+
};
|
|
118
|
+
/** A human run whose reply writes the todo list in a tool loop, then answers. */
|
|
119
|
+
const humanWithTodo = async (text: string, tasks: Array<{ title: string }>) => {
|
|
120
|
+
await fire("input", { type: "input", text, source: "interactive" });
|
|
121
|
+
transcript.push({ role: "user", content: [{ type: "text", text }], timestamp: now() });
|
|
122
|
+
const id = `todo-${now()}`;
|
|
123
|
+
const call: Message = { role: "assistant", content: [{ type: "toolCall", id, name: "todo", arguments: { action: "write", tasks } }], timestamp: now() };
|
|
124
|
+
const sentBeforeTool = await request();
|
|
125
|
+
transcript.push(call);
|
|
126
|
+
const result = await tools.get("todo")!.execute(id, { action: "write", tasks }, undefined, undefined, ctx) as { content: unknown };
|
|
127
|
+
const toolResult: Message = { role: "toolResult", toolCallId: id, toolName: "todo", content: result.content, isError: false, timestamp: now() };
|
|
128
|
+
transcript.push(toolResult);
|
|
129
|
+
await fire("turn_end", { type: "turn_end", message: call, toolResults: [toolResult] });
|
|
130
|
+
transcript.push(...pending.splice(0));
|
|
131
|
+
const sentAfterTool = await turn(say("Armé la lista."));
|
|
132
|
+
return { sentBeforeTool, sentAfterTool };
|
|
133
|
+
};
|
|
134
|
+
return { fire, requests, request, human, wake, automated, humanWithTodo, transcript };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const textOf = (message: Message | undefined) =>
|
|
138
|
+
typeof message?.content === "string" ? message.content : Array.isArray(message?.content) ? (message.content as Array<{ text?: string }>).map((part) => part.text ?? "").join(" ") : "";
|
|
139
|
+
const anchorAtTail = (request: Message[]) => {
|
|
140
|
+
const last = request.at(-1);
|
|
141
|
+
return last?.customType === REPLY_LANGUAGE_ANCHOR_TYPE ? textOf(last) : undefined;
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
/** Key order is not part of a message (Pi's replayed system head builds its keys in another order). */
|
|
145
|
+
const canonical = (value: unknown) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, (item as Record<string, unknown>)[key]])) : item);
|
|
146
|
+
|
|
147
|
+
/** For every consecutive pair: leading messages that are identical, and the first index that differs. */
|
|
148
|
+
function prefixReport(requests: Message[][]): Array<{ pair: string; previous: number; identical: number; firstDiff: number | null }> {
|
|
149
|
+
return requests.slice(1).map((next, index) => {
|
|
150
|
+
const previous = requests[index]!;
|
|
151
|
+
let identical = 0;
|
|
152
|
+
while (identical < previous.length && canonical(previous[identical]) === canonical(next[identical])) identical++;
|
|
153
|
+
return { pair: `${index + 1}->${index + 2}`, previous: previous.length, identical, firstDiff: identical === previous.length ? null : identical };
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
test("P1: a multi-turn session with wakes, automated results, a human message and a todo change sends append-only requests", async (t) => {
|
|
158
|
+
const s = session(t);
|
|
159
|
+
await s.fire("session_start", { type: "session_start" });
|
|
160
|
+
const steps: Array<[string, Message[]]> = [];
|
|
161
|
+
steps.push(["human", await s.human(HUMAN_1)]);
|
|
162
|
+
steps.push(["wake", await s.wake()]);
|
|
163
|
+
steps.push(["automated", await s.automated()]);
|
|
164
|
+
const todo = await s.humanWithTodo(HUMAN_2, [{ title: "Arreglar la admisión" }, { title: "Probar el writer" }]);
|
|
165
|
+
steps.push(["human+todo (tool call)", todo.sentBeforeTool], ["human+todo (after tool)", todo.sentAfterTool]);
|
|
166
|
+
steps.push(["wake after todo", await s.wake()]);
|
|
167
|
+
steps.push(["final human", await s.human("Gracias, cerrá todo")]);
|
|
168
|
+
|
|
169
|
+
// The anchor still reaches the model after each automated tail, quoting the human's latest own words.
|
|
170
|
+
const byStep = Object.fromEntries(steps.map(([name, sent]) => [name, anchorAtTail(sent)]));
|
|
171
|
+
assert.equal(byStep.human, undefined, "right after the human, nothing is anchored");
|
|
172
|
+
assert.ok(byStep.wake?.includes(`«${humanLanguageExcerpt(HUMAN_1)}»`), "the wake is anchored to the first human message");
|
|
173
|
+
assert.ok(byStep.automated?.includes(`«${humanLanguageExcerpt(HUMAN_1)}»`), "the automated result is anchored too");
|
|
174
|
+
assert.equal(byStep["human+todo (tool call)"], undefined);
|
|
175
|
+
assert.equal(byStep["human+todo (after tool)"], undefined, "mid tool loop, nothing is anchored");
|
|
176
|
+
assert.ok(byStep["wake after todo"]?.includes(`«${humanLanguageExcerpt(HUMAN_2)}»`), "the later wake quotes the later human message");
|
|
177
|
+
assert.equal(byStep["final human"], undefined);
|
|
178
|
+
|
|
179
|
+
// The todo list reaches the model once it changed, and stays there.
|
|
180
|
+
const todoState = (sent: Message[]) => [...sent].reverse().find((message) => message.customType === "gentle-todo-state");
|
|
181
|
+
assert.match(textOf(todoState(todo.sentAfterTool)), /Arreglar la admisión/, "the request after the todo write carries the list");
|
|
182
|
+
assert.match(textOf(todoState(s.requests.at(-1)!)), /Probar el writer/);
|
|
183
|
+
|
|
184
|
+
// Every request starts with exactly the messages of the previous one.
|
|
185
|
+
const report = prefixReport(s.requests);
|
|
186
|
+
const broken = report.filter((row) => row.firstDiff !== null);
|
|
187
|
+
assert.deepEqual(broken, [], `append-only broken at: ${JSON.stringify(broken)}\nsteps: ${steps.map(([name], index) => `${index + 1}=${name}`).join(", ")}`);
|
|
188
|
+
|
|
189
|
+
// Each anchor is in the session exactly once, so later requests and a resumed session keep it.
|
|
190
|
+
const anchors = s.transcript.filter((message) => message.customType === REPLY_LANGUAGE_ANCHOR_TYPE);
|
|
191
|
+
assert.equal(anchors.length, 3, "one persisted anchor per automated tail");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("P1 preservation: the anchor appears exactly where it did before — automated tail only, never mid tool loop, never twice", async (t) => {
|
|
195
|
+
const cases: Array<{ name: string; messages: Message[]; human?: string; child?: boolean; anchored: boolean }> = [
|
|
196
|
+
{ name: "right after the human", messages: [{ role: "user", content: HUMAN_1, timestamp: 1 }], human: HUMAN_1, anchored: false },
|
|
197
|
+
{ name: "after a subagent result", messages: [{ role: "user", content: HUMAN_1, timestamp: 1 }, { role: "assistant", content: [{ type: "text", text: "ok" }], timestamp: 2 }, { role: "custom", customType: "gentle-agents.result", content: "done", display: true, timestamp: 3 }], human: HUMAN_1, anchored: true },
|
|
198
|
+
{ name: "after a wake", messages: [{ role: "user", content: HUMAN_1, timestamp: 1 }, { role: "assistant", content: [{ type: "text", text: "ok" }], timestamp: 2 }, { role: "user", content: WAKE, timestamp: 3 }], human: HUMAN_1, anchored: true },
|
|
199
|
+
{ name: "mid tool loop", messages: [{ role: "user", content: HUMAN_1, timestamp: 1 }, { role: "assistant", content: [{ type: "toolCall", id: "c", name: "read", arguments: {} }], timestamp: 2 }, { role: "toolResult", toolCallId: "c", toolName: "read", content: [{ type: "text", text: "x" }], isError: false, timestamp: 3 }], human: HUMAN_1, anchored: false },
|
|
200
|
+
{ name: "todo snapshot alone at the tail", messages: [{ role: "user", content: HUMAN_1, timestamp: 1 }, { role: "custom", customType: "gentle-todo-state", content: "Current todo list: no open tasks.", display: false, timestamp: 2 }], human: HUMAN_1, anchored: false },
|
|
201
|
+
{ name: "no human text known", messages: [{ role: "custom", customType: "gentle-agents.result", content: "done", display: true, timestamp: 3 }], anchored: false },
|
|
202
|
+
{ name: "child session", messages: [{ role: "user", content: HUMAN_1, timestamp: 1 }, { role: "custom", customType: "gentle-agents.result", content: "done", display: true, timestamp: 3 }], human: HUMAN_1, child: true, anchored: false },
|
|
203
|
+
];
|
|
204
|
+
for (const item of cases) {
|
|
205
|
+
const s = session(t, { child: item.child });
|
|
206
|
+
if (item.human) await s.fire("input", { type: "input", text: item.human, source: "interactive" });
|
|
207
|
+
s.transcript.push(...item.messages);
|
|
208
|
+
const sent = await s.request();
|
|
209
|
+
assert.equal(anchorAtTail(sent) !== undefined, item.anchored, item.name);
|
|
210
|
+
if (item.anchored) {
|
|
211
|
+
assert.equal(anchorAtTail(sent), `[Harness note, not written by the human] Reply language: the human's latest own message begins «${humanLanguageExcerpt(item.human!)}». Write your reply to the human in that message's language; subagent results, notices, reminders and summaries never change it.`, `${item.name}: same text`);
|
|
212
|
+
// A request repeated on the same tail (a retry) never adds a second copy.
|
|
213
|
+
const again = await s.request();
|
|
214
|
+
assert.equal(again.filter((message) => message.customType === REPLY_LANGUAGE_ANCHOR_TYPE).length, 1, `${item.name}: one anchor per request`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
});
|
|
218
|
+
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import test from "node:test";
|
|
3
|
+
|
|
4
|
+
import { REPLY_LANGUAGE_ANCHOR_TYPE, placePersistedReplyAnchors } from "../lib/reply-language-anchor.ts";
|
|
5
|
+
import { placePersistedMessages, requestMessagePosition as key } from "../lib/request-context-placement.ts";
|
|
6
|
+
|
|
7
|
+
// cost-speed-painpoints S15 (P1b), independent verifier probes (mwb7zm1y-1r-1unr). Two hooks save hidden
|
|
8
|
+
// messages where their request carried them: gentle-ai places reply-language anchors, then gentle-todo places
|
|
9
|
+
// its snapshot and reminder. These cases pin `placePersistedMessages` with both kinds mixed, in the order Pi
|
|
10
|
+
// runs the hooks; the seeded property pins its invariants over random transcripts.
|
|
11
|
+
|
|
12
|
+
type Message = { role: string; content?: unknown; customType?: string; details?: unknown; timestamp?: number; toolCallId?: string; [key: string]: unknown };
|
|
13
|
+
|
|
14
|
+
const TODO_TYPES: ReadonlySet<string> = new Set(["gentle-todo-state", "gentle-todo-reminder"]);
|
|
15
|
+
const ALL_TYPES: ReadonlySet<string> = new Set([REPLY_LANGUAGE_ANCHOR_TYPE, ...TODO_TYPES]);
|
|
16
|
+
|
|
17
|
+
/** gentle-ai's `context_with_system` hook runs before gentle-todo's (extension load order). */
|
|
18
|
+
const hooks = (list: Message[]): Message[] => {
|
|
19
|
+
const anchored = placePersistedReplyAnchors(list) ?? list;
|
|
20
|
+
return placePersistedMessages(anchored, TODO_TYPES) ?? anchored;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const label = (list: Message[]) => list.map((message) =>
|
|
24
|
+
message.customType === REPLY_LANGUAGE_ANCHOR_TYPE ? "ANCHOR"
|
|
25
|
+
: message.customType ? message.customType.replace("gentle-todo-", "")
|
|
26
|
+
: message.role === "assistant" && message.content === "call" ? "A(call)"
|
|
27
|
+
: message.role === "assistant" ? "A" : message.role).join(" ");
|
|
28
|
+
|
|
29
|
+
const sys: Message = { role: "system", content: "s", timestamp: 0 };
|
|
30
|
+
const user: Message = { role: "user", content: "u", timestamp: 1 };
|
|
31
|
+
const call: Message = { role: "assistant", content: "call", timestamp: 2 };
|
|
32
|
+
const result: Message = { role: "toolResult", content: "r", timestamp: 3 };
|
|
33
|
+
const wake: Message = { role: "user", content: "[System-generated wake", timestamp: 4 };
|
|
34
|
+
const call2: Message = { role: "assistant", content: "call", timestamp: 20 };
|
|
35
|
+
const result2: Message = { role: "toolResult", content: "r", timestamp: 21 };
|
|
36
|
+
// Request k carried [sys, user, call, result, wake, ANCHOR (after wake), reminder (after the anchor)].
|
|
37
|
+
const anchor: Message = { role: "custom", customType: REPLY_LANGUAGE_ANCHOR_TYPE, content: "a", display: false, details: { after: key(wake), at: 10 }, timestamp: 10 };
|
|
38
|
+
const reminder: Message = { role: "custom", customType: "gentle-todo-reminder", content: "r", display: false, details: { after: key(anchor), at: 11 }, timestamp: 11 };
|
|
39
|
+
// Pi saves both after the reply and its tool results, stamped later.
|
|
40
|
+
const savedAnchor: Message = { ...anchor, timestamp: 22 };
|
|
41
|
+
const savedReminder: Message = { ...reminder, timestamp: 23 };
|
|
42
|
+
|
|
43
|
+
test("P1b placement: after a wake, the saved anchor and reminder both return to their place in order", () => {
|
|
44
|
+
assert.equal(label(hooks([sys, user, call, result, wake, call2, result2, savedAnchor, savedReminder])), "system user A(call) toolResult user ANCHOR reminder A(call) toolResult");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("P1b placement: when compaction removed the message they followed, both stay put", () => {
|
|
48
|
+
const summary: Message = { role: "compactionSummary", summary: "s", timestamp: 30 };
|
|
49
|
+
const compacted = [sys, summary, call2, result2, savedAnchor, savedReminder];
|
|
50
|
+
assert.equal(label(hooks(compacted)), "system compactionSummary A(call) toolResult ANCHOR reminder");
|
|
51
|
+
assert.equal(placePersistedMessages(compacted, ALL_TYPES), undefined, "nothing moves");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("P1b placement: after parallel tool results that share a timestamp, the reminder goes after the last one", () => {
|
|
55
|
+
const parallel: Message = { role: "assistant", content: "call", timestamp: 40 };
|
|
56
|
+
const first: Message = { role: "toolResult", content: "a", timestamp: 41 };
|
|
57
|
+
const second: Message = { role: "toolResult", content: "b", timestamp: 41 };
|
|
58
|
+
const saved: Message = { role: "custom", customType: "gentle-todo-reminder", content: "r", details: { after: key(second), at: 42 }, timestamp: 50 };
|
|
59
|
+
const placed = hooks([sys, user, parallel, first, second, call2, result2, saved]);
|
|
60
|
+
assert.equal(label(placed), "system user A(call) toolResult toolResult reminder A(call) toolResult");
|
|
61
|
+
assert.equal(placed[4], second, "never between a tool call and one of its results");
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("P1b placement: after a branch switch the message it followed is on the other branch, so it stays put", () => {
|
|
65
|
+
const branch = [sys, user, { role: "assistant", content: "other", timestamp: 60 }, savedReminder];
|
|
66
|
+
assert.equal(label(hooks(branch)), "system user A reminder");
|
|
67
|
+
assert.equal(placePersistedMessages(branch, ALL_TYPES), undefined);
|
|
68
|
+
assert.equal(placePersistedMessages([sys, user], ALL_TYPES), undefined, "no saved copy on this branch: nothing to do");
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("P1b placement: an anchor saved before P1b, following a reminder that was never saved, stays put", () => {
|
|
72
|
+
const legacy: Message = { ...savedAnchor, details: { after: "custom|gentle-todo-reminder|999", at: 10 } };
|
|
73
|
+
assert.equal(label(hooks([sys, user, call, result, wake, call2, result2, legacy])), "system user A(call) toolResult user A(call) toolResult ANCHOR");
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
/** Deterministic linear congruential generator, so every run checks the same lists. */
|
|
77
|
+
function random(seed: number) {
|
|
78
|
+
let state = seed;
|
|
79
|
+
return (n: number) => {
|
|
80
|
+
state = (state * 1103515245 + 12345) & 0x7fffffff;
|
|
81
|
+
// The low bits of this generator repeat with a short period; use the high ones.
|
|
82
|
+
return (state >>> 16) % n;
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* A transcript shaped like the hooks produce it: a system head, then users, plain assistants, tool batches
|
|
88
|
+
* (results may share a timestamp), unrelated custom messages and saved copies. A saved copy records a message
|
|
89
|
+
* that could have been its request's tail (never a tool call, never a result before the batch's last one),
|
|
90
|
+
* each tail at most once, or a message compaction removed.
|
|
91
|
+
*/
|
|
92
|
+
function transcript(next: (n: number) => number): Message[] {
|
|
93
|
+
let clock = 100;
|
|
94
|
+
const list: Message[] = [{ role: "system", content: "s", timestamp: 0 }];
|
|
95
|
+
const tails: Message[] = [list[0]!];
|
|
96
|
+
const blocks = 1 + next(14);
|
|
97
|
+
for (let block = 0; block < blocks; block++) {
|
|
98
|
+
const kind = next(6);
|
|
99
|
+
if (kind === 0) list.push({ role: "user", content: "u", timestamp: ++clock });
|
|
100
|
+
else if (kind === 1) list.push({ role: "assistant", content: [{ type: "text", text: "ok" }], timestamp: ++clock });
|
|
101
|
+
else if (kind === 2) {
|
|
102
|
+
const ids = Array.from({ length: 1 + next(3) }, (_, index) => `c${clock}-${index}`);
|
|
103
|
+
list.push({ role: "assistant", content: ids.map((id) => ({ type: "toolCall", id })), timestamp: ++clock });
|
|
104
|
+
const shared = next(2) === 0 ? ++clock : undefined;
|
|
105
|
+
for (const id of ids) list.push({ role: "toolResult", toolCallId: id, content: "r", timestamp: shared ?? ++clock });
|
|
106
|
+
} else if (kind === 3) list.push({ role: "custom", customType: "other", content: "x", timestamp: ++clock });
|
|
107
|
+
else {
|
|
108
|
+
const customType = [...ALL_TYPES][next(ALL_TYPES.size)]!;
|
|
109
|
+
const at = ++clock;
|
|
110
|
+
// Mostly an earlier tail, as Pi appends the saved copy after the reply that followed its request.
|
|
111
|
+
const pick = tails.length > 0 && next(5) !== 0 ? tails.splice(next(Math.max(1, tails.length - (next(4) === 0 ? 0 : 1))), 1)[0]! : undefined;
|
|
112
|
+
const after = pick === undefined ? "gone|x|1" : pick.role === "custom" && pick.details ? `custom|${pick.customType}|${(pick.details as { at: number }).at}` : key(pick);
|
|
113
|
+
// Already in place (stamped with `at`) or saved later by Pi; some carry no placement (saved by an earlier version).
|
|
114
|
+
const message: Message = { role: "custom", customType, content: "x", timestamp: next(2) === 0 ? at : ++clock };
|
|
115
|
+
if (next(4) !== 0) message.details = { after, at };
|
|
116
|
+
list.push(message);
|
|
117
|
+
}
|
|
118
|
+
const last = list.at(-1)!;
|
|
119
|
+
if (!(last.role === "assistant" && Array.isArray(last.content) && (last.content as Array<{ type: string }>).some((part) => part.type === "toolCall"))) tails.push(last);
|
|
120
|
+
}
|
|
121
|
+
return list;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const isPlacement = (message: Message) => message.role === "custom" && typeof message.customType === "string" && ALL_TYPES.has(message.customType) && message.details !== undefined;
|
|
125
|
+
|
|
126
|
+
test("P1b placement property: over seeded random transcripts the helper keeps the protocol and is idempotent", () => {
|
|
127
|
+
const next = random(7);
|
|
128
|
+
let moved = 0;
|
|
129
|
+
for (let iteration = 0; iteration < 5000; iteration++) {
|
|
130
|
+
const input = transcript(next);
|
|
131
|
+
const frozen = JSON.stringify(input);
|
|
132
|
+
const placed = placePersistedMessages(input, ALL_TYPES);
|
|
133
|
+
const output = placed ?? input;
|
|
134
|
+
if (placed !== undefined) moved++;
|
|
135
|
+
const where = `case ${iteration}: ${frozen}`;
|
|
136
|
+
assert.equal(JSON.stringify(input), frozen, `input not mutated, ${where}`);
|
|
137
|
+
assert.equal(output.length, input.length, where);
|
|
138
|
+
assert.equal(output[0], input[0], `the first message never moves, ${where}`);
|
|
139
|
+
assert.deepEqual(output.filter((message) => !isPlacement(message)), input.filter((message) => !isPlacement(message)), `other messages keep their order, ${where}`);
|
|
140
|
+
output.forEach((message, index) => {
|
|
141
|
+
if (message.role !== "assistant" || !Array.isArray(message.content)) return;
|
|
142
|
+
const ids = (message.content as Array<{ type: string; id?: string }>).filter((part) => part.type === "toolCall").map((part) => part.id);
|
|
143
|
+
ids.forEach((id, offset) => assert.equal(output[index + 1 + offset]?.toolCallId, id, `no message between a tool call and its results, ${where}`));
|
|
144
|
+
});
|
|
145
|
+
assert.equal(placePersistedMessages(output, ALL_TYPES), undefined, `a second call changes nothing, ${where}`);
|
|
146
|
+
}
|
|
147
|
+
assert.ok(moved > 500, `the generated lists exercise placement (${moved} moved)`);
|
|
148
|
+
});
|