@caupulican/pi-adaptative 0.90.12 → 0.91.2
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 +39 -0
- package/README.md +8 -10
- package/dist/bundled-resources/skills/icm-architect/LICENSE +21 -0
- package/dist/bundled-resources/skills/icm-architect/SKILL.md +112 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/CLAUDE.md +27 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/CONTEXT.md +14 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/node.md +29 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/object.md +43 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/process.md +38 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/questionnaire.md +9 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/schema.md +24 -0
- package/dist/bundled-resources/skills/icm-architect/assets/templates/stage-CONTEXT.md +21 -0
- package/dist/bundled-resources/skills/icm-architect/references/core.md +92 -0
- package/dist/bundled-resources/skills/icm-architect/references/forms.md +182 -0
- package/dist/bundled-resources/skills/icm-architect/references/system-map.md +122 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +2 -1
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-paths.d.ts +2 -2
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +1 -0
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/agent-session.d.ts +12 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +40 -10
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +2 -0
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/background-tool-task-controller.d.ts +9 -0
- package/dist/core/background-tool-task-controller.d.ts.map +1 -1
- package/dist/core/background-tool-task-controller.js +23 -0
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/bash-executor.js +3 -3
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/context/local-graph-memory-provider.d.ts +9 -0
- package/dist/core/context/local-graph-memory-provider.d.ts.map +1 -0
- package/dist/core/context/local-graph-memory-provider.js +122 -0
- package/dist/core/context/local-graph-memory-provider.js.map +1 -0
- package/dist/core/context/tool-output-packer.d.ts +2 -2
- package/dist/core/context/tool-output-packer.d.ts.map +1 -1
- package/dist/core/context/tool-output-packer.js +3 -3
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +2 -0
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +5 -0
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts +1 -0
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +16 -8
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-agent-control.d.ts +2 -0
- package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control.js.map +1 -1
- package/dist/core/delegation/worker-context-inheritance-policy.d.ts +3 -3
- package/dist/core/delegation/worker-context-inheritance-policy.js +4 -4
- package/dist/core/delegation/worker-context-inheritance-policy.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts +1 -5
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +19 -9
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +2 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.js +6 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +1 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts +0 -1
- package/dist/core/foreground-terminal-handoff-controller.d.ts.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.js +1 -2
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
- package/dist/core/goals/goal-continuation-controller.d.ts +7 -1
- package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-controller.js +16 -0
- package/dist/core/goals/goal-continuation-controller.js.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.d.ts +3 -0
- package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
- package/dist/core/goals/goal-runtime-snapshot.js +8 -1
- package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +2 -0
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +1 -0
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +18 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +62 -0
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/goals/natural-language-goal.d.ts.map +1 -1
- package/dist/core/goals/natural-language-goal.js +4 -2
- package/dist/core/goals/natural-language-goal.js.map +1 -1
- package/dist/core/human-input-controller.d.ts +3 -34
- package/dist/core/human-input-controller.d.ts.map +1 -1
- package/dist/core/human-input-controller.js +3 -161
- package/dist/core/human-input-controller.js.map +1 -1
- package/dist/core/keybindings.d.ts +5 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +2 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/learning/reflection-turn-analysis.d.ts.map +1 -1
- package/dist/core/learning/reflection-turn-analysis.js +10 -1
- package/dist/core/learning/reflection-turn-analysis.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +4 -0
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/memory-controller.d.ts +3 -0
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +18 -0
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +1 -0
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/orchestration/work-state-projection.d.ts +4 -0
- package/dist/core/orchestration/work-state-projection.d.ts.map +1 -1
- package/dist/core/orchestration/work-state-projection.js +11 -0
- package/dist/core/orchestration/work-state-projection.js.map +1 -1
- package/dist/core/pipelines/context.d.ts +6 -0
- package/dist/core/pipelines/context.d.ts.map +1 -0
- package/dist/core/pipelines/context.js +102 -0
- package/dist/core/pipelines/context.js.map +1 -0
- package/dist/core/pipelines/discover.d.ts +11 -0
- package/dist/core/pipelines/discover.d.ts.map +1 -0
- package/dist/core/pipelines/discover.js +147 -0
- package/dist/core/pipelines/discover.js.map +1 -0
- package/dist/core/pipelines/increment.d.ts +24 -0
- package/dist/core/pipelines/increment.d.ts.map +1 -0
- package/dist/core/pipelines/increment.js +121 -0
- package/dist/core/pipelines/increment.js.map +1 -0
- package/dist/core/pipelines/index.d.ts +8 -0
- package/dist/core/pipelines/index.d.ts.map +1 -0
- package/dist/core/pipelines/index.js +8 -0
- package/dist/core/pipelines/index.js.map +1 -0
- package/dist/core/pipelines/parse-contract.d.ts +10 -0
- package/dist/core/pipelines/parse-contract.d.ts.map +1 -0
- package/dist/core/pipelines/parse-contract.js +105 -0
- package/dist/core/pipelines/parse-contract.js.map +1 -0
- package/dist/core/pipelines/run-state.d.ts +26 -0
- package/dist/core/pipelines/run-state.d.ts.map +1 -0
- package/dist/core/pipelines/run-state.js +135 -0
- package/dist/core/pipelines/run-state.js.map +1 -0
- package/dist/core/pipelines/session-pipeline-run.d.ts +6 -0
- package/dist/core/pipelines/session-pipeline-run.d.ts.map +1 -0
- package/dist/core/pipelines/session-pipeline-run.js +18 -0
- package/dist/core/pipelines/session-pipeline-run.js.map +1 -0
- package/dist/core/pipelines/types.d.ts +91 -0
- package/dist/core/pipelines/types.d.ts.map +1 -0
- package/dist/core/pipelines/types.js +44 -0
- package/dist/core/pipelines/types.js.map +1 -0
- package/dist/core/reflection-controller.d.ts +2 -0
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +53 -30
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/resource-loader.d.ts +21 -0
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +45 -18
- package/dist/core/resource-loader.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 +49 -1
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +3 -0
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-role.d.ts.map +1 -1
- package/dist/core/session-role.js +2 -0
- package/dist/core/session-role.js.map +1 -1
- package/dist/core/settings-manager.d.ts +12 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +43 -9
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.js +1 -1
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +30 -22
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/task-projection.d.ts +2 -0
- package/dist/core/tasks/task-projection.d.ts.map +1 -1
- package/dist/core/tasks/task-projection.js +1 -0
- package/dist/core/tasks/task-projection.js.map +1 -1
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +6 -1
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +11 -3
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +9 -3
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +47 -5
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/goal.d.ts +16 -1
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +14 -2
- package/dist/core/tools/goal.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/output-accumulator.d.ts +5 -0
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +33 -2
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/pipeline.d.ts +35 -0
- package/dist/core/tools/pipeline.d.ts.map +1 -0
- package/dist/core/tools/pipeline.js +203 -0
- package/dist/core/tools/pipeline.js.map +1 -0
- package/dist/core/tools/skill-audit.d.ts.map +1 -1
- package/dist/core/tools/skill-audit.js +2 -1
- package/dist/core/tools/skill-audit.js.map +1 -1
- package/dist/core/tools/skill.d.ts.map +1 -1
- package/dist/core/tools/skill.js +2 -1
- package/dist/core/tools/skill.js.map +1 -1
- package/dist/core/tools/skillify.d.ts.map +1 -1
- package/dist/core/tools/skillify.js +3 -1
- package/dist/core/tools/skillify.js.map +1 -1
- package/dist/core/tools/task-steps.d.ts +1 -1
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +9 -0
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/tool-task.d.ts.map +1 -1
- package/dist/core/tools/tool-task.js +5 -1
- package/dist/core/tools/tool-task.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +1 -0
- package/dist/core/tools/write.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +3 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +66 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js +1 -1
- package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +6 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +20 -1
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-group.d.ts +4 -0
- package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-group.js +96 -7
- package/dist/modes/interactive/components/tool-group.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +8 -10
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/key-handlers.d.ts +1 -0
- package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
- package/dist/modes/interactive/key-handlers.js +2 -1
- package/dist/modes/interactive/key-handlers.js.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.js +12 -0
- package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
- package/docs/extensions.md +7 -5
- package/docs/harness-architecture.md +3 -4
- package/docs/keybindings.md +3 -2
- package/docs/quickstart.md +4 -4
- package/docs/sdk.md +3 -1
- package/docs/settings.md +16 -2
- package/docs/task-steps.md +1 -0
- package/docs/usage.md +6 -7
- package/docs/worker-profiles.md +1 -1
- package/docs/worktree-sync.md +1 -1
- 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/minimal-mode.ts +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/07-context-files.ts +5 -2
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"file-store.js","sourceRoot":"","sources":["../../../../src/core/memory/providers/file-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAG1E,OAAO,EACN,mBAAmB,EACnB,sBAAsB,EACtB,qBAAqB,GACrB,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,QAAgB,EAAE,OAAe;IAC3E,MAAM,kBAAkB,GAAG,GAAG,CAAC;IAC/B,MAAM,aAAa,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;IACxC,IAAI,aAAa,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,C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C,CAAC;4BACtF,CAAC;4BAED,IAAI,MAAM,KAAK,QAAQ;gCAAE,IAAI,CAAC,iBAAiB,GAAG,UAAU,CAAC;;gCACxD,IAAI,CAAC,eAAe,GAAG,UAAU,CAAC;4BACvC,IAAI,cAAc,IAAI,UAAU,KAAK,aAAa;gCAAE,IAAI,CAAC,OAAO,CAAC,sBAAsB,EAAE,EAAE,CAAC;4BAE5F,OAAO;gCACN,OAAO,EAAE;oCACR;wCACC,IAAI,EAAE,MAAM;wCACZ,IAAI,EAAE,wBAAwB,MAAM,KAAK,QAAQ,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,GAAG;qCAC9E;iCACD;gCACD,OAAO,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE;6BAC1B,CAAC;wBACH,CAAC,CAAC,CAAC;oBACJ,CAAC;oBAAC,OAAO,GAAG,EAAE,CAAC;wBACd,OAAO;4BACN,OAAO,EAAE;gCACR;oCACC,IAAI,EAAE,MAAM;oCACZ,IAAI,EAAE,8CAA8C,MAAM,CAAC,GAAG,CAAC,EAAE;iCACjE;6BACD;4BACD,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE;yBAC/C,CAAC;oBACH,CAAC;gBACF,CAAC;aACD;SACD,CAAC;IACH,CAAC;CACD","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport { type Static, Type } from \"typebox\";\nimport { configFile, managedMemoryStateFile } from \"../../agent-paths.ts\";\nimport type { MemoryPromptBudget } from \"../../context/memory-prompt-budget.ts\";\nimport type { ToolDefinition } from \"../../extensions/types.ts\";\nimport {\n\thasInvisibleUnicode,\n\tscanContextFileThreats,\n\tstripInvisibleUnicode,\n} from \"../../security/context-threat-scanner.ts\";\nimport { jaccard, tokenize } from \"../../tools/skill-audit.ts\";\nimport { withFileLock, writeFileAtomic } from \"../../util/atomic-file.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"../memory-provider.ts\";\nimport { UserMemoryArchive } from \"./user-memory-archive.ts\";\n\n/**\n * Confront-before-write (anti append-rot): if `content` is a near-duplicate of an existing\n * non-empty line (token Jaccard ≥ threshold — i.e. the same fact reworded), supersede that line in\n * place and return the rewritten file; otherwise return null (the caller appends normally).\n */\nexport function supersedeNearDuplicateLine(existing: string, content: string): string | null {\n\tconst NEAR_DUP_THRESHOLD = 0.6;\n\tconst contentTokens = tokenize(content);\n\tif (contentTokens.length === 0) return null;\n\tconst lines = existing.split(\"\\n\");\n\tlet bestIdx = -1;\n\tlet bestScore = NEAR_DUP_THRESHOLD;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i].trim();\n\t\tif (!line) continue;\n\t\t// Never supersede structural Markdown (headings, list markers as headings) — a fact must not\n\t\t// silently overwrite section structure.\n\t\tif (line.startsWith(\"#\")) continue;\n\t\tconst score = jaccard(contentTokens, tokenize(line));\n\t\tif (score >= bestScore) {\n\t\t\tbestScore = score;\n\t\t\tbestIdx = i;\n\t\t}\n\t}\n\tif (bestIdx === -1) return null;\n\tlines[bestIdx] = content;\n\treturn lines.join(\"\\n\");\n}\n\nconst memorySchema = Type.Object({\n\taction: Type.Union([Type.Literal(\"add\"), Type.Literal(\"replace\"), Type.Literal(\"remove\")], {\n\t\tdescription: \"Action to perform: add new content, replace existing content, or remove content\",\n\t}),\n\ttarget: Type.Union([Type.Literal(\"memory\"), Type.Literal(\"user\")], {\n\t\tdescription: \"Target file: 'memory' for MEMORY.md, 'user' for USER.md\",\n\t}),\n\tcontent: Type.Optional(Type.String({ description: \"Content to write (required for 'add' or 'replace')\" })),\n\toldContent: Type.Optional(\n\t\tType.String({ description: \"Exact substring to replace or remove (required for 'replace' or 'remove')\" }),\n\t),\n});\n\ntype MemoryParams = Static<typeof memorySchema>;\n\nexport interface FileStoreProviderOptions {\n\tonDurableMemoryChanged?: () => void;\n}\n\nexport const FILE_STORE_MEMORY_SYSTEM_NOTE =\n\t\"[System Note: Below is a snapshot of persistent memory. Proactively record verified reusable project facts and user preferences with the 'memory' tool; never store transient noise.]\";\n\ninterface ManagedMemoryState {\n\tversion: 1;\n\tcommittedDigest: string;\n\tpendingDigest?: string;\n}\n\ntype ManagedMemoryStateRead =\n\t| { status: \"missing\" }\n\t| { status: \"valid\"; state: ManagedMemoryState }\n\t| { status: \"invalid\"; raw: string };\n\nfunction contentDigest(content: string): string {\n\treturn createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction parseManagedMemoryState(raw: string): ManagedMemoryState | undefined {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null) return undefined;\n\tconst record = parsed as Record<string, unknown>;\n\tif (record.version !== 1 || typeof record.committedDigest !== \"string\") return undefined;\n\tif (record.pendingDigest !== undefined && typeof record.pendingDigest !== \"string\") return undefined;\n\treturn {\n\t\tversion: 1,\n\t\tcommittedDigest: record.committedDigest,\n\t\t...(typeof record.pendingDigest === \"string\" ? { pendingDigest: record.pendingDigest } : {}),\n\t};\n}\n\nasync function readManagedMemoryState(statePath: string): Promise<ManagedMemoryStateRead> {\n\ttry {\n\t\tconst raw = await fs.readFile(statePath, \"utf8\");\n\t\tconst state = parseManagedMemoryState(raw);\n\t\treturn state ? { status: \"valid\", state } : { status: \"invalid\", raw };\n\t} catch (error) {\n\t\tif (isMissingFileError(error)) return { status: \"missing\" };\n\t\tthrow error;\n\t}\n}\n\nfunction serializeManagedMemoryState(state: ManagedMemoryState): string {\n\treturn `${JSON.stringify(state)}\\n`;\n}\n\nasync function writeManagedMemoryState(statePath: string, state: ManagedMemoryState): Promise<void> {\n\tawait writeFileAtomic(statePath, serializeManagedMemoryState(state), { mode: 0o600 });\n}\n\nfunction reconcileManagedMemoryState(\n\tcurrentDigest: string,\n\tstate: ManagedMemoryState,\n): { recognized: true; state: ManagedMemoryState; changed: boolean } | { recognized: false } {\n\tif (currentDigest === state.committedDigest) {\n\t\tif (state.pendingDigest === undefined) return { recognized: true, state, changed: false };\n\t\treturn {\n\t\t\trecognized: true,\n\t\t\tstate: { version: 1, committedDigest: state.committedDigest },\n\t\t\tchanged: true,\n\t\t};\n\t}\n\tif (state.pendingDigest !== undefined && currentDigest === state.pendingDigest) {\n\t\treturn {\n\t\t\trecognized: true,\n\t\t\tstate: { version: 1, committedDigest: state.pendingDigest },\n\t\t\tchanged: true,\n\t\t};\n\t}\n\treturn { recognized: false };\n}\n\nfunction fitMemoryBlockToBudget(block: string, budget: MemoryPromptBudget | undefined): string {\n\tif (budget === undefined) return block;\n\tif (!budget.enabled || budget.maxLines <= 0 || budget.maxChars <= 0) return \"\";\n\tif (block.split(\"\\n\").length <= budget.maxLines && block.length <= budget.maxChars) return block;\n\t// Micro-context profiles deliberately omit a block that cannot fit whole. Larger constrained\n\t// profiles retain a bounded head and say explicitly that more memory exists on disk.\n\tif (budget.compact) return \"\";\n\n\tconst marker = \"[…memory truncated for capability budget; full files remain on disk]\";\n\tif (budget.maxLines < 2 || budget.maxChars <= marker.length + 1) return \"\";\n\tconst lines: string[] = [];\n\tlet chars = 0;\n\tconst contentCharLimit = budget.maxChars - marker.length - 1;\n\tfor (const line of block.split(\"\\n\")) {\n\t\tif (lines.length >= budget.maxLines - 1) break;\n\t\tconst separatorChars = lines.length > 0 ? 1 : 0;\n\t\tconst remaining = contentCharLimit - chars - separatorChars;\n\t\tif (remaining <= 0) break;\n\t\tconst rendered = line.length <= remaining ? line : `${line.slice(0, Math.max(0, remaining - 1))}…`;\n\t\tlines.push(rendered);\n\t\tchars += separatorChars + rendered.length;\n\t\tif (rendered.length !== line.length) break;\n\t}\n\tif (lines.length === 0) return \"\";\n\tlines.push(marker);\n\treturn lines.join(\"\\n\");\n}\n\nexport class FileStoreProvider implements MemoryProvider {\n\tpublic readonly name = \"file-store\";\n\tpublic readonly egress = \"local\";\n\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate memoryFilePath = \"\";\n\tprivate userFilePath = \"\";\n\tprivate memoryStatePath = \"\";\n\tprivate userStatePath = \"\";\n\n\tprivate lastWrittenMemory = \"\";\n\tprivate lastWrittenUser = \"\";\n\tprivate userArchive?: UserMemoryArchive;\n\tprivate readonly options: FileStoreProviderOptions;\n\n\t// Character budgets\n\tprivate static readonly BUDGET_MEMORY = 2200;\n\tprivate static readonly BUDGET_USER = 1375;\n\n\tconstructor(options: FileStoreProviderOptions = {}) {\n\t\tthis.options = options;\n\t}\n\n\tpublic isAvailable(): boolean {\n\t\treturn true;\n\t}\n\n\tpublic getCapabilities() {\n\t\treturn { surfaces: [\"context\" as const] };\n\t}\n\n\tpublic async initialize(_sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.memoryFilePath = configFile(ctx.agentDir, \"MEMORY.md\");\n\t\tthis.userFilePath = configFile(ctx.agentDir, \"USER.md\");\n\t\tthis.memoryStatePath = managedMemoryStateFile(ctx.agentDir, \"MEMORY.md\");\n\t\tthis.userStatePath = managedMemoryStateFile(ctx.agentDir, \"USER.md\");\n\t\tthis.userArchive = new UserMemoryArchive(ctx.agentDir);\n\n\t\tawait fs.mkdir(ctx.agentDir, { recursive: true });\n\t\t[this.lastWrittenMemory, this.lastWrittenUser] = await Promise.all([\n\t\t\tthis.initializeManagedFile(this.memoryFilePath, this.memoryStatePath),\n\t\t\tthis.initializeManagedFile(this.userFilePath, this.userStatePath),\n\t\t]);\n\t}\n\n\tprivate async initializeManagedFile(filePath: string, statePath: string): Promise<string> {\n\t\treturn withFileLock(filePath, async () => {\n\t\t\tlet current = \"\";\n\t\t\ttry {\n\t\t\t\tcurrent = await fs.readFile(filePath, \"utf8\");\n\t\t\t} catch (error) {\n\t\t\t\tif (!isMissingFileError(error)) throw error;\n\t\t\t\tawait writeFileAtomic(filePath, \"\", { mode: 0o600 });\n\t\t\t}\n\n\t\t\tconst currentDigest = contentDigest(current);\n\t\t\tconst stateRead = await readManagedMemoryState(statePath);\n\t\t\tif (stateRead.status === \"missing\") {\n\t\t\t\tawait writeManagedMemoryState(statePath, { version: 1, committedDigest: currentDigest });\n\t\t\t\treturn current;\n\t\t\t}\n\t\t\tif (stateRead.status === \"invalid\") {\n\t\t\t\tawait writeFileAtomic(`${statePath}.bak.${Date.now()}.${randomUUID()}`, stateRead.raw, { mode: 0o600 });\n\t\t\t\tawait writeManagedMemoryState(statePath, { version: 1, committedDigest: currentDigest });\n\t\t\t\treturn current;\n\t\t\t}\n\n\t\t\tconst reconciled = reconcileManagedMemoryState(currentDigest, stateRead.state);\n\t\t\tif (reconciled.recognized && reconciled.changed) {\n\t\t\t\tawait writeManagedMemoryState(statePath, reconciled.state);\n\t\t\t}\n\t\t\treturn current;\n\t\t});\n\t}\n\n\tpublic systemPromptBlock(budget?: MemoryPromptBudget): string {\n\t\tconst sanitize = (content: string) => {\n\t\t\t// Strip hidden/bidi-control chars before injecting memory into the prompt (defence in depth: the\n\t\t\t// write path already blocks them, but a file edited out-of-band could carry them). Strip #31.\n\t\t\tconst lines = stripInvisibleUnicode(content).cleaned.split(\"\\n\");\n\t\t\tconst sanitizedLines = lines.map((line) => {\n\t\t\t\tconst threats = scanContextFileThreats(line);\n\t\t\t\tif (threats.length > 0) {\n\t\t\t\t\treturn `[BLOCKED: potential threat detected (${threats.join(\", \")})]`;\n\t\t\t\t}\n\t\t\t\treturn line;\n\t\t\t});\n\t\t\treturn sanitizedLines.join(\"\\n\");\n\t\t};\n\n\t\t// Read-time budget guard (cost): the memory tool already caps writes at BUDGET_*, but a file edited\n\t\t// externally (or by any path that bypasses the tool) could be arbitrarily large and would then\n\t\t// bloat the system prompt on EVERY turn. Cap the injected view to the same budget so the per-turn\n\t\t// cost stays bounded; the file on disk is untouched and the model is told it was truncated.\n\t\tconst cap = (content: string, limit: number) => {\n\t\t\tif (content.length <= limit) return content;\n\t\t\treturn `${content.slice(0, limit)}\\n[…truncated to ${limit} chars for the prompt; full file is on disk]`;\n\t\t};\n\n\t\tconst mem = cap(sanitize(this.lastWrittenMemory), FileStoreProvider.BUDGET_MEMORY);\n\t\tconst usr = cap(sanitize(this.lastWrittenUser), FileStoreProvider.BUDGET_USER);\n\n\t\tconst blocks: string[] = [];\n\t\tif (mem.trim()) {\n\t\t\tblocks.push(`## MEMORY.md:\\n${mem}`);\n\t\t}\n\t\tif (usr.trim()) {\n\t\t\tblocks.push(`## USER.md:\\n${usr}`);\n\t\t}\n\n\t\tif (blocks.length === 0) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tconst block = `=== Persistent Memory (file-store) ===\\n${FILE_STORE_MEMORY_SYSTEM_NOTE}\\n\\n${blocks.join(\"\\n\\n\")}`;\n\t\treturn fitMemoryBlockToBudget(block, budget);\n\t}\n\n\tpublic async prefetch(_query: string): Promise<string> {\n\t\t// static system prompt block is sufficient for file-store default; no-op prefetch\n\t\treturn \"\";\n\t}\n\n\tpublic async shutdown(): Promise<void> {\n\t\t// no-op\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\treturn [];\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tname: \"memory\",\n\t\t\t\tlabel: \"Persistent Memory Manager\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Add, replace, or remove durable project facts and user preferences. Proactively store newly verified reusable facts; USER.md overflow is migrated into indexed OKF shards.\",\n\t\t\t\tparameters: memorySchema,\n\t\t\t\texecute: async (_toolCallId, params: MemoryParams, _signal, _onUpdate, _execCtx) => {\n\t\t\t\t\tif (this.ctx?.isChildSession) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: \"Error: Writes to persistent memory are not allowed in child sessions (subagents).\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { success: false, error: \"Child session write-gated\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tconst { action, target, content, oldContent } = params;\n\n\t\t\t\t\t// Strict-scope injection guard on the high-privilege WRITE path (agy #31): a poisoned\n\t\t\t\t\t// memory entry persists across sessions and is injected into every future system prompt,\n\t\t\t\t\t// so block outright rather than strip. Hidden/bidi-control chars have no legitimate place\n\t\t\t\t\t// in a memory note, so reject those too.\n\t\t\t\t\tif ((action === \"add\" || action === \"replace\") && content !== undefined) {\n\t\t\t\t\t\tif (hasInvisibleUnicode(content)) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: \"Error: memory write rejected — contains hidden/bidirectional control characters.\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { success: false, error: \"Invisible unicode in memory write\" },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst threats = scanContextFileThreats(content, \"strict\");\n\t\t\t\t\t\tif (threats.length > 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `Error: memory write rejected — potential injection/exfiltration detected (${threats.join(\", \")}).`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { success: false, error: \"Threat in memory write\" },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst filePath = target === \"memory\" ? this.memoryFilePath : this.userFilePath;\n\t\t\t\t\tconst statePath = target === \"memory\" ? this.memoryStatePath : this.userStatePath;\n\t\t\t\t\tconst budget = target === \"memory\" ? FileStoreProvider.BUDGET_MEMORY : FileStoreProvider.BUDGET_USER;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await withFileLock(filePath, async () => {\n\t\t\t\t\t\t\tconst currentOnDisk = await fs.readFile(filePath, \"utf8\");\n\t\t\t\t\t\t\tconst currentDigest = contentDigest(currentOnDisk);\n\t\t\t\t\t\t\tconst stateRead = await readManagedMemoryState(statePath);\n\t\t\t\t\t\t\tlet managedState: ManagedMemoryState | undefined;\n\t\t\t\t\t\t\tif (stateRead.status === \"valid\") {\n\t\t\t\t\t\t\t\tconst reconciled = reconcileManagedMemoryState(currentDigest, stateRead.state);\n\t\t\t\t\t\t\t\tif (reconciled.recognized) {\n\t\t\t\t\t\t\t\t\tmanagedState = reconciled.state;\n\t\t\t\t\t\t\t\t\tif (reconciled.changed) await writeManagedMemoryState(statePath, reconciled.state);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!managedState) {\n\t\t\t\t\t\t\t\tconst backupPath = `${filePath}.bak.${Date.now()}`;\n\t\t\t\t\t\t\t\tawait writeFileAtomic(backupPath, currentOnDisk, { mode: 0o600 });\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\ttext: `Error: Drift detected. The memory file has been modified out-of-band by an external process. A backup was created at ${backupPath}. Operation aborted.`,\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\tdetails: { success: false, error: \"Drift detected\" },\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// A peer session's committed write is authoritative. Refresh this provider's prompt\n\t\t\t\t\t\t\t// snapshot before applying the caller's mutation to that current content.\n\t\t\t\t\t\t\tif (target === \"memory\") this.lastWrittenMemory = currentOnDisk;\n\t\t\t\t\t\t\telse this.lastWrittenUser = currentOnDisk;\n\n\t\t\t\t\t\t\tlet newContent = currentOnDisk;\n\t\t\t\t\t\t\tlet archiveChanged = false;\n\t\t\t\t\t\t\tif (target === \"user\") {\n\t\t\t\t\t\t\t\tif (!this.userArchive) throw new Error(\"User memory archive is not initialized.\");\n\t\t\t\t\t\t\t\tif (action === \"add\") {\n\t\t\t\t\t\t\t\t\tif (content === undefined)\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'content' is required for action 'add'.\");\n\t\t\t\t\t\t\t\t\tconst result = await this.userArchive.apply(\n\t\t\t\t\t\t\t\t\t\tcurrentOnDisk,\n\t\t\t\t\t\t\t\t\t\t{ action, content },\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tsupersedeNearDuplicateLine,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tnewContent = result.userContent;\n\t\t\t\t\t\t\t\t\tarchiveChanged = result.archiveChanged;\n\t\t\t\t\t\t\t\t} else if (action === \"replace\") {\n\t\t\t\t\t\t\t\t\tif (content === undefined || oldContent === undefined) {\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\"Parameters 'content' and 'oldContent' are required for action 'replace'.\",\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\tconst result = await this.userArchive.apply(\n\t\t\t\t\t\t\t\t\t\tcurrentOnDisk,\n\t\t\t\t\t\t\t\t\t\t{ action, content, oldContent },\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tsupersedeNearDuplicateLine,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tnewContent = result.userContent;\n\t\t\t\t\t\t\t\t\tarchiveChanged = result.archiveChanged;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif (oldContent === undefined)\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'oldContent' is required for action 'remove'.\");\n\t\t\t\t\t\t\t\t\tconst result = await this.userArchive.apply(\n\t\t\t\t\t\t\t\t\t\tcurrentOnDisk,\n\t\t\t\t\t\t\t\t\t\t{ action, oldContent },\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tsupersedeNearDuplicateLine,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tnewContent = result.userContent;\n\t\t\t\t\t\t\t\t\tarchiveChanged = result.archiveChanged;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (action === \"add\") {\n\t\t\t\t\t\t\t\tif (content === undefined) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'content' is required for action 'add'.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst superseded = supersedeNearDuplicateLine(currentOnDisk, content);\n\t\t\t\t\t\t\t\tif (superseded !== null) {\n\t\t\t\t\t\t\t\t\tnewContent = superseded;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tnewContent =\n\t\t\t\t\t\t\t\t\t\tnewContent.endsWith(\"\\n\") || newContent === \"\"\n\t\t\t\t\t\t\t\t\t\t\t? `${newContent}${content}\\n`\n\t\t\t\t\t\t\t\t\t\t\t: `${newContent}\\n${content}\\n`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (action === \"replace\") {\n\t\t\t\t\t\t\t\tif (content === undefined || oldContent === undefined) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameters 'content' and 'oldContent' are required for action 'replace'.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (!currentOnDisk.includes(oldContent)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`The content to replace ('oldContent') was not found in the file.`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewContent = currentOnDisk.replace(oldContent, content);\n\t\t\t\t\t\t\t} else if (action === \"remove\") {\n\t\t\t\t\t\t\t\tif (oldContent === undefined) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'oldContent' is required for action 'remove'.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (!currentOnDisk.includes(oldContent)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`The content to remove ('oldContent') was not found in the file.`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewContent = currentOnDisk.replace(oldContent, \"\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (newContent.length > budget) {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\ttext: `Error: Memory budget exceeded. ${target === \"memory\" ? \"MEMORY.md\" : \"USER.md\"} limit is ${budget} characters. Current operation would result in ${newContent.length} characters.`,\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\tdetails: { success: false, error: \"Memory budget exceeded\" },\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (newContent !== currentOnDisk) {\n\t\t\t\t\t\t\t\tconst newDigest = contentDigest(newContent);\n\t\t\t\t\t\t\t\tawait writeManagedMemoryState(statePath, {\n\t\t\t\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\t\t\t\tcommittedDigest: managedState.committedDigest,\n\t\t\t\t\t\t\t\t\tpendingDigest: newDigest,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tawait writeFileAtomic(filePath, newContent, { mode: 0o600 });\n\t\t\t\t\t\t\t\tawait writeManagedMemoryState(statePath, { version: 1, committedDigest: newDigest });\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (target === \"memory\") this.lastWrittenMemory = newContent;\n\t\t\t\t\t\t\telse this.lastWrittenUser = newContent;\n\t\t\t\t\t\t\tif (archiveChanged || newContent !== currentOnDisk) this.options.onDurableMemoryChanged?.();\n\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `Successfully updated ${target === \"memory\" ? \"MEMORY.md\" : \"USER.md\"}.`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { success: true },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: `Error: Failed to perform memory operation: ${String(err)}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { success: false, error: String(err) },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"file-store.js","sourceRoot":"","sources":["../../../../src/core/memory/providers/file-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAG1E,OAAO,EAC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ACD,OAAO,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE;yBAC/C,CAAC;oBACH,CAAC;gBACF,CAAC;aACD;SACD,CAAC;IACH,CAAC;CACD","sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { promises as fs } from \"node:fs\";\nimport { type Static, Type } from \"typebox\";\nimport { configFile, managedMemoryStateFile } from \"../../agent-paths.ts\";\nimport type { MemoryPromptBudget } from \"../../context/memory-prompt-budget.ts\";\nimport type { ToolDefinition } from \"../../extensions/types.ts\";\nimport {\n\thasInvisibleUnicode,\n\tscanContextFileThreats,\n\tstripInvisibleUnicode,\n} from \"../../security/context-threat-scanner.ts\";\nimport { jaccard, tokenize } from \"../../tools/skill-audit.ts\";\nimport { withFileLock, writeFileAtomic } from \"../../util/atomic-file.ts\";\nimport type { MemoryLifecycleContext, MemoryProvider } from \"../memory-provider.ts\";\nimport { UserMemoryArchive } from \"./user-memory-archive.ts\";\n\n/**\n * Confront-before-write (anti append-rot): if `content` is a near-duplicate of an existing\n * non-empty line (token Jaccard ≥ threshold — i.e. the same fact reworded), supersede that line in\n * place and return the rewritten file; otherwise return null (the caller appends normally).\n */\nexport function supersedeNearDuplicateLine(existing: string, content: string): string | null {\n\tconst NEAR_DUP_THRESHOLD = 0.6;\n\tconst contentTokens = tokenize(content);\n\tif (contentTokens.length === 0) return null;\n\tconst lines = existing.split(\"\\n\");\n\tlet bestIdx = -1;\n\tlet bestScore = NEAR_DUP_THRESHOLD;\n\tfor (let i = 0; i < lines.length; i++) {\n\t\tconst line = lines[i].trim();\n\t\tif (!line) continue;\n\t\t// Never supersede structural Markdown (headings, list markers as headings) — a fact must not\n\t\t// silently overwrite section structure.\n\t\tif (line.startsWith(\"#\")) continue;\n\t\tconst score = jaccard(contentTokens, tokenize(line));\n\t\tif (score >= bestScore) {\n\t\t\tbestScore = score;\n\t\t\tbestIdx = i;\n\t\t}\n\t}\n\tif (bestIdx === -1) return null;\n\tlines[bestIdx] = content;\n\treturn lines.join(\"\\n\");\n}\n\nconst memorySchema = Type.Object({\n\taction: Type.Union([Type.Literal(\"add\"), Type.Literal(\"replace\"), Type.Literal(\"remove\")], {\n\t\tdescription: \"Action to perform: add new content, replace existing content, or remove content\",\n\t}),\n\ttarget: Type.Union([Type.Literal(\"memory\"), Type.Literal(\"user\")], {\n\t\tdescription: \"Target file: 'memory' for MEMORY.md, 'user' for USER.md\",\n\t}),\n\tcontent: Type.Optional(Type.String({ description: \"Content to write (required for 'add' or 'replace')\" })),\n\toldContent: Type.Optional(\n\t\tType.String({ description: \"Exact substring to replace or remove (required for 'replace' or 'remove')\" }),\n\t),\n});\n\ntype MemoryParams = Static<typeof memorySchema>;\n\nexport interface FileStoreProviderOptions {\n\tonDurableMemoryChanged?: () => void;\n}\n\nexport const FILE_STORE_MEMORY_SYSTEM_NOTE =\n\t\"[System Note: Below is a snapshot of persistent memory. Proactively record verified reusable project facts and user preferences with the 'memory' tool; never store transient noise.]\";\n\ninterface ManagedMemoryState {\n\tversion: 1;\n\tcommittedDigest: string;\n\tpendingDigest?: string;\n}\n\ntype ManagedMemoryStateRead =\n\t| { status: \"missing\" }\n\t| { status: \"valid\"; state: ManagedMemoryState }\n\t| { status: \"invalid\"; raw: string };\n\nfunction contentDigest(content: string): string {\n\treturn createHash(\"sha256\").update(content, \"utf8\").digest(\"hex\");\n}\n\nfunction isMissingFileError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && \"code\" in error && error.code === \"ENOENT\";\n}\n\nfunction parseManagedMemoryState(raw: string): ManagedMemoryState | undefined {\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(raw);\n\t} catch {\n\t\treturn undefined;\n\t}\n\tif (typeof parsed !== \"object\" || parsed === null) return undefined;\n\tconst record = parsed as Record<string, unknown>;\n\tif (record.version !== 1 || typeof record.committedDigest !== \"string\") return undefined;\n\tif (record.pendingDigest !== undefined && typeof record.pendingDigest !== \"string\") return undefined;\n\treturn {\n\t\tversion: 1,\n\t\tcommittedDigest: record.committedDigest,\n\t\t...(typeof record.pendingDigest === \"string\" ? { pendingDigest: record.pendingDigest } : {}),\n\t};\n}\n\nasync function readManagedMemoryState(statePath: string): Promise<ManagedMemoryStateRead> {\n\ttry {\n\t\tconst raw = await fs.readFile(statePath, \"utf8\");\n\t\tconst state = parseManagedMemoryState(raw);\n\t\treturn state ? { status: \"valid\", state } : { status: \"invalid\", raw };\n\t} catch (error) {\n\t\tif (isMissingFileError(error)) return { status: \"missing\" };\n\t\tthrow error;\n\t}\n}\n\nfunction serializeManagedMemoryState(state: ManagedMemoryState): string {\n\treturn `${JSON.stringify(state)}\\n`;\n}\n\nasync function writeManagedMemoryState(statePath: string, state: ManagedMemoryState): Promise<void> {\n\tawait writeFileAtomic(statePath, serializeManagedMemoryState(state), { mode: 0o600 });\n}\n\nfunction reconcileManagedMemoryState(\n\tcurrentDigest: string,\n\tstate: ManagedMemoryState,\n): { recognized: true; state: ManagedMemoryState; changed: boolean } | { recognized: false } {\n\tif (currentDigest === state.committedDigest) {\n\t\tif (state.pendingDigest === undefined) return { recognized: true, state, changed: false };\n\t\treturn {\n\t\t\trecognized: true,\n\t\t\tstate: { version: 1, committedDigest: state.committedDigest },\n\t\t\tchanged: true,\n\t\t};\n\t}\n\tif (state.pendingDigest !== undefined && currentDigest === state.pendingDigest) {\n\t\treturn {\n\t\t\trecognized: true,\n\t\t\tstate: { version: 1, committedDigest: state.pendingDigest },\n\t\t\tchanged: true,\n\t\t};\n\t}\n\treturn { recognized: false };\n}\n\nfunction fitMemoryBlockToBudget(block: string, budget: MemoryPromptBudget | undefined): string {\n\tif (budget === undefined) return block;\n\tif (!budget.enabled || budget.maxLines <= 0 || budget.maxChars <= 0) return \"\";\n\tif (block.split(\"\\n\").length <= budget.maxLines && block.length <= budget.maxChars) return block;\n\t// Micro-context profiles deliberately omit a block that cannot fit whole. Larger constrained\n\t// profiles retain a bounded head and say explicitly that more memory exists on disk.\n\tif (budget.compact) return \"\";\n\n\tconst marker = \"[…memory truncated for capability budget; full files remain on disk]\";\n\tif (budget.maxLines < 2 || budget.maxChars <= marker.length + 1) return \"\";\n\tconst lines: string[] = [];\n\tlet chars = 0;\n\tconst contentCharLimit = budget.maxChars - marker.length - 1;\n\tfor (const line of block.split(\"\\n\")) {\n\t\tif (lines.length >= budget.maxLines - 1) break;\n\t\tconst separatorChars = lines.length > 0 ? 1 : 0;\n\t\tconst remaining = contentCharLimit - chars - separatorChars;\n\t\tif (remaining <= 0) break;\n\t\tconst rendered = line.length <= remaining ? line : `${line.slice(0, Math.max(0, remaining - 1))}…`;\n\t\tlines.push(rendered);\n\t\tchars += separatorChars + rendered.length;\n\t\tif (rendered.length !== line.length) break;\n\t}\n\tif (lines.length === 0) return \"\";\n\tlines.push(marker);\n\treturn lines.join(\"\\n\");\n}\n\nexport class FileStoreProvider implements MemoryProvider {\n\tpublic readonly name = \"file-store\";\n\tpublic readonly egress = \"local\";\n\n\tprivate ctx?: MemoryLifecycleContext;\n\tprivate memoryFilePath = \"\";\n\tprivate userFilePath = \"\";\n\tprivate memoryStatePath = \"\";\n\tprivate userStatePath = \"\";\n\n\tprivate lastWrittenMemory = \"\";\n\tprivate lastWrittenUser = \"\";\n\tprivate userArchive?: UserMemoryArchive;\n\tprivate readonly options: FileStoreProviderOptions;\n\n\t// Character budgets\n\tprivate static readonly BUDGET_MEMORY = 2200;\n\tprivate static readonly BUDGET_USER = 1375;\n\n\tconstructor(options: FileStoreProviderOptions = {}) {\n\t\tthis.options = options;\n\t}\n\n\tpublic isAvailable(): boolean {\n\t\treturn true;\n\t}\n\n\tpublic getCapabilities() {\n\t\treturn { surfaces: [\"context\" as const] };\n\t}\n\n\tpublic async initialize(_sessionId: string, ctx: MemoryLifecycleContext): Promise<void> {\n\t\tthis.ctx = ctx;\n\t\tthis.memoryFilePath = configFile(ctx.agentDir, \"MEMORY.md\");\n\t\tthis.userFilePath = configFile(ctx.agentDir, \"USER.md\");\n\t\tthis.memoryStatePath = managedMemoryStateFile(ctx.agentDir, \"MEMORY.md\");\n\t\tthis.userStatePath = managedMemoryStateFile(ctx.agentDir, \"USER.md\");\n\t\tthis.userArchive = new UserMemoryArchive(ctx.agentDir);\n\n\t\tawait fs.mkdir(ctx.agentDir, { recursive: true });\n\t\t[this.lastWrittenMemory, this.lastWrittenUser] = await Promise.all([\n\t\t\tthis.initializeManagedFile(this.memoryFilePath, this.memoryStatePath),\n\t\t\tthis.initializeManagedFile(this.userFilePath, this.userStatePath),\n\t\t]);\n\t}\n\n\tprivate async initializeManagedFile(filePath: string, statePath: string): Promise<string> {\n\t\treturn withFileLock(filePath, async () => {\n\t\t\tlet current = \"\";\n\t\t\ttry {\n\t\t\t\tcurrent = await fs.readFile(filePath, \"utf8\");\n\t\t\t} catch (error) {\n\t\t\t\tif (!isMissingFileError(error)) throw error;\n\t\t\t\tawait writeFileAtomic(filePath, \"\", { mode: 0o600 });\n\t\t\t}\n\n\t\t\tconst currentDigest = contentDigest(current);\n\t\t\tconst stateRead = await readManagedMemoryState(statePath);\n\t\t\tif (stateRead.status === \"missing\") {\n\t\t\t\tawait writeManagedMemoryState(statePath, { version: 1, committedDigest: currentDigest });\n\t\t\t\treturn current;\n\t\t\t}\n\t\t\tif (stateRead.status === \"invalid\") {\n\t\t\t\tawait writeFileAtomic(`${statePath}.bak.${Date.now()}.${randomUUID()}`, stateRead.raw, { mode: 0o600 });\n\t\t\t\tawait writeManagedMemoryState(statePath, { version: 1, committedDigest: currentDigest });\n\t\t\t\treturn current;\n\t\t\t}\n\n\t\t\tconst reconciled = reconcileManagedMemoryState(currentDigest, stateRead.state);\n\t\t\tif (reconciled.recognized && reconciled.changed) {\n\t\t\t\tawait writeManagedMemoryState(statePath, reconciled.state);\n\t\t\t}\n\t\t\treturn current;\n\t\t});\n\t}\n\n\tpublic systemPromptBlock(budget?: MemoryPromptBudget): string {\n\t\tconst sanitize = (content: string) => {\n\t\t\t// Strip hidden/bidi-control chars before injecting memory into the prompt (defence in depth: the\n\t\t\t// write path already blocks them, but a file edited out-of-band could carry them). Strip #31.\n\t\t\tconst lines = stripInvisibleUnicode(content).cleaned.split(\"\\n\");\n\t\t\tconst sanitizedLines = lines.map((line) => {\n\t\t\t\tconst threats = scanContextFileThreats(line);\n\t\t\t\tif (threats.length > 0) {\n\t\t\t\t\treturn `[BLOCKED: potential threat detected (${threats.join(\", \")})]`;\n\t\t\t\t}\n\t\t\t\treturn line;\n\t\t\t});\n\t\t\treturn sanitizedLines.join(\"\\n\");\n\t\t};\n\n\t\t// Read-time budget guard (cost): the memory tool already caps writes at BUDGET_*, but a file edited\n\t\t// externally (or by any path that bypasses the tool) could be arbitrarily large and would then\n\t\t// bloat the system prompt on EVERY turn. Cap the injected view to the same budget so the per-turn\n\t\t// cost stays bounded; the file on disk is untouched and the model is told it was truncated.\n\t\tconst cap = (content: string, limit: number) => {\n\t\t\tif (content.length <= limit) return content;\n\t\t\treturn `${content.slice(0, limit)}\\n[…truncated to ${limit} chars for the prompt; full file is on disk]`;\n\t\t};\n\n\t\tconst mem = cap(sanitize(this.lastWrittenMemory), FileStoreProvider.BUDGET_MEMORY);\n\t\tconst usr = cap(sanitize(this.lastWrittenUser), FileStoreProvider.BUDGET_USER);\n\n\t\tconst blocks: string[] = [];\n\t\tif (mem.trim()) {\n\t\t\tblocks.push(`## MEMORY.md:\\n${mem}`);\n\t\t}\n\t\tif (usr.trim()) {\n\t\t\tblocks.push(`## USER.md:\\n${usr}`);\n\t\t}\n\n\t\tif (blocks.length === 0) {\n\t\t\treturn \"\";\n\t\t}\n\n\t\tconst block = `=== Persistent Memory (file-store) ===\\n${FILE_STORE_MEMORY_SYSTEM_NOTE}\\n\\n${blocks.join(\"\\n\\n\")}`;\n\t\treturn fitMemoryBlockToBudget(block, budget);\n\t}\n\n\tpublic async prefetch(_query: string): Promise<string> {\n\t\t// static system prompt block is sufficient for file-store default; no-op prefetch\n\t\treturn \"\";\n\t}\n\n\tpublic async shutdown(): Promise<void> {\n\t\t// no-op\n\t}\n\n\tpublic getContextMarkers(): string[] {\n\t\treturn [];\n\t}\n\n\tpublic getToolDefinitions(): ToolDefinition[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tname: \"memory\",\n\t\t\t\tlabel: \"Persistent Memory Manager\",\n\t\t\t\tdescription:\n\t\t\t\t\t\"Add, replace, or remove durable project facts and user preferences. Proactively store newly verified reusable facts; USER.md overflow is migrated into indexed OKF shards.\",\n\t\t\t\tpromptSnippet: \"Persist verified project facts and user preferences.\",\n\t\t\t\tpromptGuidelines: [\n\t\t\t\t\t\"Store verified facts and preferences. Repeatable multi-step procedures become skills via skillify; reflection promotes them when the write is a workflow.\",\n\t\t\t\t],\n\t\t\t\tparameters: memorySchema,\n\t\t\t\texecute: async (_toolCallId, params: MemoryParams, _signal, _onUpdate, _execCtx) => {\n\t\t\t\t\tif (this.ctx?.isChildSession) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: \"Error: Writes to persistent memory are not allowed in child sessions (subagents).\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { success: false, error: \"Child session write-gated\" },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\n\t\t\t\t\tconst { action, target, content, oldContent } = params;\n\n\t\t\t\t\t// Strict-scope injection guard on the high-privilege WRITE path (agy #31): a poisoned\n\t\t\t\t\t// memory entry persists across sessions and is injected into every future system prompt,\n\t\t\t\t\t// so block outright rather than strip. Hidden/bidi-control chars have no legitimate place\n\t\t\t\t\t// in a memory note, so reject those too.\n\t\t\t\t\tif ((action === \"add\" || action === \"replace\") && content !== undefined) {\n\t\t\t\t\t\tif (hasInvisibleUnicode(content)) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: \"Error: memory write rejected — contains hidden/bidirectional control characters.\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { success: false, error: \"Invisible unicode in memory write\" },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst threats = scanContextFileThreats(content, \"strict\");\n\t\t\t\t\t\tif (threats.length > 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `Error: memory write rejected — potential injection/exfiltration detected (${threats.join(\", \")}).`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { success: false, error: \"Threat in memory write\" },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tconst filePath = target === \"memory\" ? this.memoryFilePath : this.userFilePath;\n\t\t\t\t\tconst statePath = target === \"memory\" ? this.memoryStatePath : this.userStatePath;\n\t\t\t\t\tconst budget = target === \"memory\" ? FileStoreProvider.BUDGET_MEMORY : FileStoreProvider.BUDGET_USER;\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn await withFileLock(filePath, async () => {\n\t\t\t\t\t\t\tconst currentOnDisk = await fs.readFile(filePath, \"utf8\");\n\t\t\t\t\t\t\tconst currentDigest = contentDigest(currentOnDisk);\n\t\t\t\t\t\t\tconst stateRead = await readManagedMemoryState(statePath);\n\t\t\t\t\t\t\tlet managedState: ManagedMemoryState | undefined;\n\t\t\t\t\t\t\tif (stateRead.status === \"valid\") {\n\t\t\t\t\t\t\t\tconst reconciled = reconcileManagedMemoryState(currentDigest, stateRead.state);\n\t\t\t\t\t\t\t\tif (reconciled.recognized) {\n\t\t\t\t\t\t\t\t\tmanagedState = reconciled.state;\n\t\t\t\t\t\t\t\t\tif (reconciled.changed) await writeManagedMemoryState(statePath, reconciled.state);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (!managedState) {\n\t\t\t\t\t\t\t\tconst backupPath = `${filePath}.bak.${Date.now()}`;\n\t\t\t\t\t\t\t\tawait writeFileAtomic(backupPath, currentOnDisk, { mode: 0o600 });\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\ttext: `Error: Drift detected. The memory file has been modified out-of-band by an external process. A backup was created at ${backupPath}. Operation aborted.`,\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\tdetails: { success: false, error: \"Drift detected\" },\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t// A peer session's committed write is authoritative. Refresh this provider's prompt\n\t\t\t\t\t\t\t// snapshot before applying the caller's mutation to that current content.\n\t\t\t\t\t\t\tif (target === \"memory\") this.lastWrittenMemory = currentOnDisk;\n\t\t\t\t\t\t\telse this.lastWrittenUser = currentOnDisk;\n\n\t\t\t\t\t\t\tlet newContent = currentOnDisk;\n\t\t\t\t\t\t\tlet archiveChanged = false;\n\t\t\t\t\t\t\tif (target === \"user\") {\n\t\t\t\t\t\t\t\tif (!this.userArchive) throw new Error(\"User memory archive is not initialized.\");\n\t\t\t\t\t\t\t\tif (action === \"add\") {\n\t\t\t\t\t\t\t\t\tif (content === undefined)\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'content' is required for action 'add'.\");\n\t\t\t\t\t\t\t\t\tconst result = await this.userArchive.apply(\n\t\t\t\t\t\t\t\t\t\tcurrentOnDisk,\n\t\t\t\t\t\t\t\t\t\t{ action, content },\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tsupersedeNearDuplicateLine,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tnewContent = result.userContent;\n\t\t\t\t\t\t\t\t\tarchiveChanged = result.archiveChanged;\n\t\t\t\t\t\t\t\t} else if (action === \"replace\") {\n\t\t\t\t\t\t\t\t\tif (content === undefined || oldContent === undefined) {\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t\t\t\"Parameters 'content' and 'oldContent' are required for action 'replace'.\",\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\tconst result = await this.userArchive.apply(\n\t\t\t\t\t\t\t\t\t\tcurrentOnDisk,\n\t\t\t\t\t\t\t\t\t\t{ action, content, oldContent },\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tsupersedeNearDuplicateLine,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tnewContent = result.userContent;\n\t\t\t\t\t\t\t\t\tarchiveChanged = result.archiveChanged;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tif (oldContent === undefined)\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'oldContent' is required for action 'remove'.\");\n\t\t\t\t\t\t\t\t\tconst result = await this.userArchive.apply(\n\t\t\t\t\t\t\t\t\t\tcurrentOnDisk,\n\t\t\t\t\t\t\t\t\t\t{ action, oldContent },\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tsupersedeNearDuplicateLine,\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\tnewContent = result.userContent;\n\t\t\t\t\t\t\t\t\tarchiveChanged = result.archiveChanged;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (action === \"add\") {\n\t\t\t\t\t\t\t\tif (content === undefined) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'content' is required for action 'add'.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst superseded = supersedeNearDuplicateLine(currentOnDisk, content);\n\t\t\t\t\t\t\t\tif (superseded !== null) {\n\t\t\t\t\t\t\t\t\tnewContent = superseded;\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tnewContent =\n\t\t\t\t\t\t\t\t\t\tnewContent.endsWith(\"\\n\") || newContent === \"\"\n\t\t\t\t\t\t\t\t\t\t\t? `${newContent}${content}\\n`\n\t\t\t\t\t\t\t\t\t\t\t: `${newContent}\\n${content}\\n`;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (action === \"replace\") {\n\t\t\t\t\t\t\t\tif (content === undefined || oldContent === undefined) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameters 'content' and 'oldContent' are required for action 'replace'.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (!currentOnDisk.includes(oldContent)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`The content to replace ('oldContent') was not found in the file.`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewContent = currentOnDisk.replace(oldContent, content);\n\t\t\t\t\t\t\t} else if (action === \"remove\") {\n\t\t\t\t\t\t\t\tif (oldContent === undefined) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Parameter 'oldContent' is required for action 'remove'.\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (!currentOnDisk.includes(oldContent)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(`The content to remove ('oldContent') was not found in the file.`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tnewContent = currentOnDisk.replace(oldContent, \"\");\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (newContent.length > budget) {\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\t\ttext: `Error: Memory budget exceeded. ${target === \"memory\" ? \"MEMORY.md\" : \"USER.md\"} limit is ${budget} characters. Current operation would result in ${newContent.length} characters.`,\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\tdetails: { success: false, error: \"Memory budget exceeded\" },\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (newContent !== currentOnDisk) {\n\t\t\t\t\t\t\t\tconst newDigest = contentDigest(newContent);\n\t\t\t\t\t\t\t\tawait writeManagedMemoryState(statePath, {\n\t\t\t\t\t\t\t\t\tversion: 1,\n\t\t\t\t\t\t\t\t\tcommittedDigest: managedState.committedDigest,\n\t\t\t\t\t\t\t\t\tpendingDigest: newDigest,\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tawait writeFileAtomic(filePath, newContent, { mode: 0o600 });\n\t\t\t\t\t\t\t\tawait writeManagedMemoryState(statePath, { version: 1, committedDigest: newDigest });\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (target === \"memory\") this.lastWrittenMemory = newContent;\n\t\t\t\t\t\t\telse this.lastWrittenUser = newContent;\n\t\t\t\t\t\t\tif (archiveChanged || newContent !== currentOnDisk) this.options.onDurableMemoryChanged?.();\n\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\t\ttext: `Successfully updated ${target === \"memory\" ? \"MEMORY.md\" : \"USER.md\"}.`,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\tdetails: { success: true },\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (err) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tcontent: [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\t\t\ttext: `Error: Failed to perform memory operation: ${String(err)}`,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\tdetails: { success: false, error: String(err) },\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t];\n\t}\n}\n"]}
|
|
@@ -55,6 +55,8 @@ export interface MemoryControllerReloadSnapshot {
|
|
|
55
55
|
export declare class MemoryController {
|
|
56
56
|
private _memoryOkfProvider;
|
|
57
57
|
private _fileStoreMemoryProvider;
|
|
58
|
+
private _localGraphProvider;
|
|
59
|
+
private _localGraphResolved;
|
|
58
60
|
private _latestMemoryRetrievalReport;
|
|
59
61
|
private _latestMemoryPromptInclusionReport;
|
|
60
62
|
/** Plug-and-play memory subsystem. Recreated on each (re)initialize so reload is safe. */
|
|
@@ -93,6 +95,7 @@ export declare class MemoryController {
|
|
|
93
95
|
*/
|
|
94
96
|
private _getMemoryOkfProvider;
|
|
95
97
|
private _getFileStoreMemoryProvider;
|
|
98
|
+
private _getLocalGraphProvider;
|
|
96
99
|
private _memoryBudget;
|
|
97
100
|
private _shouldQueryFileStoreFallback;
|
|
98
101
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory-controller.d.ts","sourceRoot":"","sources":["../../src/core/memory-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAiB,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"memory-controller.d.ts","sourceRoot":"","sources":["../../src/core/memory-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,KAAK,EA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;;;;;;;;OAqBG;IACH,8BAA8B,CAAC,QAAQ,EAAE,YAAY,EAAE,EAAE,MAAM,EAAE,qBAAqB,GAAG,YAAY,EAAE,CAsFtG;IAED,kHAAkH;IAClH,8BAA8B,IAAI,2BAA2B,CAE5D;IAED;;;;;OAKG;IACH,yBAAyB,IAAI;QAC5B,SAAS,EAAE,0BAA0B,CAAC;QACtC,eAAe,EAAE,2BAA2B,CAAC;KAC7C,CAMA;IAED;;;;OAIG;IACH,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAWzC;IAED,8GAA8G;IACxG,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAQnD;IAED,oFAAoF;IAC9E,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAetD;IAED,uGAAuG;IACvG,mBAAmB,CAAC,UAAU,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,IAAI,CAErF;IAED;;;;OAIG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAyChC;IAED,mGAAmG;IACnG,sBAAsB,CAAC,QAAQ,EAAE,cAAc,GAAG,IAAI,CAIrD;IAED,sFAAsF;IACtF,6BAA6B,CAAC,QAAQ,EAAE,qBAAqB,GAAG,IAAI,CAInE;IAED,oBAAoB,IAAI,8BAA8B,CAOrD;IAED,qBAAqB,CAAC,QAAQ,EAAE,8BAA8B,GAAG,IAAI,CAKpE;IAED,0GAA0G;IAC1G,qBAAqB,IAAI,IAAI,CAK5B;CACD"}
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
import { configFile, okfMemoryDir } from "./agent-paths.js";
|
|
21
21
|
import { collectCurrentWorkMemory } from "./context/current-work-memory.js";
|
|
22
22
|
import { createFileStoreMemoryProvider } from "./context/file-store-memory-provider.js";
|
|
23
|
+
import { createLocalGraphMemoryProvider } from "./context/local-graph-memory-provider.js";
|
|
23
24
|
import { shouldQueryLongTermMemory } from "./context/long-term-memory-trigger.js";
|
|
24
25
|
import { defaultMemoryPromptInclusionReport, sanitizeMemoryRetrievalReportForDiagnostics, } from "./context/memory-diagnostics.js";
|
|
25
26
|
import { resolveMemoryPromptBudget } from "./context/memory-prompt-budget.js";
|
|
@@ -75,6 +76,8 @@ export class MemoryController {
|
|
|
75
76
|
constructor(deps) {
|
|
76
77
|
this._memoryOkfProvider = undefined;
|
|
77
78
|
this._fileStoreMemoryProvider = undefined;
|
|
79
|
+
this._localGraphProvider = undefined;
|
|
80
|
+
this._localGraphResolved = false;
|
|
78
81
|
this._latestMemoryRetrievalReport = undefined;
|
|
79
82
|
this._latestMemoryPromptInclusionReport = undefined;
|
|
80
83
|
/** Plug-and-play memory subsystem. Recreated on each (re)initialize so reload is safe. */
|
|
@@ -144,6 +147,16 @@ export class MemoryController {
|
|
|
144
147
|
});
|
|
145
148
|
return this._fileStoreMemoryProvider;
|
|
146
149
|
}
|
|
150
|
+
_getLocalGraphProvider() {
|
|
151
|
+
if (!this._localGraphResolved) {
|
|
152
|
+
this._localGraphProvider = createLocalGraphMemoryProvider({
|
|
153
|
+
cwd: this.deps.getCwd(),
|
|
154
|
+
agentDir: this.deps.getAgentDir(),
|
|
155
|
+
});
|
|
156
|
+
this._localGraphResolved = true;
|
|
157
|
+
}
|
|
158
|
+
return this._localGraphProvider;
|
|
159
|
+
}
|
|
147
160
|
_memoryBudget(configuredMaxResults) {
|
|
148
161
|
return resolveMemoryPromptBudget({
|
|
149
162
|
contextWindow: this.deps.getContextWindow(),
|
|
@@ -190,6 +203,9 @@ export class MemoryController {
|
|
|
190
203
|
const providers = this._shouldQueryFileStoreFallback(budget) ? [this._getFileStoreMemoryProvider()] : [];
|
|
191
204
|
if (longTermDecision.shouldQuery) {
|
|
192
205
|
providers.push(this._getMemoryOkfProvider(), ...this._pendingContextMemoryProviders);
|
|
206
|
+
const graph = this._getLocalGraphProvider();
|
|
207
|
+
if (graph)
|
|
208
|
+
providers.push(graph);
|
|
193
209
|
}
|
|
194
210
|
const maxResults = budget.enabled ? Math.min(settings.maxResults, budget.maxResults) : settings.maxResults;
|
|
195
211
|
const report = await retrieveMemoryForContext(providers, { query, maxResults }, {
|
|
@@ -427,6 +443,8 @@ export class MemoryController {
|
|
|
427
443
|
// Release the previous generation's providers (locks/handles) before recreating, so a
|
|
428
444
|
// reload does not orphan the old MemoryManager. No-op on first init / for file-store.
|
|
429
445
|
await this._memoryManager.shutdownAll().catch(() => { });
|
|
446
|
+
this._localGraphProvider = undefined;
|
|
447
|
+
this._localGraphResolved = false;
|
|
430
448
|
const manager = new MemoryManager();
|
|
431
449
|
manager.registerProvider(new FileStoreProvider({
|
|
432
450
|
onDurableMemoryChanged: () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory-controller.js","sourceRoot":"","sources":["../../src/core/memory-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,OAAO,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC;AAClF,OAAO,EACN,kCAAkC,EAGlC,2CAA2C,GAC3C,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAA2B,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AACvG,OAAO,EAEN,qCAAqC,EACrC,kCAAkC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAA8B,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACrG,OAAO,EAAE,8BAA8B,EAA4B,MAAM,mCAAmC,CAAC;AAC7G,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAE3E,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,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CAAC;IAED,qBAAqB,CAAC,QAAwC;QAC7D,IAAI,CAAC,uBAAuB,GAAG,CAAC,GAAG,QAAQ,CAAC,sBAAsB,CAAC,CAAC;QACpE,IAAI,CAAC,8BAA8B,GAAG,CAAC,GAAG,QAAQ,CAAC,6BAA6B,CAAC,CAAC;QAClF,IAAI,CAAC,kBAAkB,GAAG,QAAQ,CAAC,iBAAiB,CAAC;QACrD,IAAI,CAAC,wBAAwB,GAAG,QAAQ,CAAC,uBAAuB,CAAC;IAClE,CAAC;IAED,0GAA0G;IAC1G,qBAAqB;QACpB,IAAI,CAAC,uBAAuB,GAAG,EAAE,CAAC;QAClC,IAAI,CAAC,8BAA8B,GAAG,EAAE,CAAC;QACzC,IAAI,CAAC,kBAAkB,GAAG,SAAS,CAAC;QACpC,IAAI,CAAC,wBAAwB,GAAG,SAAS,CAAC;IAC3C,CAAC;CACD","sourcesContent":["/**\n * Memory controller: the session's plug-and-play memory subsystem — the read-only OKF retrieval\n * provider, the bounded prompt-evidence surfacing pilot, cross-session recall effectiveness, and the\n * live {@link MemoryManager} (bundled file-store + transcript-recall providers plus any extension\n * contributions).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the lazily-built OKF\n * provider, the latest retrieval/prompt-inclusion reports, the recreated-on-reload MemoryManager, the\n * recall {@link EffectivenessTracker}, and the extension-contributed pending providers. Everything\n * else it needs — settings, the current turn index, agent/workspace dirs, the session id, the\n * child-session flag, and the tool-registry refresh — is reached through narrow deps accessors rather\n * than the whole AgentSession.\n *\n * Context-transform boundary (deliberate): {@link runMemoryRetrieval} and\n * {@link maybeAppendMemoryEvidenceBlock} are invoked from the session's context transform as one-line\n * delegations. This controller deliberately imports no compaction/context-pipeline internals — it only\n * ever reads settings and builds the retrieval report + the bounded evidence block, so the transform\n * stays the single owner of the pass ordering.\n */\n\nimport type { AgentMessage, CustomMessage } from \"@caupulican/pi-agent-core\";\nimport { configFile, okfMemoryDir } from \"./agent-paths.ts\";\nimport { collectCurrentWorkMemory } from \"./context/current-work-memory.ts\";\nimport { createFileStoreMemoryProvider } from \"./context/file-store-memory-provider.ts\";\nimport { shouldQueryLongTermMemory } from \"./context/long-term-memory-trigger.ts\";\nimport {\n\tdefaultMemoryPromptInclusionReport,\n\ttype MemoryPromptInclusionReport,\n\ttype MemoryRetrievalDiagnostics,\n\tsanitizeMemoryRetrievalReportForDiagnostics,\n} from \"./context/memory-diagnostics.ts\";\nimport { type MemoryPromptBudget, resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport {\n\ttype MemoryProvider as ContextMemoryProvider,\n\tDEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\tDEFAULT_LOCAL_MEMORY_EGRESS_POLICY,\n} from \"./context/memory-provider-contract.ts\";\nimport { type MemoryRetrievalReport, retrieveMemoryForContext } from \"./context/memory-retrieval.ts\";\nimport { composeTieredMemoryPromptBlock, type MemoryTierCandidate } from \"./context/memory-tier-composer.ts\";\nimport { createOkfMemoryProvider } from \"./context/okf-memory-provider.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport { EffectivenessTracker } from \"./memory/effectiveness-tracker.ts\";\nimport { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { MemoryProvider } from \"./memory/memory-provider.ts\";\nimport { FILE_STORE_MEMORY_SYSTEM_NOTE, FileStoreProvider } from \"./memory/providers/file-store.ts\";\nimport { TranscriptRecallProvider } from \"./memory/providers/transcript-recall.ts\";\nimport { wrapUntrustedText } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\n/**\n * Text of the most recent user message, or \"\" if there is none (e.g. goal-continuation\n * turns with no new user input). An empty query is still valid: standing user preferences may\n * surface from the file-store retrieval fallback when the static memory prompt cannot fit,\n * while long-term providers remain gated by shouldQueryLongTermMemory().\n */\nfunction latestUserMessageText(messages: AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message.role !== \"user\") continue;\n\t\tif (typeof message.content === \"string\") return message.content;\n\t\tconst parts: string[] = [];\n\t\tfor (const part of message.content) {\n\t\t\tif (part.type === \"text\") parts.push(part.text);\n\t\t}\n\t\treturn parts.join(\"\\n\");\n\t}\n\treturn \"\";\n}\n\nfunction emptyMemoryRetrievalReport(maxResults: number): MemoryRetrievalReport {\n\treturn { request: { query: \"\", maxResults }, providerReports: [], results: [], contextItems: [] };\n}\n\nconst ENABLED_EXTERNAL_MEMORY_EGRESS_POLICY = {\n\t...DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\tenabled: true,\n\tallowedScopes: DEFAULT_LOCAL_MEMORY_EGRESS_POLICY.allowedScopes,\n\tallowExternalEgress: true,\n} as const;\n\nconst MAX_PRE_COMPRESS_MEMORY_CHARS = 4_000;\n\nfunction boundPreCompressMemory(text: string): string {\n\tconst trimmed = text.trim();\n\tif (trimmed.length <= MAX_PRE_COMPRESS_MEMORY_CHARS) return trimmed;\n\tconst suffix = \"\\n...[memory handoff truncated]\";\n\treturn `${trimmed.slice(0, MAX_PRE_COMPRESS_MEMORY_CHARS - suffix.length).trimEnd()}${suffix}`;\n}\n\nexport interface MemoryControllerDeps {\n\t/** Memory-retrieval + prompt-inclusion settings (default-on gates for retrieval and surfacing). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Current turn index, stamped into a retrieval request's `createdAtTurn`. */\n\tgetTurnIndex(): number;\n\t/** Agent root — the durable OKF memory docs live under `<agentDir>/okf-memory`. */\n\tgetAgentDir(): string;\n\t/** Workspace root, passed to provider initialization. */\n\tgetCwd(): string;\n\t/** This session's id, passed to provider initialization. */\n\tgetSessionId(): string;\n\t/** Child sessions gate durable memory writes; passed to provider initialization. */\n\tisChildSession(): boolean;\n\t/** Re-derive the tool registry after (re)init so the newly-surfaced memory tools take effect. */\n\trefreshToolRegistry(): void;\n\t/** Active model context window, used to cap prompt-visible memory. */\n\tgetContextWindow(): number | undefined;\n\t/** Latest active goal state, used for short-term current-work memory. */\n\tgetGoalState(): GoalState | undefined;\n}\n\n/** Extension-contributed memory state staged across an atomic runtime reload. */\nexport interface MemoryControllerReloadSnapshot {\n\tpendingMemoryProviders: MemoryProvider[];\n\tpendingContextMemoryProviders: ContextMemoryProvider[];\n\tmemoryOkfProvider: ContextMemoryProvider | undefined;\n\tfileStoreMemoryProvider: ContextMemoryProvider | undefined;\n}\n\nexport class MemoryController {\n\tprivate _memoryOkfProvider: ContextMemoryProvider | undefined = undefined;\n\tprivate _fileStoreMemoryProvider: ContextMemoryProvider | undefined = undefined;\n\tprivate _latestMemoryRetrievalReport: MemoryRetrievalReport | undefined = undefined;\n\tprivate _latestMemoryPromptInclusionReport: MemoryPromptInclusionReport | undefined = undefined;\n\t/** Plug-and-play memory subsystem. Recreated on each (re)initialize so reload is safe. */\n\tprivate _memoryManager: MemoryManager = new MemoryManager();\n\t/** R4: tracks whether injected recall is actually used, to adapt the recall gate. */\n\tprivate readonly _effectivenessTracker = new EffectivenessTracker();\n\t/** Memory providers registered by extensions via pi.registerMemoryProvider, applied on (re)init. */\n\tprivate _pendingMemoryProviders: MemoryProvider[] = [];\n\t/** Context-memory providers registered by extensions via pi.registerContextMemoryProvider. */\n\tprivate _pendingContextMemoryProviders: ContextMemoryProvider[] = [];\n\t/** Serializes provider write hooks without delaying the foreground turn. */\n\tprivate _lifecycleTail: Promise<void> = Promise.resolve();\n\tprivate _shutdownPromise: Promise<void> | undefined;\n\n\tprivate readonly deps: MemoryControllerDeps;\n\n\tconstructor(deps: MemoryControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The live memory manager. Callers reach prefetch / tool-definitions / markers / shutdown through it. */\n\tgetMemoryManager(): MemoryManager {\n\t\treturn this._memoryManager;\n\t}\n\n\t/** Queue one completed turn for provider-owned durable synchronization. Raw tool output is excluded by the caller. */\n\tscheduleTurnSync(userText: string, assistantText: string): void {\n\t\tif (!userText.trim() && !assistantText.trim()) return;\n\t\tconst manager = this._memoryManager;\n\t\tthis._lifecycleTail = this._lifecycleTail\n\t\t\t.then(() => manager.syncTurn(userText, assistantText))\n\t\t\t.catch((error) => {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"Memory turn synchronization failed:\",\n\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t);\n\t\t\t});\n\t}\n\n\t/** Wait for prior turn writes, then collect one bounded provider handoff for the whole compaction run. */\n\tasync onPreCompress(): Promise<string> {\n\t\tawait this._lifecycleTail;\n\t\treturn boundPreCompressMemory(await this._memoryManager.onPreCompress());\n\t}\n\n\t/** Flush write-side lifecycle hooks before releasing provider resources. Idempotent per session. */\n\tshutdown(): Promise<void> {\n\t\tthis._shutdownPromise ??= (async () => {\n\t\t\tawait this._lifecycleTail;\n\t\t\tawait this._memoryManager.onSessionEnd();\n\t\t\tawait this._memoryManager.shutdownAll();\n\t\t})();\n\t\treturn this._shutdownPromise;\n\t}\n\n\t/**\n\t * Fixed path for this slice's local Pi OKF memory documents, shared across sessions\n\t * under this agentDir (not session-scoped, unlike tool-artifacts/context-gc, since OKF\n\t * memory represents durable cross-session knowledge, not a per-session capture). Not\n\t * yet user-configurable -- see the memory-retrieval settings doc comment.\n\t */\n\tprivate _memoryOkfDir(): string {\n\t\treturn okfMemoryDir(this.deps.getAgentDir());\n\t}\n\n\t/**\n\t * Session-scoped, read-only local OKF memory provider. Lazily created ONLY when memory\n\t * retrieval is enabled (see `runMemoryRetrieval`) -- never force-created, so a session\n\t * with the setting off never touches `_memoryOkfDir()` at all (no directory access, no\n\t * creation; `createOkfMemoryProvider` itself never writes/mkdirs either way).\n\t */\n\tprivate _getMemoryOkfProvider(): ContextMemoryProvider {\n\t\tthis._memoryOkfProvider ??= createOkfMemoryProvider({ rootDir: this._memoryOkfDir() });\n\t\treturn this._memoryOkfProvider;\n\t}\n\n\tprivate _getFileStoreMemoryProvider(): ContextMemoryProvider {\n\t\tthis._fileStoreMemoryProvider ??= createFileStoreMemoryProvider({\n\t\t\tmemoryFilePath: configFile(this.deps.getAgentDir(), \"MEMORY.md\"),\n\t\t\tuserFilePath: configFile(this.deps.getAgentDir(), \"USER.md\"),\n\t\t});\n\t\treturn this._fileStoreMemoryProvider;\n\t}\n\n\tprivate _memoryBudget(configuredMaxResults: number) {\n\t\treturn resolveMemoryPromptBudget({\n\t\t\tcontextWindow: this.deps.getContextWindow(),\n\t\t\tconfiguredMaxResults,\n\t\t});\n\t}\n\n\tprivate _shouldQueryFileStoreFallback(budget: MemoryPromptBudget): boolean {\n\t\t// MEMORY.md/USER.md are already injected through the static file-store prompt on\n\t\t// normal windows, so querying them again would duplicate provider-visible memory.\n\t\t// In compact windows the static block can be omitted because it does not fit; only\n\t\t// then use the retrieval view to surface a few budget-pruned lines.\n\t\tif (!budget.enabled || !budget.compact) return false;\n\t\treturn this._memoryManager.buildSystemPromptBlock(budget).trim().length === 0;\n\t}\n\n\t/**\n\t * Observe-only local memory retrieval (see context/memory-retrieval.ts and\n\t * context/okf-memory-provider.ts): default-on, but settings-gated. When disabled,\n\t * never constructs built-in context-memory providers (no directory access under\n\t * `_memoryOkfDir()` at all) and returns an empty report -- fully fail-closed. When enabled,\n\t * queries local, read-only providers with the latest user message text (empty if there is\n\t * none, e.g. a goal-continuation turn) under `DEFAULT_LOCAL_MEMORY_EGRESS_POLICY`.\n\t * Retrieved items are only ever stored in the report; nothing here touches `messages`,\n\t * the transcript, or the provider-visible prompt. Never throws into a live turn: any\n\t * failure (including a provider search error) degrades to an empty report.\n\t */\n\tasync runMemoryRetrieval(messages: AgentMessage[]): Promise<MemoryRetrievalReport> {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\t\tif (!settings.enabled) {\n\t\t\t\tconst report = emptyMemoryRetrievalReport(settings.maxResults);\n\t\t\t\tthis._latestMemoryRetrievalReport = report;\n\t\t\t\treturn report;\n\t\t\t}\n\t\t\tconst query = latestUserMessageText(messages);\n\t\t\tconst budget = this._memoryBudget(settings.maxResults);\n\t\t\tconst currentWork = collectCurrentWorkMemory({ goalState: this.deps.getGoalState() });\n\t\t\tconst longTermDecision = shouldQueryLongTermMemory({\n\t\t\t\tlatestUserText: query,\n\t\t\t\tgoalState: this.deps.getGoalState(),\n\t\t\t\tbudget,\n\t\t\t\tcurrentWorkCandidateCount: currentWork.length,\n\t\t\t});\n\t\t\tconst providers = this._shouldQueryFileStoreFallback(budget) ? [this._getFileStoreMemoryProvider()] : [];\n\t\t\tif (longTermDecision.shouldQuery) {\n\t\t\t\tproviders.push(this._getMemoryOkfProvider(), ...this._pendingContextMemoryProviders);\n\t\t\t}\n\t\t\tconst maxResults = budget.enabled ? Math.min(settings.maxResults, budget.maxResults) : settings.maxResults;\n\t\t\tconst report = await retrieveMemoryForContext(\n\t\t\t\tproviders,\n\t\t\t\t{ query, maxResults },\n\t\t\t\t{\n\t\t\t\t\tcreatedAtTurn: this.deps.getTurnIndex(),\n\t\t\t\t\tmaxResults,\n\t\t\t\t\tdefaultLocalPolicy: DEFAULT_LOCAL_MEMORY_EGRESS_POLICY,\n\t\t\t\t\tdefaultExternalPolicy: settings.allowExternalEgress\n\t\t\t\t\t\t? ENABLED_EXTERNAL_MEMORY_EGRESS_POLICY\n\t\t\t\t\t\t: DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis._latestMemoryRetrievalReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report = emptyMemoryRetrievalReport(0);\n\t\t\tthis._latestMemoryRetrievalReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest memory-retrieval report, for tests/debugging. */\n\tgetMemoryRetrievalReport(): MemoryRetrievalReport {\n\t\treturn this._latestMemoryRetrievalReport ?? emptyMemoryRetrievalReport(0);\n\t}\n\n\tprivate _candidateForContextItem(\n\t\titem: MemoryRetrievalReport[\"contextItems\"][number],\n\t): MemoryTierCandidate | undefined {\n\t\tconst summary = item.summary?.trim();\n\t\tif (!summary) return undefined;\n\t\tconst ref = item.primaryRef?.type === \"memory\" ? item.primaryRef.ref : undefined;\n\t\tconst sourceLabel =\n\t\t\tref?.providerId === \"pi-file-store\" && ref.kind === \"user_preference\"\n\t\t\t\t? \"rule:user\"\n\t\t\t\t: `memory:${ref?.providerId ?? item.source}`;\n\t\tconst tier = ref?.kind === \"user_preference\" ? \"standing\" : \"long_term\";\n\t\treturn {\n\t\t\tid: item.id,\n\t\t\ttier,\n\t\t\tsourceLabel,\n\t\t\tsummary,\n\t\t\tscore: 0.5,\n\t\t\tevidenceRefs: item.evidenceRefs,\n\t\t};\n\t}\n\n\tprivate _memoryCandidates(report: MemoryRetrievalReport): MemoryTierCandidate[] {\n\t\treturn [\n\t\t\t...collectCurrentWorkMemory({ goalState: this.deps.getGoalState() }),\n\t\t\t...report.contextItems.flatMap((item) => {\n\t\t\t\tconst candidate = this._candidateForContextItem(item);\n\t\t\t\treturn candidate === undefined ? [] : [candidate];\n\t\t\t}),\n\t\t];\n\t}\n\n\t/**\n\t * Bounded prompt-surfacing for local memory evidence (see context/memory-tier-composer.ts):\n\t * default-on, but gated on TWO settings (`enabled` AND `includeInPrompt`) plus at least one\n\t * current-work, standing, or retrieved memory candidate -- the first\n\t * two are belt-and-suspenders on top of the fact that `runMemoryRetrieval` already\n\t * leaves `contextItems` empty whenever `enabled` is false, regardless of\n\t * `includeInPrompt`. Reuses the `report` this pass's `runMemoryRetrieval` call already\n\t * computed -- never re-queries the provider here.\n\t *\n\t * Appends exactly one ephemeral `custom`/\"memory_evidence\" message wrapped by\n\t * `wrapUntrustedText` (the same nonce-fenced boundary + always-on system-prompt rule\n\t * used for other untrusted content) to the END of `messages`. This is purely additive\n\t * (never mutates an existing message) and purely transient: `messages` here is the\n\t * array about to be sent to the provider, not `this.agent.state.messages` or anything\n\t * persisted via `sessionManager` -- so the injected message can never reach the\n\t * transcript, regardless of how many times this pass runs.\n\t *\n\t * Also records a `MemoryPromptInclusionReport` (context/memory-diagnostics.ts) at each\n\t * branch below, for context_audit's diagnostic surface only -- this is pure bookkeeping\n\t * alongside the existing branches, not a new branch/condition: the messages returned\n\t * are unchanged by this recording.\n\t */\n\tmaybeAppendMemoryEvidenceBlock(messages: AgentMessage[], report: MemoryRetrievalReport): AgentMessage[] {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\t\tconst candidates = this._memoryCandidates(report);\n\t\t\tconst base = {\n\t\t\t\tenabled: settings.enabled,\n\t\t\t\tincludeInPrompt: settings.includeInPrompt,\n\t\t\t\tselectedItemCount: candidates.length,\n\t\t\t};\n\t\t\tif (!settings.enabled) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"disabled\",\n\t\t\t\t\tincludedCount: 0,\n\t\t\t\t\tomittedCount: 0,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\t\t\tif (!settings.includeInPrompt) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"include_disabled\",\n\t\t\t\t\tincludedCount: 0,\n\t\t\t\t\tomittedCount: 0,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\t\t\tif (candidates.length === 0) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"no_results\",\n\t\t\t\t\tincludedCount: 0,\n\t\t\t\t\tomittedCount: 0,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\n\t\t\tconst budget = this._memoryBudget(settings.maxResults);\n\t\t\tconst block = composeTieredMemoryPromptBlock(candidates, budget);\n\t\t\tif (!block.text) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"empty_block\",\n\t\t\t\t\tincludedCount: block.includedCount,\n\t\t\t\t\tomittedCount: block.omittedCount,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\n\t\t\tconst wrapped = wrapUntrustedText(block.text, \"memory:tiered\");\n\t\t\tconst evidenceMessage: CustomMessage = {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: \"memory_evidence\",\n\t\t\t\tcontent: [{ type: \"text\", text: wrapped }],\n\t\t\t\tdisplay: false,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t...base,\n\t\t\t\tstatus: \"included\",\n\t\t\t\tincludedCount: block.includedCount,\n\t\t\t\tomittedCount: block.omittedCount,\n\t\t\t\tblockChars: wrapped.length,\n\t\t\t\tsourceLabel: \"memory:tiered\",\n\t\t\t};\n\t\t\treturn [...messages, evidenceMessage];\n\t\t} catch {\n\t\t\t// `base` may not exist yet if the throw happened before it was computed (e.g.\n\t\t\t// settings access or `report.contextItems` itself threw), so this branch cannot\n\t\t\t// rely on it -- fall back to safe, fixed defaults rather than risk referencing\n\t\t\t// a partially-evaluated value.\n\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\tenabled: false,\n\t\t\t\tincludeInPrompt: false,\n\t\t\t\tselectedItemCount: 0,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tincludedCount: 0,\n\t\t\t\tomittedCount: 0,\n\t\t\t\tblockChars: 0,\n\t\t\t};\n\t\t\treturn messages;\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest memory-prompt-inclusion decision, for tests/debugging and context_audit. */\n\tgetMemoryPromptInclusionReport(): MemoryPromptInclusionReport {\n\t\treturn this._latestMemoryPromptInclusionReport ?? defaultMemoryPromptInclusionReport();\n\t}\n\n\t/**\n\t * Combines the already-stored, no-arg latest reports (never re-queries the provider or\n\t * touches the OKF directory) into the safe, allow-list-projected shape context_audit\n\t * exposes. See context/memory-diagnostics.ts for why this projection is allow-list\n\t * based rather than a spread-then-delete of the raw report.\n\t */\n\tgetMemoryAuditDiagnostics(): {\n\t\tretrieval: MemoryRetrievalDiagnostics;\n\t\tpromptInclusion: MemoryPromptInclusionReport;\n\t} {\n\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\treturn {\n\t\t\tretrieval: sanitizeMemoryRetrievalReportForDiagnostics(this.getMemoryRetrievalReport(), settings),\n\t\t\tpromptInclusion: this.getMemoryPromptInclusionReport(),\n\t\t};\n\t}\n\n\t/**\n\t * Zero-I/O gate for cross-session recall (R3): skip trivial turns (short acks, slash commands) so\n\t * recall only runs when it could plausibly help. The provider's similarity cutoff is the real\n\t * filter — this just avoids the index query on turns that obviously don't warrant it.\n\t */\n\tshouldAttemptRecall(text: string): boolean {\n\t\tif (!this.deps.getSettingsManager().getMemoryRetrievalSettings().enabled) return false;\n\t\tconst t = text.trim();\n\t\tif (t.length < 12 || t.startsWith(\"/\")) return false;\n\t\tconst words = t.split(/\\s+/).filter((w) => w.length >= 3);\n\t\t// R4 adaptive gate: if recall has rarely been used lately (enough samples to trust the signal),\n\t\t// raise the bar so we only recall on clearly substantial turns — and relax it again once recall\n\t\t// starts paying off. Never fully disabled, so the loop can recover.\n\t\tconst recallRarelyUseful =\n\t\t\tthis._effectivenessTracker.sampleCount >= 5 && this._effectivenessTracker.usefulLately() < 0.15;\n\t\treturn words.length >= (recallRarelyUseful ? 6 : 3);\n\t}\n\n\t/** Legacy recall prefetch with the same hard-off and explicit external-egress policy as context retrieval. */\n\tasync prefetchRecall(query: string): Promise<string> {\n\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\tif (!settings.enabled) return \"\";\n\t\treturn this._memoryManager.prefetch(query, {\n\t\t\texternalEgressPolicy: settings.allowExternalEgress\n\t\t\t\t? ENABLED_EXTERNAL_MEMORY_EGRESS_POLICY\n\t\t\t\t: DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\t\t});\n\t}\n\n\t/** Bounded, read-only memory view for an explicitly authorized delegated worker. */\n\tasync readMemoryForLane(query: string): Promise<string> {\n\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\tif (!settings.enabled) return \"Memory retrieval is disabled by policy.\";\n\t\tconst budget = this._memoryBudget(settings.maxResults);\n\t\tconst staticBlock = this._memoryManager\n\t\t\t.buildSystemPromptBlockFresh(budget)\n\t\t\t.replace(FILE_STORE_MEMORY_SYSTEM_NOTE, \"[Read-only snapshot for a delegated worker.]\");\n\t\tconst recalled = await this.prefetchRecall(query);\n\t\tconst combined = [staticBlock, recalled]\n\t\t\t.filter((part) => part.trim().length > 0)\n\t\t\t.join(\"\\n\\n\")\n\t\t\t.slice(0, 8000);\n\t\treturn combined.length > 0\n\t\t\t? wrapUntrustedText(combined, \"worker-memory\")\n\t\t\t: \"No relevant standing memory was found.\";\n\t}\n\n\t/** R4: score whether the agent actually used an injected recall page, so the recall gate can adapt. */\n\trecordRecallOutcome(recallText: string, queryText: string, responseText: string): void {\n\t\tthis._effectivenessTracker.recordRecallOutcome(recallText, queryText, responseText);\n\t}\n\n\t/**\n\t * (Re)build the memory subsystem: a fresh MemoryManager (reload-safe), register the bundled\n\t * file-store + any extension-contributed providers, initialize, then surface the memory tools and\n\t * the frozen system-prompt block. Best-effort: never throws into the session lifecycle.\n\t */\n\tasync initialize(): Promise<void> {\n\t\ttry {\n\t\t\tawait this._lifecycleTail;\n\t\t\t// Release the previous generation's providers (locks/handles) before recreating, so a\n\t\t\t// reload does not orphan the old MemoryManager. No-op on first init / for file-store.\n\t\t\tawait this._memoryManager.shutdownAll().catch(() => {});\n\t\t\tconst manager = new MemoryManager();\n\t\t\tmanager.registerProvider(\n\t\t\t\tnew FileStoreProvider({\n\t\t\t\t\tonDurableMemoryChanged: () => {\n\t\t\t\t\t\t// OKF providers cache one bounded directory load. A USER.md overflow can create or\n\t\t\t\t\t\t// update a shard during this session, so discard only that read cache generation.\n\t\t\t\t\t\tthis._memoryOkfProvider = undefined;\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t\t// Bundled read-only cross-session recall (R3): indexes past-session transcripts and answers\n\t\t\t// prefetch() with a <memory_context> page. Never writes.\n\t\t\tmanager.registerProvider(new TranscriptRecallProvider());\n\t\t\tfor (const provider of this._pendingMemoryProviders) {\n\t\t\t\ttry {\n\t\t\t\t\tmanager.registerProvider(provider);\n\t\t\t\t} catch {\n\t\t\t\t\t// Duplicate name or reserved-tool collision — skip this provider, keep the rest.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._memoryManager = manager;\n\t\t\tawait manager.initializeAll(this.deps.getSessionId(), {\n\t\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tisChildSession: this.deps.isChildSession(),\n\t\t\t});\n\t\t\t// Surface memory tools + the frozen memory block now that providers are initialized.\n\t\t\t// refreshToolRegistry() ends in setActiveToolsByName(), which rebuilds AND assigns the\n\t\t\t// system prompt (including the memory block), so no explicit _rebuildSystemPrompt is needed.\n\t\t\tthis.deps.refreshToolRegistry();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Memory subsystem init failed:\", error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\t/** Register a memory provider contributed by an extension; applied on the next memory (re)init. */\n\tregisterMemoryProvider(provider: MemoryProvider): void {\n\t\tif (!this._pendingMemoryProviders.some((p) => p.name === provider.name)) {\n\t\t\tthis._pendingMemoryProviders.push(provider);\n\t\t}\n\t}\n\n\t/** Register a retrieval-style context memory provider contributed by an extension. */\n\tregisterContextMemoryProvider(provider: ContextMemoryProvider): void {\n\t\tif (!this._pendingContextMemoryProviders.some((p) => p.id === provider.id)) {\n\t\t\tthis._pendingContextMemoryProviders.push(provider);\n\t\t}\n\t}\n\n\tcreateReloadSnapshot(): MemoryControllerReloadSnapshot {\n\t\treturn {\n\t\t\tpendingMemoryProviders: [...this._pendingMemoryProviders],\n\t\t\tpendingContextMemoryProviders: [...this._pendingContextMemoryProviders],\n\t\t\tmemoryOkfProvider: this._memoryOkfProvider,\n\t\t\tfileStoreMemoryProvider: this._fileStoreMemoryProvider,\n\t\t};\n\t}\n\n\trestoreReloadSnapshot(snapshot: MemoryControllerReloadSnapshot): void {\n\t\tthis._pendingMemoryProviders = [...snapshot.pendingMemoryProviders];\n\t\tthis._pendingContextMemoryProviders = [...snapshot.pendingContextMemoryProviders];\n\t\tthis._memoryOkfProvider = snapshot.memoryOkfProvider;\n\t\tthis._fileStoreMemoryProvider = snapshot.fileStoreMemoryProvider;\n\t}\n\n\t/** Reload starts memory providers fresh; loaded extensions re-register before the next `initialize()`. */\n\tclearPendingProviders(): void {\n\t\tthis._pendingMemoryProviders = [];\n\t\tthis._pendingContextMemoryProviders = [];\n\t\tthis._memoryOkfProvider = undefined;\n\t\tthis._fileStoreMemoryProvider = undefined;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"memory-controller.js","sourceRoot":"","sources":["../../src/core/memory-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAGH,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,OAAO,EAAE,8BAA8B,EAAE,MAAM,0CAA0C,CAAC;AAC1F,OAAO,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC;AAClF,OAAO,EACN,kCAAkC,EAGlC,2CAA2C,GAC3C,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAA2B,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AACvG,OAAO,EAEN,qCAAqC,EACrC,kCAAkC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAA8B,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AACrG,OAAO,EA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kBAAkB,GAAG,SAAS,CAAC;QACpC,IAAI,CAAC,wBAAwB,GAAG,SAAS,CAAC;IAC3C,CAAC;CACD","sourcesContent":["/**\n * Memory controller: the session's plug-and-play memory subsystem — the read-only OKF retrieval\n * provider, the bounded prompt-evidence surfacing pilot, cross-session recall effectiveness, and the\n * live {@link MemoryManager} (bundled file-store + transcript-recall providers plus any extension\n * contributions).\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the lazily-built OKF\n * provider, the latest retrieval/prompt-inclusion reports, the recreated-on-reload MemoryManager, the\n * recall {@link EffectivenessTracker}, and the extension-contributed pending providers. Everything\n * else it needs — settings, the current turn index, agent/workspace dirs, the session id, the\n * child-session flag, and the tool-registry refresh — is reached through narrow deps accessors rather\n * than the whole AgentSession.\n *\n * Context-transform boundary (deliberate): {@link runMemoryRetrieval} and\n * {@link maybeAppendMemoryEvidenceBlock} are invoked from the session's context transform as one-line\n * delegations. This controller deliberately imports no compaction/context-pipeline internals — it only\n * ever reads settings and builds the retrieval report + the bounded evidence block, so the transform\n * stays the single owner of the pass ordering.\n */\n\nimport type { AgentMessage, CustomMessage } from \"@caupulican/pi-agent-core\";\nimport { configFile, okfMemoryDir } from \"./agent-paths.ts\";\nimport { collectCurrentWorkMemory } from \"./context/current-work-memory.ts\";\nimport { createFileStoreMemoryProvider } from \"./context/file-store-memory-provider.ts\";\nimport { createLocalGraphMemoryProvider } from \"./context/local-graph-memory-provider.ts\";\nimport { shouldQueryLongTermMemory } from \"./context/long-term-memory-trigger.ts\";\nimport {\n\tdefaultMemoryPromptInclusionReport,\n\ttype MemoryPromptInclusionReport,\n\ttype MemoryRetrievalDiagnostics,\n\tsanitizeMemoryRetrievalReportForDiagnostics,\n} from \"./context/memory-diagnostics.ts\";\nimport { type MemoryPromptBudget, resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport {\n\ttype MemoryProvider as ContextMemoryProvider,\n\tDEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\tDEFAULT_LOCAL_MEMORY_EGRESS_POLICY,\n} from \"./context/memory-provider-contract.ts\";\nimport { type MemoryRetrievalReport, retrieveMemoryForContext } from \"./context/memory-retrieval.ts\";\nimport { composeTieredMemoryPromptBlock, type MemoryTierCandidate } from \"./context/memory-tier-composer.ts\";\nimport { createOkfMemoryProvider } from \"./context/okf-memory-provider.ts\";\nimport type { GoalState } from \"./goals/goal-state.ts\";\nimport { EffectivenessTracker } from \"./memory/effectiveness-tracker.ts\";\nimport { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { MemoryProvider } from \"./memory/memory-provider.ts\";\nimport { FILE_STORE_MEMORY_SYSTEM_NOTE, FileStoreProvider } from \"./memory/providers/file-store.ts\";\nimport { TranscriptRecallProvider } from \"./memory/providers/transcript-recall.ts\";\nimport { wrapUntrustedText } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\n/**\n * Text of the most recent user message, or \"\" if there is none (e.g. goal-continuation\n * turns with no new user input). An empty query is still valid: standing user preferences may\n * surface from the file-store retrieval fallback when the static memory prompt cannot fit,\n * while long-term providers remain gated by shouldQueryLongTermMemory().\n */\nfunction latestUserMessageText(messages: AgentMessage[]): string {\n\tfor (let index = messages.length - 1; index >= 0; index--) {\n\t\tconst message = messages[index];\n\t\tif (message.role !== \"user\") continue;\n\t\tif (typeof message.content === \"string\") return message.content;\n\t\tconst parts: string[] = [];\n\t\tfor (const part of message.content) {\n\t\t\tif (part.type === \"text\") parts.push(part.text);\n\t\t}\n\t\treturn parts.join(\"\\n\");\n\t}\n\treturn \"\";\n}\n\nfunction emptyMemoryRetrievalReport(maxResults: number): MemoryRetrievalReport {\n\treturn { request: { query: \"\", maxResults }, providerReports: [], results: [], contextItems: [] };\n}\n\nconst ENABLED_EXTERNAL_MEMORY_EGRESS_POLICY = {\n\t...DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\tenabled: true,\n\tallowedScopes: DEFAULT_LOCAL_MEMORY_EGRESS_POLICY.allowedScopes,\n\tallowExternalEgress: true,\n} as const;\n\nconst MAX_PRE_COMPRESS_MEMORY_CHARS = 4_000;\n\nfunction boundPreCompressMemory(text: string): string {\n\tconst trimmed = text.trim();\n\tif (trimmed.length <= MAX_PRE_COMPRESS_MEMORY_CHARS) return trimmed;\n\tconst suffix = \"\\n...[memory handoff truncated]\";\n\treturn `${trimmed.slice(0, MAX_PRE_COMPRESS_MEMORY_CHARS - suffix.length).trimEnd()}${suffix}`;\n}\n\nexport interface MemoryControllerDeps {\n\t/** Memory-retrieval + prompt-inclusion settings (default-on gates for retrieval and surfacing). */\n\tgetSettingsManager(): SettingsManager;\n\t/** Current turn index, stamped into a retrieval request's `createdAtTurn`. */\n\tgetTurnIndex(): number;\n\t/** Agent root — the durable OKF memory docs live under `<agentDir>/okf-memory`. */\n\tgetAgentDir(): string;\n\t/** Workspace root, passed to provider initialization. */\n\tgetCwd(): string;\n\t/** This session's id, passed to provider initialization. */\n\tgetSessionId(): string;\n\t/** Child sessions gate durable memory writes; passed to provider initialization. */\n\tisChildSession(): boolean;\n\t/** Re-derive the tool registry after (re)init so the newly-surfaced memory tools take effect. */\n\trefreshToolRegistry(): void;\n\t/** Active model context window, used to cap prompt-visible memory. */\n\tgetContextWindow(): number | undefined;\n\t/** Latest active goal state, used for short-term current-work memory. */\n\tgetGoalState(): GoalState | undefined;\n}\n\n/** Extension-contributed memory state staged across an atomic runtime reload. */\nexport interface MemoryControllerReloadSnapshot {\n\tpendingMemoryProviders: MemoryProvider[];\n\tpendingContextMemoryProviders: ContextMemoryProvider[];\n\tmemoryOkfProvider: ContextMemoryProvider | undefined;\n\tfileStoreMemoryProvider: ContextMemoryProvider | undefined;\n}\n\nexport class MemoryController {\n\tprivate _memoryOkfProvider: ContextMemoryProvider | undefined = undefined;\n\tprivate _fileStoreMemoryProvider: ContextMemoryProvider | undefined = undefined;\n\tprivate _localGraphProvider: ContextMemoryProvider | undefined = undefined;\n\tprivate _localGraphResolved = false;\n\tprivate _latestMemoryRetrievalReport: MemoryRetrievalReport | undefined = undefined;\n\tprivate _latestMemoryPromptInclusionReport: MemoryPromptInclusionReport | undefined = undefined;\n\t/** Plug-and-play memory subsystem. Recreated on each (re)initialize so reload is safe. */\n\tprivate _memoryManager: MemoryManager = new MemoryManager();\n\t/** R4: tracks whether injected recall is actually used, to adapt the recall gate. */\n\tprivate readonly _effectivenessTracker = new EffectivenessTracker();\n\t/** Memory providers registered by extensions via pi.registerMemoryProvider, applied on (re)init. */\n\tprivate _pendingMemoryProviders: MemoryProvider[] = [];\n\t/** Context-memory providers registered by extensions via pi.registerContextMemoryProvider. */\n\tprivate _pendingContextMemoryProviders: ContextMemoryProvider[] = [];\n\t/** Serializes provider write hooks without delaying the foreground turn. */\n\tprivate _lifecycleTail: Promise<void> = Promise.resolve();\n\tprivate _shutdownPromise: Promise<void> | undefined;\n\n\tprivate readonly deps: MemoryControllerDeps;\n\n\tconstructor(deps: MemoryControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The live memory manager. Callers reach prefetch / tool-definitions / markers / shutdown through it. */\n\tgetMemoryManager(): MemoryManager {\n\t\treturn this._memoryManager;\n\t}\n\n\t/** Queue one completed turn for provider-owned durable synchronization. Raw tool output is excluded by the caller. */\n\tscheduleTurnSync(userText: string, assistantText: string): void {\n\t\tif (!userText.trim() && !assistantText.trim()) return;\n\t\tconst manager = this._memoryManager;\n\t\tthis._lifecycleTail = this._lifecycleTail\n\t\t\t.then(() => manager.syncTurn(userText, assistantText))\n\t\t\t.catch((error) => {\n\t\t\t\tconsole.error(\n\t\t\t\t\t\"Memory turn synchronization failed:\",\n\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t);\n\t\t\t});\n\t}\n\n\t/** Wait for prior turn writes, then collect one bounded provider handoff for the whole compaction run. */\n\tasync onPreCompress(): Promise<string> {\n\t\tawait this._lifecycleTail;\n\t\treturn boundPreCompressMemory(await this._memoryManager.onPreCompress());\n\t}\n\n\t/** Flush write-side lifecycle hooks before releasing provider resources. Idempotent per session. */\n\tshutdown(): Promise<void> {\n\t\tthis._shutdownPromise ??= (async () => {\n\t\t\tawait this._lifecycleTail;\n\t\t\tawait this._memoryManager.onSessionEnd();\n\t\t\tawait this._memoryManager.shutdownAll();\n\t\t})();\n\t\treturn this._shutdownPromise;\n\t}\n\n\t/**\n\t * Fixed path for this slice's local Pi OKF memory documents, shared across sessions\n\t * under this agentDir (not session-scoped, unlike tool-artifacts/context-gc, since OKF\n\t * memory represents durable cross-session knowledge, not a per-session capture). Not\n\t * yet user-configurable -- see the memory-retrieval settings doc comment.\n\t */\n\tprivate _memoryOkfDir(): string {\n\t\treturn okfMemoryDir(this.deps.getAgentDir());\n\t}\n\n\t/**\n\t * Session-scoped, read-only local OKF memory provider. Lazily created ONLY when memory\n\t * retrieval is enabled (see `runMemoryRetrieval`) -- never force-created, so a session\n\t * with the setting off never touches `_memoryOkfDir()` at all (no directory access, no\n\t * creation; `createOkfMemoryProvider` itself never writes/mkdirs either way).\n\t */\n\tprivate _getMemoryOkfProvider(): ContextMemoryProvider {\n\t\tthis._memoryOkfProvider ??= createOkfMemoryProvider({ rootDir: this._memoryOkfDir() });\n\t\treturn this._memoryOkfProvider;\n\t}\n\n\tprivate _getFileStoreMemoryProvider(): ContextMemoryProvider {\n\t\tthis._fileStoreMemoryProvider ??= createFileStoreMemoryProvider({\n\t\t\tmemoryFilePath: configFile(this.deps.getAgentDir(), \"MEMORY.md\"),\n\t\t\tuserFilePath: configFile(this.deps.getAgentDir(), \"USER.md\"),\n\t\t});\n\t\treturn this._fileStoreMemoryProvider;\n\t}\n\n\tprivate _getLocalGraphProvider(): ContextMemoryProvider | undefined {\n\t\tif (!this._localGraphResolved) {\n\t\t\tthis._localGraphProvider = createLocalGraphMemoryProvider({\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\t});\n\t\t\tthis._localGraphResolved = true;\n\t\t}\n\t\treturn this._localGraphProvider;\n\t}\n\n\tprivate _memoryBudget(configuredMaxResults: number) {\n\t\treturn resolveMemoryPromptBudget({\n\t\t\tcontextWindow: this.deps.getContextWindow(),\n\t\t\tconfiguredMaxResults,\n\t\t});\n\t}\n\n\tprivate _shouldQueryFileStoreFallback(budget: MemoryPromptBudget): boolean {\n\t\t// MEMORY.md/USER.md are already injected through the static file-store prompt on\n\t\t// normal windows, so querying them again would duplicate provider-visible memory.\n\t\t// In compact windows the static block can be omitted because it does not fit; only\n\t\t// then use the retrieval view to surface a few budget-pruned lines.\n\t\tif (!budget.enabled || !budget.compact) return false;\n\t\treturn this._memoryManager.buildSystemPromptBlock(budget).trim().length === 0;\n\t}\n\n\t/**\n\t * Observe-only local memory retrieval (see context/memory-retrieval.ts and\n\t * context/okf-memory-provider.ts): default-on, but settings-gated. When disabled,\n\t * never constructs built-in context-memory providers (no directory access under\n\t * `_memoryOkfDir()` at all) and returns an empty report -- fully fail-closed. When enabled,\n\t * queries local, read-only providers with the latest user message text (empty if there is\n\t * none, e.g. a goal-continuation turn) under `DEFAULT_LOCAL_MEMORY_EGRESS_POLICY`.\n\t * Retrieved items are only ever stored in the report; nothing here touches `messages`,\n\t * the transcript, or the provider-visible prompt. Never throws into a live turn: any\n\t * failure (including a provider search error) degrades to an empty report.\n\t */\n\tasync runMemoryRetrieval(messages: AgentMessage[]): Promise<MemoryRetrievalReport> {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\t\tif (!settings.enabled) {\n\t\t\t\tconst report = emptyMemoryRetrievalReport(settings.maxResults);\n\t\t\t\tthis._latestMemoryRetrievalReport = report;\n\t\t\t\treturn report;\n\t\t\t}\n\t\t\tconst query = latestUserMessageText(messages);\n\t\t\tconst budget = this._memoryBudget(settings.maxResults);\n\t\t\tconst currentWork = collectCurrentWorkMemory({ goalState: this.deps.getGoalState() });\n\t\t\tconst longTermDecision = shouldQueryLongTermMemory({\n\t\t\t\tlatestUserText: query,\n\t\t\t\tgoalState: this.deps.getGoalState(),\n\t\t\t\tbudget,\n\t\t\t\tcurrentWorkCandidateCount: currentWork.length,\n\t\t\t});\n\t\t\tconst providers = this._shouldQueryFileStoreFallback(budget) ? [this._getFileStoreMemoryProvider()] : [];\n\t\t\tif (longTermDecision.shouldQuery) {\n\t\t\t\tproviders.push(this._getMemoryOkfProvider(), ...this._pendingContextMemoryProviders);\n\t\t\t\tconst graph = this._getLocalGraphProvider();\n\t\t\t\tif (graph) providers.push(graph);\n\t\t\t}\n\t\t\tconst maxResults = budget.enabled ? Math.min(settings.maxResults, budget.maxResults) : settings.maxResults;\n\t\t\tconst report = await retrieveMemoryForContext(\n\t\t\t\tproviders,\n\t\t\t\t{ query, maxResults },\n\t\t\t\t{\n\t\t\t\t\tcreatedAtTurn: this.deps.getTurnIndex(),\n\t\t\t\t\tmaxResults,\n\t\t\t\t\tdefaultLocalPolicy: DEFAULT_LOCAL_MEMORY_EGRESS_POLICY,\n\t\t\t\t\tdefaultExternalPolicy: settings.allowExternalEgress\n\t\t\t\t\t\t? ENABLED_EXTERNAL_MEMORY_EGRESS_POLICY\n\t\t\t\t\t\t: DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\t\t\t\t},\n\t\t\t);\n\t\t\tthis._latestMemoryRetrievalReport = report;\n\t\t\treturn report;\n\t\t} catch {\n\t\t\tconst report = emptyMemoryRetrievalReport(0);\n\t\t\tthis._latestMemoryRetrievalReport = report;\n\t\t\treturn report;\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest memory-retrieval report, for tests/debugging. */\n\tgetMemoryRetrievalReport(): MemoryRetrievalReport {\n\t\treturn this._latestMemoryRetrievalReport ?? emptyMemoryRetrievalReport(0);\n\t}\n\n\tprivate _candidateForContextItem(\n\t\titem: MemoryRetrievalReport[\"contextItems\"][number],\n\t): MemoryTierCandidate | undefined {\n\t\tconst summary = item.summary?.trim();\n\t\tif (!summary) return undefined;\n\t\tconst ref = item.primaryRef?.type === \"memory\" ? item.primaryRef.ref : undefined;\n\t\tconst sourceLabel =\n\t\t\tref?.providerId === \"pi-file-store\" && ref.kind === \"user_preference\"\n\t\t\t\t? \"rule:user\"\n\t\t\t\t: `memory:${ref?.providerId ?? item.source}`;\n\t\tconst tier = ref?.kind === \"user_preference\" ? \"standing\" : \"long_term\";\n\t\treturn {\n\t\t\tid: item.id,\n\t\t\ttier,\n\t\t\tsourceLabel,\n\t\t\tsummary,\n\t\t\tscore: 0.5,\n\t\t\tevidenceRefs: item.evidenceRefs,\n\t\t};\n\t}\n\n\tprivate _memoryCandidates(report: MemoryRetrievalReport): MemoryTierCandidate[] {\n\t\treturn [\n\t\t\t...collectCurrentWorkMemory({ goalState: this.deps.getGoalState() }),\n\t\t\t...report.contextItems.flatMap((item) => {\n\t\t\t\tconst candidate = this._candidateForContextItem(item);\n\t\t\t\treturn candidate === undefined ? [] : [candidate];\n\t\t\t}),\n\t\t];\n\t}\n\n\t/**\n\t * Bounded prompt-surfacing for local memory evidence (see context/memory-tier-composer.ts):\n\t * default-on, but gated on TWO settings (`enabled` AND `includeInPrompt`) plus at least one\n\t * current-work, standing, or retrieved memory candidate -- the first\n\t * two are belt-and-suspenders on top of the fact that `runMemoryRetrieval` already\n\t * leaves `contextItems` empty whenever `enabled` is false, regardless of\n\t * `includeInPrompt`. Reuses the `report` this pass's `runMemoryRetrieval` call already\n\t * computed -- never re-queries the provider here.\n\t *\n\t * Appends exactly one ephemeral `custom`/\"memory_evidence\" message wrapped by\n\t * `wrapUntrustedText` (the same nonce-fenced boundary + always-on system-prompt rule\n\t * used for other untrusted content) to the END of `messages`. This is purely additive\n\t * (never mutates an existing message) and purely transient: `messages` here is the\n\t * array about to be sent to the provider, not `this.agent.state.messages` or anything\n\t * persisted via `sessionManager` -- so the injected message can never reach the\n\t * transcript, regardless of how many times this pass runs.\n\t *\n\t * Also records a `MemoryPromptInclusionReport` (context/memory-diagnostics.ts) at each\n\t * branch below, for context_audit's diagnostic surface only -- this is pure bookkeeping\n\t * alongside the existing branches, not a new branch/condition: the messages returned\n\t * are unchanged by this recording.\n\t */\n\tmaybeAppendMemoryEvidenceBlock(messages: AgentMessage[], report: MemoryRetrievalReport): AgentMessage[] {\n\t\ttry {\n\t\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\t\tconst candidates = this._memoryCandidates(report);\n\t\t\tconst base = {\n\t\t\t\tenabled: settings.enabled,\n\t\t\t\tincludeInPrompt: settings.includeInPrompt,\n\t\t\t\tselectedItemCount: candidates.length,\n\t\t\t};\n\t\t\tif (!settings.enabled) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"disabled\",\n\t\t\t\t\tincludedCount: 0,\n\t\t\t\t\tomittedCount: 0,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\t\t\tif (!settings.includeInPrompt) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"include_disabled\",\n\t\t\t\t\tincludedCount: 0,\n\t\t\t\t\tomittedCount: 0,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\t\t\tif (candidates.length === 0) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"no_results\",\n\t\t\t\t\tincludedCount: 0,\n\t\t\t\t\tomittedCount: 0,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\n\t\t\tconst budget = this._memoryBudget(settings.maxResults);\n\t\t\tconst block = composeTieredMemoryPromptBlock(candidates, budget);\n\t\t\tif (!block.text) {\n\t\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t\t...base,\n\t\t\t\t\tstatus: \"empty_block\",\n\t\t\t\t\tincludedCount: block.includedCount,\n\t\t\t\t\tomittedCount: block.omittedCount,\n\t\t\t\t\tblockChars: 0,\n\t\t\t\t};\n\t\t\t\treturn messages;\n\t\t\t}\n\n\t\t\tconst wrapped = wrapUntrustedText(block.text, \"memory:tiered\");\n\t\t\tconst evidenceMessage: CustomMessage = {\n\t\t\t\trole: \"custom\",\n\t\t\t\tcustomType: \"memory_evidence\",\n\t\t\t\tcontent: [{ type: \"text\", text: wrapped }],\n\t\t\t\tdisplay: false,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t};\n\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\t...base,\n\t\t\t\tstatus: \"included\",\n\t\t\t\tincludedCount: block.includedCount,\n\t\t\t\tomittedCount: block.omittedCount,\n\t\t\t\tblockChars: wrapped.length,\n\t\t\t\tsourceLabel: \"memory:tiered\",\n\t\t\t};\n\t\t\treturn [...messages, evidenceMessage];\n\t\t} catch {\n\t\t\t// `base` may not exist yet if the throw happened before it was computed (e.g.\n\t\t\t// settings access or `report.contextItems` itself threw), so this branch cannot\n\t\t\t// rely on it -- fall back to safe, fixed defaults rather than risk referencing\n\t\t\t// a partially-evaluated value.\n\t\t\tthis._latestMemoryPromptInclusionReport = {\n\t\t\t\tenabled: false,\n\t\t\t\tincludeInPrompt: false,\n\t\t\t\tselectedItemCount: 0,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tincludedCount: 0,\n\t\t\t\tomittedCount: 0,\n\t\t\t\tblockChars: 0,\n\t\t\t};\n\t\t\treturn messages;\n\t\t}\n\t}\n\n\t/** Read-only inspection of the latest memory-prompt-inclusion decision, for tests/debugging and context_audit. */\n\tgetMemoryPromptInclusionReport(): MemoryPromptInclusionReport {\n\t\treturn this._latestMemoryPromptInclusionReport ?? defaultMemoryPromptInclusionReport();\n\t}\n\n\t/**\n\t * Combines the already-stored, no-arg latest reports (never re-queries the provider or\n\t * touches the OKF directory) into the safe, allow-list-projected shape context_audit\n\t * exposes. See context/memory-diagnostics.ts for why this projection is allow-list\n\t * based rather than a spread-then-delete of the raw report.\n\t */\n\tgetMemoryAuditDiagnostics(): {\n\t\tretrieval: MemoryRetrievalDiagnostics;\n\t\tpromptInclusion: MemoryPromptInclusionReport;\n\t} {\n\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\treturn {\n\t\t\tretrieval: sanitizeMemoryRetrievalReportForDiagnostics(this.getMemoryRetrievalReport(), settings),\n\t\t\tpromptInclusion: this.getMemoryPromptInclusionReport(),\n\t\t};\n\t}\n\n\t/**\n\t * Zero-I/O gate for cross-session recall (R3): skip trivial turns (short acks, slash commands) so\n\t * recall only runs when it could plausibly help. The provider's similarity cutoff is the real\n\t * filter — this just avoids the index query on turns that obviously don't warrant it.\n\t */\n\tshouldAttemptRecall(text: string): boolean {\n\t\tif (!this.deps.getSettingsManager().getMemoryRetrievalSettings().enabled) return false;\n\t\tconst t = text.trim();\n\t\tif (t.length < 12 || t.startsWith(\"/\")) return false;\n\t\tconst words = t.split(/\\s+/).filter((w) => w.length >= 3);\n\t\t// R4 adaptive gate: if recall has rarely been used lately (enough samples to trust the signal),\n\t\t// raise the bar so we only recall on clearly substantial turns — and relax it again once recall\n\t\t// starts paying off. Never fully disabled, so the loop can recover.\n\t\tconst recallRarelyUseful =\n\t\t\tthis._effectivenessTracker.sampleCount >= 5 && this._effectivenessTracker.usefulLately() < 0.15;\n\t\treturn words.length >= (recallRarelyUseful ? 6 : 3);\n\t}\n\n\t/** Legacy recall prefetch with the same hard-off and explicit external-egress policy as context retrieval. */\n\tasync prefetchRecall(query: string): Promise<string> {\n\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\tif (!settings.enabled) return \"\";\n\t\treturn this._memoryManager.prefetch(query, {\n\t\t\texternalEgressPolicy: settings.allowExternalEgress\n\t\t\t\t? ENABLED_EXTERNAL_MEMORY_EGRESS_POLICY\n\t\t\t\t: DEFAULT_EXTERNAL_MEMORY_EGRESS_POLICY,\n\t\t});\n\t}\n\n\t/** Bounded, read-only memory view for an explicitly authorized delegated worker. */\n\tasync readMemoryForLane(query: string): Promise<string> {\n\t\tconst settings = this.deps.getSettingsManager().getMemoryRetrievalSettings();\n\t\tif (!settings.enabled) return \"Memory retrieval is disabled by policy.\";\n\t\tconst budget = this._memoryBudget(settings.maxResults);\n\t\tconst staticBlock = this._memoryManager\n\t\t\t.buildSystemPromptBlockFresh(budget)\n\t\t\t.replace(FILE_STORE_MEMORY_SYSTEM_NOTE, \"[Read-only snapshot for a delegated worker.]\");\n\t\tconst recalled = await this.prefetchRecall(query);\n\t\tconst combined = [staticBlock, recalled]\n\t\t\t.filter((part) => part.trim().length > 0)\n\t\t\t.join(\"\\n\\n\")\n\t\t\t.slice(0, 8000);\n\t\treturn combined.length > 0\n\t\t\t? wrapUntrustedText(combined, \"worker-memory\")\n\t\t\t: \"No relevant standing memory was found.\";\n\t}\n\n\t/** R4: score whether the agent actually used an injected recall page, so the recall gate can adapt. */\n\trecordRecallOutcome(recallText: string, queryText: string, responseText: string): void {\n\t\tthis._effectivenessTracker.recordRecallOutcome(recallText, queryText, responseText);\n\t}\n\n\t/**\n\t * (Re)build the memory subsystem: a fresh MemoryManager (reload-safe), register the bundled\n\t * file-store + any extension-contributed providers, initialize, then surface the memory tools and\n\t * the frozen system-prompt block. Best-effort: never throws into the session lifecycle.\n\t */\n\tasync initialize(): Promise<void> {\n\t\ttry {\n\t\t\tawait this._lifecycleTail;\n\t\t\t// Release the previous generation's providers (locks/handles) before recreating, so a\n\t\t\t// reload does not orphan the old MemoryManager. No-op on first init / for file-store.\n\t\t\tawait this._memoryManager.shutdownAll().catch(() => {});\n\t\t\tthis._localGraphProvider = undefined;\n\t\t\tthis._localGraphResolved = false;\n\t\t\tconst manager = new MemoryManager();\n\t\t\tmanager.registerProvider(\n\t\t\t\tnew FileStoreProvider({\n\t\t\t\t\tonDurableMemoryChanged: () => {\n\t\t\t\t\t\t// OKF providers cache one bounded directory load. A USER.md overflow can create or\n\t\t\t\t\t\t// update a shard during this session, so discard only that read cache generation.\n\t\t\t\t\t\tthis._memoryOkfProvider = undefined;\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t);\n\t\t\t// Bundled read-only cross-session recall (R3): indexes past-session transcripts and answers\n\t\t\t// prefetch() with a <memory_context> page. Never writes.\n\t\t\tmanager.registerProvider(new TranscriptRecallProvider());\n\t\t\tfor (const provider of this._pendingMemoryProviders) {\n\t\t\t\ttry {\n\t\t\t\t\tmanager.registerProvider(provider);\n\t\t\t\t} catch {\n\t\t\t\t\t// Duplicate name or reserved-tool collision — skip this provider, keep the rest.\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis._memoryManager = manager;\n\t\t\tawait manager.initializeAll(this.deps.getSessionId(), {\n\t\t\t\tagentDir: this.deps.getAgentDir(),\n\t\t\t\tcwd: this.deps.getCwd(),\n\t\t\t\tisChildSession: this.deps.isChildSession(),\n\t\t\t});\n\t\t\t// Surface memory tools + the frozen memory block now that providers are initialized.\n\t\t\t// refreshToolRegistry() ends in setActiveToolsByName(), which rebuilds AND assigns the\n\t\t\t// system prompt (including the memory block), so no explicit _rebuildSystemPrompt is needed.\n\t\t\tthis.deps.refreshToolRegistry();\n\t\t} catch (error) {\n\t\t\tconsole.error(\"Memory subsystem init failed:\", error instanceof Error ? error.message : String(error));\n\t\t}\n\t}\n\n\t/** Register a memory provider contributed by an extension; applied on the next memory (re)init. */\n\tregisterMemoryProvider(provider: MemoryProvider): void {\n\t\tif (!this._pendingMemoryProviders.some((p) => p.name === provider.name)) {\n\t\t\tthis._pendingMemoryProviders.push(provider);\n\t\t}\n\t}\n\n\t/** Register a retrieval-style context memory provider contributed by an extension. */\n\tregisterContextMemoryProvider(provider: ContextMemoryProvider): void {\n\t\tif (!this._pendingContextMemoryProviders.some((p) => p.id === provider.id)) {\n\t\t\tthis._pendingContextMemoryProviders.push(provider);\n\t\t}\n\t}\n\n\tcreateReloadSnapshot(): MemoryControllerReloadSnapshot {\n\t\treturn {\n\t\t\tpendingMemoryProviders: [...this._pendingMemoryProviders],\n\t\t\tpendingContextMemoryProviders: [...this._pendingContextMemoryProviders],\n\t\t\tmemoryOkfProvider: this._memoryOkfProvider,\n\t\t\tfileStoreMemoryProvider: this._fileStoreMemoryProvider,\n\t\t};\n\t}\n\n\trestoreReloadSnapshot(snapshot: MemoryControllerReloadSnapshot): void {\n\t\tthis._pendingMemoryProviders = [...snapshot.pendingMemoryProviders];\n\t\tthis._pendingContextMemoryProviders = [...snapshot.pendingContextMemoryProviders];\n\t\tthis._memoryOkfProvider = snapshot.memoryOkfProvider;\n\t\tthis._fileStoreMemoryProvider = snapshot.fileStoreMemoryProvider;\n\t}\n\n\t/** Reload starts memory providers fresh; loaded extensions re-register before the next `initialize()`. */\n\tclearPendingProviders(): void {\n\t\tthis._pendingMemoryProviders = [];\n\t\tthis._pendingContextMemoryProviders = [];\n\t\tthis._memoryOkfProvider = undefined;\n\t\tthis._fileStoreMemoryProvider = undefined;\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-capability.d.ts","sourceRoot":"","sources":["../../src/core/model-capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,oBAAoB,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,CAAC;AAExE,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,KAAK,GAAG,oBAAoB,CAAC;AAExE,MAAM,WAAW,sBAAsB;IACtC,KAAK,EAAE,oBAAoB,CAAC;IAC5B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,2GAA2G;IAC3G,oBAAoB,EAAE,MAAM,GAAG,SAAS,CAAC;IACzC,yDAAyD;IACzD,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,4EAA4E;IAC5E,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,0FAA0F;IAC1F,sBAAsB,EAAE,OAAO,CA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AOhC;AAED,6EAA6E;AAC7E,eAAO,MAAM,0BAA0B,uCAAuC,CAAC;AAE/E,0GAA0G;AAC1G,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,MAAM,CAI5F"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-capability.js","sourceRoot":"","sources":["../../src/core/model-capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAsBH,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,oFAAoF;AACpF,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,oCAAoC,GAAG,KAAK,CAAC;AAE1D;;;;GAIG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAA+D;IACnH,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,KAAK;IACd,IAAI,EAAE,KAAK;CACX,CAAC;AAEF,MAAM,CAAC,MAAM,mCAAmC,GAAsB;IACrE,UAAU;IACV,eAAe;IACf,MAAM;IACN,eAAe;IACf,kBAAkB;IAClB,cAAc;IACd,UAAU;IACV,eAAe;IACf,eAAe;IACf,oBAAoB;CACpB,CAAC;AACF,MAAM,CAAC,MAAM,sCAAsC,GAAsB;IACxE,MAAM;IACN,OAAO;IACP,MAAM;IACN,QAAQ;IACR,YAAY;IACZ,MAAM;IACN,OAAO;IACP,cAAc;IACd,+FAA+F;IAC/F,oBAAoB;CACpB,CAAC;AACF,MAAM,CAAC,MAAM,mCAAmC,GAAsB,EAAE,CAAC;AAEzE,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AACnD,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAEvC,SAAS,yBAAyB,CAAC,aAAiC;IACnE,IAAI,aAAa,KAAK,SAAS,IAAI,aAAa,IAAI,CAAC;QAAE,O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MAAM,EAAE,sBAAsB,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IAClG,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,MAAM,0BAA0B,GAAG,oCAAoC,CAAC;AAE/E,0GAA0G;AAC1G,MAAM,UAAU,uBAAuB,CAAC,OAA0B,EAAE,OAAgB;IACnF,MAAM,UAAU,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnE,MAAM,UAAU,GAAG,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnG,OAAO,GAAG,0BAA0B,GAAG,UAAU,UAAU,OAAO,CAAC,eAAe,kBAAkB,UAAU,WAAW,OAAO,CAAC,MAAM,EAAE,CAAC;AAC3I,CAAC","sourcesContent":["/**\n * Model capability auto-detection: derive what the harness may load onto a model FROM the model's\n * own metadata (`Model.contextWindow`), so small open models (4k/8k/16k windows, sub-1B params)\n * can still hold a usable chat instead of drowning in the stable prompt, tool schemas, and\n * background-lane prompts. The same class is the single input to prompt shaping and tool/lane gates.\n *\n * Derivation is metadata-first; defaults apply only when the metadata is missing (unknown/zero\n * window keeps today's full behavior rather than guessing). Detection can be disabled or forced\n * per class via the `modelCapability.mode` setting.\n */\n\nexport type ModelCapabilityClass = \"full\" | \"lean\" | \"minimal\" | \"chat\";\n\nexport type ModelCapabilityMode = \"auto\" | \"off\" | ModelCapabilityClass;\n\nexport interface ModelCapabilityProfile {\n\tclass: ModelCapabilityClass;\n\tcontextWindow?: number;\n\treasonCode: string;\n\t/** Hard aggregate character envelope for the stable system prompt; undefined = intentionally unbounded. */\n\tsystemPromptMaxChars: number | undefined;\n\t/** Allow-list; undefined = no allow-list restriction. */\n\tallowedToolNames?: readonly string[];\n\t/** Block-list applied after the allow-list; undefined = nothing blocked. */\n\tblockedToolNames?: readonly string[];\n\t/** Whether idle background lanes (goal auto-continue, research) may run on this model. */\n\tbackgroundLanesEnabled: boolean;\n\t/** Output-token cap for lane isolated completions, scaled to the window. */\n\tlaneMaxOutputTokens: number;\n}\n\n/** Windows at or above this keep the full harness surface. */\nexport const MODEL_CAPABILITY_FULL_MIN_CONTEXT = 32_768;\n/** Windows at or above this keep core tools but shed background-autonomy extras. */\nexport const MODEL_CAPABILITY_LEAN_MIN_CONTEXT = 16_384;\n/** Windows at or above this get the minimal coding set; below is chat-only. */\nexport const MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT = 8_192;\n\n/**\n * Aggregate stable-prompt envelopes. These are deliberately owned beside the classification\n * thresholds so every harness expansion must fit the same profile that owns tools and lanes.\n * Full/off profiles are intentionally unbounded; constrained profiles fail visibly on overflow.\n */\nexport const MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS: Readonly<Record<ModelCapabilityClass, number | undefined>> = {\n\tfull: undefined,\n\tlean: 8_192,\n\tminimal: 4_096,\n\tchat: 2_048,\n};\n\nexport const MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS: readonly string[] = [\n\t\"delegate\",\n\t\"context_audit\",\n\t\"goal\",\n\t\"worktree_sync\",\n\t\"improvement_loop\",\n\t\"extensionify\",\n\t\"skillify\",\n\t\"model_fitness\",\n\t\"context_scout\",\n\t\"tmux_agent_manager\",\n];\nexport const MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS: readonly string[] = [\n\t\"read\",\n\t\"skill\",\n\t\"bash\",\n\t\"python\",\n\t\"powershell\",\n\t\"edit\",\n\t\"write\",\n\t\"ask_question\",\n\t// The executor tool: minimal-class models ARE the daily-ops executors, and its schema is tiny.\n\t\"run_toolkit_script\",\n];\nexport const MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS: readonly string[] = [];\n\nexport const DEFAULT_LANE_MAX_OUTPUT_TOKENS = 2048;\nconst MIN_LANE_MAX_OUTPUT_TOKENS = 256;\n\nfunction laneOutputTokensForWindow(contextWindow: number | undefined): number {\n\tif (contextWindow === undefined || contextWindow <= 0) return DEFAULT_LANE_MAX_OUTPUT_TOKENS;\n\t// A lane completion may use at most an eighth of the window for output, floored so tiny\n\t// windows still produce something parseable.\n\treturn Math.min(DEFAULT_LANE_MAX_OUTPUT_TOKENS, Math.max(MIN_LANE_MAX_OUTPUT_TOKENS, Math.floor(contextWindow / 8)));\n}\n\nfunction profileForClass(\n\tcapabilityClass: ModelCapabilityClass,\n\treasonCode: string,\n\tcontextWindow: number | undefined,\n): ModelCapabilityProfile {\n\tconst base = {\n\t\tclass: capabilityClass,\n\t\treasonCode,\n\t\tsystemPromptMaxChars: MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS[capabilityClass],\n\t\tbackgroundLanesEnabled: true,\n\t\tlaneMaxOutputTokens: laneOutputTokensForWindow(contextWindow),\n\t\t...(contextWindow !== undefined && contextWindow > 0 ? { contextWindow } : {}),\n\t};\n\tswitch (capabilityClass) {\n\t\tcase \"full\":\n\t\t\treturn base;\n\t\tcase \"lean\":\n\t\t\treturn { ...base, blockedToolNames: MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS };\n\t\tcase \"minimal\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t\tcase \"chat\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t}\n}\n\n/**\n * Mandatory provider-neutral gate for a final system prompt. This intentionally rejects rather\n * than truncates: arbitrary truncation can silently remove security, repair, or project rules.\n */\nexport function enforceModelCapabilitySystemPromptBudget(\n\tsystemPrompt: string,\n\tprofile: Pick<ModelCapabilityProfile, \"class\" | \"systemPromptMaxChars\">,\n): string {\n\tconst maxChars = profile.systemPromptMaxChars;\n\tif (maxChars === undefined || systemPrompt.length <= maxChars) return systemPrompt;\n\tthrow new Error(\n\t\t`${profile.class} system prompt exceeds its ${maxChars}-character capability budget (${systemPrompt.length} characters). Reduce custom, extension, or harness prompt guidance, or select a more capable profile.`,\n\t);\n}\n\nexport function deriveModelCapabilityProfile(args: {\n\tcontextWindow?: number;\n\tmode?: ModelCapabilityMode;\n}): ModelCapabilityProfile {\n\tconst mode = args.mode ?? \"auto\";\n\tconst contextWindow =\n\t\targs.contextWindow !== undefined && Number.isFinite(args.contextWindow) && args.contextWindow > 0\n\t\t\t? args.contextWindow\n\t\t\t: undefined;\n\tif (mode === \"off\") {\n\t\treturn profileForClass(\"full\", \"detection_disabled\", contextWindow);\n\t}\n\tif (mode !== \"auto\") {\n\t\treturn profileForClass(mode, \"forced_by_setting\", contextWindow);\n\t}\n\n\tif (contextWindow === undefined) {\n\t\t// Metadata missing: defaults, never guesses.\n\t\treturn profileForClass(\"full\", \"unknown_context_window_defaults\", undefined);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_FULL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"full\", \"large_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_LEAN_MIN_CONTEXT) {\n\t\treturn profileForClass(\"lean\", \"lean_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"minimal\", \"minimal_context_window\", contextWindow);\n\t}\n\treturn profileForClass(\"chat\", \"chat_only_context_window\", contextWindow);\n}\n\n/** Apply the profile's allow/block lists to a requested tool-name list, preserving order. */\nexport function filterToolNamesForCapability(toolNames: readonly string[], profile: ModelCapabilityProfile): string[] {\n\tlet filtered = [...toolNames];\n\tif (profile.allowedToolNames !== undefined) {\n\t\tconst allowed = new Set(profile.allowedToolNames);\n\t\tfiltered = filtered.filter((name) => allowed.has(name));\n\t}\n\tif (profile.blockedToolNames !== undefined) {\n\t\tconst blocked = new Set(profile.blockedToolNames);\n\t\tfiltered = filtered.filter((name) => !blocked.has(name));\n\t}\n\treturn filtered;\n}\n\n/**\n * Lane-worker eligibility: a session bound to a worktree-sync lane (`--worktree-lane` /\n * `PI_WORKTREE_LANE`, see worktree-sync/runtime.ts) is expected to drive the FULL multi-step\n * lane-gate/recovery surface -- sync, conflict recovery, land -- unattended. A sub-full capability\n * class or a model with no working native tool-call path cannot reliably drive that surface. This\n * rides the SAME capability system every other adaptation in this file rides (class + context\n * window + the `/toolprobe` verdict) -- no parallel mechanism, no new env var, no new registry field.\n */\nexport type LaneWorkerRefusalReason =\n\t| \"capability_class_below_full\"\n\t| \"context_window_unknown\"\n\t| \"tool_calling_unadvertised\"\n\t| \"tool_calling_demoted\";\n\nexport interface LaneWorkerRefusal {\n\treason: LaneWorkerRefusalReason;\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow?: number;\n}\n\n/**\n * Decide whether the model described by `args` may drive a worktree-sync lane worker. First\n * failure wins, in order: capability class below full; an unknown/undeclared context window (the\n * classifier's own registry-derived SSOT -- see `deriveModelCapabilityProfile`; a full class can\n * still carry an undefined window via the `unknown_context_window_defaults` fallback); no\n * ADVERTISED native tool-call path (`Model.textToolCallProtocol` unset/false -- set true means\n * phone-only); or a GRADED `/toolprobe` demotion to \"text-protocol\"/\"none\". An UNPROBED model (no\n * verdict on record yet) is eligible on its advertised support alone -- unprobed is never treated\n * as demoted. `undefined` means eligible.\n */\nexport function evaluateLaneWorkerRefusal(args: {\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow: number | undefined;\n\ttoolCallingAdvertised: boolean;\n\ttoolCallingDemoted: boolean;\n}): LaneWorkerRefusal | undefined {\n\tconst { capabilityClass, contextWindow, toolCallingAdvertised, toolCallingDemoted } = args;\n\tif (capabilityClass !== \"full\") return { reason: \"capability_class_below_full\", capabilityClass, contextWindow };\n\tif (contextWindow === undefined) return { reason: \"context_window_unknown\", capabilityClass, contextWindow };\n\tif (!toolCallingAdvertised) return { reason: \"tool_calling_unadvertised\", capabilityClass, contextWindow };\n\tif (toolCallingDemoted) return { reason: \"tool_calling_demoted\", capabilityClass, contextWindow };\n\treturn undefined;\n}\n\n/** Stable, greppable prefix for {@link formatLaneWorkerRefusal}'s output. */\nexport const LANE_WORKER_REFUSAL_PREFIX = \"worktree-sync lane-worker refusal:\";\n\n/** Format a refusal into one deterministic, greppable line naming the lane, class, window, and reason. */\nexport function formatLaneWorkerRefusal(refusal: LaneWorkerRefusal, laneKey?: string): string {\n\tconst laneSuffix = laneKey !== undefined ? ` lane=${laneKey}` : \"\";\n\tconst windowText = refusal.contextWindow !== undefined ? String(refusal.contextWindow) : \"unknown\";\n\treturn `${LANE_WORKER_REFUSAL_PREFIX}${laneSuffix} class=${refusal.capabilityClass} contextWindow=${windowText} reason=${refusal.reason}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-capability.js","sourceRoot":"","sources":["../../src/core/model-capability.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAsBH,8DAA8D;AAC9D,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,oFAAoF;AACpF,MAAM,CAAC,MAAM,iCAAiC,GAAG,MAAM,CAAC;AACxD,+EAA+E;AAC/E,MAAM,CAAC,MAAM,oCAAoC,GAAG,KAAK,CAAC;AAE1D;;;;GAIG;AACH,MAAM,CAAC,MAAM,wCAAwC,GAA+D;IACnH,IAAI,EAAE,SAAS;IACf,IAAI,EAAE,KAAK;IACX,OAAO,EAAE,KAAK;IACd,IAAI,EAAE,KAAK;CACX,CAAC;AAEF,MAAM,CAAC,MAAM,mCAAmC,GAAsB;IACrE,UAAU;IACV,eAAe;IACf,MAAM;IACN,UAAU;IACV,eAAe;IACf,kBAAkB;IAClB,cAAc;IACd,UAAU;IACV,eAAe;IACf,eAAe;IACf,oBAAoB;CACpB,CAAC;AACF,MAAM,CAAC,MAAM,sCAAsC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EAAE,GAAG,IAAI,CAAC;IAC3F,IAAI,eAAe,KAAK,MAAM;QAAE,OAAO,EAAE,MAAM,EAAE,6BAA6B,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IACjH,IAAI,aAAa,KAAK,SAAS;QAAE,OAAO,EAAE,MAAM,EAAE,wBAAwB,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IAC7G,IAAI,CAAC,qBAAqB;QAAE,OAAO,EAAE,MAAM,EAAE,2BAA2B,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IAC3G,IAAI,kBAAkB;QAAE,OAAO,EAAE,MAAM,EAAE,sBAAsB,EAAE,eAAe,EAAE,aAAa,EAAE,CAAC;IAClG,OAAO,SAAS,CAAC;AAClB,CAAC;AAED,6EAA6E;AAC7E,MAAM,CAAC,MAAM,0BAA0B,GAAG,oCAAoC,CAAC;AAE/E,0GAA0G;AAC1G,MAAM,UAAU,uBAAuB,CAAC,OAA0B,EAAE,OAAgB;IACnF,MAAM,UAAU,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;IACnE,MAAM,UAAU,GAAG,OAAO,CAAC,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnG,OAAO,GAAG,0BAA0B,GAAG,UAAU,UAAU,OAAO,CAAC,eAAe,kBAAkB,UAAU,WAAW,OAAO,CAAC,MAAM,EAAE,CAAC;AAC3I,CAAC","sourcesContent":["/**\n * Model capability auto-detection: derive what the harness may load onto a model FROM the model's\n * own metadata (`Model.contextWindow`), so small open models (4k/8k/16k windows, sub-1B params)\n * can still hold a usable chat instead of drowning in the stable prompt, tool schemas, and\n * background-lane prompts. The same class is the single input to prompt shaping and tool/lane gates.\n *\n * Derivation is metadata-first; defaults apply only when the metadata is missing (unknown/zero\n * window keeps today's full behavior rather than guessing). Detection can be disabled or forced\n * per class via the `modelCapability.mode` setting.\n */\n\nexport type ModelCapabilityClass = \"full\" | \"lean\" | \"minimal\" | \"chat\";\n\nexport type ModelCapabilityMode = \"auto\" | \"off\" | ModelCapabilityClass;\n\nexport interface ModelCapabilityProfile {\n\tclass: ModelCapabilityClass;\n\tcontextWindow?: number;\n\treasonCode: string;\n\t/** Hard aggregate character envelope for the stable system prompt; undefined = intentionally unbounded. */\n\tsystemPromptMaxChars: number | undefined;\n\t/** Allow-list; undefined = no allow-list restriction. */\n\tallowedToolNames?: readonly string[];\n\t/** Block-list applied after the allow-list; undefined = nothing blocked. */\n\tblockedToolNames?: readonly string[];\n\t/** Whether idle background lanes (goal auto-continue, research) may run on this model. */\n\tbackgroundLanesEnabled: boolean;\n\t/** Output-token cap for lane isolated completions, scaled to the window. */\n\tlaneMaxOutputTokens: number;\n}\n\n/** Windows at or above this keep the full harness surface. */\nexport const MODEL_CAPABILITY_FULL_MIN_CONTEXT = 32_768;\n/** Windows at or above this keep core tools but shed background-autonomy extras. */\nexport const MODEL_CAPABILITY_LEAN_MIN_CONTEXT = 16_384;\n/** Windows at or above this get the minimal coding set; below is chat-only. */\nexport const MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT = 8_192;\n\n/**\n * Aggregate stable-prompt envelopes. These are deliberately owned beside the classification\n * thresholds so every harness expansion must fit the same profile that owns tools and lanes.\n * Full/off profiles are intentionally unbounded; constrained profiles fail visibly on overflow.\n */\nexport const MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS: Readonly<Record<ModelCapabilityClass, number | undefined>> = {\n\tfull: undefined,\n\tlean: 8_192,\n\tminimal: 4_096,\n\tchat: 2_048,\n};\n\nexport const MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS: readonly string[] = [\n\t\"delegate\",\n\t\"context_audit\",\n\t\"goal\",\n\t\"pipeline\",\n\t\"worktree_sync\",\n\t\"improvement_loop\",\n\t\"extensionify\",\n\t\"skillify\",\n\t\"model_fitness\",\n\t\"context_scout\",\n\t\"tmux_agent_manager\",\n];\nexport const MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS: readonly string[] = [\n\t\"read\",\n\t\"skill\",\n\t\"bash\",\n\t\"python\",\n\t\"powershell\",\n\t\"edit\",\n\t\"write\",\n\t\"ask_question\",\n\t// The executor tool: minimal-class models ARE the daily-ops executors, and its schema is tiny.\n\t\"run_toolkit_script\",\n];\nexport const MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS: readonly string[] = [];\n\nexport const DEFAULT_LANE_MAX_OUTPUT_TOKENS = 2048;\nconst MIN_LANE_MAX_OUTPUT_TOKENS = 256;\n\nfunction laneOutputTokensForWindow(contextWindow: number | undefined): number {\n\tif (contextWindow === undefined || contextWindow <= 0) return DEFAULT_LANE_MAX_OUTPUT_TOKENS;\n\t// A lane completion may use at most an eighth of the window for output, floored so tiny\n\t// windows still produce something parseable.\n\treturn Math.min(DEFAULT_LANE_MAX_OUTPUT_TOKENS, Math.max(MIN_LANE_MAX_OUTPUT_TOKENS, Math.floor(contextWindow / 8)));\n}\n\nfunction profileForClass(\n\tcapabilityClass: ModelCapabilityClass,\n\treasonCode: string,\n\tcontextWindow: number | undefined,\n): ModelCapabilityProfile {\n\tconst base = {\n\t\tclass: capabilityClass,\n\t\treasonCode,\n\t\tsystemPromptMaxChars: MODEL_CAPABILITY_SYSTEM_PROMPT_MAX_CHARS[capabilityClass],\n\t\tbackgroundLanesEnabled: true,\n\t\tlaneMaxOutputTokens: laneOutputTokensForWindow(contextWindow),\n\t\t...(contextWindow !== undefined && contextWindow > 0 ? { contextWindow } : {}),\n\t};\n\tswitch (capabilityClass) {\n\t\tcase \"full\":\n\t\t\treturn base;\n\t\tcase \"lean\":\n\t\t\treturn { ...base, blockedToolNames: MODEL_CAPABILITY_LEAN_BLOCKED_TOOLS };\n\t\tcase \"minimal\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_MINIMAL_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t\tcase \"chat\":\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tallowedToolNames: MODEL_CAPABILITY_CHAT_ALLOWED_TOOLS,\n\t\t\t\tbackgroundLanesEnabled: false,\n\t\t\t};\n\t}\n}\n\n/**\n * Mandatory provider-neutral gate for a final system prompt. This intentionally rejects rather\n * than truncates: arbitrary truncation can silently remove security, repair, or project rules.\n */\nexport function enforceModelCapabilitySystemPromptBudget(\n\tsystemPrompt: string,\n\tprofile: Pick<ModelCapabilityProfile, \"class\" | \"systemPromptMaxChars\">,\n): string {\n\tconst maxChars = profile.systemPromptMaxChars;\n\tif (maxChars === undefined || systemPrompt.length <= maxChars) return systemPrompt;\n\tthrow new Error(\n\t\t`${profile.class} system prompt exceeds its ${maxChars}-character capability budget (${systemPrompt.length} characters). Reduce custom, extension, or harness prompt guidance, or select a more capable profile.`,\n\t);\n}\n\nexport function deriveModelCapabilityProfile(args: {\n\tcontextWindow?: number;\n\tmode?: ModelCapabilityMode;\n}): ModelCapabilityProfile {\n\tconst mode = args.mode ?? \"auto\";\n\tconst contextWindow =\n\t\targs.contextWindow !== undefined && Number.isFinite(args.contextWindow) && args.contextWindow > 0\n\t\t\t? args.contextWindow\n\t\t\t: undefined;\n\tif (mode === \"off\") {\n\t\treturn profileForClass(\"full\", \"detection_disabled\", contextWindow);\n\t}\n\tif (mode !== \"auto\") {\n\t\treturn profileForClass(mode, \"forced_by_setting\", contextWindow);\n\t}\n\n\tif (contextWindow === undefined) {\n\t\t// Metadata missing: defaults, never guesses.\n\t\treturn profileForClass(\"full\", \"unknown_context_window_defaults\", undefined);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_FULL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"full\", \"large_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_LEAN_MIN_CONTEXT) {\n\t\treturn profileForClass(\"lean\", \"lean_context_window\", contextWindow);\n\t}\n\tif (contextWindow >= MODEL_CAPABILITY_MINIMAL_MIN_CONTEXT) {\n\t\treturn profileForClass(\"minimal\", \"minimal_context_window\", contextWindow);\n\t}\n\treturn profileForClass(\"chat\", \"chat_only_context_window\", contextWindow);\n}\n\n/** Apply the profile's allow/block lists to a requested tool-name list, preserving order. */\nexport function filterToolNamesForCapability(toolNames: readonly string[], profile: ModelCapabilityProfile): string[] {\n\tlet filtered = [...toolNames];\n\tif (profile.allowedToolNames !== undefined) {\n\t\tconst allowed = new Set(profile.allowedToolNames);\n\t\tfiltered = filtered.filter((name) => allowed.has(name));\n\t}\n\tif (profile.blockedToolNames !== undefined) {\n\t\tconst blocked = new Set(profile.blockedToolNames);\n\t\tfiltered = filtered.filter((name) => !blocked.has(name));\n\t}\n\treturn filtered;\n}\n\n/**\n * Lane-worker eligibility: a session bound to a worktree-sync lane (`--worktree-lane` /\n * `PI_WORKTREE_LANE`, see worktree-sync/runtime.ts) is expected to drive the FULL multi-step\n * lane-gate/recovery surface -- sync, conflict recovery, land -- unattended. A sub-full capability\n * class or a model with no working native tool-call path cannot reliably drive that surface. This\n * rides the SAME capability system every other adaptation in this file rides (class + context\n * window + the `/toolprobe` verdict) -- no parallel mechanism, no new env var, no new registry field.\n */\nexport type LaneWorkerRefusalReason =\n\t| \"capability_class_below_full\"\n\t| \"context_window_unknown\"\n\t| \"tool_calling_unadvertised\"\n\t| \"tool_calling_demoted\";\n\nexport interface LaneWorkerRefusal {\n\treason: LaneWorkerRefusalReason;\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow?: number;\n}\n\n/**\n * Decide whether the model described by `args` may drive a worktree-sync lane worker. First\n * failure wins, in order: capability class below full; an unknown/undeclared context window (the\n * classifier's own registry-derived SSOT -- see `deriveModelCapabilityProfile`; a full class can\n * still carry an undefined window via the `unknown_context_window_defaults` fallback); no\n * ADVERTISED native tool-call path (`Model.textToolCallProtocol` unset/false -- set true means\n * phone-only); or a GRADED `/toolprobe` demotion to \"text-protocol\"/\"none\". An UNPROBED model (no\n * verdict on record yet) is eligible on its advertised support alone -- unprobed is never treated\n * as demoted. `undefined` means eligible.\n */\nexport function evaluateLaneWorkerRefusal(args: {\n\tcapabilityClass: ModelCapabilityClass;\n\tcontextWindow: number | undefined;\n\ttoolCallingAdvertised: boolean;\n\ttoolCallingDemoted: boolean;\n}): LaneWorkerRefusal | undefined {\n\tconst { capabilityClass, contextWindow, toolCallingAdvertised, toolCallingDemoted } = args;\n\tif (capabilityClass !== \"full\") return { reason: \"capability_class_below_full\", capabilityClass, contextWindow };\n\tif (contextWindow === undefined) return { reason: \"context_window_unknown\", capabilityClass, contextWindow };\n\tif (!toolCallingAdvertised) return { reason: \"tool_calling_unadvertised\", capabilityClass, contextWindow };\n\tif (toolCallingDemoted) return { reason: \"tool_calling_demoted\", capabilityClass, contextWindow };\n\treturn undefined;\n}\n\n/** Stable, greppable prefix for {@link formatLaneWorkerRefusal}'s output. */\nexport const LANE_WORKER_REFUSAL_PREFIX = \"worktree-sync lane-worker refusal:\";\n\n/** Format a refusal into one deterministic, greppable line naming the lane, class, window, and reason. */\nexport function formatLaneWorkerRefusal(refusal: LaneWorkerRefusal, laneKey?: string): string {\n\tconst laneSuffix = laneKey !== undefined ? ` lane=${laneKey}` : \"\";\n\tconst windowText = refusal.contextWindow !== undefined ? String(refusal.contextWindow) : \"unknown\";\n\treturn `${LANE_WORKER_REFUSAL_PREFIX}${laneSuffix} class=${refusal.capabilityClass} contextWindow=${windowText} reason=${refusal.reason}`;\n}\n"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type BackgroundToolTaskRef } from "../background-tool-task-controller.ts";
|
|
1
2
|
import type { GoalState } from "../goals/goal-state.ts";
|
|
2
3
|
import { type OpenTaskStepProjection } from "../tasks/task-projection.ts";
|
|
3
4
|
import type { TaskStepsState } from "../tasks/task-state.ts";
|
|
@@ -19,6 +20,8 @@ export interface SessionWorkStateProjection {
|
|
|
19
20
|
unlinkedOpenTaskStepIds: readonly string[];
|
|
20
21
|
unknownRequirementIds: readonly string[];
|
|
21
22
|
unboundDelegatedTaskIds: readonly string[];
|
|
23
|
+
/** Background tool_task ids still running and cited by the goal or an open step. */
|
|
24
|
+
runningToolTaskIds: readonly string[];
|
|
22
25
|
}
|
|
23
26
|
export declare function goalObjectiveId(goalId: string): string;
|
|
24
27
|
export declare function projectGoalObjective(goal: GoalState): GoalObjectiveProjection;
|
|
@@ -28,5 +31,6 @@ export declare function projectSessionWorkState(args: {
|
|
|
28
31
|
goalState: GoalState | undefined;
|
|
29
32
|
taskStepsState: TaskStepsState | undefined;
|
|
30
33
|
taskRuntime?: TaskRuntimeProjection;
|
|
34
|
+
backgroundToolTasks?: readonly BackgroundToolTaskRef[];
|
|
31
35
|
}): SessionWorkStateProjection;
|
|
32
36
|
//# sourceMappingURL=work-state-projection.d.ts.map
|