@caupulican/pi-adaptative 0.81.38 → 0.81.39
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/CHANGELOG.md +79 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +18 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +131 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +196 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +308 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +22 -2
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +585 -24
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +749 -27
- package/dist/bundled-resources/runtimes/pi-shell-engine/commands/__init__.py +43 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +270 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +252 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +399 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +575 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +52 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +49 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +734 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +238 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +132 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +116 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +287 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +137 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +100 -0
- package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +579 -0
- package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +19 -9
- package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +22 -5
- package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +5 -5
- package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +28 -7
- package/dist/cli/args.d.ts +3 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +15 -0
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-paths.d.ts +49 -0
- package/dist/core/agent-paths.d.ts.map +1 -0
- package/dist/core/agent-paths.js +107 -0
- package/dist/core/agent-paths.js.map +1 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +3 -3
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +234 -17
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +484 -62
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +9 -0
- package/dist/core/autonomy/contracts.d.ts.map +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/lane-tracker.d.ts +10 -1
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tracker.js +5 -1
- package/dist/core/autonomy/lane-tracker.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +122 -6
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +446 -89
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/bash-execution-controller.d.ts +4 -0
- package/dist/core/bash-execution-controller.d.ts.map +1 -1
- package/dist/core/bash-execution-controller.js +7 -1
- package/dist/core/bash-execution-controller.js.map +1 -1
- package/dist/core/compaction-support.d.ts +13 -3
- package/dist/core/compaction-support.d.ts.map +1 -1
- package/dist/core/compaction-support.js +43 -7
- package/dist/core/compaction-support.js.map +1 -1
- package/dist/core/context/context-audit.d.ts +33 -1
- package/dist/core/context/context-audit.d.ts.map +1 -1
- package/dist/core/context/context-audit.js +31 -5
- package/dist/core/context/context-audit.js.map +1 -1
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +16 -1
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +26 -4
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +137 -14
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost-guard.d.ts +19 -3
- package/dist/core/cost-guard.d.ts.map +1 -1
- package/dist/core/cost-guard.js +18 -3
- package/dist/core/cost-guard.js.map +1 -1
- package/dist/core/delegation/session-worker-result.d.ts +34 -4
- package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
- package/dist/core/delegation/session-worker-result.js +64 -4
- package/dist/core/delegation/session-worker-result.js.map +1 -1
- package/dist/core/delegation/worker-result.d.ts +42 -1
- package/dist/core/delegation/worker-result.d.ts.map +1 -1
- package/dist/core/delegation/worker-result.js +68 -0
- package/dist/core/delegation/worker-result.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +20 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +1 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +51 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/goal-loop-controller.d.ts +17 -1
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +79 -11
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/goal-continuation-controller.d.ts +48 -2
- package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-controller.js +77 -0
- package/dist/core/goals/goal-continuation-controller.js.map +1 -1
- package/dist/core/goals/goal-continuation-defaults.d.ts +39 -0
- package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-defaults.js +42 -0
- package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.d.ts +4 -0
- package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.js +51 -10
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.d.ts +101 -2
- package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.js +87 -4
- package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
- package/dist/core/goals/goal-state.d.ts +89 -1
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +71 -5
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +56 -2
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +111 -5
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/goals/session-goal-state.d.ts +11 -2
- package/dist/core/goals/session-goal-state.d.ts.map +1 -1
- package/dist/core/goals/session-goal-state.js +32 -17
- package/dist/core/goals/session-goal-state.js.map +1 -1
- package/dist/core/keybindings.d.ts +10 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +10 -2
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/learning/observation-store.d.ts +12 -3
- package/dist/core/learning/observation-store.d.ts.map +1 -1
- package/dist/core/learning/observation-store.js +30 -15
- package/dist/core/learning/observation-store.js.map +1 -1
- package/dist/core/learning/skill-curator.d.ts +5 -1
- package/dist/core/learning/skill-curator.d.ts.map +1 -1
- package/dist/core/learning/skill-curator.js +21 -19
- package/dist/core/learning/skill-curator.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts +65 -3
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +186 -26
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts +1 -1
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +6 -6
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/model-capability.d.ts +34 -0
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +42 -1
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-router/tool-escalation.d.ts +15 -0
- package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
- package/dist/core/model-router/tool-escalation.js +23 -1
- package/dist/core/model-router/tool-escalation.js.map +1 -1
- package/dist/core/model-router-controller.d.ts +34 -7
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +95 -16
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/models/adaptation-store.d.ts +7 -0
- package/dist/core/models/adaptation-store.d.ts.map +1 -1
- package/dist/core/models/adaptation-store.js +47 -11
- package/dist/core/models/adaptation-store.js.map +1 -1
- package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
- package/dist/core/models/default-model-suggestions.js +17 -0
- package/dist/core/models/default-model-suggestions.js.map +1 -1
- package/dist/core/models/fitness-store.d.ts +3 -0
- package/dist/core/models/fitness-store.d.ts.map +1 -1
- package/dist/core/models/fitness-store.js +11 -2
- package/dist/core/models/fitness-store.js.map +1 -1
- package/dist/core/models/llamacpp-runtime.d.ts +180 -0
- package/dist/core/models/llamacpp-runtime.d.ts.map +1 -0
- package/dist/core/models/llamacpp-runtime.js +475 -0
- package/dist/core/models/llamacpp-runtime.js.map +1 -0
- package/dist/core/models/local-registration.d.ts +40 -0
- package/dist/core/models/local-registration.d.ts.map +1 -1
- package/dist/core/models/local-registration.js +94 -5
- package/dist/core/models/local-registration.js.map +1 -1
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +6 -5
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/model-ref.d.ts +7 -0
- package/dist/core/models/model-ref.d.ts.map +1 -1
- package/dist/core/models/model-ref.js +26 -0
- package/dist/core/models/model-ref.js.map +1 -1
- package/dist/core/models/needle-runtime.d.ts +257 -0
- package/dist/core/models/needle-runtime.d.ts.map +1 -0
- package/dist/core/models/needle-runtime.js +519 -0
- package/dist/core/models/needle-runtime.js.map +1 -0
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts +89 -0
- package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -0
- package/dist/core/models/prism-llamacpp-lifecycle.js +121 -0
- package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +11 -10
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/process-matrix/codes.d.ts +72 -0
- package/dist/core/process-matrix/codes.d.ts.map +1 -0
- package/dist/core/process-matrix/codes.js +15 -0
- package/dist/core/process-matrix/codes.js.map +1 -0
- package/dist/core/process-matrix/runtime.d.ts +63 -0
- package/dist/core/process-matrix/runtime.d.ts.map +1 -0
- package/dist/core/process-matrix/runtime.js +310 -0
- package/dist/core/process-matrix/runtime.js.map +1 -0
- package/dist/core/process-matrix/store.d.ts +22 -0
- package/dist/core/process-matrix/store.d.ts.map +1 -0
- package/dist/core/process-matrix/store.js +80 -0
- package/dist/core/process-matrix/store.js.map +1 -0
- package/dist/core/process-matrix/supervisor.d.ts +72 -0
- package/dist/core/process-matrix/supervisor.d.ts.map +1 -0
- package/dist/core/process-matrix/supervisor.js +130 -0
- package/dist/core/process-matrix/supervisor.js.map +1 -0
- package/dist/core/profile-registry.d.ts +7 -0
- package/dist/core/profile-registry.d.ts.map +1 -1
- package/dist/core/profile-registry.js +20 -0
- package/dist/core/profile-registry.js.map +1 -1
- package/dist/core/python-runtime.d.ts.map +1 -1
- package/dist/core/python-runtime.js +3 -3
- package/dist/core/python-runtime.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +29 -5
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +215 -126
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/reload-blockers.d.ts +36 -0
- package/dist/core/reload-blockers.d.ts.map +1 -1
- package/dist/core/reload-blockers.js +44 -0
- package/dist/core/reload-blockers.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +8 -7
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +58 -5
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +209 -25
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +6 -0
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +66 -52
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -3
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-role.d.ts +31 -0
- package/dist/core/session-role.d.ts.map +1 -0
- package/dist/core/session-role.js +52 -0
- package/dist/core/session-role.js.map +1 -0
- package/dist/core/settings-manager.d.ts +42 -3
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +94 -60
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +12 -0
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +6 -0
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +14 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +20 -3
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/session-task-state.d.ts +11 -2
- package/dist/core/tasks/session-task-state.d.ts.map +1 -1
- package/dist/core/tasks/session-task-state.js +27 -11
- package/dist/core/tasks/session-task-state.js.map +1 -1
- package/dist/core/tasks/task-contract-monitor.d.ts +45 -0
- package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -0
- package/dist/core/tasks/task-contract-monitor.js +56 -0
- package/dist/core/tasks/task-contract-monitor.js.map +1 -0
- package/dist/core/tasks/task-state.d.ts +8 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +28 -1
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tool-gate-controller.d.ts.map +1 -1
- package/dist/core/tool-gate-controller.js +5 -0
- package/dist/core/tool-gate-controller.js.map +1 -1
- package/dist/core/tool-recovery-log-records.d.ts +7 -0
- package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
- package/dist/core/tool-recovery-log-records.js +14 -6
- package/dist/core/tool-recovery-log-records.js.map +1 -1
- package/dist/core/tool-selection/promotion.d.ts +54 -0
- package/dist/core/tool-selection/promotion.d.ts.map +1 -0
- package/dist/core/tool-selection/promotion.js +81 -0
- package/dist/core/tool-selection/promotion.js.map +1 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts +37 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-performance-store.js +87 -3
- package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
- package/dist/core/tool-selection/tool-selection-controller.d.ts +45 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
- package/dist/core/tool-selection/tool-selection-controller.js +96 -0
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
- package/dist/core/tools/bash.d.ts +18 -0
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +95 -16
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate-status.d.ts +14 -0
- package/dist/core/tools/delegate-status.d.ts.map +1 -1
- package/dist/core/tools/delegate-status.js +82 -7
- package/dist/core/tools/delegate-status.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +25 -8
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/goal.d.ts +94 -3
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +165 -15
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/model-fitness.d.ts +7 -0
- package/dist/core/tools/model-fitness.d.ts.map +1 -1
- package/dist/core/tools/model-fitness.js +2 -2
- package/dist/core/tools/model-fitness.js.map +1 -1
- package/dist/core/tools/shell-contract-router.d.ts +6 -1
- package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
- package/dist/core/tools/shell-contract-router.js +23 -2
- package/dist/core/tools/shell-contract-router.js.map +1 -1
- package/dist/core/tools/shell-session.d.ts +89 -0
- package/dist/core/tools/shell-session.d.ts.map +1 -0
- package/dist/core/tools/shell-session.js +432 -0
- package/dist/core/tools/shell-session.js.map +1 -0
- package/dist/core/tools/task-steps.d.ts +4 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +63 -8
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/tmux-dispatch.d.ts +86 -0
- package/dist/core/tools/tmux-dispatch.d.ts.map +1 -0
- package/dist/core/tools/tmux-dispatch.js +91 -0
- package/dist/core/tools/tmux-dispatch.js.map +1 -0
- package/dist/core/tools/windows-shell-engine.d.ts +42 -0
- package/dist/core/tools/windows-shell-engine.d.ts.map +1 -0
- package/dist/core/tools/windows-shell-engine.js +153 -0
- package/dist/core/tools/windows-shell-engine.js.map +1 -0
- package/dist/core/tools/windows-shell-state.d.ts +40 -0
- package/dist/core/tools/windows-shell-state.d.ts.map +1 -0
- package/dist/core/tools/windows-shell-state.js +59 -0
- package/dist/core/tools/windows-shell-state.js.map +1 -0
- package/dist/core/tools/worktree-sync.d.ts +24 -0
- package/dist/core/tools/worktree-sync.d.ts.map +1 -0
- package/dist/core/tools/worktree-sync.js +338 -0
- package/dist/core/tools/worktree-sync.js.map +1 -0
- package/dist/core/trust-manager.d.ts +4 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +20 -2
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/util/atomic-file.d.ts +55 -0
- package/dist/core/util/atomic-file.d.ts.map +1 -0
- package/dist/core/util/atomic-file.js +255 -0
- package/dist/core/util/atomic-file.js.map +1 -0
- package/dist/core/util/minimatch-cache.d.ts +33 -0
- package/dist/core/util/minimatch-cache.d.ts.map +1 -0
- package/dist/core/util/minimatch-cache.js +0 -0
- package/dist/core/util/minimatch-cache.js.map +1 -0
- package/dist/core/worktree-sync/codes.d.ts +227 -0
- package/dist/core/worktree-sync/codes.d.ts.map +1 -0
- package/dist/core/worktree-sync/codes.js +14 -0
- package/dist/core/worktree-sync/codes.js.map +1 -0
- package/dist/core/worktree-sync/git-engine.d.ts +156 -0
- package/dist/core/worktree-sync/git-engine.d.ts.map +1 -0
- package/dist/core/worktree-sync/git-engine.js +1191 -0
- package/dist/core/worktree-sync/git-engine.js.map +1 -0
- package/dist/core/worktree-sync/lane-gate.d.ts +75 -0
- package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -0
- package/dist/core/worktree-sync/lane-gate.js +360 -0
- package/dist/core/worktree-sync/lane-gate.js.map +1 -0
- package/dist/core/worktree-sync/runtime.d.ts +47 -0
- package/dist/core/worktree-sync/runtime.d.ts.map +1 -0
- package/dist/core/worktree-sync/runtime.js +96 -0
- package/dist/core/worktree-sync/runtime.js.map +1 -0
- package/dist/core/worktree-sync/store.d.ts +69 -0
- package/dist/core/worktree-sync/store.d.ts.map +1 -0
- package/dist/core/worktree-sync/store.js +247 -0
- package/dist/core/worktree-sync/store.js.map +1 -0
- package/dist/core/worktree-sync/watcher.d.ts +29 -0
- package/dist/core/worktree-sync/watcher.d.ts.map +1 -0
- package/dist/core/worktree-sync/watcher.js +93 -0
- package/dist/core/worktree-sync/watcher.js.map +1 -0
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +94 -0
- package/dist/main.js.map +1 -1
- package/dist/migrations.d.ts +9 -0
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +38 -0
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.d.ts +16 -1
- package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
- package/dist/modes/interactive/auto-learn-controller.js +50 -8
- package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
- package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/profile-resource-editor.js +23 -1
- package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +4 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts +43 -0
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +290 -3
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +24 -4
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/dist/utils/fs-watch.d.ts +11 -0
- package/dist/utils/fs-watch.d.ts.map +1 -1
- package/dist/utils/fs-watch.js +20 -2
- package/dist/utils/fs-watch.js.map +1 -1
- package/dist/utils/highlight-js-languages.d.ts +4 -0
- package/dist/utils/highlight-js-languages.d.ts.map +1 -0
- package/dist/utils/highlight-js-languages.js +573 -0
- package/dist/utils/highlight-js-languages.js.map +1 -0
- package/dist/utils/shell.d.ts +7 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +21 -6
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +53 -5
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +112 -1
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/process-matrix.md +120 -0
- package/docs/settings.md +3 -0
- package/docs/tmux-agent-manager.md +85 -2
- package/docs/windows.md +52 -3
- package/docs/work-directory.md +29 -0
- package/docs/worktree-sync.md +250 -0
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +10 -4
- package/docs/integration-sweep-builder-blueprint-2026-07-09.md +0 -365
- package/docs/integration-sweep-resume-2026-07-09.md +0 -407
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-pipeline.js","sourceRoot":"","sources":["../../src/core/context-pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAGH,OAAO,EAEN,qBAAqB,EACrB,wBAAwB,EAGxB,WAAW,GACX,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,YAAY,EAAkC,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACrH,OAAO,EAAsB,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAC7F,OAAO,EAA2B,eAAe,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAgC,MAAM,yCAAyC,CAAC;AAC5G,OAAO,EACN,sBAAsB,EAGtB,gBAAgB,GAChB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,E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;QACvB,MAAM,UAAU,GAAI,OAAiC,CAAC,OAAO,CAAC;QAC9D,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE,CAAC;YACpC,KAAK,IAAI,UAAU,CAAC,MAAM,CAAC;YAC3B,SAAS;QACV,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC;YAChC,SAAS;QACV,CAAC;QACD,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE,CAAC;YAChC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC/B,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC;gBACtB,SAAS;YACV,CAAC;YACD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBACzC,SAAS;YACV,CAAC;YACD,IAAI,OAAQ,KAA4B,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC5D,KAAK,IAAK,KAA2B,CAAC,IAAI,EAAE,MAAM,IAAI,CAAC,CAAC;YACzD,CAAC;YACD,IAAI,OAAQ,KAAgC,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;gBACpE,KAAK,IAAK,KAA+B,CAAC,QAAQ,EAAE,MAAM,IAAI,CAAC,CAAC;YACjE,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["/**\n * Context pipeline: the session's per-turn context-shaping subsystem — the observe-only context\n * audit, the shadow prompt-policy plan and its correlation with legacy context-gc, the enforcement\n * pilot, the relevance-curation queue + the fitness-gated curation model resolver / brain-curation\n * drain + compaction pre-digest, the legacy context-gc pass and its packed-artifact reference\n * release, the tool-output artifact store, and the current-context token estimate.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the latest\n * audit/policy/correlation/enforcement/gc reports, the {@link BrainCurator} sidecar and its last\n * skip reasons, and the lazily-built tool-artifact store. Everything else it needs — the turn\n * index, the session/settings managers, the model registry, agent/workspace dirs, the active tool\n * names, the disposed flag, the isolated-completion primitive, spawned-usage accounting, and the\n * live {@link MemoryManager} — is reached through narrow deps accessors rather than the whole\n * AgentSession.\n *\n * Context-transform boundary (deliberate): the per-turn stages ({@link estimateCurrentContextTokens},\n * {@link runContextAudit}, {@link runPromptPolicyPlanning}, {@link applyContextGc},\n * {@link correlatePromptPolicyWithContextGc}, {@link runPromptEnforcement},\n * {@link enqueueRelevanceCuration}, {@link maybeDrainBrainCuration}) are invoked from the session's\n * context transform as one-line delegations, so the transform stays the single owner of the pass\n * ordering. This controller reaches {@link MemoryController} functionality only through\n * {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports\n * the pipeline — keeping the transform the one place the two subsystems meet.\n */\n\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport {\n\ttype CompactionEntry,\n\testimateContextTokens,\n\tgetLatestCompactionEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n\tTokenBudget,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session.ts\";\nimport { BrainCurator, type CurationTelemetrySnapshot, preDigestConversationText } from \"./context/brain-curator.ts\";\nimport { type ArtifactStore, createFileArtifactStore } from \"./context/context-artifacts.ts\";\nimport { type ContextAuditReport, runContextAudit } from \"./context/context-audit.ts\";\nimport { enforcePromptPolicy, type PromptEnforcementReport } from \"./context/context-prompt-enforcement.ts\";\nimport {\n\tcorrelateWithContextGc,\n\ttype PromptPolicyGcCorrelationReport,\n\ttype PromptPolicyShadowReport,\n\tplanPromptPolicy,\n} from \"./context/context-prompt-policy.ts\";\nimport { acquireContextStoreRetention, type ContextStoreRetentionLease } from \"./context/context-store-retention.ts\";\nimport { applyContextGc, type ContextGcReport } from \"./context-gc.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport { HF_TRANSFORMERS_PROVIDER, OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\nfunction joinTextPrefix(content: readonly unknown[], maxChars = Number.POSITIVE_INFINITY): string {\n\tlet found = false;\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null || (part as { type?: unknown }).type !== \"text\") continue;\n\t\tconst blockText = (part as { text?: unknown }).text;\n\t\tif (typeof blockText !== \"string\") continue;\n\t\tif (!found) {\n\t\t\tfound = true;\n\t\t\tif (blockText.length >= maxChars) return blockText.slice(0, maxChars);\n\t\t\ttext = blockText;\n\t\t\tcontinue;\n\t\t}\n\t\tconst available = maxChars - text.length;\n\t\tif (available <= 0) return text;\n\t\tif (available === 1) return `${text}\\n`;\n\t\tconst remaining = available - 1;\n\t\ttext += `\\n${blockText.slice(0, remaining)}`;\n\t\tif (blockText.length >= remaining) return text;\n\t}\n\treturn text;\n}\n\n/** Latest user prompt text in the provider-visible array. */\nexport function latestUserPromptText(messages: AgentMessage[], maxChars = Number.POSITIVE_INFINITY): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tif (typeof message.content === \"string\") {\n\t\t\treturn message.content.length > maxChars ? message.content.slice(0, maxChars) : message.content;\n\t\t}\n\t\tconst text = joinTextPrefix(message.content, maxChars);\n\t\tif (text.length > 0) return text;\n\t}\n\treturn \"\";\n}\n\n/** Read a packed artifact-producing tool result's `details.artifactId`, if present, without `any`. */\nfunction extractArtifactId(message: AgentMessage | undefined): string | undefined {\n\tif (!message || message.role !== \"toolResult\") return undefined;\n\tconst details = (message as { details?: unknown }).details;\n\tif (typeof details !== \"object\" || details === null) return undefined;\n\tconst artifactId = (details as { artifactId?: unknown }).artifactId;\n\treturn typeof artifactId === \"string\" ? artifactId : undefined;\n}\n\nexport interface ContextPipelineDeps {\n\t/** Current turn index, stamped into audit/policy/enforcement reports. */\n\tgetTurnIndex(): number;\n\t/** Session log: audit lookup, gc/artifact storage dirs, curation entries, token-estimate compaction anchor. */\n\tgetSessionManager(): SessionManager;\n\t/** Context-gc / prompt-enforcement / curation settings (all opt-in gates). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured curation model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Foreground model currently executing the transformed request. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Root dir the host-keyed {@link FitnessStore} and per-session gc/artifact storage live under. */\n\tgetAgentDir(): string;\n\t/** Workspace root, passed to the context-gc pass. */\n\tgetCwd(): string;\n\t/** Currently-active tool names — enforcement checks whether artifact_retrieve is a live affordance. */\n\tgetActiveToolNames(): string[];\n\t/** A disposed session must never persist a curation/pre-digest entry. */\n\tisDisposed(): boolean;\n\t/** The live memory manager — the active providers' page markers feed the semantic-gc scan. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Roll a curation drain's spawned usage into session accounting (idempotent per reportId). */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts?: { label?: string; sourceSessionId?: string; reportId?: string },\n\t): string | undefined;\n\t/** One-shot LLM call fully isolated from the main session — the curation/pre-digest execution primitive. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n}\n\nexport class ContextPipeline {\n\tprivate _latestContextGcReport: ContextGcReport | undefined = undefined;\n\t/** Brain-curation sidecar (design: brain-context-curation-design.md). Inert unless the\n\t * contextPolicy.curation setting is enabled AND the model passes the digest fitness gate. */\n\tprivate readonly _brainCurator = new BrainCurator();\n\tprivate _lastCurationSkipReason: string | undefined = undefined;\n\tprivate _lastPreDigestSkipReason: string | undefined = undefined;\n\tprivate _toolArtifactStore: ArtifactStore | undefined = undefined;\n\tprivate _contextStoreRetentionLease: ContextStoreRetentionLease | undefined;\n\tprivate _latestContextAuditReport: ContextAuditReport | undefined = undefined;\n\tprivate _latestPromptPolicyReport: PromptPolicyShadowReport | undefined = undefined;\n\tprivate _latestPromptPolicyGcCorrelation: PromptPolicyGcCorrelationReport | undefined = undefined;\n\tprivate _latestPromptEnforcementReport: PromptEnforcementReport | undefined = undefined;\n\tprivate readonly _tokenBudget = new TokenBudget();\n\tprivate _hasTokenBudgetAnchor = false;\n\tprivate _tokenBudgetAnchorCompactionId: string | undefined = undefined;\n\tprivate _lastTokenBudgetAnchorKey: string | undefined = undefined;\n\t/** Incremental current-branch lookup used by the per-turn audit. It retains only tool calls\n\t * still present in the provider-visible context, so compaction also bounds this cache. */\n\tprivate _sessionEntryLookupCache: { leafId: string | null; byToolCallId: Map<string, string> } | undefined =\n\t\tundefined;\n\n\tprivate readonly deps: ContextPipelineDeps;\n\n\tconstructor(deps: ContextPipelineDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate _ensureContextStoreRetention(): ContextStoreRetentionLease {\n\t\tif (!this._contextStoreRetentionLease) {\n\t\t\tthis._contextStoreRetentionLease = acquireContextStoreRetention(\n\t\t\t\tthis.deps.getAgentDir(),\n\t\t\t\tthis.deps.getSessionManager().getSessionId(),\n\t\t\t);\n\t\t}\n\t\treturn this._contextStoreRetentionLease;\n\t}\n\n\tprivate _contextGcStorageDir(): string {\n\t\treturn this._ensureContextStoreRetention().gcDir;\n\t}\n\n\tprivate _toolArtifactsDir(): string {\n\t\treturn this._ensureContextStoreRetention().artifactsDir;\n\t}\n\n\t/**\n\t * Session-scoped, filesystem-backed artifact store for first-capture-then-bound tool\n\t * output (grep/find/run_toolkit_script -- see tool-output-artifacts.md). Lazily created and\n\t * cached so every tool construction in this session shares one store instance.\n\t *\n\t * `packToolOutput()` registers a reference (the packing tool call's id) at pack time\n\t * and fails closed, so packed artifacts are never prematurely collected.\n\t * `_releaseGcPackedArtifactReferences()` (called from `applyContextGc()`) releases\n\t * that reference once context-gc packs the result out of live context, and\n\t * opportunistically reclaims now-unreferenced artifacts via `cleanup()`.\n\t * Cross-session retention is enforced when either payload store is first used. Active\n\t * sessions hold PID-marked leases; inactive stores are pruned by age, count, and bytes.\n\t */\n\tgetToolArtifactStore(): ArtifactStore {\n\t\tthis._toolArtifactStore ??= createFileArtifactStore({ baseDir: this._toolArtifactsDir() });\n\t\treturn this._toolArtifactStore;\n\t}\n\n\t/**\n\t * Best-effort final sweep of any already-released (zero-reference) tool-output artifact at\n\t * session dispose. Reads the field (not the getter) so a session that never packed anything\n\t * doesn't force-create a store/dir just to sweep it.\n\t */\n\tcleanupToolArtifactStoreOnDispose(): void {\n\t\tthis._toolArtifactStore?.cleanup();\n\t\tthis._contextStoreRetentionLease?.release();\n\t\tthis._contextStoreRetentionLease = undefined;\n\t}\n\n\t/**\n\t * Map tool-result call ids to persisted session-entry ids. Linear branch growth is handled\n\t * incrementally by walking only entries appended since the cached leaf; a branch switch falls\n\t * back to one full rebuild so lookups never leak entries from the abandoned branch.\n\t */\n\tprivate _getLatestCompactionEntry(): CompactionEntry | null {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tlet currentId = leafId;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tconst entry = getEntry(currentId);\n\t\t\t\tif (!entry) break;\n\t\t\t\tif (entry.type === \"compaction\") return entry;\n\t\t\t\tcurrentId = entry.parentId;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\treturn getLatestCompactionEntry(sessionManager.getBranch());\n\t}\n\n\tprivate _buildSessionEntryIdLookup(\n\t\twantedToolCallIds: ReadonlySet<string>,\n\t): (toolCallId: string) => string | undefined {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tconst cached = this._sessionEntryLookupCache;\n\t\tif (cached) {\n\t\t\tfor (const toolCallId of cached.byToolCallId.keys()) {\n\t\t\t\tif (!wantedToolCallIds.has(toolCallId)) cached.byToolCallId.delete(toolCallId);\n\t\t\t}\n\t\t}\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tif (cached?.leafId === leafId) {\n\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t}\n\t\t\tif (cached) {\n\t\t\t\tconst appendedEntries: SessionEntry[] = [];\n\t\t\t\tlet cursor = leafId;\n\t\t\t\twhile (cursor !== null && cursor !== cached.leafId) {\n\t\t\t\t\tconst entry = getEntry(cursor);\n\t\t\t\t\tif (!entry) break;\n\t\t\t\t\tappendedEntries.push(entry);\n\t\t\t\t\tcursor = entry.parentId;\n\t\t\t\t}\n\t\t\t\tif (cursor === cached.leafId) {\n\t\t\t\t\tfor (let index = appendedEntries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = appendedEntries[index];\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcached.byToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcached.leafId = leafId;\n\t\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst byToolCallId = new Map<string, string>();\n\t\tfor (const entry of sessionManager.getBranch()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t) {\n\t\t\t\tbyToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t}\n\t\t}\n\t\tif (leafId !== undefined) this._sessionEntryLookupCache = { leafId, byToolCallId };\n\t\treturn (toolCallId) => byToolCallId.get(toolCallId);\n\t}\n\n\t/**\n\t * Phase 1 observe-only audit pass (see context/context-audit.ts): converts live\n\t * toolResult messages into ContextItems and runs the existing retention/hard-constraint\n\t * evaluators over them, storing the latest deterministic report for tests/debugging.\n\t * Read-only with respect to messages, the transcript, and artifact references -- uses\n\t * `_toolArtifactStore` (the field), not `getToolArtifactStore()` (the getter), so a\n\t * session that never packed anything doesn't force-create a store/dir just to audit.\n\t * Never throws into a live turn: any failure degrades to an empty report.\n\t */\n\trunContextAudit(messages: AgentMessage[]): ContextAuditReport {\n\t\ttry {\n\t\t\tconst wantedToolCallIds = new Set(\n\t\t\t\tmessages.filter((message) => message.role === \"toolResult\").map((message) => message.toolCallId),\n\t\t\t);\n\t\t\tconst report = runContextAudit(messages, {\n\t\t\t\tturnIndex: this.deps.getTurnIndex(),\n\t\t\t\tartifactStore: this._toolArtifactStore,\n\t\t\t\tsessionEntryIdForToolCallId: this._buildSessionEntryIdLookup(wantedToolCallIds),\n\t\t\t});\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: ContextAuditReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the context audit. With `messages`, recomputes fresh against\n\t * the given array (still no mutation of messages/transcript/artifact refs); without,\n\t * returns the last report computed during a real transform pass.\n\t */\n\tgetContextAuditReport(messages?: AgentMessage[]): ContextAuditReport {\n\t\tif (messages) return this.runContextAudit(messages);\n\t\treturn this._latestContextAuditReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Observe-first shadow/planning pass (see context/context-prompt-policy.ts): re-shapes\n\t * the audit report into a per-item policy plan whose `appliedAction` is always\n\t * \"keep_raw\" -- this never enforces anything, it only records what the policy engine\n\t * would say. Never throws into a live turn: any failure degrades to an empty report.\n\t */\n\trunPromptPolicyPlanning(auditReport: ContextAuditReport): PromptPolicyShadowReport {\n\t\ttry {\n\t\t\tconst report = planPromptPolicy(auditReport);\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: PromptPolicyShadowReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the shadow policy plan. With `messages`, recomputes fresh\n\t * (audit + plan) against the given array; without, returns the last plan computed\n\t * during a real transform pass. Never mutates messages/transcript/artifact refs.\n\t */\n\tgetPromptPolicyReport(messages?: AgentMessage[]): PromptPolicyShadowReport {\n\t\tif (messages) return this.runPromptPolicyPlanning(this.runContextAudit(messages));\n\t\treturn this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Report-only correlation between the shadow plan just computed this turn and what the\n\t * legacy context-gc pass actually packed. Runs after `applyContextGc()` has already\n\t * produced its report; never influences context-gc itself. Never throws into a live\n\t * turn: any failure degrades to an empty correlation.\n\t */\n\tcorrelatePromptPolicyWithContextGc(gcReport: ContextGcReport): void {\n\t\tconst shadowReport = this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\ttry {\n\t\t\tthis._latestPromptPolicyGcCorrelation = correlateWithContextGc(shadowReport, gcReport);\n\t\t} catch {\n\t\t\tthis._latestPromptPolicyGcCorrelation = { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest shadow-plan/legacy-gc correlation, for tests/debugging. */\n\tgetPromptPolicyGcCorrelation(): PromptPolicyGcCorrelationReport {\n\t\treturn this._latestPromptPolicyGcCorrelation ?? { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t}\n\n\t/**\n\t * First enforcement pilot (see context/context-prompt-enforcement.ts): opt-in,\n\t * default-disabled stub-in-place of stale artifact-backed tool_output results in the\n\t * provider-visible message array only. Runs on `messages` AFTER context-gc has already\n\t * produced its own result, so legacy context-gc's own packing/reporting is completely\n\t * unaffected by this pass -- it only ever acts on messages gc left untouched this turn.\n\t * Never throws into a live turn: any failure degrades to returning `messages` unchanged.\n\t */\n\trunPromptEnforcement(\n\t\tmessages: AgentMessage[],\n\t\tshadowReport: PromptPolicyShadowReport,\n\t): { messages: AgentMessage[]; report: PromptEnforcementReport } {\n\t\ttry {\n\t\t\tconst persistedSettings = this.deps.getSettingsManager().getContextPromptEnforcementSettings();\n\t\t\tconst curationEnabled = this.deps.getSettingsManager().getContextCurationSettings().enabled;\n\t\t\tconst settings = {\n\t\t\t\t...persistedSettings,\n\t\t\t\t// Runtime fact, never assumed: artifact_retrieve is a companion affordance\n\t\t\t\t// (auto-activated alongside grep/find), not a default/global tool, so active\n\t\t\t\t// tools can differ turn to turn -- see context-prompt-enforcement.ts's doc\n\t\t\t\t// comment on why this is checked separately from hasAvailableRetrievalPath.\n\t\t\t\tretrievalToolAvailable: this.deps.getActiveToolNames().includes(\"artifact_retrieve\"),\n\t\t\t\tbrainRelevance: curationEnabled ? (itemId: string) => this._brainCurator.getRelevance(itemId) : undefined,\n\t\t\t};\n\t\t\tconst result = enforcePromptPolicy(messages, shadowReport, settings);\n\t\t\tthis._latestPromptEnforcementReport = result.report;\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: PromptEnforcementReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptEnforcementReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue relevance-scoring jobs for stale, artifact-backed tool outputs the enforcement\n\t * pilot could act on. Pure queueing — the verdicts only ever take effect through the\n\t * asymmetric advisory lever inside enforcePromptPolicy. Never throws into a turn.\n\t */\n\tenqueueRelevanceCuration(messages: AgentMessage[], shadowReport: PromptPolicyShadowReport): void {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tif (!settings.enabled) return;\n\t\t\tconst goal = latestUserPromptText(messages, 400);\n\t\t\tfor (const item of shadowReport.items) {\n\t\t\t\tif (!item.hasAvailableRetrievalPath) continue;\n\t\t\t\tconst message = messages[item.messageIndex];\n\t\t\t\tif (!message || message.role !== \"toolResult\" || message.toolCallId !== item.toolCallId) continue;\n\t\t\t\tif (message.isError) continue;\n\t\t\t\tconst details = message.details as\n\t\t\t\t\t| { contextGc?: { packed?: unknown }; promptPolicy?: { enforced?: unknown } }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (details?.contextGc?.packed === true || details?.promptPolicy?.enforced === true) continue;\n\t\t\t\tconst text = joinTextPrefix(message.content, 4000);\n\t\t\t\tif (text.length === 0) continue;\n\t\t\t\tthis._brainCurator.enqueue({ kind: \"relevance\", key: item.itemId, content: text, goal });\n\t\t\t}\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Drain gate: settings on, model configured+authed, and the model has PASSED the digest\n\t * fitness probe on THIS host (design: unfit or unprobed models are refused with a visible\n\t * reason, never silently degraded). Fire-and-forget; never throws into a turn.\n\t */\n\t/**\n\t * Resolve the curation model IFF every gate passes: setting enabled, model configured,\n\t * resolvable+authed, and digest-fitness-proven on THIS host (canonical \"provider/id\" ref —\n\t * runModelFitness stores reports under it, while settings.model may be a bare id or pattern).\n\t * Sets _lastCurationSkipReason on refusal; never throws.\n\t */\n\tprivate _effectiveContextWindowFromFitness(model: Model<Api>): number {\n\t\tconst registered = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n\t\tconst capacity = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === `${model.provider}/${model.id}`)?.report.capacity?.servedContextWindow;\n\t\treturn capacity && capacity > 0 ? Math.min(registered, capacity) : registered;\n\t}\n\n\tresolveCurationModelIfFit(): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\tif (!settings.enabled) {\n\t\t\t// Never surface a stale refusal reason for a feature the user has since disabled.\n\t\t\tthis._lastCurationSkipReason = undefined;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!settings.model) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unset\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst resolved = resolveCliModel({ cliModel: settings.model, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unresolved\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst canonicalRef = `${resolved.model.provider}/${resolved.model.id}`;\n\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === canonicalRef);\n\t\tconst verdict = evaluateSurfaceFitness(\"curation\", fitness?.report);\n\t\tif (!verdict.fit) {\n\t\t\tthis._lastCurationSkipReason =\n\t\t\t\tverdict.reason === \"unprobed\" ? \"curation_model_unprobed\" : \"curation_model_digest_unfit\";\n\t\t\treturn undefined;\n\t\t}\n\t\tthis._lastCurationSkipReason = undefined;\n\t\treturn resolved.model;\n\t}\n\n\tmaybeDrainBrainCuration(): void {\n\t\ttry {\n\t\t\tif (!this._brainCurator.hasWork() || this._brainCurator.isDraining) return;\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return;\n\t\t\tconst foregroundModel = this.deps.getModel();\n\t\t\tconst foregroundIsManagedLocal =\n\t\t\t\tforegroundModel?.provider === OLLAMA_PROVIDER || foregroundModel?.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tconst curatorIsManagedLocal =\n\t\t\t\tmodel.provider === OLLAMA_PROVIDER || model.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tif (foregroundIsManagedLocal && curatorIsManagedLocal) {\n\t\t\t\t// Local foreground accuracy/latency wins. A fire-and-forget curator can otherwise reach\n\t\t\t\t// a single-parallel server first and make the user's request wait behind sidecar work.\n\t\t\t\tthis._lastCurationSkipReason = \"curation_deferred_for_local_foreground\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tvoid this._drainBrainCuration(model, settings.maxJobsPerTurn);\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Compaction pre-digest gate (design surface 3): everything the drain gate requires PLUS a\n\t * RUNTIME reliability proof — the curator must have run >=5 jobs on this session with a parse\n\t * failure rate <=5% before it is trusted to pre-digest compaction input. Returns undefined\n\t * (verbatim compaction, byte-for-byte today's behavior) whenever any gate refuses.\n\t */\n\tbuildCompactionPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined {\n\t\ttry {\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return undefined;\n\t\t\tconst telemetry = this._brainCurator.telemetry();\n\t\t\tif (telemetry.jobsRun < 5 || telemetry.parseFailures / telemetry.jobsRun > 0.05) {\n\t\t\t\tthis._lastPreDigestSkipReason = \"curation_predigest_reliability_unproven\";\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tthis._lastPreDigestSkipReason = undefined;\n\t\t\treturn async (text, signal) => {\n\t\t\t\tconst effectiveWindow = this._effectiveContextWindowFromFitness(model);\n\t\t\t\tconst chunkChars = Number.isFinite(effectiveWindow)\n\t\t\t\t\t? Math.max(1_000, Math.floor((effectiveWindow - 1024) * 4))\n\t\t\t\t\t: undefined;\n\t\t\t\tconst result = await preDigestConversationText({\n\t\t\t\t\ttext,\n\t\t\t\t\tsignal,\n\t\t\t\t\tchunkChars,\n\t\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal: chunkSignal }) => {\n\t\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\t\tmaxTokens: 512,\n\t\t\t\t\t\t\tsignal: chunkSignal,\n\t\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (!this.deps.isDisposed() && result.totalChunks > 0) {\n\t\t\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation-predigest\", {\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\ttotalChunks: result.totalChunks,\n\t\t\t\t\t\tdigested: result.digested,\n\t\t\t\t\t\tfailed: result.failed,\n\t\t\t\t\t\tcharsBefore: text.length,\n\t\t\t\t\t\tcharsAfter: result.text.length,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn result.text;\n\t\t\t};\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async _drainBrainCuration(model: Model<Api>, maxJobs: number): Promise<void> {\n\t\ttry {\n\t\t\t// ACCUMULATE across all drained jobs (the drain runs the completer once PER job) —\n\t\t\t// keeping only the last job's usage would under-report every multi-job drain.\n\t\t\tlet spentUsage: AssistantMessage[\"usage\"] | undefined;\n\t\t\tconst results = await this._brainCurator.drain({\n\t\t\t\tmaxJobs,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\tmaxTokens: 256,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Both curation system prompts are static — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t});\n\t\t\t\t\tconst usage = completion.usage;\n\t\t\t\t\tif (!spentUsage) {\n\t\t\t\t\t\tspentUsage = structuredClone(usage);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspentUsage.input += usage.input;\n\t\t\t\t\t\tspentUsage.output += usage.output;\n\t\t\t\t\t\tspentUsage.cacheRead += usage.cacheRead;\n\t\t\t\t\t\tspentUsage.cacheWrite += usage.cacheWrite;\n\t\t\t\t\t\tspentUsage.totalTokens += usage.totalTokens;\n\t\t\t\t\t\tspentUsage.cost.input += usage.cost.input;\n\t\t\t\t\t\tspentUsage.cost.output += usage.cost.output;\n\t\t\t\t\t\tspentUsage.cost.cacheRead += usage.cost.cacheRead;\n\t\t\t\t\t\tspentUsage.cost.cacheWrite += usage.cost.cacheWrite;\n\t\t\t\t\t\tspentUsage.cost.total += usage.cost.total;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\t// Honest accounting even for free local models: token visibility is the contract.\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"context-curator\" });\n\t\t\t}\n\t\t\tif (this.deps.isDisposed() || results.length === 0) return;\n\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation\", {\n\t\t\t\tversion: 1,\n\t\t\t\tresults: results.map((result) => ({\n\t\t\t\t\tkey: result.key,\n\t\t\t\t\tkind: result.kind,\n\t\t\t\t\tok: result.ok,\n\t\t\t\t\tms: result.ms,\n\t\t\t\t\t...(result.digest !== undefined ? { digest: result.digest } : {}),\n\t\t\t\t\t...(result.relevant !== undefined ? { relevant: result.relevant, confidence: result.confidence } : {}),\n\t\t\t\t})),\n\t\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\t});\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/** Curation status for diagnostics/dashboard: settings, live telemetry, last refusal reason. */\n\tgetContextCurationStatus(): {\n\t\tenabled: boolean;\n\t\tmodel?: string;\n\t\ttelemetry: CurationTelemetrySnapshot;\n\t\tlastSkipReason?: string;\n\t\tlastPreDigestSkipReason?: string;\n\t} {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\treturn {\n\t\t\tenabled: settings.enabled,\n\t\t\tmodel: settings.model,\n\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\tlastSkipReason: this._lastCurationSkipReason,\n\t\t\tlastPreDigestSkipReason: this._lastPreDigestSkipReason,\n\t\t};\n\t}\n\n\t/** Read-only inspection of the latest prompt-enforcement report, for tests/debugging. */\n\tgetPromptEnforcementReport(): PromptEnforcementReport {\n\t\treturn this._latestPromptEnforcementReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\tapplyContextGc(\n\t\tmessages: AgentMessage[],\n\t\twritePayloads: boolean,\n\t): { messages: AgentMessage[]; report: ContextGcReport } {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextGcSettings();\n\t\t\t// Merge the ACTIVE memory providers' own page markers (e.g. transcript-recall's\n\t\t\t// \"<memory_context\") into the semantic-memory marker list. The settings default is\n\t\t\t// provider-agnostic and non-empty, so without this merge the recall pages the bundled\n\t\t\t// default provider actually emits are never recognized as semantic-memory pages and\n\t\t\t// accumulate raw for the life of the session — the exact growth Bug #7 GC exists to stop.\n\t\t\tconst providerMarkers = this.deps.getMemoryManager().getContextMarkers();\n\t\t\tconst curationSettings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tconst result = applyContextGc(messages, {\n\t\t\t\t...settings,\n\t\t\t\tsemanticMemory: {\n\t\t\t\t\t...settings.semanticMemory,\n\t\t\t\t\tmarkers: [...new Set([...settings.semanticMemory.markers, ...providerMarkers])],\n\t\t\t\t},\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tstorageDir: this._contextGcStorageDir(),\n\t\t\t\twritePayloads,\n\t\t\t\tcuration: curationSettings.enabled\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tresolveDigest: (digestKey) => {\n\t\t\t\t\t\t\t\tconst digest = this._brainCurator.getDigest(digestKey);\n\t\t\t\t\t\t\t\t// Count serves on the REAL per-turn pass only, never the report path.\n\t\t\t\t\t\t\t\tif (digest !== undefined && writePayloads) this._brainCurator.noteDigestServed();\n\t\t\t\t\t\t\t\treturn digest;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t// Only the real per-turn pass enqueues work; the read-only report path\n\t\t\t\t\t\t\t// (writePayloads=false) stays side-effect free.\n\t\t\t\t\t\t\tonPacked: writePayloads\n\t\t\t\t\t\t\t\t? (record, originalText) => {\n\t\t\t\t\t\t\t\t\t\tthis._brainCurator.enqueue({\n\t\t\t\t\t\t\t\t\t\t\tkind: \"stub_digest\",\n\t\t\t\t\t\t\t\t\t\t\tkey: record.key ?? record.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tcontent: originalText,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t\tthis._latestContextGcReport = result.report;\n\t\t\t// Only release/reclaim on the real per-turn pass (writePayloads=true), never on\n\t\t\t// the read-only status-report path (getContextGcReport with writePayloads=false),\n\t\t\t// so merely inspecting the report can't have side effects.\n\t\t\tif (writePayloads && result.report.packedCount > 0) {\n\t\t\t\tthis._releaseGcPackedArtifactReferences(messages, result.report);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: ContextGcReport = {\n\t\t\t\tenabled: false,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t};\n\t\t\tthis._latestContextGcReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Reference-release + cleanup lifecycle: once context-gc has packed an artifact-producing\n\t * tool result (grep/find/run_toolkit_script) out of the live prompt (the message is no longer current/active working\n\t * context -- see contracts-and-retention.md's \"ephemeral\"/\"expired\" retention\n\t * classes), release the pack-time reference `packToolOutput()` registered for it, and\n\t * opportunistically reclaim now-unreferenced artifacts. This is the other half of the\n\t * D2b-1 gate: artifacts were being registered but never released, so they accumulated\n\t * for the life of the session.\n\t *\n\t * `record.toolCallId` (from context-gc's packed record) is exactly the holder id\n\t * `packToolOutput()` used when it called `addReference()` -- both trace back to the\n\t * same tool call's id -- so no separate bookkeeping is needed to find it.\n\t */\n\tprivate _releaseGcPackedArtifactReferences(messages: AgentMessage[], report: ContextGcReport): void {\n\t\tconst store = this._toolArtifactStore;\n\t\tif (!store) return; // no store was ever constructed, so nothing could have been packed to one\n\n\t\tlet releasedAny = false;\n\t\tfor (const record of report.records) {\n\t\t\tif (record.toolName !== \"grep\" && record.toolName !== \"find\" && record.toolName !== \"run_toolkit_script\")\n\t\t\t\tcontinue;\n\t\t\tconst artifactId = extractArtifactId(messages[record.messageIndex]);\n\t\t\tif (!artifactId) continue;\n\t\t\tif (store.removeReference(artifactId, record.toolCallId)) releasedAny = true;\n\t\t}\n\t\t// Cleanup only runs immediately after a release actually happened in this pass, so\n\t\t// a long session doesn't re-scan the artifact directory on every turn once nothing\n\t\t// new became eligible for release.\n\t\tif (releasedAny) store.cleanup();\n\t}\n\n\tgetContextGcReport(messages?: AgentMessage[]): ContextGcReport {\n\t\tif (messages) return this.applyContextGc(messages, false).report;\n\t\treturn (\n\t\t\tthis._latestContextGcReport ?? {\n\t\t\t\tenabled: this.deps.getSettingsManager().getContextGcSettings().enabled,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t}\n\t\t);\n\t}\n\n\tobserveProviderUsage(messages: AgentMessage[], usageMessage: AssistantMessage): void {\n\t\tif (usageMessage.stopReason === \"error\" || usageMessage.stopReason === \"aborted\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null || messages[estimate.lastUsageIndex] !== usageMessage) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (!compactionEntry) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageMessage.timestamp <= compactionTimestamp) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst coveredChars = estimateConversationChars(messages, 0, estimate.lastUsageIndex + 1);\n\t\tif (estimate.usageTokens <= 0 || coveredChars <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst anchorKey = `${compactionEntry.id}:${usageMessage.timestamp}:${estimate.usageTokens}:${coveredChars}`;\n\t\tif (anchorKey === this._lastTokenBudgetAnchorKey) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._tokenBudget.anchor(estimate.usageTokens, coveredChars);\n\t\tthis._hasTokenBudgetAnchor = true;\n\t\tthis._tokenBudgetAnchorCompactionId = compactionEntry.id;\n\t\tthis._lastTokenBudgetAnchorKey = anchorKey;\n\t}\n\n\testimateCurrentContextTokens(messages: AgentMessage[]): number {\n\t\tconst estimate = estimateContextTokens(messages);\n\t\tif (estimate.lastUsageIndex === null) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tconst usageMessage = messages[estimate.lastUsageIndex];\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (usageMessage?.role !== \"assistant\" || !compactionEntry) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\t\tconst usageTimestamp = (usageMessage as AssistantMessage).timestamp;\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageTimestamp <= compactionTimestamp) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tif (!this._hasTokenBudgetAnchor || this._tokenBudgetAnchorCompactionId !== compactionEntry.id) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\n\t\tconst deltaChars = estimateConversationChars(messages, estimate.lastUsageIndex + 1, messages.length);\n\t\treturn this._tokenBudget.current(deltaChars, estimate.tokens);\n\t}\n}\n\n/**\n * Estimate covered characters from the provider-visible context messages.\n */\nfunction estimateConversationChars(messages: AgentMessage[], start = 0, end = messages.length): number {\n\tlet total = 0;\n\tfor (let index = Math.max(0, start); index < Math.min(messages.length, end); index++) {\n\t\tconst message = messages[index];\n\t\tif (!message) continue;\n\t\tconst rawContent = (message as { content?: unknown }).content;\n\t\tif (typeof rawContent === \"string\") {\n\t\t\ttotal += rawContent.length;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!Array.isArray(rawContent)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const block of rawContent) {\n\t\t\tif (typeof block === \"string\") {\n\t\t\t\ttotal += block.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!block || typeof block !== \"object\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\t\ttotal += (block as { text?: string }).text?.length ?? 0;\n\t\t\t}\n\t\t\tif (typeof (block as { thinking?: unknown }).thinking === \"string\") {\n\t\t\t\ttotal += (block as { thinking?: string }).thinking?.length ?? 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"context-pipeline.js","sourceRoot":"","sources":["../../src/core/context-pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAEN,sBAAsB,EACtB,cAAc,EACd,wBAAwB,EAGxB,WAAW,GACX,MAAM,gCAAgC,CAAC;AAGxC,OAAO,EAAE,YAAY,EAAkC,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACrH,OAAO,EAAsB,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAC7F,OAAO,EAIN,eAAe,GACf,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,mBAAmB,EAAgC,MAAM,yCAAyC,CAAC;AAC5G,OAAO,EACN,sBAAsB,EAGtB,gBAAgB,GAChB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,4BAA4B,EAAmC,MAAM,sCAAsC,CAAC;AACrH,OAAO,EAAE,cAAc,EAAwB,MAAM,iBAAiB,CAAC;AAGvE,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC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AI,CAAC,OAAO;YAAE,SAAS;QACvB,MAAM,UAAU,GAAI,OAAiC,CAAC,OAAO,CAAC;QAC9D,IAAI,OAAO,UAAU,KAAK,QAAQ,EAAE,CAAC;YACpC,KAAK,IAAI,UAAU,CAAC,MAAM,CAAC;YAC3B,SAAS;QACV,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC;YAChC,SAAS;QACV,CAAC;QACD,KAAK,MAAM,KAAK,IAAI,UAAU,EAAE,CAAC;YAChC,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBAC/B,KAAK,IAAI,KAAK,CAAC,MAAM,CAAC;gBACtB,SAAS;YACV,CAAC;YACD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;gBACzC,SAAS;YACV,CAAC;YACD,IAAI,OAAQ,KAA4B,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC5D,KAAK,IAAK,KAA2B,CAAC,IAAI,EAAE,MAAM,IAAI,CAAC,CAAC;YACzD,CAAC;YACD,IAAI,OAAQ,KAAgC,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;gBACpE,KAAK,IAAK,KAA+B,CAAC,QAAQ,EAAE,MAAM,IAAI,CAAC,CAAC;YACjE,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["/**\n * Context pipeline: the session's per-turn context-shaping subsystem — the observe-only context\n * audit, the shadow prompt-policy plan and its correlation with legacy context-gc, the enforcement\n * pilot, the relevance-curation queue + the fitness-gated curation model resolver / brain-curation\n * drain + compaction pre-digest, the legacy context-gc pass and its packed-artifact reference\n * release, the tool-output artifact store, and the current-context token estimate.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the latest\n * audit/policy/correlation/enforcement/gc reports, the {@link BrainCurator} sidecar and its last\n * skip reasons, and the lazily-built tool-artifact store. Everything else it needs — the turn\n * index, the session/settings managers, the model registry, agent/workspace dirs, the active tool\n * names, the disposed flag, the isolated-completion primitive, spawned-usage accounting, and the\n * live {@link MemoryManager} — is reached through narrow deps accessors rather than the whole\n * AgentSession.\n *\n * Context-transform boundary (deliberate): the per-turn stages ({@link estimateCurrentContextTokens},\n * {@link runContextAudit}, {@link runPromptPolicyPlanning}, {@link applyContextGc},\n * {@link correlatePromptPolicyWithContextGc}, {@link runPromptEnforcement},\n * {@link enqueueRelevanceCuration}, {@link maybeDrainBrainCuration}) are invoked from the session's\n * context transform as one-line delegations, so the transform stays the single owner of the pass\n * ordering. This controller reaches {@link MemoryController} functionality only through\n * {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports\n * the pipeline — keeping the transform the one place the two subsystems meet.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport {\n\ttype CompactionEntry,\n\tcalculateContextTokens,\n\testimateTokens,\n\tgetLatestCompactionEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n\tTokenBudget,\n} from \"@caupulican/pi-agent-core/node\";\nimport type { Api, AssistantMessage, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session.ts\";\nimport { BrainCurator, type CurationTelemetrySnapshot, preDigestConversationText } from \"./context/brain-curator.ts\";\nimport { type ArtifactStore, createFileArtifactStore } from \"./context/context-artifacts.ts\";\nimport {\n\ttype ContextAuditMemo,\n\ttype ContextAuditOptions,\n\ttype ContextAuditReport,\n\trunContextAudit,\n} from \"./context/context-audit.ts\";\nimport { enforcePromptPolicy, type PromptEnforcementReport } from \"./context/context-prompt-enforcement.ts\";\nimport {\n\tcorrelateWithContextGc,\n\ttype PromptPolicyGcCorrelationReport,\n\ttype PromptPolicyShadowReport,\n\tplanPromptPolicy,\n} from \"./context/context-prompt-policy.ts\";\nimport { acquireContextStoreRetention, type ContextStoreRetentionLease } from \"./context/context-store-retention.ts\";\nimport { applyContextGc, type ContextGcReport } from \"./context-gc.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { resolveCliModel } from \"./model-resolver.ts\";\nimport { evaluateSurfaceFitness } from \"./model-router/fitness-gate.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport { HF_TRANSFORMERS_PROVIDER, OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\n/**\n * Deterministic `addSpawnedUsage` reportId: `kind` + session id + a content hash of `identity`\n * (never `Date.now`/random). Same identity on a retry of the same logical work unit yields the same\n * id, so the ledger's `seenSubagentReportIds` dedupe catches a duplicate report instead of\n * double-counting spend.\n */\nfunction deriveSpawnedUsageReportId(kind: string, sessionId: string, identity: string): string {\n\tconst digest = createHash(\"sha256\").update(identity).digest(\"hex\").slice(0, 16);\n\treturn `${kind}:${sessionId}:${digest}`;\n}\n\nfunction joinTextPrefix(content: readonly unknown[], maxChars = Number.POSITIVE_INFINITY): string {\n\tlet found = false;\n\tlet text = \"\";\n\tfor (const part of content) {\n\t\tif (typeof part !== \"object\" || part === null || (part as { type?: unknown }).type !== \"text\") continue;\n\t\tconst blockText = (part as { text?: unknown }).text;\n\t\tif (typeof blockText !== \"string\") continue;\n\t\tif (!found) {\n\t\t\tfound = true;\n\t\t\tif (blockText.length >= maxChars) return blockText.slice(0, maxChars);\n\t\t\ttext = blockText;\n\t\t\tcontinue;\n\t\t}\n\t\tconst available = maxChars - text.length;\n\t\tif (available <= 0) return text;\n\t\tif (available === 1) return `${text}\\n`;\n\t\tconst remaining = available - 1;\n\t\ttext += `\\n${blockText.slice(0, remaining)}`;\n\t\tif (blockText.length >= remaining) return text;\n\t}\n\treturn text;\n}\n\n/** Latest user prompt text in the provider-visible array. */\nexport function latestUserPromptText(messages: AgentMessage[], maxChars = Number.POSITIVE_INFINITY): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message || message.role !== \"user\") continue;\n\t\tif (typeof message.content === \"string\") {\n\t\t\treturn message.content.length > maxChars ? message.content.slice(0, maxChars) : message.content;\n\t\t}\n\t\tconst text = joinTextPrefix(message.content, maxChars);\n\t\tif (text.length > 0) return text;\n\t}\n\treturn \"\";\n}\n\n/** Read a packed artifact-producing tool result's `details.artifactId`, if present, without `any`. */\nfunction extractArtifactId(message: AgentMessage | undefined): string | undefined {\n\tif (!message || message.role !== \"toolResult\") return undefined;\n\tconst details = (message as { details?: unknown }).details;\n\tif (typeof details !== \"object\" || details === null) return undefined;\n\tconst artifactId = (details as { artifactId?: unknown }).artifactId;\n\treturn typeof artifactId === \"string\" ? artifactId : undefined;\n}\n\n/** Per-message memo of `estimateTokens(message)`, keyed by message object identity --\n * same contract as {@link ContextAuditMemo}. See `estimateContextTokensMemoized`. */\ntype TokenMemo = Map<AgentMessage, number>;\n\ninterface ContextTokenEstimate {\n\ttokens: number;\n\tusageTokens: number;\n\ttrailingTokens: number;\n\tlastUsageIndex: number | null;\n}\n\n/** Mirrors compaction.ts's private `getAssistantUsage`: a non-aborted, non-error assistant\n * message's usage, or undefined. */\nfunction assistantUsageForTokenEstimate(message: AgentMessage): Usage | undefined {\n\tif (message.role !== \"assistant\") return undefined;\n\tconst assistant = message as AssistantMessage;\n\tif (assistant.stopReason === \"aborted\" || assistant.stopReason === \"error\" || !assistant.usage) return undefined;\n\treturn assistant.usage;\n}\n\n/** Mirrors compaction.ts's private `getLastAssistantUsageInfo`: the most recent message with\n * usable usage and its index, scanning from the end. */\nfunction findLastAssistantUsage(messages: AgentMessage[]): { usage: Usage; index: number } | undefined {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (!message) continue;\n\t\tconst usage = assistantUsageForTokenEstimate(message);\n\t\tif (usage) return { usage, index };\n\t}\n\treturn undefined;\n}\n\n/**\n * Incremental-memo reimplementation of `estimateContextTokens` (compaction.ts), built\n * from that module's exported per-message primitives (`estimateTokens`, `calculateContextTokens`)\n * instead of adding a memo parameter to `estimateContextTokens` itself: compaction.ts is left\n * unmodified, so the incremental design stays entirely inside context-pipeline.ts, matching a\n * \"zero agent-session.ts change\" scope. The orchestration (finding the last-assistant-usage\n * boundary, summing) is cheap and always reruns in full; only the expensive per-message\n * `estimateTokens` text scan is memoized, keyed by message object identity exactly like\n * `_auditMemo`. Produces byte-identical output to `estimateContextTokens(messages)` for the\n * same input regardless of `memo` -- see the equivalence test.\n */\nfunction estimateContextTokensMemoized(messages: AgentMessage[], memo?: TokenMemo): ContextTokenEstimate {\n\tconst freshMemo: TokenMemo | undefined = memo ? new Map() : undefined;\n\tconst tokensFor = (message: AgentMessage): number => {\n\t\tconst cached = memo?.get(message);\n\t\tconst tokens = cached ?? estimateTokens(message);\n\t\tfreshMemo?.set(message, tokens);\n\t\treturn tokens;\n\t};\n\n\tconst usageInfo = findLastAssistantUsage(messages);\n\tlet result: ContextTokenEstimate;\n\tif (!usageInfo) {\n\t\tlet estimated = 0;\n\t\tfor (const message of messages) {\n\t\t\testimated += tokensFor(message);\n\t\t}\n\t\tresult = { tokens: estimated, usageTokens: 0, trailingTokens: estimated, lastUsageIndex: null };\n\t} else {\n\t\tconst usageTokens = calculateContextTokens(usageInfo.usage);\n\t\tlet trailingTokens = 0;\n\t\tfor (let index = usageInfo.index + 1; index < messages.length; index++) {\n\t\t\ttrailingTokens += tokensFor(messages[index]);\n\t\t}\n\t\tresult = { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };\n\t}\n\n\tif (memo && freshMemo) {\n\t\tmemo.clear();\n\t\tfor (const [key, value] of freshMemo) memo.set(key, value);\n\t}\n\treturn result;\n}\n\nexport interface ContextPipelineDeps {\n\t/** Current turn index, stamped into audit/policy/enforcement reports. */\n\tgetTurnIndex(): number;\n\t/** Session log: audit lookup, gc/artifact storage dirs, curation entries, token-estimate compaction anchor. */\n\tgetSessionManager(): SessionManager;\n\t/** Context-gc / prompt-enforcement / curation settings (all opt-in gates). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Resolves a configured curation model pattern against configured auth. */\n\tgetModelRegistry(): ModelRegistry;\n\t/** Foreground model currently executing the transformed request. */\n\tgetModel(): Model<Api> | undefined;\n\t/** Root dir the host-keyed {@link FitnessStore} and per-session gc/artifact storage live under. */\n\tgetAgentDir(): string;\n\t/** Workspace root, passed to the context-gc pass. */\n\tgetCwd(): string;\n\t/** Currently-active tool names — enforcement checks whether artifact_retrieve is a live affordance. */\n\tgetActiveToolNames(): string[];\n\t/** A disposed session must never persist a curation/pre-digest entry. */\n\tisDisposed(): boolean;\n\t/** The live memory manager — the active providers' page markers feed the semantic-gc scan. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Roll a curation drain's spawned usage into session accounting (idempotent per reportId).\n\t * `reportId` is REQUIRED: every caller derives a stable id from the work unit's identity\n\t * so a retry cannot double-count. */\n\taddSpawnedUsage(\n\t\tusage: Usage,\n\t\topts: { label?: string; sourceSessionId?: string; reportId: string },\n\t): string | undefined;\n\t/** One-shot LLM call fully isolated from the main session — the curation/pre-digest execution primitive. */\n\trunIsolatedCompletion(opts: IsolatedCompletionOptions): Promise<IsolatedCompletionResult>;\n}\n\nexport class ContextPipeline {\n\tprivate _latestContextGcReport: ContextGcReport | undefined = undefined;\n\t/** Brain-curation sidecar (design: brain-context-curation-design.md). Inert unless the\n\t * contextPolicy.curation setting is enabled AND the model passes the digest fitness gate. */\n\tprivate readonly _brainCurator = new BrainCurator();\n\tprivate _lastCurationSkipReason: string | undefined = undefined;\n\tprivate _lastPreDigestSkipReason: string | undefined = undefined;\n\tprivate _toolArtifactStore: ArtifactStore | undefined = undefined;\n\tprivate _contextStoreRetentionLease: ContextStoreRetentionLease | undefined;\n\tprivate _latestContextAuditReport: ContextAuditReport | undefined = undefined;\n\tprivate _latestPromptPolicyReport: PromptPolicyShadowReport | undefined = undefined;\n\tprivate _latestPromptPolicyGcCorrelation: PromptPolicyGcCorrelationReport | undefined = undefined;\n\tprivate _latestPromptEnforcementReport: PromptEnforcementReport | undefined = undefined;\n\tprivate readonly _tokenBudget = new TokenBudget();\n\tprivate _hasTokenBudgetAnchor = false;\n\tprivate _tokenBudgetAnchorCompactionId: string | undefined = undefined;\n\tprivate _lastTokenBudgetAnchorKey: string | undefined = undefined;\n\t/** Incremental current-branch lookup used by the per-turn audit. It retains only tool calls\n\t * still present in the provider-visible context, so compaction also bounds this cache. */\n\tprivate _sessionEntryLookupCache: { leafId: string | null; byToolCallId: Map<string, string> } | undefined =\n\t\tundefined;\n\t/** Incremental memo for the hot-path audit's expensive per-message work, keyed by\n\t * message object identity -- see {@link ContextAuditMemo}'s doc for the invalidation\n\t * contract. Rebuilt fresh (stale entries dropped) by `runContextAudit` every pass. */\n\tprivate readonly _auditMemo: ContextAuditMemo = new Map();\n\t/** Incremental memo for the per-message token estimate `estimateContextTokensMemoized`\n\t * relies on -- same object-identity-keyed, fresh-rebuild-per-pass contract as `_auditMemo`,\n\t * just for a plain `estimateTokens(message)` number instead of a built ContextItem. */\n\tprivate readonly _tokenMemo: TokenMemo = new Map();\n\n\tprivate readonly deps: ContextPipelineDeps;\n\n\tconstructor(deps: ContextPipelineDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate _ensureContextStoreRetention(): ContextStoreRetentionLease {\n\t\tif (!this._contextStoreRetentionLease) {\n\t\t\tthis._contextStoreRetentionLease = acquireContextStoreRetention(\n\t\t\t\tthis.deps.getAgentDir(),\n\t\t\t\tthis.deps.getSessionManager().getSessionId(),\n\t\t\t);\n\t\t}\n\t\treturn this._contextStoreRetentionLease;\n\t}\n\n\tprivate _contextGcStorageDir(): string {\n\t\treturn this._ensureContextStoreRetention().gcDir;\n\t}\n\n\tprivate _toolArtifactsDir(): string {\n\t\treturn this._ensureContextStoreRetention().artifactsDir;\n\t}\n\n\t/**\n\t * Session-scoped, filesystem-backed artifact store for first-capture-then-bound tool\n\t * output (grep/find/run_toolkit_script -- see tool-output-artifacts.md). Lazily created and\n\t * cached so every tool construction in this session shares one store instance.\n\t *\n\t * `packToolOutput()` registers a reference (the packing tool call's id) at pack time\n\t * and fails closed, so packed artifacts are never prematurely collected.\n\t * `_releaseGcPackedArtifactReferences()` (called from `applyContextGc()`) releases\n\t * that reference once context-gc packs the result out of live context, and\n\t * opportunistically reclaims now-unreferenced artifacts via `cleanup()`.\n\t * Cross-session retention is enforced when either payload store is first used. Active\n\t * sessions hold PID-marked leases; inactive stores are pruned by age, count, and bytes.\n\t */\n\tgetToolArtifactStore(): ArtifactStore {\n\t\tthis._toolArtifactStore ??= createFileArtifactStore({ baseDir: this._toolArtifactsDir() });\n\t\treturn this._toolArtifactStore;\n\t}\n\n\t/**\n\t * Best-effort final sweep of any already-released (zero-reference) tool-output artifact at\n\t * session dispose. Reads the field (not the getter) so a session that never packed anything\n\t * doesn't force-create a store/dir just to sweep it.\n\t */\n\tcleanupToolArtifactStoreOnDispose(): void {\n\t\tthis._toolArtifactStore?.cleanup();\n\t\tthis._contextStoreRetentionLease?.release();\n\t\tthis._contextStoreRetentionLease = undefined;\n\t\t// Release memoized message references promptly so a disposed session's messages are\n\t\t// GC-eligible even if this ContextPipeline instance itself briefly lingers.\n\t\tthis._auditMemo.clear();\n\t\tthis._tokenMemo.clear();\n\t}\n\n\t/**\n\t * Map tool-result call ids to persisted session-entry ids. Linear branch growth is handled\n\t * incrementally by walking only entries appended since the cached leaf; a branch switch falls\n\t * back to one full rebuild so lookups never leak entries from the abandoned branch.\n\t */\n\tprivate _getLatestCompactionEntry(): CompactionEntry | null {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tlet currentId = leafId;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tconst entry = getEntry(currentId);\n\t\t\t\tif (!entry) break;\n\t\t\t\tif (entry.type === \"compaction\") return entry;\n\t\t\t\tcurrentId = entry.parentId;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\t\treturn getLatestCompactionEntry(sessionManager.getBranch());\n\t}\n\n\tprivate _buildSessionEntryIdLookup(\n\t\twantedToolCallIds: ReadonlySet<string>,\n\t): (toolCallId: string) => string | undefined {\n\t\tconst sessionManager = this.deps.getSessionManager();\n\t\tconst indexedSessionManager = sessionManager as unknown as {\n\t\t\tgetLeafId?: () => string | null;\n\t\t\tgetEntry?: (id: string) => SessionEntry | undefined;\n\t\t};\n\t\tconst getLeafId = indexedSessionManager.getLeafId?.bind(sessionManager);\n\t\tconst getEntry = indexedSessionManager.getEntry?.bind(sessionManager);\n\t\tconst leafId = getLeafId?.();\n\t\tconst cached = this._sessionEntryLookupCache;\n\t\tif (cached) {\n\t\t\tfor (const toolCallId of cached.byToolCallId.keys()) {\n\t\t\t\tif (!wantedToolCallIds.has(toolCallId)) cached.byToolCallId.delete(toolCallId);\n\t\t\t}\n\t\t}\n\t\tif (getLeafId && getEntry && leafId !== undefined) {\n\t\t\tif (cached?.leafId === leafId) {\n\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t}\n\t\t\tif (cached) {\n\t\t\t\tconst appendedEntries: SessionEntry[] = [];\n\t\t\t\tlet cursor = leafId;\n\t\t\t\twhile (cursor !== null && cursor !== cached.leafId) {\n\t\t\t\t\tconst entry = getEntry(cursor);\n\t\t\t\t\tif (!entry) break;\n\t\t\t\t\tappendedEntries.push(entry);\n\t\t\t\t\tcursor = entry.parentId;\n\t\t\t\t}\n\t\t\t\tif (cursor === cached.leafId) {\n\t\t\t\t\tfor (let index = appendedEntries.length - 1; index >= 0; index--) {\n\t\t\t\t\t\tconst entry = appendedEntries[index];\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tentry.type === \"message\" &&\n\t\t\t\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tcached.byToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcached.leafId = leafId;\n\t\t\t\t\treturn (toolCallId) => cached.byToolCallId.get(toolCallId);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tconst byToolCallId = new Map<string, string>();\n\t\tfor (const entry of sessionManager.getBranch()) {\n\t\t\tif (\n\t\t\t\tentry.type === \"message\" &&\n\t\t\t\tentry.message.role === \"toolResult\" &&\n\t\t\t\twantedToolCallIds.has(entry.message.toolCallId)\n\t\t\t) {\n\t\t\t\tbyToolCallId.set(entry.message.toolCallId, entry.id);\n\t\t\t}\n\t\t}\n\t\tif (leafId !== undefined) this._sessionEntryLookupCache = { leafId, byToolCallId };\n\t\treturn (toolCallId) => byToolCallId.get(toolCallId);\n\t}\n\n\t/** Options shared by the memoized hot path and the no-memo full-scan path. */\n\tprivate _buildContextAuditOptions(messages: AgentMessage[]): ContextAuditOptions {\n\t\tconst wantedToolCallIds = new Set(\n\t\t\tmessages.filter((message) => message.role === \"toolResult\").map((message) => message.toolCallId),\n\t\t);\n\t\treturn {\n\t\t\tturnIndex: this.deps.getTurnIndex(),\n\t\t\tartifactStore: this._toolArtifactStore,\n\t\t\tsessionEntryIdForToolCallId: this._buildSessionEntryIdLookup(wantedToolCallIds),\n\t\t};\n\t}\n\n\t/**\n\t * Phase 1 observe-only audit pass (see context/context-audit.ts): converts live\n\t * toolResult messages into ContextItems and runs the existing retention/hard-constraint\n\t * evaluators over them, storing the latest deterministic report for tests/debugging.\n\t * Read-only with respect to messages, the transcript, and artifact references -- uses\n\t * `_toolArtifactStore` (the field), not `getToolArtifactStore()` (the getter), so a\n\t * session that never packed anything doesn't force-create a store/dir just to audit.\n\t * Never throws into a live turn: any failure degrades to an empty report.\n\t *\n\t * This is the memoized hot path (the real per-turn context transform calls it every\n\t * round trip via agent-session.ts's one-line delegation) -- see `_auditMemo`'s doc for the\n\t * incremental design. `getContextAuditReport`/`getPromptPolicyReport`'s `messages`-arg\n\t * recompute variants deliberately do NOT go through this method (see\n\t * `_runContextAuditFullScan`), so a read-only debug/test peek at a hypothetical `messages`\n\t * array can never evict a live entry out of the hot-path memo.\n\t */\n\trunContextAudit(messages: AgentMessage[]): ContextAuditReport {\n\t\ttry {\n\t\t\tconst report = runContextAudit(messages, this._buildContextAuditOptions(messages), this._auditMemo);\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: ContextAuditReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/** No-memo full-scan variant of {@link runContextAudit}, for read-only recompute callers. */\n\tprivate _runContextAuditFullScan(messages: AgentMessage[]): ContextAuditReport {\n\t\ttry {\n\t\t\tconst report = runContextAudit(messages, this._buildContextAuditOptions(messages));\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: ContextAuditReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestContextAuditReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the context audit. With `messages`, recomputes fresh against\n\t * the given array (still no mutation of messages/transcript/artifact refs) -- a pure\n\t * full scan, bypassing the hot-path memo (see `_runContextAuditFullScan`); without,\n\t * returns the last report computed during a real transform pass.\n\t */\n\tgetContextAuditReport(messages?: AgentMessage[]): ContextAuditReport {\n\t\tif (messages) return this._runContextAuditFullScan(messages);\n\t\treturn this._latestContextAuditReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Observe-first shadow/planning pass (see context/context-prompt-policy.ts): re-shapes\n\t * the audit report into a per-item policy plan whose `appliedAction` is always\n\t * \"keep_raw\" -- this never enforces anything, it only records what the policy engine\n\t * would say. Never throws into a live turn: any failure degrades to an empty report.\n\t */\n\trunPromptPolicyPlanning(auditReport: ContextAuditReport): PromptPolicyShadowReport {\n\t\ttry {\n\t\t\tconst report = planPromptPolicy(auditReport);\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report: PromptPolicyShadowReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptPolicyReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/**\n\t * Read-only inspection of the shadow policy plan. With `messages`, recomputes fresh\n\t * (audit + plan) against the given array; without, returns the last plan computed\n\t * during a real transform pass. Never mutates messages/transcript/artifact refs.\n\t */\n\tgetPromptPolicyReport(messages?: AgentMessage[]): PromptPolicyShadowReport {\n\t\tif (messages) return this.runPromptPolicyPlanning(this._runContextAuditFullScan(messages));\n\t\treturn this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\t/**\n\t * Report-only correlation between the shadow plan just computed this turn and what the\n\t * legacy context-gc pass actually packed. Runs after `applyContextGc()` has already\n\t * produced its report; never influences context-gc itself. Never throws into a live\n\t * turn: any failure degrades to an empty correlation.\n\t */\n\tcorrelatePromptPolicyWithContextGc(gcReport: ContextGcReport): void {\n\t\tconst shadowReport = this._latestPromptPolicyReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\ttry {\n\t\t\tthis._latestPromptPolicyGcCorrelation = correlateWithContextGc(shadowReport, gcReport);\n\t\t} catch {\n\t\t\tthis._latestPromptPolicyGcCorrelation = { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest shadow-plan/legacy-gc correlation, for tests/debugging. */\n\tgetPromptPolicyGcCorrelation(): PromptPolicyGcCorrelationReport {\n\t\treturn this._latestPromptPolicyGcCorrelation ?? { turnIndex: this.deps.getTurnIndex(), entries: [] };\n\t}\n\n\t/**\n\t * First enforcement pilot (see context/context-prompt-enforcement.ts): opt-in,\n\t * default-disabled stub-in-place of stale artifact-backed tool_output results in the\n\t * provider-visible message array only. Runs on `messages` AFTER context-gc has already\n\t * produced its own result, so legacy context-gc's own packing/reporting is completely\n\t * unaffected by this pass -- it only ever acts on messages gc left untouched this turn.\n\t * Never throws into a live turn: any failure degrades to returning `messages` unchanged.\n\t */\n\trunPromptEnforcement(\n\t\tmessages: AgentMessage[],\n\t\tshadowReport: PromptPolicyShadowReport,\n\t): { messages: AgentMessage[]; report: PromptEnforcementReport } {\n\t\ttry {\n\t\t\tconst persistedSettings = this.deps.getSettingsManager().getContextPromptEnforcementSettings();\n\t\t\tconst curationEnabled = this.deps.getSettingsManager().getContextCurationSettings().enabled;\n\t\t\tconst settings = {\n\t\t\t\t...persistedSettings,\n\t\t\t\t// Runtime fact, never assumed: artifact_retrieve is a companion affordance\n\t\t\t\t// (auto-activated alongside grep/find), not a default/global tool, so active\n\t\t\t\t// tools can differ turn to turn -- see context-prompt-enforcement.ts's doc\n\t\t\t\t// comment on why this is checked separately from hasAvailableRetrievalPath.\n\t\t\t\tretrievalToolAvailable: this.deps.getActiveToolNames().includes(\"artifact_retrieve\"),\n\t\t\t\tbrainRelevance: curationEnabled ? (itemId: string) => this._brainCurator.getRelevance(itemId) : undefined,\n\t\t\t};\n\t\t\tconst result = enforcePromptPolicy(messages, shadowReport, settings);\n\t\t\tthis._latestPromptEnforcementReport = result.report;\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: PromptEnforcementReport = { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t\t\tthis._latestPromptEnforcementReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Enqueue relevance-scoring jobs for stale, artifact-backed tool outputs the enforcement\n\t * pilot could act on. Pure queueing — the verdicts only ever take effect through the\n\t * asymmetric advisory lever inside enforcePromptPolicy. Never throws into a turn.\n\t */\n\tenqueueRelevanceCuration(messages: AgentMessage[], shadowReport: PromptPolicyShadowReport): void {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tif (!settings.enabled) return;\n\t\t\tconst goal = latestUserPromptText(messages, 400);\n\t\t\tfor (const item of shadowReport.items) {\n\t\t\t\tif (!item.hasAvailableRetrievalPath) continue;\n\t\t\t\tconst message = messages[item.messageIndex];\n\t\t\t\tif (!message || message.role !== \"toolResult\" || message.toolCallId !== item.toolCallId) continue;\n\t\t\t\tif (message.isError) continue;\n\t\t\t\tconst details = message.details as\n\t\t\t\t\t| { contextGc?: { packed?: unknown }; promptPolicy?: { enforced?: unknown } }\n\t\t\t\t\t| undefined;\n\t\t\t\tif (details?.contextGc?.packed === true || details?.promptPolicy?.enforced === true) continue;\n\t\t\t\tconst text = joinTextPrefix(message.content, 4000);\n\t\t\t\tif (text.length === 0) continue;\n\t\t\t\tthis._brainCurator.enqueue({ kind: \"relevance\", key: item.itemId, content: text, goal });\n\t\t\t}\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Drain gate: settings on, model configured+authed, and the model has PASSED the digest\n\t * fitness probe on THIS host (design: unfit or unprobed models are refused with a visible\n\t * reason, never silently degraded). Fire-and-forget; never throws into a turn.\n\t */\n\t/**\n\t * Resolve the curation model IFF every gate passes: setting enabled, model configured,\n\t * resolvable+authed, and digest-fitness-proven on THIS host (canonical \"provider/id\" ref —\n\t * runModelFitness stores reports under it, while settings.model may be a bare id or pattern).\n\t * Sets _lastCurationSkipReason on refusal; never throws.\n\t */\n\tprivate _effectiveContextWindowFromFitness(model: Model<Api>): number {\n\t\tconst registered = model.contextWindow > 0 ? model.contextWindow : Number.POSITIVE_INFINITY;\n\t\tconst capacity = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === `${model.provider}/${model.id}`)?.report.capacity?.servedContextWindow;\n\t\treturn capacity && capacity > 0 ? Math.min(registered, capacity) : registered;\n\t}\n\n\tresolveCurationModelIfFit(): Model<Api> | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\tif (!settings.enabled) {\n\t\t\t// Never surface a stale refusal reason for a feature the user has since disabled.\n\t\t\tthis._lastCurationSkipReason = undefined;\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!settings.model) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unset\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst resolved = resolveCliModel({ cliModel: settings.model, modelRegistry: this.deps.getModelRegistry() });\n\t\tif (!resolved.model || !this.deps.getModelRegistry().hasConfiguredAuth(resolved.model)) {\n\t\t\tthis._lastCurationSkipReason = \"curation_model_unresolved\";\n\t\t\treturn undefined;\n\t\t}\n\t\tconst canonicalRef = `${resolved.model.provider}/${resolved.model.id}`;\n\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t.getForHost()\n\t\t\t.find((entry) => entry.model === canonicalRef);\n\t\tconst verdict = evaluateSurfaceFitness(\"curation\", fitness?.report);\n\t\tif (!verdict.fit) {\n\t\t\tthis._lastCurationSkipReason =\n\t\t\t\tverdict.reason === \"unprobed\" ? \"curation_model_unprobed\" : \"curation_model_digest_unfit\";\n\t\t\treturn undefined;\n\t\t}\n\t\tthis._lastCurationSkipReason = undefined;\n\t\treturn resolved.model;\n\t}\n\n\tmaybeDrainBrainCuration(): void {\n\t\ttry {\n\t\t\tif (!this._brainCurator.hasWork() || this._brainCurator.isDraining) return;\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return;\n\t\t\tconst foregroundModel = this.deps.getModel();\n\t\t\tconst foregroundIsManagedLocal =\n\t\t\t\tforegroundModel?.provider === OLLAMA_PROVIDER || foregroundModel?.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tconst curatorIsManagedLocal =\n\t\t\t\tmodel.provider === OLLAMA_PROVIDER || model.provider === HF_TRANSFORMERS_PROVIDER;\n\t\t\tif (foregroundIsManagedLocal && curatorIsManagedLocal) {\n\t\t\t\t// Local foreground accuracy/latency wins. A fire-and-forget curator can otherwise reach\n\t\t\t\t// a single-parallel server first and make the user's request wait behind sidecar work.\n\t\t\t\tthis._lastCurationSkipReason = \"curation_deferred_for_local_foreground\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tvoid this._drainBrainCuration(model, settings.maxJobsPerTurn);\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/**\n\t * Compaction pre-digest gate (design surface 3): everything the drain gate requires PLUS a\n\t * RUNTIME reliability proof — the curator must have run >=5 jobs on this session with a parse\n\t * failure rate <=5% before it is trusted to pre-digest compaction input. Returns undefined\n\t * (verbatim compaction, byte-for-byte today's behavior) whenever any gate refuses.\n\t */\n\tbuildCompactionPreDigest(): ((text: string, signal?: AbortSignal) => Promise<string>) | undefined {\n\t\ttry {\n\t\t\tconst model = this.resolveCurationModelIfFit();\n\t\t\tif (!model) return undefined;\n\t\t\tconst telemetry = this._brainCurator.telemetry();\n\t\t\tif (telemetry.jobsRun < 5 || telemetry.parseFailures / telemetry.jobsRun > 0.05) {\n\t\t\t\tthis._lastPreDigestSkipReason = \"curation_predigest_reliability_unproven\";\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tthis._lastPreDigestSkipReason = undefined;\n\t\t\treturn async (text, signal) => {\n\t\t\t\tconst effectiveWindow = this._effectiveContextWindowFromFitness(model);\n\t\t\t\tconst chunkChars = Number.isFinite(effectiveWindow)\n\t\t\t\t\t? Math.max(1_000, Math.floor((effectiveWindow - 1024) * 4))\n\t\t\t\t\t: undefined;\n\t\t\t\tconst result = await preDigestConversationText({\n\t\t\t\t\ttext,\n\t\t\t\t\tsignal,\n\t\t\t\t\tchunkChars,\n\t\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal: chunkSignal }) => {\n\t\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\t\tmaxTokens: 512,\n\t\t\t\t\t\t\tsignal: chunkSignal,\n\t\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\t\t// Stable per-lane synthetic affinity key so repeat pre-digest chunk\n\t\t\t\t\t\t\t// calls hit the same cache-warm backend.\n\t\t\t\t\t\t\tlaneKind: \"curation\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t\tif (!this.deps.isDisposed() && result.totalChunks > 0) {\n\t\t\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation-predigest\", {\n\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\ttotalChunks: result.totalChunks,\n\t\t\t\t\t\tdigested: result.digested,\n\t\t\t\t\t\tfailed: result.failed,\n\t\t\t\t\t\tcharsBefore: text.length,\n\t\t\t\t\t\tcharsAfter: result.text.length,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn result.text;\n\t\t\t};\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async _drainBrainCuration(model: Model<Api>, maxJobs: number): Promise<void> {\n\t\ttry {\n\t\t\t// ACCUMULATE across all drained jobs (the drain runs the completer once PER job) —\n\t\t\t// keeping only the last job's usage would under-report every multi-job drain.\n\t\t\tlet spentUsage: AssistantMessage[\"usage\"] | undefined;\n\t\t\tconst results = await this._brainCurator.drain({\n\t\t\t\tmaxJobs,\n\t\t\t\tcomplete: async ({ systemPrompt, userPrompt, signal }) => {\n\t\t\t\t\tconst completion = await this.deps.runIsolatedCompletion({\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t\tthinkingLevel: \"off\",\n\t\t\t\t\t\tmaxTokens: 256,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\t// Both curation system prompts are static — the provider can cache the prefix.\n\t\t\t\t\t\tcacheRetention: \"short\",\n\t\t\t\t\t\t// Stable per-lane synthetic affinity key so repeat curation jobs hit the\n\t\t\t\t\t\t// same cache-warm backend.\n\t\t\t\t\t\tlaneKind: \"curation\",\n\t\t\t\t\t});\n\t\t\t\t\tconst usage = completion.usage;\n\t\t\t\t\tif (!spentUsage) {\n\t\t\t\t\t\tspentUsage = structuredClone(usage);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tspentUsage.input += usage.input;\n\t\t\t\t\t\tspentUsage.output += usage.output;\n\t\t\t\t\t\tspentUsage.cacheRead += usage.cacheRead;\n\t\t\t\t\t\tspentUsage.cacheWrite += usage.cacheWrite;\n\t\t\t\t\t\tspentUsage.totalTokens += usage.totalTokens;\n\t\t\t\t\t\tspentUsage.cost.input += usage.cost.input;\n\t\t\t\t\t\tspentUsage.cost.output += usage.cost.output;\n\t\t\t\t\t\tspentUsage.cost.cacheRead += usage.cost.cacheRead;\n\t\t\t\t\t\tspentUsage.cost.cacheWrite += usage.cost.cacheWrite;\n\t\t\t\t\t\tspentUsage.cost.total += usage.cost.total;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttext: completion.text,\n\t\t\t\t\t\tcostUsd: completion.usage.cost.total,\n\t\t\t\t\t\tstopReason: String(completion.stopReason),\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t});\n\t\t\t// Honest accounting even for free local models: token visibility is the contract.\n\t\t\tif (spentUsage && (spentUsage.cost.total > 0 || spentUsage.totalTokens > 0)) {\n\t\t\t\t// `reportId` keyed on the drained jobs' own idempotency keys — stable across a\n\t\t\t\t// retry of the same drain batch, distinct across genuinely different batches.\n\t\t\t\tconst reportId = deriveSpawnedUsageReportId(\n\t\t\t\t\t\"context-curator\",\n\t\t\t\t\tthis.deps.getSessionManager().getSessionId(),\n\t\t\t\t\tresults.map((result) => result.key).join(\" \"),\n\t\t\t\t);\n\t\t\t\tthis.deps.addSpawnedUsage(spentUsage, { label: \"context-curator\", reportId });\n\t\t\t}\n\t\t\tif (this.deps.isDisposed() || results.length === 0) return;\n\t\t\tthis.deps.getSessionManager().appendCustomEntry(\"brain-curation\", {\n\t\t\t\tversion: 1,\n\t\t\t\tresults: results.map((result) => ({\n\t\t\t\t\tkey: result.key,\n\t\t\t\t\tkind: result.kind,\n\t\t\t\t\tok: result.ok,\n\t\t\t\t\tms: result.ms,\n\t\t\t\t\t...(result.digest !== undefined ? { digest: result.digest } : {}),\n\t\t\t\t\t...(result.relevant !== undefined ? { relevant: result.relevant, confidence: result.confidence } : {}),\n\t\t\t\t})),\n\t\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\t});\n\t\t} catch {\n\t\t\t// curation is a sidecar; it must never disrupt a turn\n\t\t}\n\t}\n\n\t/** Curation status for diagnostics/dashboard: settings, live telemetry, last refusal reason. */\n\tgetContextCurationStatus(): {\n\t\tenabled: boolean;\n\t\tmodel?: string;\n\t\ttelemetry: CurationTelemetrySnapshot;\n\t\tlastSkipReason?: string;\n\t\tlastPreDigestSkipReason?: string;\n\t} {\n\t\tconst settings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\treturn {\n\t\t\tenabled: settings.enabled,\n\t\t\tmodel: settings.model,\n\t\t\ttelemetry: this._brainCurator.telemetry(),\n\t\t\tlastSkipReason: this._lastCurationSkipReason,\n\t\t\tlastPreDigestSkipReason: this._lastPreDigestSkipReason,\n\t\t};\n\t}\n\n\t/** Read-only inspection of the latest prompt-enforcement report, for tests/debugging. */\n\tgetPromptEnforcementReport(): PromptEnforcementReport {\n\t\treturn this._latestPromptEnforcementReport ?? { turnIndex: this.deps.getTurnIndex(), items: [] };\n\t}\n\n\tapplyContextGc(\n\t\tmessages: AgentMessage[],\n\t\twritePayloads: boolean,\n\t): { messages: AgentMessage[]; report: ContextGcReport } {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getContextGcSettings();\n\t\t\t// Merge the ACTIVE memory providers' own page markers (e.g. transcript-recall's\n\t\t\t// \"<memory_context\") into the semantic-memory marker list. The settings default is\n\t\t\t// provider-agnostic and non-empty, so without this merge the recall pages the bundled\n\t\t\t// default provider actually emits are never recognized as semantic-memory pages and\n\t\t\t// accumulate raw for the life of the session — the exact growth Bug #7 GC exists to stop.\n\t\t\tconst providerMarkers = this.deps.getMemoryManager().getContextMarkers();\n\t\t\tconst curationSettings = this.deps.getSettingsManager().getContextCurationSettings();\n\t\t\tconst result = applyContextGc(messages, {\n\t\t\t\t...settings,\n\t\t\t\tsemanticMemory: {\n\t\t\t\t\t...settings.semanticMemory,\n\t\t\t\t\tmarkers: [...new Set([...settings.semanticMemory.markers, ...providerMarkers])],\n\t\t\t\t},\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tstorageDir: this._contextGcStorageDir(),\n\t\t\t\twritePayloads,\n\t\t\t\tcuration: curationSettings.enabled\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tresolveDigest: (digestKey) => {\n\t\t\t\t\t\t\t\tconst digest = this._brainCurator.getDigest(digestKey);\n\t\t\t\t\t\t\t\t// Count serves on the REAL per-turn pass only, never the report path.\n\t\t\t\t\t\t\t\tif (digest !== undefined && writePayloads) this._brainCurator.noteDigestServed();\n\t\t\t\t\t\t\t\treturn digest;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t// Only the real per-turn pass enqueues work; the read-only report path\n\t\t\t\t\t\t\t// (writePayloads=false) stays side-effect free.\n\t\t\t\t\t\t\tonPacked: writePayloads\n\t\t\t\t\t\t\t\t? (record, originalText) => {\n\t\t\t\t\t\t\t\t\t\tthis._brainCurator.enqueue({\n\t\t\t\t\t\t\t\t\t\t\tkind: \"stub_digest\",\n\t\t\t\t\t\t\t\t\t\t\tkey: record.key ?? record.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tcontent: originalText,\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t: undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t\tthis._latestContextGcReport = result.report;\n\t\t\t// Only release/reclaim on the real per-turn pass (writePayloads=true), never on\n\t\t\t// the read-only status-report path (getContextGcReport with writePayloads=false),\n\t\t\t// so merely inspecting the report can't have side effects.\n\t\t\tif (writePayloads && result.report.packedCount > 0) {\n\t\t\t\tthis._releaseGcPackedArtifactReferences(messages, result.report);\n\t\t\t}\n\t\t\treturn result;\n\t\t} catch {\n\t\t\tconst report: ContextGcReport = {\n\t\t\t\tenabled: false,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t};\n\t\t\tthis._latestContextGcReport = report;\n\t\t\treturn { messages, report };\n\t\t}\n\t}\n\n\t/**\n\t * Reference-release + cleanup lifecycle: once context-gc has packed an artifact-producing\n\t * tool result (grep/find/run_toolkit_script) out of the live prompt (the message is no longer current/active working\n\t * context -- see contracts-and-retention.md's \"ephemeral\"/\"expired\" retention\n\t * classes), release the pack-time reference `packToolOutput()` registered for it, and\n\t * opportunistically reclaim now-unreferenced artifacts. This is the other half of the\n\t * D2b-1 gate: artifacts were being registered but never released, so they accumulated\n\t * for the life of the session.\n\t *\n\t * `record.toolCallId` (from context-gc's packed record) is exactly the holder id\n\t * `packToolOutput()` used when it called `addReference()` -- both trace back to the\n\t * same tool call's id -- so no separate bookkeeping is needed to find it.\n\t */\n\tprivate _releaseGcPackedArtifactReferences(messages: AgentMessage[], report: ContextGcReport): void {\n\t\tconst store = this._toolArtifactStore;\n\t\tif (!store) return; // no store was ever constructed, so nothing could have been packed to one\n\n\t\tlet releasedAny = false;\n\t\tfor (const record of report.records) {\n\t\t\tif (record.toolName !== \"grep\" && record.toolName !== \"find\" && record.toolName !== \"run_toolkit_script\")\n\t\t\t\tcontinue;\n\t\t\tconst artifactId = extractArtifactId(messages[record.messageIndex]);\n\t\t\tif (!artifactId) continue;\n\t\t\tif (store.removeReference(artifactId, record.toolCallId)) releasedAny = true;\n\t\t}\n\t\t// Cleanup only runs immediately after a release actually happened in this pass, so\n\t\t// a long session doesn't re-scan the artifact directory on every turn once nothing\n\t\t// new became eligible for release.\n\t\tif (releasedAny) store.cleanup();\n\t}\n\n\tgetContextGcReport(messages?: AgentMessage[]): ContextGcReport {\n\t\tif (messages) return this.applyContextGc(messages, false).report;\n\t\treturn (\n\t\t\tthis._latestContextGcReport ?? {\n\t\t\t\tenabled: this.deps.getSettingsManager().getContextGcSettings().enabled,\n\t\t\t\tpackedCount: 0,\n\t\t\t\toriginalTokens: 0,\n\t\t\t\tpackedTokens: 0,\n\t\t\t\tsavedTokens: 0,\n\t\t\t\trecords: [],\n\t\t\t}\n\t\t);\n\t}\n\n\tobserveProviderUsage(messages: AgentMessage[], usageMessage: AssistantMessage): void {\n\t\tif (usageMessage.stopReason === \"error\" || usageMessage.stopReason === \"aborted\") {\n\t\t\treturn;\n\t\t}\n\n\t\tconst estimate = estimateContextTokensMemoized(messages, this._tokenMemo);\n\t\tif (estimate.lastUsageIndex === null || messages[estimate.lastUsageIndex] !== usageMessage) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (!compactionEntry) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageMessage.timestamp <= compactionTimestamp) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst coveredChars = estimateConversationChars(messages, 0, estimate.lastUsageIndex + 1);\n\t\tif (estimate.usageTokens <= 0 || coveredChars <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst anchorKey = `${compactionEntry.id}:${usageMessage.timestamp}:${estimate.usageTokens}:${coveredChars}`;\n\t\tif (anchorKey === this._lastTokenBudgetAnchorKey) {\n\t\t\treturn;\n\t\t}\n\n\t\tthis._tokenBudget.anchor(estimate.usageTokens, coveredChars);\n\t\tthis._hasTokenBudgetAnchor = true;\n\t\tthis._tokenBudgetAnchorCompactionId = compactionEntry.id;\n\t\tthis._lastTokenBudgetAnchorKey = anchorKey;\n\t}\n\n\testimateCurrentContextTokens(messages: AgentMessage[]): number {\n\t\tconst estimate = estimateContextTokensMemoized(messages, this._tokenMemo);\n\t\tif (estimate.lastUsageIndex === null) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tconst usageMessage = messages[estimate.lastUsageIndex];\n\t\tconst compactionEntry = this._getLatestCompactionEntry();\n\t\tif (usageMessage?.role !== \"assistant\" || !compactionEntry) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\t\tconst usageTimestamp = (usageMessage as AssistantMessage).timestamp;\n\t\tconst compactionTimestamp = new Date(compactionEntry.timestamp).getTime();\n\t\tif (usageTimestamp <= compactionTimestamp) {\n\t\t\treturn this._tokenBudget.estimateDelta(estimateConversationChars(messages));\n\t\t}\n\n\t\tif (!this._hasTokenBudgetAnchor || this._tokenBudgetAnchorCompactionId !== compactionEntry.id) {\n\t\t\treturn estimate.tokens;\n\t\t}\n\n\t\tconst deltaChars = estimateConversationChars(messages, estimate.lastUsageIndex + 1, messages.length);\n\t\treturn this._tokenBudget.current(deltaChars, estimate.tokens);\n\t}\n}\n\n/**\n * Estimate covered characters from the provider-visible context messages.\n */\nfunction estimateConversationChars(messages: AgentMessage[], start = 0, end = messages.length): number {\n\tlet total = 0;\n\tfor (let index = Math.max(0, start); index < Math.min(messages.length, end); index++) {\n\t\tconst message = messages[index];\n\t\tif (!message) continue;\n\t\tconst rawContent = (message as { content?: unknown }).content;\n\t\tif (typeof rawContent === \"string\") {\n\t\t\ttotal += rawContent.length;\n\t\t\tcontinue;\n\t\t}\n\t\tif (!Array.isArray(rawContent)) {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const block of rawContent) {\n\t\t\tif (typeof block === \"string\") {\n\t\t\t\ttotal += block.length;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!block || typeof block !== \"object\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (typeof (block as { text?: unknown }).text === \"string\") {\n\t\t\t\ttotal += (block as { text?: string }).text?.length ?? 0;\n\t\t\t}\n\t\t\tif (typeof (block as { thinking?: unknown }).thinking === \"string\") {\n\t\t\t\ttotal += (block as { thinking?: string }).thinking?.length ?? 0;\n\t\t\t}\n\t\t}\n\t}\n\treturn total;\n}\n"]}
|
|
@@ -42,14 +42,30 @@ export interface CostGuardSettings {
|
|
|
42
42
|
}
|
|
43
43
|
export declare const DEFAULT_COST_GUARD_SETTINGS: CostGuardSettings;
|
|
44
44
|
export interface CostGuardDecision {
|
|
45
|
-
/** True when the guard is enabled AND the projected
|
|
45
|
+
/** True when the guard is enabled AND the projected TOTAL (estUsd + backgroundUsd) exceeds the ceiling. */
|
|
46
46
|
over: boolean;
|
|
47
|
+
/** Projected USD cost of the next foreground call alone (unchanged meaning — what the footer's "/turn" label shows). */
|
|
47
48
|
estUsd: number;
|
|
49
|
+
/** Background/spawned-lane USD spend (research/worker/reflection/fitness) folded into this decision — the caller decides the window (e.g. since the current turn began). */
|
|
50
|
+
backgroundUsd: number;
|
|
51
|
+
/** `estUsd + backgroundUsd` — the value actually compared against `thresholdUsd`. */
|
|
52
|
+
totalUsd: number;
|
|
48
53
|
thresholdUsd: number;
|
|
49
54
|
action: CostGuardAction;
|
|
50
55
|
}
|
|
51
|
-
/**
|
|
52
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Decide whether the projected turn cost trips the guard. Disabled (`maxTurnUsd<=0`) is never `over`.
|
|
58
|
+
*
|
|
59
|
+
* `cumulativeBackgroundUsd` (default 0) is spawned/background-lane spend (research, worker delegation,
|
|
60
|
+
* reflection, model-fitness probes — see {@link SpawnedUsageTotals}) folded into the same ceiling as the
|
|
61
|
+
* next foreground call. This function is window-agnostic — it just sums whatever the caller passes — but
|
|
62
|
+
* the intended caller convention (agent-session.ts) is spend attributed to the CURRENT turn only (a
|
|
63
|
+
* baseline snapshotted at the top of the turn, subtracted from the live cumulative total), not the
|
|
64
|
+
* session's entire lifetime, so a turn that is cheap in the foreground but has quietly spent a lot in
|
|
65
|
+
* background lanes THIS turn still trips the guard, without a prior turn's spend keeping it stuck over
|
|
66
|
+
* forever (still warn-only by default).
|
|
67
|
+
*/
|
|
68
|
+
export declare function evaluateCostGuard(estUsd: number, settings: CostGuardSettings, cumulativeBackgroundUsd?: number): CostGuardDecision;
|
|
53
69
|
/** Reasoning levels in descending cost order, used to pick the next-cheaper level on a downgrade. */
|
|
54
70
|
declare const REASONING_LADDER: readonly ["ultra", "max", "xhigh", "high", "medium", "low", "minimal", "off"];
|
|
55
71
|
export type ReasoningLevel = (typeof REASONING_LADDER)[number];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cost-guard.d.ts","sourceRoot":"","sources":["../../src/core/cost-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,gEAAgE;AAChE,MAAM,WAAW,cAAc;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED;;;;;;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AAqE;AACrE,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,WAAW,CAAC;AAEnD,MAAM,WAAW,iBAAiB;IACjC,yEAAyE;IACzE,UAAU,EAAE,MAAM,CAAC;IACnB,iGAAiG;IACjG,MAAM,EAAE,eAAe,CAAC;CACxB;AAED,eAAO,MAAM,2BAA2B,EAAE,iBAGzC,CAAC;AAEF,MAAM,WAAW,iBAAiB;IACjC,2GAA2G;IAC3G,IAAI,EAAE,OAAO,CAAC;IACd,0HAAwH;IACxH,MAAM,EAAE,MAAM,CAAC;IACf,8KAA4K;IAC5K,aAAa,EAAE,MAAM,CAAC;IACtB,uFAAqF;IACrF,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,eAAe,CAAC;CACxB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,iBAAiB,CAChC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,iBAAiB,EAC3B,uBAAuB,SAAI,GACzB,iBAAiB,CAYnB;AAED,qGAAqG;AACrG,QAAA,MAAM,gBAAgB,+EAAgF,CAAC;AACvG,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,gBAAgB,CAAC,CAAC,MAAM,CAAC,CAAC;AAC/D,MAAM,MAAM,kBAAkB,GAAG,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAO1F;;;;;GAKG;AACH,wBAAgB,kBAAkB,CACjC,OAAO,EAAE,MAAM,EACf,eAAe,CAAC,EAAE,SAAS,cAAc,EAAE,EAC3C,SAAS,CAAC,EAAE,kBAAkB,GAC5B,cAAc,GAAG,MAAM,CAczB","sourcesContent":["/**\n * Proactive per-turn token cost guard (Hermes-parity superiority item #34).\n *\n * Hermes (and pi today) only react to context growth by compressing AFTER it's expensive. This estimates\n * the dollar cost of the NEXT LLM call BEFORE it is submitted, so the agent can warn the user or\n * automatically reduce reasoning effort before a runaway billing spike — a proactive ceiling, not a\n * reactive cleanup. Pure functions: no I/O, fully testable.\n */\n\n/** Per-million-token USD prices, as carried on `Model.cost`. */\nexport interface ModelTokenCost {\n\tinput: number;\n\toutput: number;\n\tcacheRead?: number;\n\tcacheWrite?: number;\n}\n\n/**\n * Estimate the USD cost of one turn: the whole current context is billed as input, plus up to\n * `maxOutputTokens` of output. `cachedInputTokens` (prefix-cache hits) are billed at the cheaper\n * cache-read rate. Fresh input is billed once at the higher of the uncached-input and cache-write\n * rates because a provider may select that prefix for a new cache write. This is an UPPER bound on\n * the turn (it also assumes the model emits its full output budget), which is what a spending ceiling\n * should bound against.\n */\nexport function estimateTurnCostUsd(args: {\n\tinputTokens: number;\n\tmaxOutputTokens: number;\n\tcost: ModelTokenCost;\n\tcachedInputTokens?: number;\n\tlongContextPricing?: { thresholdTokens: number; inputMultiplier: number; outputMultiplier: number };\n}): number {\n\tconst { inputTokens, maxOutputTokens, cost } = args;\n\tconst cached = Math.max(0, Math.min(args.cachedInputTokens ?? 0, inputTokens));\n\tconst freshInput = inputTokens - cached;\n\tconst cacheReadRate = cost.cacheRead ?? cost.input;\n\tconst freshInputRate = Math.max(cost.input, cost.cacheWrite ?? cost.input);\n\tconst longContextPricing = args.longContextPricing;\n\tconst useLongContextTier = longContextPricing && inputTokens > longContextPricing.thresholdTokens;\n\tconst inputMultiplier = useLongContextTier ? longContextPricing.inputMultiplier : 1;\n\tconst outputMultiplier = useLongContextTier ? longContextPricing.outputMultiplier : 1;\n\tconst inputUsd = ((freshInput * freshInputRate + cached * cacheReadRate) * inputMultiplier) / 1_000_000;\n\tconst outputUsd = (Math.max(0, maxOutputTokens) * cost.output * outputMultiplier) / 1_000_000;\n\treturn inputUsd + outputUsd;\n}\n\n/** What to do when a turn's projected cost exceeds the threshold. */\nexport type CostGuardAction = \"warn\" | \"downgrade\";\n\nexport interface CostGuardSettings {\n\t/** Per-turn projected USD threshold. `0` disables the guard entirely. */\n\tmaxTurnUsd: number;\n\t/** Over the ceiling: `warn` (surface a notice) or `downgrade` (also reduce reasoning effort). */\n\taction: CostGuardAction;\n}\n\nexport const DEFAULT_COST_GUARD_SETTINGS: CostGuardSettings = {\n\tmaxTurnUsd: 2.5,\n\taction: \"warn\",\n};\n\nexport interface CostGuardDecision {\n\t/** True when the guard is enabled AND the projected TOTAL (estUsd + backgroundUsd) exceeds the ceiling. */\n\tover: boolean;\n\t/** Projected USD cost of the next foreground call alone (unchanged meaning — what the footer's \"/turn\" label shows). */\n\testUsd: number;\n\t/** Background/spawned-lane USD spend (research/worker/reflection/fitness) folded into this decision — the caller decides the window (e.g. since the current turn began). */\n\tbackgroundUsd: number;\n\t/** `estUsd + backgroundUsd` — the value actually compared against `thresholdUsd`. */\n\ttotalUsd: number;\n\tthresholdUsd: number;\n\taction: CostGuardAction;\n}\n\n/**\n * Decide whether the projected turn cost trips the guard. Disabled (`maxTurnUsd<=0`) is never `over`.\n *\n * `cumulativeBackgroundUsd` (default 0) is spawned/background-lane spend (research, worker delegation,\n * reflection, model-fitness probes — see {@link SpawnedUsageTotals}) folded into the same ceiling as the\n * next foreground call. This function is window-agnostic — it just sums whatever the caller passes — but\n * the intended caller convention (agent-session.ts) is spend attributed to the CURRENT turn only (a\n * baseline snapshotted at the top of the turn, subtracted from the live cumulative total), not the\n * session's entire lifetime, so a turn that is cheap in the foreground but has quietly spent a lot in\n * background lanes THIS turn still trips the guard, without a prior turn's spend keeping it stuck over\n * forever (still warn-only by default).\n */\nexport function evaluateCostGuard(\n\testUsd: number,\n\tsettings: CostGuardSettings,\n\tcumulativeBackgroundUsd = 0,\n): CostGuardDecision {\n\tconst enabled = settings.maxTurnUsd > 0;\n\tconst backgroundUsd = Math.max(0, cumulativeBackgroundUsd);\n\tconst totalUsd = estUsd + backgroundUsd;\n\treturn {\n\t\tover: enabled && totalUsd > settings.maxTurnUsd,\n\t\testUsd,\n\t\tbackgroundUsd,\n\t\ttotalUsd,\n\t\tthresholdUsd: settings.maxTurnUsd,\n\t\taction: settings.action,\n\t};\n}\n\n/** Reasoning levels in descending cost order, used to pick the next-cheaper level on a downgrade. */\nconst REASONING_LADDER = [\"ultra\", \"max\", \"xhigh\", \"high\", \"medium\", \"low\", \"minimal\", \"off\"] as const;\nexport type ReasoningLevel = (typeof REASONING_LADDER)[number];\nexport type ReasoningEffortMap = Readonly<Partial<Record<ReasoningLevel, string | null>>>;\n\nfunction effectiveReasoningEffort(level: ReasoningLevel, effortMap: ReasoningEffortMap | undefined): string | null {\n\tconst mapped = effortMap?.[level];\n\treturn mapped === undefined ? level : mapped;\n}\n\n/**\n * One supported step down the reasoning ladder (cost reduction) from `current`. When\n * `supportedLevels` is provided, unsupported intermediate levels are skipped instead of relying on a\n * provider clamp that may move back upward. Returns `current` unchanged when already at the model's\n * floor or unrecognized — the guard never raises effort, only lowers it.\n */\nexport function downgradeReasoning(\n\tcurrent: string,\n\tsupportedLevels?: readonly ReasoningLevel[],\n\teffortMap?: ReasoningEffortMap,\n): ReasoningLevel | string {\n\tconst i = REASONING_LADDER.indexOf(current as ReasoningLevel);\n\tif (i < 0) return current;\n\tif (!supportedLevels) {\n\t\treturn REASONING_LADDER[Math.min(i + 1, REASONING_LADDER.length - 1)];\n\t}\n\tconst supported = new Set<ReasoningLevel>(supportedLevels);\n\tconst currentEffort = effectiveReasoningEffort(current as ReasoningLevel, effortMap);\n\tfor (let nextIndex = i + 1; nextIndex < REASONING_LADDER.length; nextIndex++) {\n\t\tconst candidate = REASONING_LADDER[nextIndex];\n\t\tif (supported.has(candidate) && effectiveReasoningEffort(candidate, effortMap) !== currentEffort)\n\t\t\treturn candidate;\n\t}\n\treturn current;\n}\n"]}
|
package/dist/core/cost-guard.js
CHANGED
|
@@ -32,12 +32,27 @@ export const DEFAULT_COST_GUARD_SETTINGS = {
|
|
|
32
32
|
maxTurnUsd: 2.5,
|
|
33
33
|
action: "warn",
|
|
34
34
|
};
|
|
35
|
-
/**
|
|
36
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Decide whether the projected turn cost trips the guard. Disabled (`maxTurnUsd<=0`) is never `over`.
|
|
37
|
+
*
|
|
38
|
+
* `cumulativeBackgroundUsd` (default 0) is spawned/background-lane spend (research, worker delegation,
|
|
39
|
+
* reflection, model-fitness probes — see {@link SpawnedUsageTotals}) folded into the same ceiling as the
|
|
40
|
+
* next foreground call. This function is window-agnostic — it just sums whatever the caller passes — but
|
|
41
|
+
* the intended caller convention (agent-session.ts) is spend attributed to the CURRENT turn only (a
|
|
42
|
+
* baseline snapshotted at the top of the turn, subtracted from the live cumulative total), not the
|
|
43
|
+
* session's entire lifetime, so a turn that is cheap in the foreground but has quietly spent a lot in
|
|
44
|
+
* background lanes THIS turn still trips the guard, without a prior turn's spend keeping it stuck over
|
|
45
|
+
* forever (still warn-only by default).
|
|
46
|
+
*/
|
|
47
|
+
export function evaluateCostGuard(estUsd, settings, cumulativeBackgroundUsd = 0) {
|
|
37
48
|
const enabled = settings.maxTurnUsd > 0;
|
|
49
|
+
const backgroundUsd = Math.max(0, cumulativeBackgroundUsd);
|
|
50
|
+
const totalUsd = estUsd + backgroundUsd;
|
|
38
51
|
return {
|
|
39
|
-
over: enabled &&
|
|
52
|
+
over: enabled && totalUsd > settings.maxTurnUsd,
|
|
40
53
|
estUsd,
|
|
54
|
+
backgroundUsd,
|
|
55
|
+
totalUsd,
|
|
41
56
|
thresholdUsd: settings.maxTurnUsd,
|
|
42
57
|
action: settings.action,
|
|
43
58
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cost-guard.js","sourceRoot":"","sources":["../../src/core/cost-guard.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAUH;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,IAMnC,EAAU;IACV,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;IACpD,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GA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C;IACvE,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,GAAG,CAAiB,eAAe,CAAC,CAAC;IAC3D,MAAM,aAAa,GAAG,wBAAwB,CAAC,OAAyB,EAAE,SAAS,CAAC,CAAC;IACrF,KAAK,IAAI,SAAS,GAAG,CAAC,GAAG,CAAC,EAAE,SAAS,GAAG,gBAAgB,CAAC,MAAM,EAAE,SAAS,EAAE,EAAE,CAAC;QAC9E,MAAM,SAAS,GAAG,gBAAgB,CAAC,SAAS,CAAC,CAAC;QAC9C,IAAI,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,wBAAwB,CAAC,SAAS,EAAE,SAAS,CAAC,KAAK,aAAa;YAC/F,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,OAAO,OAAO,CAAC;AAAA,CACf","sourcesContent":["/**\n * Proactive per-turn token cost guard (Hermes-parity superiority item #34).\n *\n * Hermes (and pi today) only react to context growth by compressing AFTER it's expensive. This estimates\n * the dollar cost of the NEXT LLM call BEFORE it is submitted, so the agent can warn the user or\n * automatically reduce reasoning effort before a runaway billing spike — a proactive ceiling, not a\n * reactive cleanup. Pure functions: no I/O, fully testable.\n */\n\n/** Per-million-token USD prices, as carried on `Model.cost`. */\nexport interface ModelTokenCost {\n\tinput: number;\n\toutput: number;\n\tcacheRead?: number;\n\tcacheWrite?: number;\n}\n\n/**\n * Estimate the USD cost of one turn: the whole current context is billed as input, plus up to\n * `maxOutputTokens` of output. `cachedInputTokens` (prefix-cache hits) are billed at the cheaper\n * cache-read rate. Fresh input is billed once at the higher of the uncached-input and cache-write\n * rates because a provider may select that prefix for a new cache write. This is an UPPER bound on\n * the turn (it also assumes the model emits its full output budget), which is what a spending ceiling\n * should bound against.\n */\nexport function estimateTurnCostUsd(args: {\n\tinputTokens: number;\n\tmaxOutputTokens: number;\n\tcost: ModelTokenCost;\n\tcachedInputTokens?: number;\n\tlongContextPricing?: { thresholdTokens: number; inputMultiplier: number; outputMultiplier: number };\n}): number {\n\tconst { inputTokens, maxOutputTokens, cost } = args;\n\tconst cached = Math.max(0, Math.min(args.cachedInputTokens ?? 0, inputTokens));\n\tconst freshInput = inputTokens - cached;\n\tconst cacheReadRate = cost.cacheRead ?? cost.input;\n\tconst freshInputRate = Math.max(cost.input, cost.cacheWrite ?? cost.input);\n\tconst longContextPricing = args.longContextPricing;\n\tconst useLongContextTier = longContextPricing && inputTokens > longContextPricing.thresholdTokens;\n\tconst inputMultiplier = useLongContextTier ? longContextPricing.inputMultiplier : 1;\n\tconst outputMultiplier = useLongContextTier ? longContextPricing.outputMultiplier : 1;\n\tconst inputUsd = ((freshInput * freshInputRate + cached * cacheReadRate) * inputMultiplier) / 1_000_000;\n\tconst outputUsd = (Math.max(0, maxOutputTokens) * cost.output * outputMultiplier) / 1_000_000;\n\treturn inputUsd + outputUsd;\n}\n\n/** What to do when a turn's projected cost exceeds the threshold. */\nexport type CostGuardAction = \"warn\" | \"downgrade\";\n\nexport interface CostGuardSettings {\n\t/** Per-turn projected USD threshold. `0` disables the guard entirely. */\n\tmaxTurnUsd: number;\n\t/** Over the ceiling: `warn` (surface a notice) or `downgrade` (also reduce reasoning effort). */\n\taction: CostGuardAction;\n}\n\nexport const DEFAULT_COST_GUARD_SETTINGS: CostGuardSettings = {\n\tmaxTurnUsd: 2.5,\n\taction: \"warn\",\n};\n\nexport interface CostGuardDecision {\n\t/** True when the guard is enabled AND the projected TOTAL (estUsd + backgroundUsd) exceeds the ceiling. */\n\tover: boolean;\n\t/** Projected USD cost of the next foreground call alone (unchanged meaning — what the footer's \"/turn\" label shows). */\n\testUsd: number;\n\t/** Background/spawned-lane USD spend (research/worker/reflection/fitness) folded into this decision — the caller decides the window (e.g. since the current turn began). */\n\tbackgroundUsd: number;\n\t/** `estUsd + backgroundUsd` — the value actually compared against `thresholdUsd`. */\n\ttotalUsd: number;\n\tthresholdUsd: number;\n\taction: CostGuardAction;\n}\n\n/**\n * Decide whether the projected turn cost trips the guard. Disabled (`maxTurnUsd<=0`) is never `over`.\n *\n * `cumulativeBackgroundUsd` (default 0) is spawned/background-lane spend (research, worker delegation,\n * reflection, model-fitness probes — see {@link SpawnedUsageTotals}) folded into the same ceiling as the\n * next foreground call. This function is window-agnostic — it just sums whatever the caller passes — but\n * the intended caller convention (agent-session.ts) is spend attributed to the CURRENT turn only (a\n * baseline snapshotted at the top of the turn, subtracted from the live cumulative total), not the\n * session's entire lifetime, so a turn that is cheap in the foreground but has quietly spent a lot in\n * background lanes THIS turn still trips the guard, without a prior turn's spend keeping it stuck over\n * forever (still warn-only by default).\n */\nexport function evaluateCostGuard(\n\testUsd: number,\n\tsettings: CostGuardSettings,\n\tcumulativeBackgroundUsd = 0,\n): CostGuardDecision {\n\tconst enabled = settings.maxTurnUsd > 0;\n\tconst backgroundUsd = Math.max(0, cumulativeBackgroundUsd);\n\tconst totalUsd = estUsd + backgroundUsd;\n\treturn {\n\t\tover: enabled && totalUsd > settings.maxTurnUsd,\n\t\testUsd,\n\t\tbackgroundUsd,\n\t\ttotalUsd,\n\t\tthresholdUsd: settings.maxTurnUsd,\n\t\taction: settings.action,\n\t};\n}\n\n/** Reasoning levels in descending cost order, used to pick the next-cheaper level on a downgrade. */\nconst REASONING_LADDER = [\"ultra\", \"max\", \"xhigh\", \"high\", \"medium\", \"low\", \"minimal\", \"off\"] as const;\nexport type ReasoningLevel = (typeof REASONING_LADDER)[number];\nexport type ReasoningEffortMap = Readonly<Partial<Record<ReasoningLevel, string | null>>>;\n\nfunction effectiveReasoningEffort(level: ReasoningLevel, effortMap: ReasoningEffortMap | undefined): string | null {\n\tconst mapped = effortMap?.[level];\n\treturn mapped === undefined ? level : mapped;\n}\n\n/**\n * One supported step down the reasoning ladder (cost reduction) from `current`. When\n * `supportedLevels` is provided, unsupported intermediate levels are skipped instead of relying on a\n * provider clamp that may move back upward. Returns `current` unchanged when already at the model's\n * floor or unrecognized — the guard never raises effort, only lowers it.\n */\nexport function downgradeReasoning(\n\tcurrent: string,\n\tsupportedLevels?: readonly ReasoningLevel[],\n\teffortMap?: ReasoningEffortMap,\n): ReasoningLevel | string {\n\tconst i = REASONING_LADDER.indexOf(current as ReasoningLevel);\n\tif (i < 0) return current;\n\tif (!supportedLevels) {\n\t\treturn REASONING_LADDER[Math.min(i + 1, REASONING_LADDER.length - 1)];\n\t}\n\tconst supported = new Set<ReasoningLevel>(supportedLevels);\n\tconst currentEffort = effectiveReasoningEffort(current as ReasoningLevel, effortMap);\n\tfor (let nextIndex = i + 1; nextIndex < REASONING_LADDER.length; nextIndex++) {\n\t\tconst candidate = REASONING_LADDER[nextIndex];\n\t\tif (supported.has(candidate) && effectiveReasoningEffort(candidate, effortMap) !== currentEffort)\n\t\t\treturn candidate;\n\t}\n\treturn current;\n}\n"]}
|
|
@@ -4,13 +4,43 @@ export declare const WORKER_RESULT_CUSTOM_TYPE = "worker_result";
|
|
|
4
4
|
export interface WorkerResultSnapshotPayload {
|
|
5
5
|
version: 1;
|
|
6
6
|
result: WorkerResult;
|
|
7
|
-
/** The originating request
|
|
7
|
+
/** The originating request: persisted so a result is auditable against exactly what was
|
|
8
8
|
* asked — instructions, route, and the capability envelope that bounded it. Optional for
|
|
9
|
-
* backward compatibility with
|
|
9
|
+
* backward compatibility with entries recorded before this field existed. */
|
|
10
10
|
request?: WorkerRequest;
|
|
11
11
|
}
|
|
12
|
-
export declare function appendWorkerResultSnapshot(sessionManager: Pick<SessionManager, "appendCustomEntry">, result: WorkerResult, request?: WorkerRequest
|
|
13
|
-
/**
|
|
12
|
+
export declare function appendWorkerResultSnapshot(sessionManager: Pick<SessionManager, "appendCustomEntry">, result: WorkerResult, request?: WorkerRequest,
|
|
13
|
+
/** Baseline for relative changedFiles when re-deriving the review marker; forwarded to
|
|
14
|
+
* `isParentReviewRequired`/`validateWorkerResult`. Defaults to `process.cwd()`, matching the
|
|
15
|
+
* validator's own documented default for single-cwd-per-process callers. */
|
|
16
|
+
options?: {
|
|
17
|
+
cwd?: string;
|
|
18
|
+
}): string;
|
|
19
|
+
/** Requests persisted alongside results (absent for entries recorded before this field existed). */
|
|
14
20
|
export declare function getWorkerRequestSnapshots(entries: readonly SessionEntry[]): WorkerRequest[];
|
|
15
21
|
export declare function getWorkerResultSnapshots(entries: readonly SessionEntry[]): WorkerResult[];
|
|
22
|
+
/**
|
|
23
|
+
* Latest persisted snapshot (result + originating request, when available) for one worker
|
|
24
|
+
* requestId — "latest wins" over the append-only entries, the same collapse `delegate_status`
|
|
25
|
+
* already performs when it maps results by requestId. Used to read, and durably update, the
|
|
26
|
+
* parent-review marker.
|
|
27
|
+
*/
|
|
28
|
+
export declare function getLatestWorkerResultSnapshot(entries: readonly SessionEntry[], requestId: string): WorkerResultSnapshotPayload | undefined;
|
|
29
|
+
export type AcknowledgeWorkerReviewReason = "unknown_worker_result" | "not_flagged" | "already_reviewed";
|
|
30
|
+
export type AcknowledgeWorkerReviewResult = {
|
|
31
|
+
ok: true;
|
|
32
|
+
requestId: string;
|
|
33
|
+
reviewedAt: string;
|
|
34
|
+
} | {
|
|
35
|
+
ok: false;
|
|
36
|
+
reason: AcknowledgeWorkerReviewReason;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Durably acknowledge an unreviewed worker mutation. Re-appends the latest snapshot for
|
|
40
|
+
* `requestId` with `parentReviewedAt` set, so the ack is a first-class entry in the same
|
|
41
|
+
* append-only audit trail as the original result — it survives reload and any future re-read of
|
|
42
|
+
* `getWorkerResultSnapshots`/`getLatestWorkerResultSnapshot` (both are "latest wins"). Never
|
|
43
|
+
* write-blocking: this only marks the mutation reviewed, it does not touch the worker's files.
|
|
44
|
+
*/
|
|
45
|
+
export declare function acknowledgeWorkerResultReview(sessionManager: Pick<SessionManager, "appendCustomEntry" | "getEntries">, requestId: string, now?: () => string): AcknowledgeWorkerReviewResult;
|
|
16
46
|
//# sourceMappingURL=session-worker-result.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-worker-result.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/session-worker-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACnF,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAG5E,eAAO,MAAM,yBAAyB,kBAAkB,CAAC;AAEzD,MAAM,WAAW,2BAA2B;IAC3C,OAAO,EAAE,CAAC,CAAC;IACX,MAAM,EAAE,YAAY,CAAC;IACrB;;
|
|
1
|
+
{"version":3,"file":"session-worker-result.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/session-worker-result.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACnF,OAAO,KAAK,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAG5E,eAAO,MAAM,yBAAyB,kBAAkB,CAAC;AAEzD,MAAM,WAAW,2BAA2B;IAC3C,OAAO,EAAE,CAAC,CAAC;IACX,MAAM,EAAE,YAAY,CAAC;IACrB;;iFAE6E;IAC7E,OAAO,CAAC,EAAE,aAAa,CAAC;CACxB;AAED,wBAAgB,0BAA0B,CACzC,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,CAAC,EACzD,MAAM,EAAE,YAAY,EACpB,OAAO,CAAC,EAAE,aAAa;AACvB;;4EAE4E;AAC5E,OAAO,CAAC,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,GACxB,MAAM,CAgBR;AAED,oGAAoG;AACpG,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,aAAa,EAAE,CAY3F;AAQD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,YAAY,EAAE,CAmBzF;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC5C,OAAO,EAAE,SAAS,YAAY,EAAE,EAChC,SAAS,EAAE,MAAM,GACf,2BAA2B,GAAG,SAAS,CAkBzC;AAED,MAAM,MAAM,6BAA6B,GAAG,uBAAuB,GAAG,aAAa,GAAG,kBAAkB,CAAC;AAEzG,MAAM,MAAM,6BAA6B,GACtC;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GACnD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,6BAA6B,CAAA;CAAE,CAAC;AAExD;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC5C,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,GAAG,YAAY,CAAC,EACxE,SAAS,EAAE,MAAM,EACjB,GAAG,GAAE,MAAM,MAAuC,GAChD,6BAA6B,CAQ/B","sourcesContent":["import type { SessionEntry, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { WorkerRequest, WorkerResult } from \"../autonomy/contracts.ts\";\nimport { cloneWorkerResultForStorage, isParentReviewRequired, isWorkerResult } from \"./worker-result.ts\";\n\nexport const WORKER_RESULT_CUSTOM_TYPE = \"worker_result\";\n\nexport interface WorkerResultSnapshotPayload {\n\tversion: 1;\n\tresult: WorkerResult;\n\t/** The originating request: persisted so a result is auditable against exactly what was\n\t * asked — instructions, route, and the capability envelope that bounded it. Optional for\n\t * backward compatibility with entries recorded before this field existed. */\n\trequest?: WorkerRequest;\n}\n\nexport function appendWorkerResultSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tresult: WorkerResult,\n\trequest?: WorkerRequest,\n\t/** Baseline for relative changedFiles when re-deriving the review marker; forwarded to\n\t * `isParentReviewRequired`/`validateWorkerResult`. Defaults to `process.cwd()`, matching the\n\t * validator's own documented default for single-cwd-per-process callers. */\n\toptions?: { cwd?: string },\n): string {\n\tconst stored = cloneWorkerResultForStorage(result);\n\t// Stamp the parent-review marker here by re-running the SAME gate\n\t// (validateWorkerResult, via isParentReviewRequired) that originally decided\n\t// ask-user/parent_review_required, so the marker can never drift from the gate's own verdict.\n\t// Only computable when `request` is available; callers that omit it (legacy callers) leave the\n\t// field unset — \"unknown\", never falsely \"false\".\n\tif (request) {\n\t\tstored.parentReviewRequired = isParentReviewRequired({ request, result, cwd: options?.cwd });\n\t}\n\tconst payload: WorkerResultSnapshotPayload = {\n\t\tversion: 1,\n\t\tresult: stored,\n\t\t...(request ? { request: structuredClone(request) } : {}),\n\t};\n\treturn sessionManager.appendCustomEntry(WORKER_RESULT_CUSTOM_TYPE, payload);\n}\n\n/** Requests persisted alongside results (absent for entries recorded before this field existed). */\nexport function getWorkerRequestSnapshots(entries: readonly SessionEntry[]): WorkerRequest[] {\n\tconst requests: WorkerRequest[] = [];\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_RESULT_CUSTOM_TYPE) continue;\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload) || payload.version !== 1) continue;\n\t\tconst request = payload.request;\n\t\tif (isPlainRecord(request) && typeof request.id === \"string\") {\n\t\t\trequests.push(structuredClone(request) as unknown as WorkerRequest);\n\t\t}\n\t}\n\treturn requests;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function getWorkerResultSnapshots(entries: readonly SessionEntry[]): WorkerResult[] {\n\tconst results: WorkerResult[] = [];\n\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_RESULT_CUSTOM_TYPE) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload)) continue;\n\t\tif (payload.version !== 1) continue;\n\t\tif (!(\"result\" in payload)) continue;\n\t\tconst result = payload.result;\n\t\tif (isWorkerResult(result)) {\n\t\t\tresults.push(cloneWorkerResultForStorage(result));\n\t\t}\n\t}\n\n\treturn results;\n}\n\n/**\n * Latest persisted snapshot (result + originating request, when available) for one worker\n * requestId — \"latest wins\" over the append-only entries, the same collapse `delegate_status`\n * already performs when it maps results by requestId. Used to read, and durably update, the\n * parent-review marker.\n */\nexport function getLatestWorkerResultSnapshot(\n\tentries: readonly SessionEntry[],\n\trequestId: string,\n): WorkerResultSnapshotPayload | undefined {\n\tlet latest: WorkerResultSnapshotPayload | undefined;\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_RESULT_CUSTOM_TYPE) continue;\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload) || payload.version !== 1 || !(\"result\" in payload)) continue;\n\t\tconst result = payload.result;\n\t\tif (!isWorkerResult(result) || result.requestId !== requestId) continue;\n\t\tconst request = payload.request;\n\t\tlatest = {\n\t\t\tversion: 1,\n\t\t\tresult: cloneWorkerResultForStorage(result),\n\t\t\t...(isPlainRecord(request) && typeof request.id === \"string\"\n\t\t\t\t? { request: structuredClone(request) as unknown as WorkerRequest }\n\t\t\t\t: {}),\n\t\t};\n\t}\n\treturn latest;\n}\n\nexport type AcknowledgeWorkerReviewReason = \"unknown_worker_result\" | \"not_flagged\" | \"already_reviewed\";\n\nexport type AcknowledgeWorkerReviewResult =\n\t| { ok: true; requestId: string; reviewedAt: string }\n\t| { ok: false; reason: AcknowledgeWorkerReviewReason };\n\n/**\n * Durably acknowledge an unreviewed worker mutation. Re-appends the latest snapshot for\n * `requestId` with `parentReviewedAt` set, so the ack is a first-class entry in the same\n * append-only audit trail as the original result — it survives reload and any future re-read of\n * `getWorkerResultSnapshots`/`getLatestWorkerResultSnapshot` (both are \"latest wins\"). Never\n * write-blocking: this only marks the mutation reviewed, it does not touch the worker's files.\n */\nexport function acknowledgeWorkerResultReview(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\" | \"getEntries\">,\n\trequestId: string,\n\tnow: () => string = () => new Date().toISOString(),\n): AcknowledgeWorkerReviewResult {\n\tconst latest = getLatestWorkerResultSnapshot(sessionManager.getEntries(), requestId);\n\tif (!latest) return { ok: false, reason: \"unknown_worker_result\" };\n\tif (!latest.result.parentReviewRequired) return { ok: false, reason: \"not_flagged\" };\n\tif (latest.result.parentReviewedAt) return { ok: false, reason: \"already_reviewed\" };\n\tconst reviewedAt = now();\n\tappendWorkerResultSnapshot(sessionManager, { ...latest.result, parentReviewedAt: reviewedAt }, latest.request);\n\treturn { ok: true, requestId, reviewedAt };\n}\n"]}
|