@caupulican/pi-adaptative 0.86.17 → 0.90.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/README.md +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +14 -15
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +14 -16
- package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +4 -4
- package/dist/core/agent-session.d.ts +23 -33
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +76 -109
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +16 -0
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/subagent-prompt.d.ts +2 -1
- package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -1
- package/dist/core/autonomy/subagent-prompt.js +2 -18
- package/dist/core/autonomy/subagent-prompt.js.map +1 -1
- package/dist/core/background-tool-task-controller.js +5 -5
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +22 -2
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +75 -39
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/context/brain-curator.d.ts +2 -3
- package/dist/core/context/brain-curator.d.ts.map +1 -1
- package/dist/core/context/brain-curator.js +3 -20
- package/dist/core/context/brain-curator.js.map +1 -1
- package/dist/core/context/context-composition.d.ts +2 -1
- package/dist/core/context/context-composition.d.ts.map +1 -1
- package/dist/core/context/context-composition.js +6 -1
- package/dist/core/context/context-composition.js.map +1 -1
- package/dist/core/context/memory-prompt-block.js +1 -1
- package/dist/core/context/memory-prompt-block.js.map +1 -1
- package/dist/core/context/tool-output-packer.js +1 -1
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.js +10 -10
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +4 -4
- package/dist/core/context-pipeline.js +4 -4
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +1 -2
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/session-worker-claim.d.ts +2 -2
- package/dist/core/delegation/session-worker-claim.js +2 -2
- package/dist/core/delegation/session-worker-claim.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-resource-materializer.js +3 -3
- package/dist/core/delegation/worker-resource-materializer.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts +2 -13
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +5 -67
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/extensions/builtin.js +4 -4
- package/dist/core/extensions/builtin.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +6 -2
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +21 -9
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.js +2 -2
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
- package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
- package/dist/core/goals/compact-goal-context.js +13 -9
- package/dist/core/goals/compact-goal-context.js.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.js +1 -1
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
- package/dist/core/human-input-controller.js +1 -1
- package/dist/core/human-input-controller.js.map +1 -1
- package/dist/core/improvement-loop.js +13 -13
- package/dist/core/improvement-loop.js.map +1 -1
- package/dist/core/learning/reflection-engine.d.ts +2 -1
- package/dist/core/learning/reflection-engine.d.ts.map +1 -1
- package/dist/core/learning/reflection-engine.js +4 -24
- package/dist/core/learning/reflection-engine.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +1 -1
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-router/route-judge.d.ts +2 -1
- package/dist/core/model-router/route-judge.d.ts.map +1 -1
- package/dist/core/model-router/route-judge.js +4 -12
- package/dist/core/model-router/route-judge.js.map +1 -1
- package/dist/core/models/perf-profile.d.ts +1 -1
- package/dist/core/models/perf-profile.d.ts.map +1 -1
- package/dist/core/models/perf-profile.js +2 -8
- package/dist/core/models/perf-profile.js.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.d.ts +1 -1
- package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.js +1 -6
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
- package/dist/core/process-matrix/resume-launcher.js +3 -3
- package/dist/core/process-matrix/resume-launcher.js.map +1 -1
- package/dist/core/process-matrix/runtime.d.ts +2 -0
- package/dist/core/process-matrix/runtime.d.ts.map +1 -1
- package/dist/core/process-matrix/runtime.js +23 -19
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/provider-prompt-contracts.d.ts +34 -0
- package/dist/core/provider-prompt-contracts.d.ts.map +1 -0
- package/dist/core/provider-prompt-contracts.js +133 -0
- package/dist/core/provider-prompt-contracts.js.map +1 -0
- package/dist/core/provider-request-context-controller.d.ts +40 -0
- package/dist/core/provider-request-context-controller.d.ts.map +1 -0
- package/dist/core/provider-request-context-controller.js +68 -0
- package/dist/core/provider-request-context-controller.js.map +1 -0
- package/dist/core/provider-request-runtime-controller.d.ts +22 -0
- package/dist/core/provider-request-runtime-controller.d.ts.map +1 -0
- package/dist/core/provider-request-runtime-controller.js +87 -0
- package/dist/core/provider-request-runtime-controller.js.map +1 -0
- package/dist/core/provider-tool-text.d.ts +7 -0
- package/dist/core/provider-tool-text.d.ts.map +1 -0
- package/dist/core/provider-tool-text.js +42 -0
- package/dist/core/provider-tool-text.js.map +1 -0
- package/dist/core/research/model-fitness.d.ts +2 -5
- package/dist/core/research/model-fitness.d.ts.map +1 -1
- package/dist/core/research/model-fitness.js +2 -20
- package/dist/core/research/model-fitness.js.map +1 -1
- package/dist/core/research/research-runner.d.ts +2 -1
- package/dist/core/research/research-runner.d.ts.map +1 -1
- package/dist/core/research/research-runner.js +6 -21
- package/dist/core/research/research-runner.js.map +1 -1
- package/dist/core/risk-classifier.d.ts.map +1 -1
- package/dist/core/risk-classifier.js +9 -1
- package/dist/core/risk-classifier.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +3 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +20 -25
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +2 -1
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +2 -16
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.js +6 -6
- package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
- package/dist/core/secrets/credential-manager.d.ts +11 -1
- package/dist/core/secrets/credential-manager.d.ts.map +1 -1
- package/dist/core/secrets/credential-manager.js +28 -7
- package/dist/core/secrets/credential-manager.js.map +1 -1
- package/dist/core/secrets/credential-migration-source.d.ts +20 -0
- package/dist/core/secrets/credential-migration-source.d.ts.map +1 -0
- package/dist/core/secrets/credential-migration-source.js +113 -0
- package/dist/core/secrets/credential-migration-source.js.map +1 -0
- package/dist/core/secrets/credential-session-connection.d.ts +9 -0
- package/dist/core/secrets/credential-session-connection.d.ts.map +1 -0
- package/dist/core/secrets/credential-session-connection.js +39 -0
- package/dist/core/secrets/credential-session-connection.js.map +1 -0
- package/dist/core/security/untrusted-boundary.d.ts +2 -2
- package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
- package/dist/core/security/untrusted-boundary.js +3 -10
- package/dist/core/security/untrusted-boundary.js.map +1 -1
- package/dist/core/session-role.d.ts.map +1 -1
- package/dist/core/session-role.js +1 -2
- package/dist/core/session-role.js.map +1 -1
- package/dist/core/skill-vault.d.ts +98 -0
- package/dist/core/skill-vault.d.ts.map +1 -0
- package/dist/core/skill-vault.js +270 -0
- package/dist/core/skill-vault.js.map +1 -0
- package/dist/core/skills.d.ts +10 -9
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +42 -50
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +1 -1
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +20 -60
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +4 -4
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +87 -121
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +6 -7
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tool-capability-policy.d.ts.map +1 -1
- package/dist/core/tool-capability-policy.js +2 -1
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tool-protocol-controller.d.ts.map +1 -1
- package/dist/core/tool-protocol-controller.js +4 -7
- package/dist/core/tool-protocol-controller.js.map +1 -1
- package/dist/core/tool-selection/promotion.d.ts.map +1 -1
- package/dist/core/tool-selection/promotion.js +2 -6
- package/dist/core/tool-selection/promotion.js.map +1 -1
- package/dist/core/toolkit/reflex-interpreter.d.ts +2 -1
- package/dist/core/toolkit/reflex-interpreter.d.ts.map +1 -1
- package/dist/core/toolkit/reflex-interpreter.js +2 -14
- package/dist/core/toolkit/reflex-interpreter.js.map +1 -1
- package/dist/core/tools/ask-question.js +6 -6
- package/dist/core/tools/ask-question.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +8 -7
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate-status.d.ts +17 -13
- package/dist/core/tools/delegate-status.d.ts.map +1 -1
- package/dist/core/tools/delegate-status.js +111 -226
- package/dist/core/tools/delegate-status.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +29 -2
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +149 -48
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit.js +3 -3
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/extensionify-runtime.js +4 -4
- package/dist/core/tools/extensionify-runtime.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +2 -4
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/goal.js +3 -3
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/grep.js +2 -2
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/model-fitness.js +4 -4
- package/dist/core/tools/model-fitness.js.map +1 -1
- package/dist/core/tools/profile-writer.d.ts +30 -16
- package/dist/core/tools/profile-writer.d.ts.map +1 -1
- package/dist/core/tools/profile-writer.js +98 -59
- package/dist/core/tools/profile-writer.js.map +1 -1
- package/dist/core/tools/python.js +6 -6
- package/dist/core/tools/python.js.map +1 -1
- package/dist/core/tools/run-process.js +4 -4
- package/dist/core/tools/run-process.js.map +1 -1
- package/dist/core/tools/run-toolkit-script.js +4 -4
- package/dist/core/tools/run-toolkit-script.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts +32 -3
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +141 -34
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/core/tools/skill.d.ts +29 -0
- package/dist/core/tools/skill.d.ts.map +1 -0
- package/dist/core/tools/skill.js +79 -0
- package/dist/core/tools/skill.js.map +1 -0
- package/dist/core/tools/task-steps.js +4 -4
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +2 -0
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/worktree-sync.js +6 -6
- package/dist/core/tools/worktree-sync.js.map +1 -1
- package/dist/core/tools/write.js +3 -3
- package/dist/core/tools/write.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.js +1 -1
- package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/report-commands.js +1 -1
- package/dist/modes/interactive/report-commands.js.map +1 -1
- package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/secret-menu-controller.js +2 -18
- package/dist/modes/interactive/secret-menu-controller.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +1 -1
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/docs/compaction.md +45 -25
- package/docs/extensions.md +23 -7
- package/docs/settings.md +3 -3
- package/docs/skills.md +14 -10
- package/docs/task-steps.md +2 -2
- package/docs/tmux-agent-manager.md +1 -1
- package/docs/tool-repair.md +18 -1
- package/docs/usage.md +4 -2
- package/docs/worker-profiles.md +3 -3
- package/docs/worktree-sync.md +2 -2
- package/examples/extensions/custom-compaction.ts +5 -17
- 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/summarize.ts +3 -5
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/04-skills.ts +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/util/json-size.d.ts +0 -3
- package/dist/core/util/json-size.d.ts.map +0 -1
- package/dist/core/util/json-size.js +0 -95
- package/dist/core/util/json-size.js.map +0 -1
|
@@ -13,14 +13,14 @@
|
|
|
13
13
|
* live {@link MemoryManager} — is reached through narrow deps accessors rather than the whole
|
|
14
14
|
* AgentSession.
|
|
15
15
|
*
|
|
16
|
-
*
|
|
16
|
+
* Provider-request planning boundary (deliberate): the per-turn stages ({@link estimateCurrentContextTokens},
|
|
17
17
|
* {@link runContextAudit}, {@link runPromptPolicyPlanning}, {@link applyContextGc},
|
|
18
18
|
* {@link correlatePromptPolicyWithContextGc}, {@link runPromptEnforcement},
|
|
19
19
|
* {@link enqueueRelevanceCuration}, {@link maybeDrainBrainCuration}) are invoked from the session's
|
|
20
|
-
* context
|
|
20
|
+
* request context controller as one-line delegations, so that controller owns the pass
|
|
21
21
|
* ordering. This controller reaches {@link MemoryController} functionality only through
|
|
22
22
|
* {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports
|
|
23
|
-
* the pipeline — keeping
|
|
23
|
+
* the pipeline — keeping request planning the one place the two subsystems meet.
|
|
24
24
|
*/
|
|
25
25
|
import { type SessionManager } from "@caupulican/pi-agent-core/session";
|
|
26
26
|
import type { AgentMessage } from "@caupulican/pi-agent-core/types";
|
|
@@ -138,7 +138,7 @@ export declare class ContextPipeline {
|
|
|
138
138
|
* session that never packed anything doesn't force-create a store/dir just to audit.
|
|
139
139
|
* Never throws into a live turn: any failure degrades to an empty report.
|
|
140
140
|
*
|
|
141
|
-
* This is the memoized hot path (
|
|
141
|
+
* This is the memoized hot path (provider-request planning calls it every
|
|
142
142
|
* round trip via agent-session.ts's one-line delegation) -- see `_auditMemo`'s doc for the
|
|
143
143
|
* incremental design. `getContextAuditReport`/`getPromptPolicyReport`'s `messages`-arg
|
|
144
144
|
* recompute variants deliberately do NOT go through this method (see
|
|
@@ -13,14 +13,14 @@
|
|
|
13
13
|
* live {@link MemoryManager} — is reached through narrow deps accessors rather than the whole
|
|
14
14
|
* AgentSession.
|
|
15
15
|
*
|
|
16
|
-
*
|
|
16
|
+
* Provider-request planning boundary (deliberate): the per-turn stages ({@link estimateCurrentContextTokens},
|
|
17
17
|
* {@link runContextAudit}, {@link runPromptPolicyPlanning}, {@link applyContextGc},
|
|
18
18
|
* {@link correlatePromptPolicyWithContextGc}, {@link runPromptEnforcement},
|
|
19
19
|
* {@link enqueueRelevanceCuration}, {@link maybeDrainBrainCuration}) are invoked from the session's
|
|
20
|
-
* context
|
|
20
|
+
* request context controller as one-line delegations, so that controller owns the pass
|
|
21
21
|
* ordering. This controller reaches {@link MemoryController} functionality only through
|
|
22
22
|
* {@link ContextPipelineDeps.getMemoryManager} (never imports it), and MemoryController never imports
|
|
23
|
-
* the pipeline — keeping
|
|
23
|
+
* the pipeline — keeping request planning the one place the two subsystems meet.
|
|
24
24
|
*/
|
|
25
25
|
import { calculateContextTokens, estimateTokens, getApplicableAssistantUsageInfo, } from "@caupulican/pi-agent-core/compaction/compaction";
|
|
26
26
|
import { TokenBudget } from "@caupulican/pi-agent-core/compaction/token-budget";
|
|
@@ -259,7 +259,7 @@ export class ContextPipeline {
|
|
|
259
259
|
* session that never packed anything doesn't force-create a store/dir just to audit.
|
|
260
260
|
* Never throws into a live turn: any failure degrades to an empty report.
|
|
261
261
|
*
|
|
262
|
-
* This is the memoized hot path (
|
|
262
|
+
* This is the memoized hot path (provider-request planning calls it every
|
|
263
263
|
* round trip via agent-session.ts's one-line delegation) -- see `_auditMemo`'s doc for the
|
|
264
264
|
* incremental design. `getContextAuditReport`/`getPromptPolicyReport`'s `messages`-arg
|
|
265
265
|
* recompute variants deliberately do NOT go through this method (see
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-pipeline.js","sourceRoot":"","sources":["../../src/core/context-pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EACN,sBAAsB,EACtB,cAAc,EACd,+BAA+B,GAC/B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,mDAAmD,CAAC;AAChF,OAAO,EAEN,wBAAwB,GAGxB,MAAM,mCAAmC,CAAC;AAE3C,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,MAAM,iCAAiC,CAAC;AAG7E,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,EACN,4BAA4B,EAE5B,kBAAkB,EAClB,0BAA0B,GAC1B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AACpF,OAAO,EAAE,cAAc,EAAwB,MAAM,iBAAiB,CAAC;AACvE,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAG1E,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAA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n 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 {\n\tcalculateContextTokens,\n\testimateTokens,\n\tgetApplicableAssistantUsageInfo,\n} from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport { TokenBudget } from \"@caupulican/pi-agent-core/compaction/token-budget\";\nimport {\n\ttype CompactionEntry,\n\tgetLatestCompactionEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n} from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport { addUsage, createEmptyUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Api, AssistantMessage, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session-contracts.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 {\n\tacquireContextStoreRetention,\n\ttype ContextStoreRetentionLease,\n\tgetContextStoreDir,\n\tmigrateLegacyContextStores,\n} from \"./context/context-store-retention.ts\";\nimport { latestUserPromptText, textContentPrefix } from \"./context/message-text.ts\";\nimport { applyContextGc, type ContextGcReport } from \"./context-gc.ts\";\nimport { runIsolatedTextCompletion } from \"./isolated-text-completion.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 { resolveSessionEntryIndex } from \"./session-entry-index.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { reportSpawnedUsage } from \"./spawned-usage.ts\";\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/**\n * Incremental-memo implementation of `estimateContextTokens` (compaction.ts). The shared\n * `getApplicableAssistantUsageInfo` owns usage-anchor selection so compaction rewrites cannot make\n * this hot path drift from the canonical estimator. 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 same\n * 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 = getApplicableAssistantUsageInfo(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 getContextStoreDir(this.deps.getAgentDir(), \"gc\", this.deps.getSessionManager().getSessionId());\n\t}\n\n\tprivate _toolArtifactsDir(): string {\n\t\treturn getContextStoreDir(this.deps.getAgentDir(), \"artifacts\", this.deps.getSessionManager().getSessionId());\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({\n\t\t\tbaseDir: this._toolArtifactsDir(),\n\t\t\tprepareBaseDir: () =>\n\t\t\t\tmigrateLegacyContextStores(this.deps.getAgentDir(), this.deps.getSessionManager().getSessionId()),\n\t\t\tacquireBaseDir: () => this._ensureContextStoreRetention().artifactsDir,\n\t\t});\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 index = resolveSessionEntryIndex(sessionManager);\n\t\tif (index) {\n\t\t\tlet currentId = index.leafId;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tconst entry = index.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 index = resolveSessionEntryIndex(sessionManager);\n\t\tconst leafId = index?.leafId;\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 (index && 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 = index.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 = textContentPrefix(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: ({ systemPrompt, userPrompt, signal: chunkSignal }) =>\n\t\t\t\t\t\trunIsolatedTextCompletion(this.deps, {\n\t\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\t\tuserPrompt,\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});\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\tconst spentUsage = createEmptyUsage();\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 runIsolatedTextCompletion(this.deps, {\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tuserPrompt,\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\taddUsage(spentUsage, completion.usage);\n\t\t\t\t\treturn completion;\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\treportSpawnedUsage(this.deps, spentUsage, {\n\t\t\t\tkind: \"context-curator\",\n\t\t\t\tlabel: \"context-curator\",\n\t\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\t\t// Preserve the previous space-joined report identity without allocating it.\n\t\t\t\tidentity: results.map((result) => result.key),\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\tacquireStorageDir: () => this._ensureContextStoreRetention().gcDir,\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\tif (writePayloads) this._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\tif (writePayloads) this._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"]}
|
|
1
|
+
{"version":3,"file":"context-pipeline.js","sourceRoot":"","sources":["../../src/core/context-pipeline.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH,OAAO,EACN,sBAAsB,EACtB,cAAc,EACd,+BAA+B,GAC/B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,WAAW,EAAE,MAAM,mDAAmD,CAAC;AAChF,O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;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;AACd,CAAC","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 * Provider-request planning 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 * request context controller as one-line delegations, so that controller owns 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 request planning the one place the two subsystems meet.\n */\n\nimport {\n\tcalculateContextTokens,\n\testimateTokens,\n\tgetApplicableAssistantUsageInfo,\n} from \"@caupulican/pi-agent-core/compaction/compaction\";\nimport { TokenBudget } from \"@caupulican/pi-agent-core/compaction/token-budget\";\nimport {\n\ttype CompactionEntry,\n\tgetLatestCompactionEntry,\n\ttype SessionEntry,\n\ttype SessionManager,\n} from \"@caupulican/pi-agent-core/session\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport { addUsage, createEmptyUsage } from \"@caupulican/pi-agent-core/usage\";\nimport type { Api, AssistantMessage, Model, Usage } from \"@caupulican/pi-ai\";\nimport type { IsolatedCompletionOptions, IsolatedCompletionResult } from \"./agent-session-contracts.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 {\n\tacquireContextStoreRetention,\n\ttype ContextStoreRetentionLease,\n\tgetContextStoreDir,\n\tmigrateLegacyContextStores,\n} from \"./context/context-store-retention.ts\";\nimport { latestUserPromptText, textContentPrefix } from \"./context/message-text.ts\";\nimport { applyContextGc, type ContextGcReport } from \"./context-gc.ts\";\nimport { runIsolatedTextCompletion } from \"./isolated-text-completion.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 { resolveSessionEntryIndex } from \"./session-entry-index.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { reportSpawnedUsage } from \"./spawned-usage.ts\";\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/**\n * Incremental-memo implementation of `estimateContextTokens` (compaction.ts). The shared\n * `getApplicableAssistantUsageInfo` owns usage-anchor selection so compaction rewrites cannot make\n * this hot path drift from the canonical estimator. 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 same\n * 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 = getApplicableAssistantUsageInfo(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 getContextStoreDir(this.deps.getAgentDir(), \"gc\", this.deps.getSessionManager().getSessionId());\n\t}\n\n\tprivate _toolArtifactsDir(): string {\n\t\treturn getContextStoreDir(this.deps.getAgentDir(), \"artifacts\", this.deps.getSessionManager().getSessionId());\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({\n\t\t\tbaseDir: this._toolArtifactsDir(),\n\t\t\tprepareBaseDir: () =>\n\t\t\t\tmigrateLegacyContextStores(this.deps.getAgentDir(), this.deps.getSessionManager().getSessionId()),\n\t\t\tacquireBaseDir: () => this._ensureContextStoreRetention().artifactsDir,\n\t\t});\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 index = resolveSessionEntryIndex(sessionManager);\n\t\tif (index) {\n\t\t\tlet currentId = index.leafId;\n\t\t\twhile (currentId !== null) {\n\t\t\t\tconst entry = index.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 index = resolveSessionEntryIndex(sessionManager);\n\t\tconst leafId = index?.leafId;\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 (index && 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 = index.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 (provider-request planning 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 = textContentPrefix(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: ({ systemPrompt, userPrompt, signal: chunkSignal }) =>\n\t\t\t\t\t\trunIsolatedTextCompletion(this.deps, {\n\t\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\t\tuserPrompt,\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});\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\tconst spentUsage = createEmptyUsage();\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 runIsolatedTextCompletion(this.deps, {\n\t\t\t\t\t\tsystemPrompt,\n\t\t\t\t\t\tuserPrompt,\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\taddUsage(spentUsage, completion.usage);\n\t\t\t\t\treturn completion;\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\treportSpawnedUsage(this.deps, spentUsage, {\n\t\t\t\tkind: \"context-curator\",\n\t\t\t\tlabel: \"context-curator\",\n\t\t\t\tsessionId: this.deps.getSessionManager().getSessionId(),\n\t\t\t\t// Preserve the previous space-joined report identity without allocating it.\n\t\t\t\tidentity: results.map((result) => result.key),\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\tacquireStorageDir: () => this._ensureContextStoreRetention().gcDir,\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\tif (writePayloads) this._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\tif (writePayloads) this._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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-tool-surface.d.ts","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAG,MAAe,CAAC;AAEtD,wBAAgB,yBAAyB,CAAC,SAAS,GAAE,MAAM,CAAC,QAA2B,GAAG,SAAS,MAAM,EAAE,
|
|
1
|
+
{"version":3,"file":"default-tool-surface.d.ts","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,sBAAsB,EAAG,MAAe,CAAC;AAEtD,wBAAgB,yBAAyB,CAAC,SAAS,GAAE,MAAM,CAAC,QAA2B,GAAG,SAAS,MAAM,EAAE,CAgB1G;AAED,4CAA4C;AAC5C,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAAgC,CAAC;AAExF,yFAAyF;AACzF,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,SAAS,MAAM,EAAE,EACxB,SAAS,GAAE,MAAM,CAAC,QAA2B,GAC3C,MAAM,EAAE,CAeV"}
|
|
@@ -12,17 +12,16 @@ export const STABLE_SHELL_TOOL_NAME = "bash";
|
|
|
12
12
|
export function getDefaultActiveToolNames(_platform = process.platform) {
|
|
13
13
|
return [
|
|
14
14
|
"read",
|
|
15
|
+
"skill",
|
|
15
16
|
STABLE_SHELL_TOOL_NAME,
|
|
16
17
|
"python",
|
|
17
18
|
"edit",
|
|
18
19
|
"write",
|
|
19
|
-
"context_audit",
|
|
20
20
|
"goal",
|
|
21
21
|
"task_steps",
|
|
22
22
|
"ask_question",
|
|
23
23
|
"secret_store",
|
|
24
24
|
"delegate",
|
|
25
|
-
"profile_writer",
|
|
26
25
|
"tool_task",
|
|
27
26
|
"run_toolkit_script",
|
|
28
27
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"default-tool-surface.js","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAe,CAAC;AAEtD,MAAM,UAAU,yBAAyB,CAAC,SAAS,GAAoB,OAAO,CAAC,QAAQ;IACtF,OAAO;QACN,MAAM;QACN,sBAAsB;QACtB,QAAQ;QACR,MAAM;QACN,OAAO;QACP,
|
|
1
|
+
{"version":3,"file":"default-tool-surface.js","sourceRoot":"","sources":["../../src/core/default-tool-surface.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAe,CAAC;AAEtD,MAAM,UAAU,yBAAyB,CAAC,SAAS,GAAoB,OAAO,CAAC,QAAQ;IACtF,OAAO;QACN,MAAM;QACN,OAAO;QACP,sBAAsB;QACtB,QAAQ;QACR,MAAM;QACN,OAAO;QACP,MAAM;QACN,YAAY;QACZ,cAAc;QACd,cAAc;QACd,UAAU;QACV,WAAW;QACX,oBAAoB;KACpB,CAAC;AACH,CAAC;AAED,4CAA4C;AAC5C,MAAM,CAAC,MAAM,yBAAyB,GAAsB,yBAAyB,EAAE,CAAC;AAExF,yFAAyF;AACzF,MAAM,UAAU,uBAAuB,CACtC,KAAwB,EACxB,SAAS,GAAoB,OAAO,CAAC,QAAQ;IAE7C,MAAM,MAAM,GAAa,EAAE,CAAC;IAC5B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QAC1B,IAAI,QAAQ,GAAG,IAAI,CAAC;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC;QACxC,IAAI,KAAK,KAAK,YAAY,EAAE,CAAC;YAC5B,QAAQ,GAAG,sBAAsB,CAAC;QACnC,CAAC;aAAM,IAAI,CAAC,aAAa,EAAE,SAAS,EAAE,oBAAoB,EAAE,IAAI,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACnF,QAAQ,GAAG,QAAQ,CAAC;QACrB,CAAC;aAAM,IAAI,CAAC,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YAC5E,QAAQ,GAAG,sBAAsB,CAAC;QACnC,CAAC;QACD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAAE,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["/**\n * Default built-in tool request shared by every AgentSession construction path.\n *\n * RuntimeBuilder still registers additional opt-in tools, while model capability and UAC profile\n * filters may only narrow this request. Keeping the SDK and direct-runtime paths on one list avoids\n * silently losing goal/delegation/toolkit capabilities in SDK-created interactive sessions.\n *\n * `bash` is the stable agent shell contract on every platform; its finite grammar routes to\n * PowerShell on Windows. `python` is a separate bounded, uv-managed execution contract.\n */\nexport const STABLE_SHELL_TOOL_NAME = \"bash\" as const;\n\nexport function getDefaultActiveToolNames(_platform: NodeJS.Platform = process.platform): readonly string[] {\n\treturn [\n\t\t\"read\",\n\t\t\"skill\",\n\t\tSTABLE_SHELL_TOOL_NAME,\n\t\t\"python\",\n\t\t\"edit\",\n\t\t\"write\",\n\t\t\"goal\",\n\t\t\"task_steps\",\n\t\t\"ask_question\",\n\t\t\"secret_store\",\n\t\t\"delegate\",\n\t\t\"tool_task\",\n\t\t\"run_toolkit_script\",\n\t];\n}\n\n/** Current-process default tool request. */\nexport const DEFAULT_ACTIVE_TOOL_NAMES: readonly string[] = getDefaultActiveToolNames();\n\n/** Map legacy/platform-specific shell and tool alias names to stable agent contracts. */\nexport function mapToolNamesForPlatform(\n\tnames: readonly string[],\n\t_platform: NodeJS.Platform = process.platform,\n): string[] {\n\tconst mapped: string[] = [];\n\tfor (const name of names) {\n\t\tlet resolved = name;\n\t\tconst lower = name.toLowerCase().trim();\n\t\tif (lower === \"powershell\") {\n\t\t\tresolved = STABLE_SHELL_TOOL_NAME;\n\t\t} else if ([\"python_tool\", \"python3\", \"python_interpreter\", \"py\"].includes(lower)) {\n\t\t\tresolved = \"python\";\n\t\t} else if ([\"bash_tool\", \"shell\", \"sh\", \"terminal\", \"cmd\"].includes(lower)) {\n\t\t\tresolved = STABLE_SHELL_TOOL_NAME;\n\t\t}\n\t\tif (!mapped.includes(resolved)) mapped.push(resolved);\n\t}\n\treturn mapped;\n}\n"]}
|
|
@@ -19,8 +19,8 @@ export declare function getWorkerRequestSnapshots(entries: readonly SessionEntry
|
|
|
19
19
|
export declare function getWorkerClaimSnapshots(entries: readonly SessionEntry[]): WorkerClaim[];
|
|
20
20
|
/**
|
|
21
21
|
* Latest persisted snapshot (claim + originating request, when available) for one worker
|
|
22
|
-
* requestId — "latest wins" over the append-only entries, the same collapse `
|
|
23
|
-
*
|
|
22
|
+
* requestId — "latest wins" over the append-only entries, the same collapse `delegate status`
|
|
23
|
+
* performs when it maps results by requestId. Used to read, and durably update, the
|
|
24
24
|
* parent-review marker.
|
|
25
25
|
*/
|
|
26
26
|
export declare function getLatestWorkerClaimSnapshot(entries: readonly SessionEntry[], requestId: string): WorkerClaimSnapshotPayload | undefined;
|
|
@@ -51,8 +51,8 @@ export function getWorkerClaimSnapshots(entries) {
|
|
|
51
51
|
}
|
|
52
52
|
/**
|
|
53
53
|
* Latest persisted snapshot (claim + originating request, when available) for one worker
|
|
54
|
-
* requestId — "latest wins" over the append-only entries, the same collapse `
|
|
55
|
-
*
|
|
54
|
+
* requestId — "latest wins" over the append-only entries, the same collapse `delegate status`
|
|
55
|
+
* performs when it maps results by requestId. Used to read, and durably update, the
|
|
56
56
|
* parent-review marker.
|
|
57
57
|
*/
|
|
58
58
|
export function getLatestWorkerClaimSnapshot(entries, requestId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"session-worker-claim.js","sourceRoot":"","sources":["../../../src/core/delegation/session-worker-claim.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,4BAA4B,EAC5B,6BAA6B,EAC7B,mBAAmB,EACnB,kCAAkC,GAIlC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EACN,0BAA0B,EAC1B,sBAAsB,EACtB,aAAa,EACb,2BAA2B,GAC3B,MAAM,mBAAmB,CAAC;AAE3B,MAAM,CAAC,MAAM,wBAAwB,GAAG,cAAc,CAAC;AAQvD,MAAM,2BAA2B,GAA+C;IAC/E,UAAU,EAAE,wBAAwB;IACpC,QAAQ,EAAE,OAAO;IACjB,OAAO,EAAE,aAAa;IACtB,KAAK,EAAE,0BAA0B;CACjC,CAAC;AAEF,MAAM,UAAU,yBAAyB,CACxC,cAAyD,EACzD,KAAkB,EAClB,OAAuB;AACvB;;4EAE4E;AAC5E,OAA0B;IAE1B,MAAM,eAAe,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,0BAA0B,CAAC,eAAe,CAAC,CAAC;IAC3D,kEAAkE;IAClE,4EAA4E;IAC5E,8FAA8F;IAC9F,gG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,EAAE,aAAa,EAAE,CAAC;IACpF,IAAI,MAAM,CAAC,KAAK,CAAC,gBAAgB;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,kBAAkB,EAAE,CAAC;IACpF,MAAM,UAAU,GAAG,GAAG,EAAE,CAAC;IACzB,yBAAyB,CAAC,cAAc,EAAE,EAAE,GAAG,MAAM,CAAC,KAAK,EAAE,gBAAgB,EAAE,UAAU,EAAE,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IAC7G,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,UAAU,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import type { SessionEntry, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { WorkerClaim, WorkerRequest } from \"../autonomy/contracts.ts\";\nimport {\n\tdecodeSessionSnapshotPayload,\n\tgetActiveSessionBranchEntries,\n\tgetSessionSnapshots,\n\tisVersionOneSessionSnapshotPayload,\n\ttype SessionBranchEntrySource,\n\ttype SessionSnapshotCodec,\n\ttype SessionSnapshotPayload,\n} from \"../session-snapshot.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\nimport {\n\tcloneWorkerClaimForStorage,\n\tisParentReviewRequired,\n\tisWorkerClaim,\n\tnormalizeWorkerClaimForHost,\n} from \"./worker-claim.ts\";\n\nexport const WORKER_CLAIM_CUSTOM_TYPE = \"worker_claim\";\n\nexport type WorkerClaimSnapshotPayload = SessionSnapshotPayload<\"claim\", WorkerClaim> & {\n\t/** The originating request, when the host has one, makes a claim auditable against the\n\t * instructions, route, and capability envelope that bounded it. */\n\trequest?: WorkerRequest;\n};\n\nconst WORKER_CLAIM_SNAPSHOT_CODEC: SessionSnapshotCodec<WorkerClaim, \"claim\"> = {\n\tcustomType: WORKER_CLAIM_CUSTOM_TYPE,\n\tvalueKey: \"claim\",\n\tisValue: isWorkerClaim,\n\tclone: cloneWorkerClaimForStorage,\n};\n\nexport function appendWorkerClaimSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tclaim: WorkerClaim,\n\trequest?: WorkerRequest,\n\t/** Baseline for relative changedFiles when re-deriving the review marker; forwarded to\n\t * `isParentReviewRequired`/`validateWorkerClaim`. 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 normalizedClaim = normalizeWorkerClaimForHost(claim);\n\tconst stored = cloneWorkerClaimForStorage(normalizedClaim);\n\t// Stamp the parent-review marker here by re-running the SAME gate\n\t// (validateWorkerClaim, 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; externally managed lanes leave the field unset —\n\t// \"unknown\", never falsely \"false\".\n\tif (request) {\n\t\tstored.parentReviewRequired = isParentReviewRequired({ request, claim: normalizedClaim, cwd: options?.cwd });\n\t}\n\tconst payload: WorkerClaimSnapshotPayload = {\n\t\tversion: 1,\n\t\tclaim: stored,\n\t\t...(request ? { request: structuredClone(request) } : {}),\n\t};\n\treturn sessionManager.appendCustomEntry(WORKER_CLAIM_CUSTOM_TYPE, payload);\n}\n\n/** Requests persisted alongside worker claims. */\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_CLAIM_CUSTOM_TYPE) continue;\n\t\tconst payload = entry.data;\n\t\tif (!isVersionOneSessionSnapshotPayload(payload)) 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\nexport function getWorkerClaimSnapshots(entries: readonly SessionEntry[]): WorkerClaim[] {\n\treturn getSessionSnapshots(entries, WORKER_CLAIM_SNAPSHOT_CODEC);\n}\n\n/**\n * Latest persisted snapshot (claim + originating request, when available) for one worker\n * requestId — \"latest wins\" over the append-only entries, the same collapse `
|
|
1
|
+
{"version":3,"file":"session-worker-claim.js","sourceRoot":"","sources":["../../../src/core/delegation/session-worker-claim.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,4BAA4B,EAC5B,6BAA6B,EAC7B,mBAAmB,EACnB,kCAAkC,GAIlC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EACN,0BAA0B,EAC1B,sBAAsB,EACtB,aAAa,EACb,2BAA2B,GAC3B,MAAM,mBAAmB,CAAC;AAE3B,MAAM,CAAC,MAAM,wBAAwB,GAAG,cAAc,CAAC;AAQvD,MAAM,2BAA2B,GAA+C;IAC/E,UAAU,EAAE,wBAAwB;IACpC,QAAQ,EAAE,OAAO;IACjB,OAAO,EAAE,aAAa;IACtB,KAAK,EAAE,0BAA0B;CACjC,CAAC;AAEF,MAAM,UAAU,yBAAyB,CACxC,cAAyD,EACzD,KAAkB,EAClB,OAAuB;AACvB;;4EAE4E;AAC5E,OAA0B;IAE1B,MAAM,eAAe,GAAG,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,0BAA0B,CAAC,eAAe,CAAC,CAAC;IAC3D,kEAAkE;IAClE,4EAA4E;IAC5E,8FAA8F;IAC9F,gGAAgG;IAChG,oCAAoC;IACpC,IAAI,OAAO,EAAE,CAAC;QACb,MAAM,CAAC,oBAAoB,GAAG,sBAAsB,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,eAAe,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC;IAC9G,CAAC;IACD,MAAM,OAAO,GAA+B;QAC3C,OAAO,EAAE,CAAC;QACV,KAAK,EAAE,MAAM;QACb,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,eAAe,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,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CAAC;AAC5C,CAAC","sourcesContent":["import type { SessionEntry, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { WorkerClaim, WorkerRequest } from \"../autonomy/contracts.ts\";\nimport {\n\tdecodeSessionSnapshotPayload,\n\tgetActiveSessionBranchEntries,\n\tgetSessionSnapshots,\n\tisVersionOneSessionSnapshotPayload,\n\ttype SessionBranchEntrySource,\n\ttype SessionSnapshotCodec,\n\ttype SessionSnapshotPayload,\n} from \"../session-snapshot.ts\";\nimport { isPlainRecord } from \"../util/value-guards.ts\";\nimport {\n\tcloneWorkerClaimForStorage,\n\tisParentReviewRequired,\n\tisWorkerClaim,\n\tnormalizeWorkerClaimForHost,\n} from \"./worker-claim.ts\";\n\nexport const WORKER_CLAIM_CUSTOM_TYPE = \"worker_claim\";\n\nexport type WorkerClaimSnapshotPayload = SessionSnapshotPayload<\"claim\", WorkerClaim> & {\n\t/** The originating request, when the host has one, makes a claim auditable against the\n\t * instructions, route, and capability envelope that bounded it. */\n\trequest?: WorkerRequest;\n};\n\nconst WORKER_CLAIM_SNAPSHOT_CODEC: SessionSnapshotCodec<WorkerClaim, \"claim\"> = {\n\tcustomType: WORKER_CLAIM_CUSTOM_TYPE,\n\tvalueKey: \"claim\",\n\tisValue: isWorkerClaim,\n\tclone: cloneWorkerClaimForStorage,\n};\n\nexport function appendWorkerClaimSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tclaim: WorkerClaim,\n\trequest?: WorkerRequest,\n\t/** Baseline for relative changedFiles when re-deriving the review marker; forwarded to\n\t * `isParentReviewRequired`/`validateWorkerClaim`. 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 normalizedClaim = normalizeWorkerClaimForHost(claim);\n\tconst stored = cloneWorkerClaimForStorage(normalizedClaim);\n\t// Stamp the parent-review marker here by re-running the SAME gate\n\t// (validateWorkerClaim, 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; externally managed lanes leave the field unset —\n\t// \"unknown\", never falsely \"false\".\n\tif (request) {\n\t\tstored.parentReviewRequired = isParentReviewRequired({ request, claim: normalizedClaim, cwd: options?.cwd });\n\t}\n\tconst payload: WorkerClaimSnapshotPayload = {\n\t\tversion: 1,\n\t\tclaim: stored,\n\t\t...(request ? { request: structuredClone(request) } : {}),\n\t};\n\treturn sessionManager.appendCustomEntry(WORKER_CLAIM_CUSTOM_TYPE, payload);\n}\n\n/** Requests persisted alongside worker claims. */\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_CLAIM_CUSTOM_TYPE) continue;\n\t\tconst payload = entry.data;\n\t\tif (!isVersionOneSessionSnapshotPayload(payload)) 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\nexport function getWorkerClaimSnapshots(entries: readonly SessionEntry[]): WorkerClaim[] {\n\treturn getSessionSnapshots(entries, WORKER_CLAIM_SNAPSHOT_CODEC);\n}\n\n/**\n * Latest persisted snapshot (claim + originating request, when available) for one worker\n * requestId — \"latest wins\" over the append-only entries, the same collapse `delegate status`\n * performs when it maps results by requestId. Used to read, and durably update, the\n * parent-review marker.\n */\nexport function getLatestWorkerClaimSnapshot(\n\tentries: readonly SessionEntry[],\n\trequestId: string,\n): WorkerClaimSnapshotPayload | undefined {\n\tlet latest: WorkerClaimSnapshotPayload | undefined;\n\tfor (const entry of entries) {\n\t\tif (entry.type !== \"custom\" || entry.customType !== WORKER_CLAIM_CUSTOM_TYPE) continue;\n\t\tconst payload = entry.data;\n\t\tif (!isVersionOneSessionSnapshotPayload(payload)) continue;\n\t\tconst claim = decodeSessionSnapshotPayload(payload, WORKER_CLAIM_SNAPSHOT_CODEC);\n\t\tif (!claim || claim.requestId !== requestId) continue;\n\t\tconst request = payload.request;\n\t\tlatest = {\n\t\t\tversion: 1,\n\t\t\tclaim,\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_claim\" | \"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 claim — it survives reload and any future re-read of\n * `getWorkerClaimSnapshots`/`getLatestWorkerClaimSnapshot` (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 acknowledgeWorkerClaimReview(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\"> & SessionBranchEntrySource,\n\trequestId: string,\n\tnow: () => string = () => new Date().toISOString(),\n): AcknowledgeWorkerReviewResult {\n\tconst latest = getLatestWorkerClaimSnapshot(getActiveSessionBranchEntries(sessionManager), requestId);\n\tif (!latest) return { ok: false, reason: \"unknown_worker_claim\" };\n\tif (!latest.claim.parentReviewRequired) return { ok: false, reason: \"not_flagged\" };\n\tif (latest.claim.parentReviewedAt) return { ok: false, reason: \"already_reviewed\" };\n\tconst reviewedAt = now();\n\tappendWorkerClaimSnapshot(sessionManager, { ...latest.claim, parentReviewedAt: reviewedAt }, latest.request);\n\treturn { ok: true, requestId, reviewedAt };\n}\n"]}
|
|
@@ -1093,7 +1093,7 @@ export class WorkerAgentControlCoordinator {
|
|
|
1093
1093
|
`laneId=${args.record.laneId}`,
|
|
1094
1094
|
`status=${args.record.status}`,
|
|
1095
1095
|
...(args.record.reasonCode ? [`reasonCode=${args.record.reasonCode}`] : []),
|
|
1096
|
-
`
|
|
1096
|
+
`Transcript: delegate action="transcript" agentId="${args.childAgentId}". Entries complete; omittedMessages marks whole omissions; empty page may continue via nextCursor.`,
|
|
1097
1097
|
].join("\n");
|
|
1098
1098
|
const idempotencyKey = `terminal-handoff:${args.terminalAttemptId}`;
|
|
1099
1099
|
const transcriptInput = {
|