@snoai/memory 0.0.0-stage → 1.0.1
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/LICENSE +176 -0
- package/README.md +33 -2
- package/config/b-profile-section-registry.json +118 -0
- package/config/llm/compiled/2026-05-19T230932Z/manifest.json +25 -0
- package/config/llm/compiled/2026-05-19T230932Z/registry-root.json +67 -0
- package/config/llm/compiled/2026-05-19T230932Z/resolved/mem_claw/openai_gpt_5_nano.json +5 -0
- package/config/llm/compiled/2026-05-19T230932Z/resolved/mem_claw/openrouter_auto.json +5 -0
- package/config/llm/compiled/2026-05-19T230932Z/resolved/mem_claw/sno_ai_extract.json +5 -0
- package/config/llm/compiled/2026-05-19T230932Z/source/mem_claw/openai_gpt_5_nano.mda +24 -0
- package/config/llm/compiled/2026-05-19T230932Z/source/mem_claw/openrouter_auto.mda +24 -0
- package/config/llm/compiled/2026-05-19T230932Z/source/mem_claw/sno_ai_extract.mda +24 -0
- package/config/llm/compiled/2026-07-21T001311Z/manifest.json +43 -0
- package/config/llm/compiled/2026-07-21T001311Z/registry-root.json +97 -0
- package/config/llm/compiled/2026-07-21T001311Z/resolved/mem_claw/openai_gpt_5_nano.json +5 -0
- package/config/llm/compiled/2026-07-21T001311Z/resolved/mem_claw/openrouter_auto.json +5 -0
- package/config/llm/compiled/2026-07-21T001311Z/resolved/mem_claw/sno_ai_extract.json +5 -0
- package/config/llm/compiled/2026-07-21T001311Z/resolved/mem_claw/sno_conflict_verdict.json +10 -0
- package/config/llm/compiled/2026-07-21T001311Z/resolved/mem_claw/sno_extract_chat.json +10 -0
- package/config/llm/compiled/2026-07-21T001311Z/resolved/mem_claw/sno_extract_profile.json +10 -0
- package/config/llm/compiled/2026-07-21T001311Z/source/mem_claw/openai_gpt_5_nano.mda +24 -0
- package/config/llm/compiled/2026-07-21T001311Z/source/mem_claw/openrouter_auto.mda +24 -0
- package/config/llm/compiled/2026-07-21T001311Z/source/mem_claw/sno_ai_extract.mda +24 -0
- package/config/llm/compiled/2026-07-21T001311Z/source/mem_claw/sno_conflict_verdict.mda +27 -0
- package/config/llm/compiled/2026-07-21T001311Z/source/mem_claw/sno_extract_chat.mda +27 -0
- package/config/llm/compiled/2026-07-21T001311Z/source/mem_claw/sno_extract_profile.mda +27 -0
- package/config/llm/compiled/2026-08-29T060335Z/manifest.json +43 -0
- package/config/llm/compiled/2026-08-29T060335Z/registry-root.json +97 -0
- package/config/llm/compiled/2026-08-29T060335Z/resolved/mem_claw/openai_gpt_5_nano.json +5 -0
- package/config/llm/compiled/2026-08-29T060335Z/resolved/mem_claw/openrouter_auto.json +5 -0
- package/config/llm/compiled/2026-08-29T060335Z/resolved/mem_claw/sno_ai_extract.json +5 -0
- package/config/llm/compiled/2026-08-29T060335Z/resolved/mem_claw/sno_conflict_verdict.json +10 -0
- package/config/llm/compiled/2026-08-29T060335Z/resolved/mem_claw/sno_extract_chat.json +10 -0
- package/config/llm/compiled/2026-08-29T060335Z/resolved/mem_claw/sno_extract_profile.json +10 -0
- package/config/llm/compiled/2026-08-29T060335Z/source/mem_claw/openai_gpt_5_nano.mda +24 -0
- package/config/llm/compiled/2026-08-29T060335Z/source/mem_claw/openrouter_auto.mda +24 -0
- package/config/llm/compiled/2026-08-29T060335Z/source/mem_claw/sno_ai_extract.mda +24 -0
- package/config/llm/compiled/2026-08-29T060335Z/source/mem_claw/sno_conflict_verdict.mda +27 -0
- package/config/llm/compiled/2026-08-29T060335Z/source/mem_claw/sno_extract_chat.mda +27 -0
- package/config/llm/compiled/2026-08-29T060335Z/source/mem_claw/sno_extract_profile.mda +27 -0
- package/config/llm/compiled/2026-09-04T004828Z/manifest.json +43 -0
- package/config/llm/compiled/2026-09-04T004828Z/registry-root.json +97 -0
- package/config/llm/compiled/2026-09-04T004828Z/resolved/mem_claw/openai_gpt_5_nano.json +5 -0
- package/config/llm/compiled/2026-09-04T004828Z/resolved/mem_claw/openrouter_auto.json +5 -0
- package/config/llm/compiled/2026-09-04T004828Z/resolved/mem_claw/sno_ai_extract.json +5 -0
- package/config/llm/compiled/2026-09-04T004828Z/resolved/mem_claw/sno_conflict_verdict.json +10 -0
- package/config/llm/compiled/2026-09-04T004828Z/resolved/mem_claw/sno_extract_chat.json +10 -0
- package/config/llm/compiled/2026-09-04T004828Z/resolved/mem_claw/sno_extract_profile.json +10 -0
- package/config/llm/compiled/2026-09-04T004828Z/source/mem_claw/openai_gpt_5_nano.mda +24 -0
- package/config/llm/compiled/2026-09-04T004828Z/source/mem_claw/openrouter_auto.mda +24 -0
- package/config/llm/compiled/2026-09-04T004828Z/source/mem_claw/sno_ai_extract.mda +24 -0
- package/config/llm/compiled/2026-09-04T004828Z/source/mem_claw/sno_conflict_verdict.mda +27 -0
- package/config/llm/compiled/2026-09-04T004828Z/source/mem_claw/sno_extract_chat.mda +27 -0
- package/config/llm/compiled/2026-09-04T004828Z/source/mem_claw/sno_extract_profile.mda +27 -0
- package/config/llm/current.json +4 -0
- package/config/llm/source/mem_claw/openai_gpt_5_nano.mda +24 -0
- package/config/llm/source/mem_claw/openrouter_auto.mda +24 -0
- package/config/llm/source/mem_claw/sno_ai_extract.mda +24 -0
- package/config/llm/source/mem_claw/sno_conflict_verdict.mda +27 -0
- package/config/llm/source/mem_claw/sno_extract_chat.mda +27 -0
- package/config/llm/source/mem_claw/sno_extract_profile.mda +27 -0
- package/config/llm.trust.json +37 -0
- package/dist/_types-CUKHSRkS.d.ts +103 -0
- package/dist/access-tracker-BbEvEocb.d.ts +110 -0
- package/dist/adapter-B7Jox9-6.d.ts +69 -0
- package/dist/adapter-XaRHZWZ2.js +333 -0
- package/dist/agent-llm-port-5oXgBpzJ.d.ts +53 -0
- package/dist/all-resources-BQK2ugjB.js +6379 -0
- package/dist/all-resources-Dij6l5h0.d.ts +18 -0
- package/dist/ambient-learning-text-normalizer-CxjATmMp.js +170 -0
- package/dist/ambient-learning-text-normalizer-_fH3LeuK.d.ts +10 -0
- package/dist/atomic-extraction-reply-BJ9XV_9s.js +863 -0
- package/dist/atomic-extraction-skill-CcXmuCqL.js +56 -0
- package/dist/atomic-memory-extraction-C5rmogoY.js +3605 -0
- package/dist/atomic-memory-extraction-d9EG-4ti.d.ts +327 -0
- package/dist/b-profile-section-dictionary-provider-BHkoNqgk.js +1812 -0
- package/dist/b-profile-section-dictionary-provider-BxbksLj3.d.ts +62 -0
- package/dist/best-effort-BPZSzKk0.d.ts +9 -0
- package/dist/calendar-instruction-CzqZbAPG.js +194 -0
- package/dist/capture-policy-detector-CxbHPkMX.d.ts +53 -0
- package/dist/capture-policy-detector-DaMfy9CZ.js +357 -0
- package/dist/classifier-DnbbtwTS.d.ts +272 -0
- package/dist/client.d.ts +34 -0
- package/dist/client.js +306 -0
- package/dist/coding-skin.d.ts +51 -0
- package/dist/coding-skin.js +55 -0
- package/dist/config-CL90qYva.js +2576 -0
- package/dist/connection-3IVXpuPE.d.ts +391 -0
- package/dist/connection-C9YD5sgm.js +297 -0
- package/dist/daily-log-generator-CH_KuWHs.js +469 -0
- package/dist/daily-log-generator-CsQPHl4A.d.ts +73 -0
- package/dist/daily-spend-estimator-DiwzBlo1.d.ts +8 -0
- package/dist/data-bootstrap-Bl3lthzE.d.ts +30 -0
- package/dist/data-bootstrap-P8sie9WA.js +172 -0
- package/dist/data-paths-C7sNdqvP.d.ts +22 -0
- package/dist/derived-suppression-cache-CI0durYx.d.ts +36 -0
- package/dist/diagnostic-encoder.d.ts +6 -0
- package/dist/diagnostic-encoder.js +29 -0
- package/dist/embedding-provider-client-Q_hJonK9.js +294 -0
- package/dist/embedding-provider-client-vynZMuit.d.ts +94 -0
- package/dist/entry-metadata-parser-BIVSMCIk.js +20 -0
- package/dist/error-D-wb-rZw.js +23 -0
- package/dist/error-signals-D8_3vYu4.d.ts +28 -0
- package/dist/error-signals-lMH2uAdV.js +134 -0
- package/dist/errors-CeVRxf9V.d.ts +49 -0
- package/dist/extraction-text-sanitizer-B_AhIecT.d.ts +32 -0
- package/dist/i18n-text-DbD6Qify.d.ts +13 -0
- package/dist/index-0aqS8pVF.d.ts +351 -0
- package/dist/index-BO4RU_mc.d.ts +650 -0
- package/dist/index-DL8AVj0Z.d.ts +571 -0
- package/dist/index.d.ts +65 -0
- package/dist/index.js +1201 -0
- package/dist/intent-analyzer-B5XVrWwe.d.ts +28 -0
- package/dist/internal/config/index.d.ts +2 -0
- package/dist/internal/config/index.js +581 -0
- package/dist/internal/config/plugin-config-schema.d.ts +2 -0
- package/dist/internal/config/plugin-config-schema.js +2 -0
- package/dist/internal/config/product-mode.d.ts +2 -0
- package/dist/internal/config/product-mode.js +36 -0
- package/dist/internal/config/settings.d.ts +2 -0
- package/dist/internal/config/settings.js +265 -0
- package/dist/internal/config/skill-categories.d.ts +4 -0
- package/dist/internal/config/skill-categories.js +68 -0
- package/dist/internal/config/skin-defaults.d.ts +6 -0
- package/dist/internal/config/skin-defaults.js +6 -0
- package/dist/internal/contract/discovery.d.ts +10 -0
- package/dist/internal/contract/discovery.js +53 -0
- package/dist/internal/contract/profile.d.ts +2 -0
- package/dist/internal/contract/profile.js +44 -0
- package/dist/internal/contract/routes.d.ts +2 -0
- package/dist/internal/contract/routes.js +62 -0
- package/dist/internal/engine/bindings/memory-cli-shared.d.ts +47 -0
- package/dist/internal/engine/bindings/memory-cli-shared.js +84 -0
- package/dist/internal/engine/bindings/memory-forget-tool.d.ts +5 -0
- package/dist/internal/engine/bindings/memory-forget-tool.js +66 -0
- package/dist/internal/engine/bindings/memory-list-tool.d.ts +5 -0
- package/dist/internal/engine/bindings/memory-list-tool.js +57 -0
- package/dist/internal/engine/bindings/memory-recall-tool.d.ts +10 -0
- package/dist/internal/engine/bindings/memory-recall-tool.js +283 -0
- package/dist/internal/engine/bindings/memory-reflection-resolve-tool.d.ts +5 -0
- package/dist/internal/engine/bindings/memory-reflection-resolve-tool.js +150 -0
- package/dist/internal/engine/bindings/memory-stats-tool.d.ts +5 -0
- package/dist/internal/engine/bindings/memory-stats-tool.js +43 -0
- package/dist/internal/engine/bindings/memory-store-tool.d.ts +5 -0
- package/dist/internal/engine/bindings/memory-store-tool.js +165 -0
- package/dist/internal/engine/bindings/memory-tool-access.d.ts +16 -0
- package/dist/internal/engine/bindings/memory-tool-access.js +46 -0
- package/dist/internal/engine/bindings/memory-tool-formatting.d.ts +62 -0
- package/dist/internal/engine/bindings/memory-tool-formatting.js +106 -0
- package/dist/internal/engine/bindings/memory-tool-results.d.ts +8 -0
- package/dist/internal/engine/bindings/memory-tool-results.js +41 -0
- package/dist/internal/engine/bindings/memory-tool-schemas.d.ts +109 -0
- package/dist/internal/engine/bindings/memory-tool-schemas.js +75 -0
- package/dist/internal/engine/bindings/memory-update-tool.d.ts +5 -0
- package/dist/internal/engine/bindings/memory-update-tool.js +127 -0
- package/dist/internal/engine/bindings/sno-station-mem-ambient-learning-hook.d.ts +14 -0
- package/dist/internal/engine/bindings/sno-station-mem-ambient-learning-hook.js +248 -0
- package/dist/internal/engine/bindings/sno-station-mem-auto-recall-hook.d.ts +12 -0
- package/dist/internal/engine/bindings/sno-station-mem-auto-recall-hook.js +324 -0
- package/dist/internal/engine/bindings/sno-station-mem-hook-types.d.ts +56 -0
- package/dist/internal/engine/bindings/sno-station-mem-hook-types.js +1 -0
- package/dist/internal/engine/bindings/sno-station-mem-insight-distill-factory.d.ts +14 -0
- package/dist/internal/engine/bindings/sno-station-mem-insight-distill-factory.js +119 -0
- package/dist/internal/engine/bindings/sno-station-mem-message-transcript.d.ts +52 -0
- package/dist/internal/engine/bindings/sno-station-mem-message-transcript.js +145 -0
- package/dist/internal/engine/bindings/sno-station-mem-reset-hook.d.ts +10 -0
- package/dist/internal/engine/bindings/sno-station-mem-reset-hook.js +9 -0
- package/dist/internal/engine/bindings/sno-station-mem-runtime-mode.d.ts +36 -0
- package/dist/internal/engine/bindings/sno-station-mem-runtime-mode.js +104 -0
- package/dist/internal/engine/bindings/sno-station-mem-session-state.d.ts +10 -0
- package/dist/internal/engine/bindings/sno-station-mem-session-state.js +27 -0
- package/dist/internal/engine/eval/trace.d.ts +2 -0
- package/dist/internal/engine/eval/trace.js +151 -0
- package/dist/internal/engine/extraction/ambient-learning-text-normalizer.d.ts +2 -0
- package/dist/internal/engine/extraction/ambient-learning-text-normalizer.js +2 -0
- package/dist/internal/engine/extraction/atomic-memory-extraction.d.ts +2 -0
- package/dist/internal/engine/extraction/atomic-memory-extraction.js +2 -0
- package/dist/internal/engine/extraction/b-profile-section-dictionary-provider.d.ts +2 -0
- package/dist/internal/engine/extraction/b-profile-section-dictionary-provider.js +2 -0
- package/dist/internal/engine/extraction/b-profile-section-rekey.d.ts +49 -0
- package/dist/internal/engine/extraction/b-profile-section-rekey.js +730 -0
- package/dist/internal/engine/extraction/capture-policy-detector.d.ts +2 -0
- package/dist/internal/engine/extraction/capture-policy-detector.js +2 -0
- package/dist/internal/engine/extraction/embedding-provider-client.d.ts +2 -0
- package/dist/internal/engine/extraction/embedding-provider-client.js +2 -0
- package/dist/internal/engine/extraction/extraction-text-sanitizer.d.ts +2 -0
- package/dist/internal/engine/extraction/extraction-text-sanitizer.js +114 -0
- package/dist/internal/engine/extraction/memory-metadata-codec.d.ts +3 -0
- package/dist/internal/engine/extraction/memory-metadata-codec.js +2 -0
- package/dist/internal/engine/extraction/memory-temporality-classifier.d.ts +2 -0
- package/dist/internal/engine/extraction/memory-temporality-classifier.js +2 -0
- package/dist/internal/engine/i18n/all-resources.d.ts +2 -0
- package/dist/internal/engine/i18n/all-resources.js +2 -0
- package/dist/internal/engine/i18n/locales.d.ts +2 -0
- package/dist/internal/engine/i18n/locales.js +19 -0
- package/dist/internal/engine/i18n/res/_types.d.ts +2 -0
- package/dist/internal/engine/i18n/res/_types.js +11 -0
- package/dist/internal/engine/observability/adapter.d.ts +2 -0
- package/dist/internal/engine/observability/adapter.js +2 -0
- package/dist/internal/engine/observability/best-effort.d.ts +2 -0
- package/dist/internal/engine/observability/best-effort.js +41 -0
- package/dist/internal/engine/observability/early-diagnostics.js +2 -0
- package/dist/internal/engine/observability/memory-snapshot.d.ts +2 -0
- package/dist/internal/engine/observability/memory-snapshot.js +44 -0
- package/dist/internal/engine/observability/observable-embedder.d.ts +2 -0
- package/dist/internal/engine/observability/observable-embedder.js +43 -0
- package/dist/internal/engine/observability/observable-llm-client.d.ts +2 -0
- package/dist/internal/engine/observability/observable-llm-client.js +98 -0
- package/dist/internal/engine/observability/observable-memory-store.d.ts +2 -0
- package/dist/internal/engine/observability/observable-memory-store.js +701 -0
- package/dist/internal/engine/observability/observable-retriever.d.ts +2 -0
- package/dist/internal/engine/observability/observable-retriever.js +95 -0
- package/dist/internal/engine/observability/runtime-diagnostics.d.ts +13 -0
- package/dist/internal/engine/observability/runtime-diagnostics.js +96 -0
- package/dist/internal/engine/observability/session-registry.d.ts +2 -0
- package/dist/internal/engine/observability/session-registry.js +58 -0
- package/dist/internal/engine/observability/version-metadata.d.ts +7 -0
- package/dist/internal/engine/observability/version-metadata.js +59 -0
- package/dist/internal/engine/operations/daily-spend-estimator.d.ts +2 -0
- package/dist/internal/engine/operations/daily-spend-estimator.js +97 -0
- package/dist/internal/engine/operations/learning-file-maintenance.d.ts +2 -0
- package/dist/internal/engine/operations/learning-file-maintenance.js +255 -0
- package/dist/internal/engine/operations/memory-tier-promoter.d.ts +2 -0
- package/dist/internal/engine/operations/memory-tier-promoter.js +95 -0
- package/dist/internal/engine/operations/runtime-audit-log.d.ts +3 -0
- package/dist/internal/engine/operations/runtime-audit-log.js +3 -0
- package/dist/internal/engine/provider/canonical-memory-corpus.d.ts +38 -0
- package/dist/internal/engine/provider/canonical-memory-corpus.js +253 -0
- package/dist/internal/engine/provider/provider-registration.d.ts +39 -0
- package/dist/internal/engine/provider/provider-registration.js +2 -0
- package/dist/internal/engine/provider/provider-row-renderer.d.ts +7 -0
- package/dist/internal/engine/provider/provider-row-renderer.js +53 -0
- package/dist/internal/engine/provider/provider-types.d.ts +2 -0
- package/dist/internal/engine/provider/provider-types.js +1 -0
- package/dist/internal/engine/reflection/daily-log-generator.d.ts +2 -0
- package/dist/internal/engine/reflection/daily-log-generator.js +2 -0
- package/dist/internal/engine/reflection/reflection-command-hooks.d.ts +2 -0
- package/dist/internal/engine/reflection/reflection-command-hooks.js +2 -0
- package/dist/internal/engine/reflection/reflection-deps.d.ts +2 -0
- package/dist/internal/engine/reflection/reflection-deps.js +1 -0
- package/dist/internal/engine/reflection/reflection-embedded-generator.d.ts +2 -0
- package/dist/internal/engine/reflection/reflection-embedded-generator.js +2 -0
- package/dist/internal/engine/reflection/reflection-injection-hooks.d.ts +2 -0
- package/dist/internal/engine/reflection/reflection-injection-hooks.js +219 -0
- package/dist/internal/engine/reflection/reflection-lifecycle-hooks.d.ts +2 -0
- package/dist/internal/engine/reflection/reflection-lifecycle-hooks.js +63 -0
- package/dist/internal/engine/reflection/strategy-hook-runner.d.ts +4 -0
- package/dist/internal/engine/reflection/strategy-hook-runner.js +3 -0
- package/dist/internal/engine/rem/classifier.d.ts +2 -0
- package/dist/internal/engine/rem/classifier.js +180 -0
- package/dist/internal/engine/rem/index.d.ts +4 -0
- package/dist/internal/engine/rem/index.js +2551 -0
- package/dist/internal/engine/rem/types.d.ts +2 -0
- package/dist/internal/engine/rem/types.js +40 -0
- package/dist/internal/engine/retrieval/access-tracker.d.ts +2 -0
- package/dist/internal/engine/retrieval/access-tracker.js +314 -0
- package/dist/internal/engine/retrieval/intent-analyzer.d.ts +2 -0
- package/dist/internal/engine/retrieval/intent-analyzer.js +27 -0
- package/dist/internal/engine/retrieval/retrieval-gate.d.ts +2 -0
- package/dist/internal/engine/retrieval/retrieval-gate.js +47 -0
- package/dist/internal/engine/retrieval/retriever.d.ts +2 -0
- package/dist/internal/engine/retrieval/retriever.js +2 -0
- package/dist/internal/engine/security/memory-scope-policy.d.ts +2 -0
- package/dist/internal/engine/security/memory-scope-policy.js +2 -0
- package/dist/internal/engine/security/redact.d.ts +2 -0
- package/dist/internal/engine/security/redact.js +34 -0
- package/dist/internal/engine/security/scopes.d.ts +3 -0
- package/dist/internal/engine/security/scopes.js +3 -0
- package/dist/internal/engine/shared/errors.d.ts +2 -0
- package/dist/internal/engine/shared/errors.js +66 -0
- package/dist/internal/engine/shared/i18n-text.d.ts +2 -0
- package/dist/internal/engine/shared/i18n-text.js +58 -0
- package/dist/internal/engine/shared/iso-date-time.d.ts +16 -0
- package/dist/internal/engine/shared/iso-date-time.js +40 -0
- package/dist/internal/engine/shared/lru.d.ts +2 -0
- package/dist/internal/engine/shared/lru.js +30 -0
- package/dist/internal/engine/shared/memory-kind-policy.d.ts +2 -0
- package/dist/internal/engine/shared/memory-kind-policy.js +64 -0
- package/dist/internal/engine/shared/paths.d.ts +3 -0
- package/dist/internal/engine/shared/paths.js +2 -0
- package/dist/internal/engine/shared/types.d.ts +3 -0
- package/dist/internal/engine/shared/types.js +25 -0
- package/dist/internal/engine/shared/utils.d.ts +2 -0
- package/dist/internal/engine/shared/utils.js +175 -0
- package/dist/internal/engine/telemetry/memory-telemetry-api.d.ts +134 -0
- package/dist/internal/engine/telemetry/memory-telemetry-api.js +730 -0
- package/dist/internal/engine/telemetry/memory-telemetry-observability.d.ts +24 -0
- package/dist/internal/engine/telemetry/memory-telemetry-observability.js +133 -0
- package/dist/internal/engine/telemetry/memory-telemetry-outbox.d.ts +2 -0
- package/dist/internal/engine/telemetry/memory-telemetry-outbox.js +443 -0
- package/dist/internal/engine/telemetry/memory-telemetry-types.d.ts +2 -0
- package/dist/internal/engine/telemetry/memory-telemetry-types.js +21 -0
- package/dist/internal/engine/telemetry/observe-ledger.d.ts +30 -0
- package/dist/internal/engine/telemetry/observe-ledger.js +111 -0
- package/dist/internal/model/agent-llm-port.d.ts +2 -0
- package/dist/internal/model/agent-llm-port.js +1 -0
- package/dist/internal/model/llm-client.d.ts +3 -0
- package/dist/internal/model/llm-client.js +3 -0
- package/dist/internal/model/llm-failure.d.ts +26 -0
- package/dist/internal/model/llm-failure.js +63 -0
- package/dist/internal/model/llm-mode-routing.d.ts +22 -0
- package/dist/internal/model/llm-mode-routing.js +37 -0
- package/dist/internal/store/atomic-memory-cutover-sql.d.ts +13 -0
- package/dist/internal/store/atomic-memory-cutover-sql.js +237 -0
- package/dist/internal/store/connection.d.ts +2 -0
- package/dist/internal/store/connection.js +2 -0
- package/dist/internal/store/data-bootstrap.d.ts +2 -0
- package/dist/internal/store/data-bootstrap.js +2 -0
- package/dist/internal/store/data-paths.d.ts +2 -0
- package/dist/internal/store/data-paths.js +65 -0
- package/dist/internal/store/maintenance.d.ts +75 -0
- package/dist/internal/store/maintenance.js +1401 -0
- package/dist/internal/store/memory-kinds-cutover-migrator.d.ts +28 -0
- package/dist/internal/store/memory-kinds-cutover-migrator.js +415 -0
- package/dist/internal/store/migrations.d.ts +27 -0
- package/dist/internal/store/migrations.js +201 -0
- package/dist/internal/store/sqlite-runtime.d.ts +2 -0
- package/dist/internal/store/sqlite-runtime.js +109 -0
- package/dist/internal/store/store.d.ts +3 -0
- package/dist/internal/store/store.js +2 -0
- package/dist/learning-file-maintenance-9b-Ut6Kv.d.ts +30 -0
- package/dist/llm-client-BSYUAcUb.js +1374 -0
- package/dist/llm-client-DOTSGzhe.d.ts +51 -0
- package/dist/locales-JxGmkG6t.d.ts +7 -0
- package/dist/log-site-catalog.generated-BMKWj-Nx.js +2321 -0
- package/dist/log-site-catalog.json +1 -0
- package/dist/lru-DyoaTyIs.d.ts +14 -0
- package/dist/memdump.d.ts +52 -0
- package/dist/memdump.js +163 -0
- package/dist/memory-entry-projector-DHo8jH10.js +1015 -0
- package/dist/memory-kind-policy-BiuRjSJc.d.ts +23 -0
- package/dist/memory-metadata-codec-DL1sbJiN.js +577 -0
- package/dist/memory-metadata-codec-DUvsYe_X.d.ts +68 -0
- package/dist/memory-runtime-DqUS4cWi.js +19459 -0
- package/dist/memory-scope-policy-1gg5QlWZ.d.ts +67 -0
- package/dist/memory-scope-policy-DICSCURA.js +283 -0
- package/dist/memory-snapshot-CqY1BUUA.d.ts +16 -0
- package/dist/memory-source-order-YMRoeDLd.js +134 -0
- package/dist/memory-store-base-CQ_bHlYA.d.ts +1094 -0
- package/dist/memory-store-shared-DqpWJXZZ.js +158 -0
- package/dist/memory-store-write-validation-B_hDG2zf.js +243 -0
- package/dist/memory-telemetry-incidents-BWA9kcZx.js +8 -0
- package/dist/memory-telemetry-metadata-CA7W8tK6.js +77 -0
- package/dist/memory-telemetry-outbox-ddTdImt7.d.ts +74 -0
- package/dist/memory-telemetry-receipts-MAJecvXQ.d.ts +34 -0
- package/dist/memory-telemetry-receipts-YsxbwOAf.js +91 -0
- package/dist/memory-telemetry-types-CufVmrCs.d.ts +14 -0
- package/dist/memory-temporality-classifier-BUjXG5o7.js +184 -0
- package/dist/memory-temporality-classifier-Brht5jyK.d.ts +43 -0
- package/dist/memory-tier-promoter-CqGxCkue.d.ts +43 -0
- package/dist/memory-tool-dependencies-CatGzI9R.d.ts +14 -0
- package/dist/memory-tool-dependencies-DjUoelnm.js +19 -0
- package/dist/model-call-table-CspopkBg.js +563 -0
- package/dist/model-reply-text-CKopStP2.js +334 -0
- package/dist/observable-embedder-CNNe9gkg.d.ts +17 -0
- package/dist/observable-llm-client-CRuKlefQ.d.ts +21 -0
- package/dist/observable-memory-store-CnGDpOY5.d.ts +73 -0
- package/dist/observable-retriever-Cooc62Qw.d.ts +23 -0
- package/dist/operation-cancellation-CTKWwNHk.js +81 -0
- package/dist/paths-qVF-5uBq.d.ts +1 -0
- package/dist/plugin-config-schema-C0UUbOmG.d.ts +413 -0
- package/dist/plugin-config-schema-YJLyIIcJ.js +361 -0
- package/dist/profile-TWPJ_myr.d.ts +13 -0
- package/dist/profile-section-writer-BhGKPBjw.js +2149 -0
- package/dist/provider-registration-CF1tg8Xy.js +721 -0
- package/dist/provider-runtime-types-DFhtdA6d.d.ts +134 -0
- package/dist/provider-types-CZGm6v88.d.ts +23 -0
- package/dist/redact-BTIZcHQL.d.ts +5 -0
- package/dist/reflection-command-hooks-ClUl-iv6.js +644 -0
- package/dist/reflection-command-hooks-G1-dI2Av.d.ts +32 -0
- package/dist/reflection-deps-Ccm2Jf5W.d.ts +19 -0
- package/dist/reflection-embedded-generator-BRvqV5N-.js +130 -0
- package/dist/reflection-embedded-generator-kfQfKEYV.d.ts +14 -0
- package/dist/reflection-injection-hooks-CS_uhjoD.d.ts +43 -0
- package/dist/reflection-lifecycle-hooks-CRSpUdLi.d.ts +27 -0
- package/dist/relation-dictionary-Cev1kyLe.js +4248 -0
- package/dist/release-download.d.ts +8 -0
- package/dist/release-download.js +32 -0
- package/dist/relevant-memories-context-m8nuFZcM.js +23 -0
- package/dist/rem-batch-executor-Dg2HgROM.js +2 -0
- package/dist/rem-batch-executor-DuC4nYyf.js +31640 -0
- package/dist/rem-consumer-retrieval-CR0dtcHR.js +246 -0
- package/dist/rem-trigger-Hn6od8IV.js +730 -0
- package/dist/resolver-Dy-hnjCR.js +103 -0
- package/dist/results-C3ZLroMb.js +140 -0
- package/dist/retrieval-gate-Bx2Zg7jD.d.ts +31 -0
- package/dist/retriever-Dxss5fRv.d.ts +469 -0
- package/dist/retriever-ZoLvPRHq.js +1757 -0
- package/dist/rolldown-runtime-D7D4PA-g.js +13 -0
- package/dist/routes-DLHT__Ay.js +60 -0
- package/dist/runtime-audit-log-BCeujlEp.js +430 -0
- package/dist/runtime-audit-log-zpQiR9HT.d.ts +149 -0
- package/dist/scopes-CSOn6zdd.js +71 -0
- package/dist/scopes-CtrY-YQ3.d.ts +23 -0
- package/dist/server-CSvxchqg.js +1412 -0
- package/dist/session-registry-DBoE7AvZ.d.ts +14 -0
- package/dist/sidecar/main.d.ts +1 -0
- package/dist/sidecar/main.js +56 -0
- package/dist/signed-registry-constants-Bv0fgZ8Q.d.ts +12 -0
- package/dist/signed-registry-constants-yq3DlG3B.js +82 -0
- package/dist/sno-station-mem-runtime-dependencies-CoWqUMbK.js +30 -0
- package/dist/sno-station-mem-runtime-dependencies-DHESIuPn.d.ts +31 -0
- package/dist/sqlite-runtime-L_ywirTm.d.ts +58 -0
- package/dist/store-C8sUTssE.d.ts +27 -0
- package/dist/store-nPql26YM.js +5830 -0
- package/dist/strategy-hook-runner-Bxy851Xx.d.ts +16 -0
- package/dist/strategy-hook-runner-Djify5Rw.js +110 -0
- package/dist/token-counter-BD1f48Km.js +73 -0
- package/dist/trace-C1JxMfs-.d.ts +86 -0
- package/dist/types-CWdhXLxr.d.ts +477 -0
- package/dist/types-pVomjzqR.d.ts +132 -0
- package/dist/unplaced-candidate-migration-CbQHzcEM.js +940 -0
- package/dist/utils-Ctb9aevJ.d.ts +34 -0
- package/drizzle/0000_initial.sql +10 -0
- package/drizzle/0001_virtual_tables.sql +34 -0
- package/drizzle/0002_add_indexes.sql +11 -0
- package/drizzle/0003_content_hash_lookup_index.sql +2 -0
- package/drizzle/0004_chunk_swap.sql +60 -0
- package/drizzle/0005_drop_legacy_vec_fts.sql +10 -0
- package/drizzle/0006_fts_simple.sql +45 -0
- package/drizzle/0007_restore_simple_fts.sql +40 -0
- package/drizzle/0008_widen_memory_hash_unique_index.sql +4 -0
- package/drizzle/0009_memory_telemetry.sql +109 -0
- package/drizzle/0010_provider_mappings.sql +27 -0
- package/drizzle/0011_db_optimization.sql +82 -0
- package/drizzle/0012_b_profile_lanes.sql +9 -0
- package/drizzle/0013_extraction_timestamps.sql +6 -0
- package/drizzle/0014_extraction_timestamp_source.sql +3 -0
- package/drizzle/0015_task_lifecycle_state.sql +101 -0
- package/drizzle/0016_task_lifecycle_legacy_migration.sql +144 -0
- package/drizzle/0017_unplaced_candidates.sql +15 -0
- package/drizzle/0018_rem_batch_chassis.sql +71 -0
- package/drizzle/0019_profile_recovery_entries.sql +17 -0
- package/drizzle/0020_rem_scan_retry_progress.down.sql +14 -0
- package/drizzle/0020_rem_scan_retry_progress.sql +24 -0
- package/drizzle/0021_rem_two_facet_storage.down.sql +14 -0
- package/drizzle/0021_rem_two_facet_storage.sql +42 -0
- package/drizzle/0022_rem_facet_chunk_versions.down.sql +4 -0
- package/drizzle/0022_rem_facet_chunk_versions.sql +4 -0
- package/drizzle/0023_rem_defect_ledger.sql +40 -0
- package/drizzle/0024_rem_unbuilt_foundations.down.sql +13 -0
- package/drizzle/0024_rem_unbuilt_foundations.sql +65 -0
- package/drizzle/0025_rem_journal_operation_constraint.sql +28 -0
- package/drizzle/0026_rem_journal_detail.sql +1 -0
- package/drizzle/0027_legacy_nodix_namespace.sql +3 -0
- package/drizzle/0028_memory_timezone.sql +23 -0
- package/drizzle/0029_rem_write_hash_symmetry.sql +17 -0
- package/drizzle/0030_atomic_memory_additive.sql +105 -0
- package/drizzle/0031_atomic_extraction_ledger.sql +23 -0
- package/drizzle/0032_atomic_memory_entities.sql +12 -0
- package/drizzle/0033_todo_own_store.sql +99 -0
- package/drizzle/meta/0000_snapshot.json +87 -0
- package/drizzle/meta/_journal.json +244 -0
- package/generated/rem-operations.json +1 -0
- package/package.json +126 -4
- package/scripts/download-simple-tokenizer.mjs +254 -0
- package/settings.default.json +243 -0
- package/skills/extract-atomic-memory/SKILL.md +298 -0
- package/skills/extract-atomic-memory/references/account-for-turns.md +9 -0
- package/skills/extract-atomic-memory/references/calendar-meaning.md +64 -0
- package/skills/extract-atomic-memory/references/capture.md +120 -0
- package/skills/extract-atomic-memory/references/enrichment.md +92 -0
- package/skills/extract-atomic-memory/references/missing-durable-half.md +6 -0
- package/skills/extract-atomic-memory/references/progress-classification.md +21 -0
- package/skills/extract-atomic-memory/references/resolve-subject.md +19 -0
- package/skills/extract-atomic-memory/references/surrounding-context.md +10 -0
- package/skills/extract-atomic-memory/references/user-subject-guard.md +29 -0
- package/skills/judge-group-closure/SKILL.md +25 -0
- package/skills/judge-rem-memory-updates/SKILL.md +56 -0
- package/skills/judge-rem-memory-updates/agents/openai.yaml +4 -0
- package/skills/judge-retired-position/SKILL.md +25 -0
- package/skills/judge-task-lifecycle/SKILL.md +45 -0
- package/skills/key-state-attribute/SKILL.md +16 -0
- package/skills/resolve-entity-identity/SKILL.md +24 -0
- package/skills/resolve-relative-time/SKILL.md +22 -0
- package/sqlite-extensions/LICENSE-simple-tokenizer +28 -0
- package/sqlite-extensions/LICENSE-sqlite-vec +21 -0
- package/sqlite-extensions/linux-arm64/vec0.so +0 -0
- package/sqlite-extensions/linux-x64/vec0.so +0 -0
|
@@ -0,0 +1,1015 @@
|
|
|
1
|
+
import { a as buildInsightMetadata, c as stringifyInsightMetadata } from "./memory-metadata-codec-DL1sbJiN.js";
|
|
2
|
+
import { n as RESOURCES_BY_LOCALE } from "./all-resources-BQK2ugjB.js";
|
|
3
|
+
import { t as resolveLocale } from "./resolver-Dy-hnjCR.js";
|
|
4
|
+
import { t as parseReflectionMetadata } from "./entry-metadata-parser-BIVSMCIk.js";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { sanitizeContentIngress } from "@snoai/content-sanitizer";
|
|
7
|
+
//#region src/engine/reflection/reflection-entry-projector-types.ts
|
|
8
|
+
const REFLECTION_DERIVE_LOGISTIC_K = 1.2;
|
|
9
|
+
const REFLECTION_DERIVE_FALLBACK_BASE_WEIGHT = .35;
|
|
10
|
+
const DEFAULT_REFLECTION_DERIVED_MAX_AGE_MS = 12096e5;
|
|
11
|
+
//#endregion
|
|
12
|
+
//#region src/engine/reflection/line-quality-ranker.ts
|
|
13
|
+
/** @file line-quality-ranker.ts
|
|
14
|
+
* @purpose Ranks reflection candidates by usefulness, severity, and recency signals.
|
|
15
|
+
* @boundary Reflection metadata, cache state, and retrieval-style scoring rules.
|
|
16
|
+
* @see daily-log-generator.ts, derived-line-cache.ts, entry-metadata-parser.ts.
|
|
17
|
+
*/
|
|
18
|
+
/**
|
|
19
|
+
* Reflection relevance ranking — logistic decay scoring.
|
|
20
|
+
*/
|
|
21
|
+
const REFLECTION_FALLBACK_SCORE_FACTOR = .75;
|
|
22
|
+
function finiteAtLeast(value, minimum, fallback) {
|
|
23
|
+
if (!Number.isFinite(value)) return fallback;
|
|
24
|
+
return Math.max(minimum, value);
|
|
25
|
+
}
|
|
26
|
+
function finitePositive(value, fallback) {
|
|
27
|
+
return Number.isFinite(value) && value > 0 ? value : fallback;
|
|
28
|
+
}
|
|
29
|
+
function clampUnit(value, fallback) {
|
|
30
|
+
if (!Number.isFinite(value)) return fallback;
|
|
31
|
+
return Math.max(0, Math.min(1, value));
|
|
32
|
+
}
|
|
33
|
+
/** Computes reflection logistic as a side-effect-free reflection result ranking value. */
|
|
34
|
+
function computeReflectionLogistic(ageDays, midpointDays, k) {
|
|
35
|
+
const normalizedAgeDays = finiteAtLeast(ageDays, 0, 0);
|
|
36
|
+
const normalizedMidpointDays = finitePositive(midpointDays, 1);
|
|
37
|
+
const normalizedK = finitePositive(k, .1);
|
|
38
|
+
const distanceFromMidpoint = normalizedAgeDays - normalizedMidpointDays;
|
|
39
|
+
return 1 / (1 + Math.exp(normalizedK * distanceFromMidpoint));
|
|
40
|
+
}
|
|
41
|
+
/** Computes reflection score as a side-effect-free reflection result ranking value. */
|
|
42
|
+
function computeReflectionScore(input) {
|
|
43
|
+
const recencyWeight = computeReflectionLogistic(input.ageDays, input.midpointDays, input.k);
|
|
44
|
+
const baseWeight = finitePositive(input.baseWeight, 1);
|
|
45
|
+
const qualityWeight = clampUnit(input.quality, 1);
|
|
46
|
+
const sourceReliability = input.usedFallback ? REFLECTION_FALLBACK_SCORE_FACTOR : 1;
|
|
47
|
+
return recencyWeight * baseWeight * qualityWeight * sourceReliability;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Normalizes reflection line for aggregation at the boundary before reflection result ranking
|
|
51
|
+
* uses it.
|
|
52
|
+
*/
|
|
53
|
+
function normalizeReflectionLineForAggregation(line) {
|
|
54
|
+
return String(line).trim().replace(/\s+/g, " ").toLowerCase();
|
|
55
|
+
}
|
|
56
|
+
//#endregion
|
|
57
|
+
//#region src/engine/reflection/reflection-markdown-sections.ts
|
|
58
|
+
/** @file reflection-markdown-sections.ts
|
|
59
|
+
* @purpose Extracts named markdown sections and bullet lists from reflection payloads.
|
|
60
|
+
* @boundary Raw markdown parsing only; no reflection-domain classification.
|
|
61
|
+
*/
|
|
62
|
+
/** Extracts section markdown from raw runtime payloads with partial-data tolerance. */
|
|
63
|
+
function extractSectionMarkdown(markdown, heading) {
|
|
64
|
+
const lines = markdown.split(/\r?\n/);
|
|
65
|
+
const headingNeedle = `## ${heading}`.toLowerCase();
|
|
66
|
+
let inSection = false;
|
|
67
|
+
const collected = [];
|
|
68
|
+
for (const raw of lines) {
|
|
69
|
+
const lower = raw.trim().toLowerCase();
|
|
70
|
+
if (lower.startsWith("## ")) {
|
|
71
|
+
if (inSection && lower !== headingNeedle) break;
|
|
72
|
+
inSection = lower === headingNeedle;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (!inSection) continue;
|
|
76
|
+
collected.push(raw);
|
|
77
|
+
}
|
|
78
|
+
return collected.join("\n").trim();
|
|
79
|
+
}
|
|
80
|
+
/** Parses section bullets into the normalized shape used by reflection text slicing. */
|
|
81
|
+
function parseSectionBullets(markdown, heading) {
|
|
82
|
+
const lines = extractSectionMarkdown(markdown, heading).split(/\r?\n/);
|
|
83
|
+
const collected = [];
|
|
84
|
+
for (const raw of lines) {
|
|
85
|
+
const line = raw.trim();
|
|
86
|
+
if (line.startsWith("- ") || line.startsWith("* ")) {
|
|
87
|
+
const normalized = line.slice(2).trim();
|
|
88
|
+
if (normalized) collected.push(normalized);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return collected;
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
//#region src/engine/reflection/reflection-markdown-types.ts
|
|
95
|
+
const PARSER_HEADINGS = {
|
|
96
|
+
context: "Context",
|
|
97
|
+
decisionsDurable: "Decisions (durable)",
|
|
98
|
+
invariants: "Invariants",
|
|
99
|
+
invariantsAndReflections: "Invariants & Reflections",
|
|
100
|
+
derived: "Derived",
|
|
101
|
+
openLoops: "Open loops / next actions",
|
|
102
|
+
userModelDeltas: "User model deltas (about the human)",
|
|
103
|
+
agentModelDeltas: "Agent model deltas (about the assistant/system)",
|
|
104
|
+
lessonsAndPitfalls: "Lessons & pitfalls (symptom / cause / fix / prevention)",
|
|
105
|
+
learningGovernance: "Learning governance candidates (.learnings / promotion / skill extraction)"
|
|
106
|
+
};
|
|
107
|
+
//#endregion
|
|
108
|
+
//#region src/engine/reflection/reflection-slice-sanitizer.ts
|
|
109
|
+
/** @file reflection-slice-sanitizer.ts
|
|
110
|
+
* @purpose Normalizes reflection slice lines and filters unsafe injectable text.
|
|
111
|
+
* @boundary Line-level sanitization and injection detection only.
|
|
112
|
+
*/
|
|
113
|
+
/**
|
|
114
|
+
* Tests whether is placeholder reflection slice line without mutating reflection text slicing
|
|
115
|
+
* state.
|
|
116
|
+
*/
|
|
117
|
+
function isPlaceholderReflectionSliceLine(line) {
|
|
118
|
+
const normalized = line.replace(/\*\*/g, "").trim();
|
|
119
|
+
if (!normalized) return true;
|
|
120
|
+
if (/^\(none( captured)?\)$/i.test(normalized)) return true;
|
|
121
|
+
if (/^(invariants?|reflections?|derived)[::]$/i.test(normalized)) return true;
|
|
122
|
+
if (/apply this session'?s deltas next run/i.test(normalized)) return true;
|
|
123
|
+
if (/apply this session'?s distilled changes next run/i.test(normalized)) return true;
|
|
124
|
+
if (/investigate why embedded reflection generation failed/i.test(normalized)) return true;
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
/** Normalizes reflection slice line at the boundary before reflection text slicing uses it. */
|
|
128
|
+
function normalizeReflectionSliceLine(line) {
|
|
129
|
+
return sanitizeContentIngress({
|
|
130
|
+
source: "generic-text",
|
|
131
|
+
content: line
|
|
132
|
+
}).projections.plainText.replace(/\*\*/g, "").replace(/^(invariants?|reflections?|derived)[::]\s*/i, "").trim();
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Implements sanitize reflection slice lines as the local reflection text slicing operation.
|
|
136
|
+
*/
|
|
137
|
+
function sanitizeReflectionSliceLines(lines) {
|
|
138
|
+
return lines.map(normalizeReflectionSliceLine).filter((line) => !isPlaceholderReflectionSliceLine(line));
|
|
139
|
+
}
|
|
140
|
+
const INJECTABLE_REFLECTION_BLOCK_PATTERNS = [
|
|
141
|
+
/^\s*(?:(?:next|this)(?:\s+run)?\s+)?(?:ignore|disregard|forget|override|bypass)\b[\s\S]{0,80}\b(?:instructions?|guardrails?|policy|developer|system)\b/i,
|
|
142
|
+
/\b(?:reveal|print|dump|show|output)\b[\s\S]{0,80}\b(?:system prompt|developer prompt|hidden prompt|hidden instructions?|full prompt|prompt verbatim|secrets?|keys?|tokens?)\b/i,
|
|
143
|
+
/<\s*\/?\s*(?:system|assistant|user|tool|developer|inherited-rules|derived-focus)\b[^>]*>/i,
|
|
144
|
+
/^(?:system|assistant|user|developer|tool)\s*:/i
|
|
145
|
+
];
|
|
146
|
+
function stripReflectionListPrefix(line) {
|
|
147
|
+
return line.replace(/^\s*(?:[-*•]+|\d+[.)])\s+/, "").trim();
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Tests whether is unsafe injectable reflection line without mutating reflection text slicing
|
|
151
|
+
* state.
|
|
152
|
+
*/
|
|
153
|
+
function isUnsafeInjectableReflectionLine(line) {
|
|
154
|
+
const normalized = stripReflectionListPrefix(normalizeReflectionSliceLine(line));
|
|
155
|
+
if (!normalized) return true;
|
|
156
|
+
return INJECTABLE_REFLECTION_BLOCK_PATTERNS.some((pattern) => pattern.test(normalized));
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Implements sanitize injectable reflection lines as the local reflection text slicing operation.
|
|
160
|
+
*/
|
|
161
|
+
function sanitizeInjectableReflectionLines(lines) {
|
|
162
|
+
return sanitizeReflectionSliceLines(lines).filter((line) => !isUnsafeInjectableReflectionLine(line));
|
|
163
|
+
}
|
|
164
|
+
//#endregion
|
|
165
|
+
//#region src/engine/reflection/reflection-governance-parser.ts
|
|
166
|
+
/** @file reflection-governance-parser.ts
|
|
167
|
+
* @purpose Parses reflection lessons and learning-governance candidates.
|
|
168
|
+
* @boundary Governance markdown extraction only; storage and promotion are out of scope.
|
|
169
|
+
*/
|
|
170
|
+
/**
|
|
171
|
+
* Extracts reflection learning governance candidates from raw inputs while tolerating partial
|
|
172
|
+
* data.
|
|
173
|
+
*/
|
|
174
|
+
function extractReflectionLearningGovernanceCandidates(reflectionText) {
|
|
175
|
+
const section = extractSectionMarkdown(reflectionText, PARSER_HEADINGS.learningGovernance);
|
|
176
|
+
if (!section) return [];
|
|
177
|
+
const parsed = section.split(/(?=^###\s+Entry(?![\p{L}\p{N}]))/gimu).map((block) => block.trim()).filter(Boolean).map(parseReflectionGovernanceEntry).filter((entry) => entry !== null);
|
|
178
|
+
if (parsed.length > 0) return parsed;
|
|
179
|
+
const fallbackBullets = sanitizeReflectionSliceLines(parseSectionBullets(reflectionText, PARSER_HEADINGS.learningGovernance));
|
|
180
|
+
if (fallbackBullets.length === 0) return [];
|
|
181
|
+
return [{
|
|
182
|
+
priority: "medium",
|
|
183
|
+
status: "pending",
|
|
184
|
+
area: "config",
|
|
185
|
+
summary: "Reflection learning governance candidates",
|
|
186
|
+
details: fallbackBullets.map((line) => `- ${line}`).join("\n"),
|
|
187
|
+
suggestedAction: "Review the governance candidates, promote durable rules to AGENTS.md / SOUL.md / TOOLS.md when stable, and extract a skill if the pattern becomes reusable."
|
|
188
|
+
}];
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* Parses reflection governance entry into the normalized shape used by reflection text
|
|
192
|
+
* slicing.
|
|
193
|
+
*/
|
|
194
|
+
function parseReflectionGovernanceEntry(block) {
|
|
195
|
+
const body = block.replace(/^###\s+Entry(?![\p{L}\p{N}])[^\n]*\n?/iu, "").trim();
|
|
196
|
+
if (!body) return null;
|
|
197
|
+
/** Reads field and applies reflection text slicing fallback behavior for missing data. */
|
|
198
|
+
const readField = (label) => {
|
|
199
|
+
const value = body.match(new RegExp(`^\\*\\*${label}\\*\\*:\\s*(.+)$`, "im"))?.[1]?.trim();
|
|
200
|
+
return value ? value : void 0;
|
|
201
|
+
};
|
|
202
|
+
/** Reads section and applies reflection text slicing fallback behavior for missing data. */
|
|
203
|
+
const readSection = (label) => {
|
|
204
|
+
const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
205
|
+
const value = body.match(new RegExp(`^###\\s+${escaped}\\s*\\n([\\s\\S]*?)(?=^###\\s+|$)`, "im"))?.[1]?.trim();
|
|
206
|
+
return value ? value : void 0;
|
|
207
|
+
};
|
|
208
|
+
const summary = readSection("Summary");
|
|
209
|
+
if (!summary) return null;
|
|
210
|
+
return {
|
|
211
|
+
priority: readField("Priority"),
|
|
212
|
+
status: readField("Status"),
|
|
213
|
+
area: readField("Area"),
|
|
214
|
+
summary,
|
|
215
|
+
details: readSection("Details"),
|
|
216
|
+
suggestedAction: readSection("Suggested Action")
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
//#endregion
|
|
220
|
+
//#region src/engine/reflection/reflection-mapped-memory-parser.ts
|
|
221
|
+
/** @file reflection-mapped-memory-parser.ts
|
|
222
|
+
* @purpose Extracts mapped memory rows from reflection markdown sections.
|
|
223
|
+
* @boundary Reflection markdown to mapped-memory DTOs only.
|
|
224
|
+
*/
|
|
225
|
+
/**
|
|
226
|
+
* Extracts reflection mapped memory items with sanitizer from raw inputs while tolerating
|
|
227
|
+
* partial data.
|
|
228
|
+
*/
|
|
229
|
+
function extractReflectionMappedMemoryItemsWithSanitizer(reflectionText, sanitizeLines) {
|
|
230
|
+
return [
|
|
231
|
+
{
|
|
232
|
+
heading: PARSER_HEADINGS.userModelDeltas,
|
|
233
|
+
category: "profile",
|
|
234
|
+
mappedKind: "user-model"
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
heading: PARSER_HEADINGS.agentModelDeltas,
|
|
238
|
+
category: "lesson",
|
|
239
|
+
mappedKind: "agent-model"
|
|
240
|
+
},
|
|
241
|
+
{
|
|
242
|
+
heading: PARSER_HEADINGS.lessonsAndPitfalls,
|
|
243
|
+
category: "lesson",
|
|
244
|
+
mappedKind: "lesson"
|
|
245
|
+
},
|
|
246
|
+
{
|
|
247
|
+
heading: PARSER_HEADINGS.decisionsDurable,
|
|
248
|
+
category: "episodic",
|
|
249
|
+
mappedKind: "decision"
|
|
250
|
+
}
|
|
251
|
+
].flatMap(({ heading, category, mappedKind }) => {
|
|
252
|
+
const lines = sanitizeLines(parseSectionBullets(reflectionText, heading));
|
|
253
|
+
const groupSize = lines.length;
|
|
254
|
+
return lines.map((text, ordinal) => ({
|
|
255
|
+
text,
|
|
256
|
+
category,
|
|
257
|
+
heading,
|
|
258
|
+
mappedKind,
|
|
259
|
+
ordinal,
|
|
260
|
+
groupSize
|
|
261
|
+
}));
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Extracts injectable reflection mapped memory items from raw inputs while tolerating partial
|
|
266
|
+
* data.
|
|
267
|
+
*/
|
|
268
|
+
function extractInjectableReflectionMappedMemoryItems(reflectionText) {
|
|
269
|
+
return extractReflectionMappedMemoryItemsWithSanitizer(reflectionText, sanitizeInjectableReflectionLines);
|
|
270
|
+
}
|
|
271
|
+
//#endregion
|
|
272
|
+
//#region src/engine/reflection/reflection-slice-extractor.ts
|
|
273
|
+
/** @file reflection-slice-extractor.ts
|
|
274
|
+
* @purpose Classifies reflection markdown into invariant and derived slice items.
|
|
275
|
+
* @boundary Slice extraction only; mapped-memory parsing lives separately.
|
|
276
|
+
*/
|
|
277
|
+
/** Tests whether is invariant rule like without mutating reflection text slicing state. */
|
|
278
|
+
function isInvariantRuleLike(line, classifiers) {
|
|
279
|
+
return classifiers.invariantSignals.some((pattern) => testPattern(pattern, line));
|
|
280
|
+
}
|
|
281
|
+
/** Tests whether is derived delta like without mutating reflection text slicing state. */
|
|
282
|
+
function isDerivedDeltaLike(line, classifiers) {
|
|
283
|
+
return classifiers.derivedSignals.some((pattern) => testPattern(pattern, line));
|
|
284
|
+
}
|
|
285
|
+
/** Tests whether is open loop action without mutating reflection text slicing state. */
|
|
286
|
+
function isOpenLoopAction(line, classifiers) {
|
|
287
|
+
return classifiers.openLoopSignals.some((pattern) => testPattern(pattern, line));
|
|
288
|
+
}
|
|
289
|
+
function testPattern(pattern, text) {
|
|
290
|
+
pattern.lastIndex = 0;
|
|
291
|
+
const matches = pattern.test(text);
|
|
292
|
+
pattern.lastIndex = 0;
|
|
293
|
+
return matches;
|
|
294
|
+
}
|
|
295
|
+
/**
|
|
296
|
+
* Extracts reflection slices with sanitizer from raw runtime payloads with partial-data
|
|
297
|
+
* tolerance.
|
|
298
|
+
*/
|
|
299
|
+
function extractReflectionSlicesWithSanitizer(reflectionText, sanitizeLines) {
|
|
300
|
+
const classifiers = RESOURCES_BY_LOCALE[resolveLocale({ text: reflectionText })].reflectionSliceClassifiers;
|
|
301
|
+
const invariantSection = parseSectionBullets(reflectionText, PARSER_HEADINGS.invariants);
|
|
302
|
+
const derivedSection = parseSectionBullets(reflectionText, PARSER_HEADINGS.derived);
|
|
303
|
+
const mergedSection = parseSectionBullets(reflectionText, PARSER_HEADINGS.invariantsAndReflections);
|
|
304
|
+
const invariantsPrimary = sanitizeLines(invariantSection);
|
|
305
|
+
const derivedPrimary = sanitizeLines(derivedSection);
|
|
306
|
+
const invariantLinesLegacy = sanitizeLines(mergedSection.filter((line) => classifiers.invariantLegacySignals.some((pattern) => testPattern(pattern, line)))).filter((line) => isInvariantRuleLike(line, classifiers));
|
|
307
|
+
const reflectionLinesLegacy = sanitizeLines(mergedSection.filter((line) => classifiers.derivedLegacySignals.some((pattern) => testPattern(pattern, line)))).filter((line) => isDerivedDeltaLike(line, classifiers));
|
|
308
|
+
const openLoopLines = sanitizeLines(parseSectionBullets(reflectionText, PARSER_HEADINGS.openLoops)).filter((line) => isOpenLoopAction(line, classifiers));
|
|
309
|
+
const durableDecisionLines = sanitizeLines(parseSectionBullets(reflectionText, PARSER_HEADINGS.decisionsDurable)).filter((line) => isInvariantRuleLike(line, classifiers));
|
|
310
|
+
const invariants = invariantsPrimary.length > 0 ? invariantsPrimary : invariantSection.length > 0 ? [] : invariantLinesLegacy.length > 0 ? invariantLinesLegacy : mergedSection.length > 0 ? [] : durableDecisionLines;
|
|
311
|
+
const derived = derivedPrimary.length > 0 ? derivedPrimary : [...reflectionLinesLegacy, ...openLoopLines];
|
|
312
|
+
return {
|
|
313
|
+
invariants: invariants.slice(0, 8),
|
|
314
|
+
derived: derived.slice(0, 10)
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
/** Extracts injectable reflection slices from raw inputs while tolerating partial data. */
|
|
318
|
+
function extractInjectableReflectionSlices(reflectionText) {
|
|
319
|
+
return extractReflectionSlicesWithSanitizer(reflectionText, sanitizeInjectableReflectionLines);
|
|
320
|
+
}
|
|
321
|
+
/**
|
|
322
|
+
* Assembles reflection slice items from slices from validated inputs for deterministic reflection
|
|
323
|
+
* text slicing.
|
|
324
|
+
*/
|
|
325
|
+
function buildReflectionSliceItemsFromSlices(slices) {
|
|
326
|
+
const invariantGroupSize = slices.invariants.length;
|
|
327
|
+
const derivedGroupSize = slices.derived.length;
|
|
328
|
+
const invariantItems = slices.invariants.map((text, ordinal) => ({
|
|
329
|
+
text,
|
|
330
|
+
itemKind: "invariant",
|
|
331
|
+
section: "Invariants",
|
|
332
|
+
ordinal,
|
|
333
|
+
groupSize: invariantGroupSize
|
|
334
|
+
}));
|
|
335
|
+
const derivedItems = slices.derived.map((text, ordinal) => ({
|
|
336
|
+
text,
|
|
337
|
+
itemKind: "derived",
|
|
338
|
+
section: "Derived",
|
|
339
|
+
ordinal,
|
|
340
|
+
groupSize: derivedGroupSize
|
|
341
|
+
}));
|
|
342
|
+
return [...invariantItems, ...derivedItems];
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Extracts injectable reflection slice items from raw inputs while tolerating partial data.
|
|
346
|
+
*/
|
|
347
|
+
function extractInjectableReflectionSliceItems(reflectionText) {
|
|
348
|
+
return buildReflectionSliceItemsFromSlices(extractInjectableReflectionSlices(reflectionText));
|
|
349
|
+
}
|
|
350
|
+
const REFLECTION_ITEM_DECAY_DEFAULTS = {
|
|
351
|
+
invariant: {
|
|
352
|
+
midpointDays: 45,
|
|
353
|
+
k: .22,
|
|
354
|
+
baseWeight: 1.1,
|
|
355
|
+
quality: 1
|
|
356
|
+
},
|
|
357
|
+
derived: {
|
|
358
|
+
midpointDays: 7,
|
|
359
|
+
k: .65,
|
|
360
|
+
baseWeight: 1,
|
|
361
|
+
quality: .95
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
/**
|
|
365
|
+
* Returns reflection item decay defaults from reflection item persistence state without side
|
|
366
|
+
* effects.
|
|
367
|
+
*/
|
|
368
|
+
function getReflectionItemDecayDefaults(itemKind) {
|
|
369
|
+
return { ...REFLECTION_ITEM_DECAY_DEFAULTS[itemKind] };
|
|
370
|
+
}
|
|
371
|
+
function itemPayloadKind(itemKind) {
|
|
372
|
+
return itemKind === "invariant" ? "item-invariant" : "item-derived";
|
|
373
|
+
}
|
|
374
|
+
function itemPlansFromParams(params) {
|
|
375
|
+
const errorSignals = params.toolErrorSignals.map((signal) => signal.signatureHash);
|
|
376
|
+
return params.items.map((source) => ({
|
|
377
|
+
source,
|
|
378
|
+
payloadKind: itemPayloadKind(source.itemKind),
|
|
379
|
+
defaults: getReflectionItemDecayDefaults(source.itemKind),
|
|
380
|
+
errorSignals
|
|
381
|
+
}));
|
|
382
|
+
}
|
|
383
|
+
function metadataFromItemPlan(params, plan) {
|
|
384
|
+
const { source, defaults } = plan;
|
|
385
|
+
return {
|
|
386
|
+
type: "memory-reflection-item",
|
|
387
|
+
reflectionVersion: 4,
|
|
388
|
+
stage: "reflect-store",
|
|
389
|
+
eventId: params.eventId,
|
|
390
|
+
itemKind: source.itemKind,
|
|
391
|
+
section: source.section,
|
|
392
|
+
ordinal: source.ordinal,
|
|
393
|
+
groupSize: source.groupSize,
|
|
394
|
+
agentId: params.agentId,
|
|
395
|
+
sessionKey: params.sessionKey,
|
|
396
|
+
sessionId: params.sessionId,
|
|
397
|
+
storedAt: params.runAt,
|
|
398
|
+
usedFallback: params.usedFallback,
|
|
399
|
+
errorSignals: plan.errorSignals,
|
|
400
|
+
decayModel: "logistic",
|
|
401
|
+
decayMidpointDays: defaults.midpointDays,
|
|
402
|
+
decayK: defaults.k,
|
|
403
|
+
baseWeight: defaults.baseWeight,
|
|
404
|
+
quality: defaults.quality,
|
|
405
|
+
...params.sourceReflectionPath ? { sourceReflectionPath: params.sourceReflectionPath } : {}
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* Assembles reflection item payloads from validated inputs for deterministic reflection item
|
|
410
|
+
* persistence.
|
|
411
|
+
*/
|
|
412
|
+
function buildReflectionItemPayloads(params) {
|
|
413
|
+
return itemPlansFromParams(params).map((plan) => {
|
|
414
|
+
return {
|
|
415
|
+
kind: plan.payloadKind,
|
|
416
|
+
text: plan.source.text,
|
|
417
|
+
metadata: metadataFromItemPlan(params, plan)
|
|
418
|
+
};
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
//#endregion
|
|
422
|
+
//#region src/engine/reflection/reflection-entry-utils.ts
|
|
423
|
+
function isReflectionMetadataType(type) {
|
|
424
|
+
return type === "memory-reflection-item" || type === "memory-reflection";
|
|
425
|
+
}
|
|
426
|
+
function isOwnedByAgent(metadata, agentId) {
|
|
427
|
+
const owner = typeof metadata.agentId === "string" ? metadata.agentId.trim() : "";
|
|
428
|
+
const itemKind = metadata.itemKind;
|
|
429
|
+
if (itemKind === "derived") {
|
|
430
|
+
if (!owner) return agentId === "main";
|
|
431
|
+
return owner === agentId;
|
|
432
|
+
}
|
|
433
|
+
if (itemKind === void 0 || itemKind === "invariant") {
|
|
434
|
+
if (!owner) return agentId === "main";
|
|
435
|
+
return owner === agentId || owner === "main";
|
|
436
|
+
}
|
|
437
|
+
return false;
|
|
438
|
+
}
|
|
439
|
+
function toStringArray(value) {
|
|
440
|
+
if (!Array.isArray(value)) return [];
|
|
441
|
+
return value.map((item) => String(item).trim()).filter(Boolean);
|
|
442
|
+
}
|
|
443
|
+
function metadataTimestamp(metadata, fallbackTs) {
|
|
444
|
+
const storedAt = Number(metadata.storedAt);
|
|
445
|
+
if (Number.isFinite(storedAt) && storedAt > 0) return storedAt;
|
|
446
|
+
return Number.isFinite(fallbackTs) ? fallbackTs : Date.now();
|
|
447
|
+
}
|
|
448
|
+
function readPositiveNumber(value, fallback) {
|
|
449
|
+
const num = Number(value);
|
|
450
|
+
if (!Number.isFinite(num) || num <= 0) return fallback;
|
|
451
|
+
return num;
|
|
452
|
+
}
|
|
453
|
+
function readClampedNumber(value, fallback, min, max) {
|
|
454
|
+
const num = Number(value);
|
|
455
|
+
return Math.max(min, Math.min(max, Number.isFinite(num) ? num : fallback));
|
|
456
|
+
}
|
|
457
|
+
//#endregion
|
|
458
|
+
//#region src/engine/reflection/reflection-line-loader.ts
|
|
459
|
+
/** @file reflection-line-loader.ts
|
|
460
|
+
* @purpose Load, score, and rank invariant and derived reflection lines.
|
|
461
|
+
* @boundary Reads in-memory entries only; no persistence or I/O.
|
|
462
|
+
*/
|
|
463
|
+
function loadAgentReflectionSlicesFromEntries(params) {
|
|
464
|
+
const now = Number.isFinite(params.now) ? Number(params.now) : Date.now();
|
|
465
|
+
const deriveMaxAgeMs = Number.isFinite(params.deriveMaxAgeMs) ? Math.max(0, Number(params.deriveMaxAgeMs)) : DEFAULT_REFLECTION_DERIVED_MAX_AGE_MS;
|
|
466
|
+
const invariantMaxAgeMs = Number.isFinite(params.invariantMaxAgeMs) ? Math.max(0, Number(params.invariantMaxAgeMs)) : void 0;
|
|
467
|
+
const reflectionRows = params.entries.map((entry) => ({
|
|
468
|
+
entry,
|
|
469
|
+
metadata: parseReflectionMetadata(entry.metadata)
|
|
470
|
+
})).filter(({ metadata }) => isReflectionMetadataType(metadata.type) && isOwnedByAgent(metadata, params.agentId)).sort((a, b) => b.entry.timestamp - a.entry.timestamp).slice(0, 160);
|
|
471
|
+
const itemRows = reflectionRows.filter(({ metadata }) => metadata.type === "memory-reflection-item");
|
|
472
|
+
const legacyRows = reflectionRows.filter(({ metadata }) => metadata.type === "memory-reflection");
|
|
473
|
+
const unresolvedItemRows = itemRows.filter(({ metadata }) => metadata.resolvedAt === void 0);
|
|
474
|
+
const resolvedItemRows = itemRows.filter(({ metadata }) => metadata.resolvedAt !== void 0);
|
|
475
|
+
const hasItemRows = itemRows.length > 0;
|
|
476
|
+
const hasLegacyRows = legacyRows.length > 0;
|
|
477
|
+
const resolvedInvariantTexts = new Set(resolvedItemRows.filter(({ metadata }) => metadata.itemKind === "invariant").flatMap(({ entry }) => sanitizeInjectableReflectionLines([entry.text])).map((line) => normalizeReflectionLineForAggregation(line)));
|
|
478
|
+
const resolvedDerivedTexts = new Set(resolvedItemRows.filter(({ metadata }) => metadata.itemKind === "derived").flatMap(({ entry }) => sanitizeInjectableReflectionLines([entry.text])).map((line) => normalizeReflectionLineForAggregation(line)));
|
|
479
|
+
const legacyHasUniqueInvariant = legacyRows.some(({ metadata }) => sanitizeInjectableReflectionLines(toStringArray(metadata.invariants)).some((line) => !resolvedInvariantTexts.has(normalizeReflectionLineForAggregation(line))));
|
|
480
|
+
const legacyHasUniqueDerived = legacyRows.some(({ metadata }) => sanitizeInjectableReflectionLines(toStringArray(metadata.derived)).some((line) => !resolvedDerivedTexts.has(normalizeReflectionLineForAggregation(line))));
|
|
481
|
+
if (hasItemRows && unresolvedItemRows.length === 0 && (!hasLegacyRows || !legacyHasUniqueInvariant && !legacyHasUniqueDerived)) return {
|
|
482
|
+
invariants: [],
|
|
483
|
+
derived: [],
|
|
484
|
+
invariantSources: [],
|
|
485
|
+
derivedSources: []
|
|
486
|
+
};
|
|
487
|
+
const invariantLegacyRows = legacyRows.filter(({ metadata }) => {
|
|
488
|
+
const lines = sanitizeInjectableReflectionLines(toStringArray(metadata.invariants));
|
|
489
|
+
if (lines.length === 0) return false;
|
|
490
|
+
return lines.some((line) => !resolvedInvariantTexts.has(normalizeReflectionLineForAggregation(line)));
|
|
491
|
+
});
|
|
492
|
+
const derivedLegacyRows = legacyRows.filter(({ metadata }) => {
|
|
493
|
+
const lines = sanitizeInjectableReflectionLines(toStringArray(metadata.derived));
|
|
494
|
+
if (lines.length === 0) return false;
|
|
495
|
+
return lines.some((line) => !resolvedDerivedTexts.has(normalizeReflectionLineForAggregation(line)));
|
|
496
|
+
});
|
|
497
|
+
const invariantLines = rankReflectionLines(buildInvariantCandidates(unresolvedItemRows, invariantLegacyRows, resolvedInvariantTexts), {
|
|
498
|
+
now,
|
|
499
|
+
maxAgeMs: invariantMaxAgeMs,
|
|
500
|
+
limit: 8
|
|
501
|
+
});
|
|
502
|
+
const derivedLines = rankReflectionLines(buildDerivedCandidates(unresolvedItemRows, derivedLegacyRows, params.agentId, resolvedDerivedTexts), {
|
|
503
|
+
now,
|
|
504
|
+
maxAgeMs: deriveMaxAgeMs,
|
|
505
|
+
limit: 10
|
|
506
|
+
});
|
|
507
|
+
return {
|
|
508
|
+
invariants: invariantLines.lines,
|
|
509
|
+
derived: derivedLines.lines,
|
|
510
|
+
invariantSources: invariantLines.sources,
|
|
511
|
+
derivedSources: derivedLines.sources
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
function buildInvariantCandidates(itemRows, legacyRows, resolvedTexts) {
|
|
515
|
+
const itemCandidates = itemRows.filter(({ metadata }) => metadata.itemKind === "invariant").flatMap(({ entry, metadata }) => {
|
|
516
|
+
const safeLines = sanitizeInjectableReflectionLines([entry.text]);
|
|
517
|
+
if (safeLines.length === 0) return [];
|
|
518
|
+
const defaults = getReflectionItemDecayDefaults("invariant");
|
|
519
|
+
const timestamp = metadataTimestamp(metadata, entry.timestamp);
|
|
520
|
+
return safeLines.map((line) => ({
|
|
521
|
+
line,
|
|
522
|
+
timestamp,
|
|
523
|
+
midpointDays: readPositiveNumber(metadata.decayMidpointDays, defaults.midpointDays),
|
|
524
|
+
k: readPositiveNumber(metadata.decayK, defaults.k),
|
|
525
|
+
baseWeight: readPositiveNumber(metadata.baseWeight, defaults.baseWeight),
|
|
526
|
+
quality: readClampedNumber(metadata.quality, defaults.quality, .2, 1),
|
|
527
|
+
usedFallback: metadata.usedFallback === true,
|
|
528
|
+
source: buildReflectionLineSource(entry, line, metadata)
|
|
529
|
+
}));
|
|
530
|
+
});
|
|
531
|
+
if (itemCandidates.length > 0) return itemCandidates;
|
|
532
|
+
return legacyRows.flatMap(({ entry, metadata }) => {
|
|
533
|
+
const defaults = getReflectionItemDecayDefaults("invariant");
|
|
534
|
+
const timestamp = metadataTimestamp(metadata, entry.timestamp);
|
|
535
|
+
return sanitizeInjectableReflectionLines(toStringArray(metadata.invariants)).filter((line) => !resolvedTexts.has(normalizeReflectionLineForAggregation(line))).map((line) => ({
|
|
536
|
+
line,
|
|
537
|
+
timestamp,
|
|
538
|
+
midpointDays: defaults.midpointDays,
|
|
539
|
+
k: defaults.k,
|
|
540
|
+
baseWeight: defaults.baseWeight,
|
|
541
|
+
quality: defaults.quality,
|
|
542
|
+
usedFallback: metadata.usedFallback === true,
|
|
543
|
+
source: buildReflectionLineSource(entry, line, metadata)
|
|
544
|
+
}));
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
function buildDerivedCandidates(itemRows, legacyRows, queryingAgentId, resolvedTexts) {
|
|
548
|
+
const itemCandidates = itemRows.filter(({ metadata }) => metadata.itemKind === "derived").flatMap(({ entry, metadata }) => {
|
|
549
|
+
const safeLines = sanitizeInjectableReflectionLines([entry.text]);
|
|
550
|
+
if (safeLines.length === 0) return [];
|
|
551
|
+
const defaults = getReflectionItemDecayDefaults("derived");
|
|
552
|
+
const timestamp = metadataTimestamp(metadata, entry.timestamp);
|
|
553
|
+
return safeLines.map((line) => ({
|
|
554
|
+
line,
|
|
555
|
+
timestamp,
|
|
556
|
+
midpointDays: readPositiveNumber(metadata.decayMidpointDays, defaults.midpointDays),
|
|
557
|
+
k: readPositiveNumber(metadata.decayK, defaults.k),
|
|
558
|
+
baseWeight: readPositiveNumber(metadata.baseWeight, defaults.baseWeight),
|
|
559
|
+
quality: readClampedNumber(metadata.quality, defaults.quality, .2, 1),
|
|
560
|
+
usedFallback: metadata.usedFallback === true,
|
|
561
|
+
source: buildReflectionLineSource(entry, line, metadata)
|
|
562
|
+
}));
|
|
563
|
+
});
|
|
564
|
+
if (itemCandidates.length > 0) return itemCandidates;
|
|
565
|
+
return legacyRows.filter(({ metadata }) => {
|
|
566
|
+
if (sanitizeInjectableReflectionLines(toStringArray(metadata.derived)).length === 0) return true;
|
|
567
|
+
const owner = typeof metadata.agentId === "string" ? metadata.agentId.trim() : "";
|
|
568
|
+
return owner !== "" && owner === queryingAgentId;
|
|
569
|
+
}).flatMap(({ entry, metadata }) => {
|
|
570
|
+
const timestamp = metadataTimestamp(metadata, entry.timestamp);
|
|
571
|
+
const lines = sanitizeInjectableReflectionLines(toStringArray(metadata.derived));
|
|
572
|
+
if (lines.length === 0) return [];
|
|
573
|
+
const defaults = {
|
|
574
|
+
midpointDays: 3,
|
|
575
|
+
k: REFLECTION_DERIVE_LOGISTIC_K,
|
|
576
|
+
baseWeight: resolveLegacyDeriveBaseWeight(metadata),
|
|
577
|
+
quality: computeDerivedLineQuality(lines.length)
|
|
578
|
+
};
|
|
579
|
+
return lines.filter((line) => !resolvedTexts.has(normalizeReflectionLineForAggregation(line))).map((line) => ({
|
|
580
|
+
line,
|
|
581
|
+
timestamp,
|
|
582
|
+
midpointDays: readPositiveNumber(metadata.decayMidpointDays, defaults.midpointDays),
|
|
583
|
+
k: readPositiveNumber(metadata.decayK, defaults.k),
|
|
584
|
+
baseWeight: readPositiveNumber(metadata.deriveBaseWeight, defaults.baseWeight),
|
|
585
|
+
quality: readClampedNumber(metadata.deriveQuality, defaults.quality, .2, 1),
|
|
586
|
+
usedFallback: metadata.usedFallback === true,
|
|
587
|
+
source: buildReflectionLineSource(entry, line, metadata)
|
|
588
|
+
}));
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
function rankReflectionLines(candidates, options) {
|
|
592
|
+
const lineScores = /* @__PURE__ */ new Map();
|
|
593
|
+
for (const candidate of candidates) {
|
|
594
|
+
const timestamp = Number.isFinite(candidate.timestamp) ? candidate.timestamp : options.now;
|
|
595
|
+
const maxAge = options.maxAgeMs;
|
|
596
|
+
if (maxAge !== void 0 && Number.isFinite(maxAge) && maxAge >= 0 && options.now - timestamp > maxAge) continue;
|
|
597
|
+
const score = computeReflectionScore({
|
|
598
|
+
ageDays: Math.max(0, (options.now - timestamp) / 864e5),
|
|
599
|
+
midpointDays: candidate.midpointDays,
|
|
600
|
+
k: candidate.k,
|
|
601
|
+
baseWeight: candidate.baseWeight,
|
|
602
|
+
quality: candidate.quality,
|
|
603
|
+
usedFallback: candidate.usedFallback
|
|
604
|
+
});
|
|
605
|
+
if (!Number.isFinite(score) || score <= 0) continue;
|
|
606
|
+
const key = normalizeReflectionLineForAggregation(candidate.line);
|
|
607
|
+
if (!key) continue;
|
|
608
|
+
const current = lineScores.get(key);
|
|
609
|
+
if (!current) {
|
|
610
|
+
lineScores.set(key, {
|
|
611
|
+
line: candidate.line,
|
|
612
|
+
score,
|
|
613
|
+
latestTs: timestamp,
|
|
614
|
+
source: candidate.source
|
|
615
|
+
});
|
|
616
|
+
continue;
|
|
617
|
+
}
|
|
618
|
+
current.score += score;
|
|
619
|
+
if (timestamp > current.latestTs) {
|
|
620
|
+
current.latestTs = timestamp;
|
|
621
|
+
current.line = candidate.line;
|
|
622
|
+
current.source = candidate.source;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
const ranked = [...lineScores.values()].sort((a, b) => {
|
|
626
|
+
if (b.score !== a.score) return b.score - a.score;
|
|
627
|
+
if (b.latestTs !== a.latestTs) return b.latestTs - a.latestTs;
|
|
628
|
+
return a.line.localeCompare(b.line);
|
|
629
|
+
}).slice(0, options.limit);
|
|
630
|
+
return {
|
|
631
|
+
lines: ranked.map((item) => item.line),
|
|
632
|
+
sources: ranked.flatMap((item, index) => item.source ? [{
|
|
633
|
+
...item.source,
|
|
634
|
+
line: item.line,
|
|
635
|
+
rank: index + 1,
|
|
636
|
+
score: item.score
|
|
637
|
+
}] : [])
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
function buildReflectionLineSource(entry, line, metadata) {
|
|
641
|
+
if (!entry.factId) return void 0;
|
|
642
|
+
const sourceAgentId = typeof metadata.agentId === "string" && metadata.agentId.trim() ? metadata.agentId.trim() : "main";
|
|
643
|
+
return {
|
|
644
|
+
line,
|
|
645
|
+
rowId: entry.id,
|
|
646
|
+
factId: entry.factId,
|
|
647
|
+
sourceAgentId,
|
|
648
|
+
memoryKind: entry.category,
|
|
649
|
+
projectId: entry.projectId
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
function computeDerivedLineQuality(nonPlaceholderLineCount) {
|
|
653
|
+
const n = Number.isFinite(nonPlaceholderLineCount) ? Math.max(0, Math.floor(nonPlaceholderLineCount)) : 0;
|
|
654
|
+
if (n <= 0) return .2;
|
|
655
|
+
return Math.min(1, .55 + Math.min(6, n) * .075);
|
|
656
|
+
}
|
|
657
|
+
function resolveLegacyDeriveBaseWeight(metadata) {
|
|
658
|
+
const explicit = Number(metadata.deriveBaseWeight);
|
|
659
|
+
if (Number.isFinite(explicit) && explicit > 0) return Math.max(.1, Math.min(1.2, explicit));
|
|
660
|
+
if (metadata.usedFallback === true) return REFLECTION_DERIVE_FALLBACK_BASE_WEIGHT;
|
|
661
|
+
return 1;
|
|
662
|
+
}
|
|
663
|
+
//#endregion
|
|
664
|
+
//#region src/engine/reflection/mapped-memory-metadata-builder.ts
|
|
665
|
+
/** @file mapped-memory-metadata-builder.ts
|
|
666
|
+
* @purpose Maps raw reflection metadata into typed fields used by ranking and storage.
|
|
667
|
+
* @boundary Reflection extraction output and schema-compatible persistence.
|
|
668
|
+
* @see entry-metadata-parser.ts, slice-item-payload-builder.ts, types.ts.
|
|
669
|
+
*/
|
|
670
|
+
/**
|
|
671
|
+
* Reflection mapped metadata builder.
|
|
672
|
+
*
|
|
673
|
+
* Builds metadata for "mapped" reflection items (user-model, agent-model,
|
|
674
|
+
* lesson, decision) with kind-specific decay defaults.
|
|
675
|
+
*/
|
|
676
|
+
const REFLECTION_MAPPED_DECAY_DEFAULTS = {
|
|
677
|
+
decision: {
|
|
678
|
+
midpointDays: 45,
|
|
679
|
+
k: .25,
|
|
680
|
+
baseWeight: 1.1,
|
|
681
|
+
quality: 1
|
|
682
|
+
},
|
|
683
|
+
"user-model": {
|
|
684
|
+
midpointDays: 21,
|
|
685
|
+
k: .3,
|
|
686
|
+
baseWeight: 1,
|
|
687
|
+
quality: .95
|
|
688
|
+
},
|
|
689
|
+
"agent-model": {
|
|
690
|
+
midpointDays: 10,
|
|
691
|
+
k: .35,
|
|
692
|
+
baseWeight: .95,
|
|
693
|
+
quality: .93
|
|
694
|
+
},
|
|
695
|
+
lesson: {
|
|
696
|
+
midpointDays: 7,
|
|
697
|
+
k: .45,
|
|
698
|
+
baseWeight: .9,
|
|
699
|
+
quality: .9
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
/**
|
|
703
|
+
* Returns reflection mapped decay defaults from reflection metadata mapping state without side
|
|
704
|
+
* effects.
|
|
705
|
+
*/
|
|
706
|
+
function getReflectionMappedDecayDefaults(kind) {
|
|
707
|
+
return { ...REFLECTION_MAPPED_DECAY_DEFAULTS[kind] };
|
|
708
|
+
}
|
|
709
|
+
function buildReflectionAntiPatternSignature(kind, text) {
|
|
710
|
+
const normalized = text.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim().replace(/\s+/g, " ");
|
|
711
|
+
return `reflection:${kind}:${createHash("sha256").update(`${kind}\0${normalized}`).digest("hex").slice(0, 20)}`;
|
|
712
|
+
}
|
|
713
|
+
function mappedSessionFields(params) {
|
|
714
|
+
return {
|
|
715
|
+
agentId: params.agentId,
|
|
716
|
+
sessionKey: params.sessionKey,
|
|
717
|
+
sessionId: params.sessionId,
|
|
718
|
+
storedAt: params.runAt,
|
|
719
|
+
usedFallback: params.usedFallback
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
function mappedItemFields(item) {
|
|
723
|
+
return {
|
|
724
|
+
mappedKind: item.mappedKind,
|
|
725
|
+
mappedCategory: item.category,
|
|
726
|
+
section: item.heading,
|
|
727
|
+
ordinal: item.ordinal,
|
|
728
|
+
groupSize: item.groupSize
|
|
729
|
+
};
|
|
730
|
+
}
|
|
731
|
+
function mappedDecayFields(defaults) {
|
|
732
|
+
return {
|
|
733
|
+
decayModel: "logistic",
|
|
734
|
+
decayMidpointDays: defaults.midpointDays,
|
|
735
|
+
decayK: defaults.k,
|
|
736
|
+
baseWeight: defaults.baseWeight,
|
|
737
|
+
quality: defaults.quality
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Assembles reflection mapped metadata from validated inputs for deterministic reflection
|
|
742
|
+
* metadata mapping.
|
|
743
|
+
*/
|
|
744
|
+
function buildReflectionMappedMetadata(params) {
|
|
745
|
+
const defaults = getReflectionMappedDecayDefaults(params.mappedItem.mappedKind);
|
|
746
|
+
const sessionFields = mappedSessionFields(params);
|
|
747
|
+
return {
|
|
748
|
+
type: "memory-reflection-mapped",
|
|
749
|
+
reflectionVersion: 4,
|
|
750
|
+
stage: "reflect-store",
|
|
751
|
+
eventId: params.eventId,
|
|
752
|
+
...mappedItemFields(params.mappedItem),
|
|
753
|
+
...sessionFields,
|
|
754
|
+
errorSignals: params.toolErrorSignals.map((signal) => signal.signatureHash),
|
|
755
|
+
...mappedDecayFields(defaults),
|
|
756
|
+
...params.sourceReflectionPath ? { sourceReflectionPath: params.sourceReflectionPath } : {}
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
function normalizeRunAt(runAt) {
|
|
760
|
+
if (!Number.isFinite(runAt)) return Date.now();
|
|
761
|
+
return Math.max(0, Math.floor(runAt));
|
|
762
|
+
}
|
|
763
|
+
function formatReflectionEventDate(runAt) {
|
|
764
|
+
return new Date(runAt).toISOString().replace(/[-:.TZ]/g, "").slice(0, 14);
|
|
765
|
+
}
|
|
766
|
+
function hashReflectionEventIdentity(identity) {
|
|
767
|
+
return createHash("sha1").update(`${identity.runAt}|${identity.sessionKey}|${identity.sessionId}|${identity.agentId}|${identity.command}`).digest("hex").slice(0, 8);
|
|
768
|
+
}
|
|
769
|
+
function eventIdentityFromParams(params) {
|
|
770
|
+
return {
|
|
771
|
+
runAt: params.runAt,
|
|
772
|
+
sessionKey: params.sessionKey,
|
|
773
|
+
sessionId: params.sessionId,
|
|
774
|
+
agentId: params.agentId,
|
|
775
|
+
command: params.command
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
function collectErrorSignalHashes(signals) {
|
|
779
|
+
return signals.map((signal) => signal.signatureHash);
|
|
780
|
+
}
|
|
781
|
+
/** Creates a deterministic event id from run time, session, agent, and command. */
|
|
782
|
+
function createReflectionEventId(params) {
|
|
783
|
+
const identity = {
|
|
784
|
+
...params,
|
|
785
|
+
runAt: normalizeRunAt(params.runAt)
|
|
786
|
+
};
|
|
787
|
+
return `refl-${formatReflectionEventDate(identity.runAt)}-${hashReflectionEventIdentity(identity)}`;
|
|
788
|
+
}
|
|
789
|
+
function buildReflectionEventMetadata(params, eventId) {
|
|
790
|
+
return {
|
|
791
|
+
type: "memory-reflection-event",
|
|
792
|
+
reflectionVersion: 4,
|
|
793
|
+
kind: "episodic",
|
|
794
|
+
memory_category: "episodic",
|
|
795
|
+
stage: "reflect-store",
|
|
796
|
+
eventId,
|
|
797
|
+
sessionKey: params.sessionKey,
|
|
798
|
+
sessionId: params.sessionId,
|
|
799
|
+
agentId: params.agentId,
|
|
800
|
+
command: params.command,
|
|
801
|
+
storedAt: params.runAt,
|
|
802
|
+
asserted_at: params.runAt,
|
|
803
|
+
event_at: new Date(params.runAt).toISOString(),
|
|
804
|
+
usedFallback: params.usedFallback,
|
|
805
|
+
errorSignals: collectErrorSignalHashes(params.toolErrorSignals),
|
|
806
|
+
...params.sourceReflectionPath ? { sourceReflectionPath: params.sourceReflectionPath } : {}
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
function renderReflectionEventText(params, eventId) {
|
|
810
|
+
return [
|
|
811
|
+
`reflection-event · ${params.scope}`,
|
|
812
|
+
`eventId=${eventId}`,
|
|
813
|
+
`session=${params.sessionId}`,
|
|
814
|
+
`agent=${params.agentId}`,
|
|
815
|
+
`command=${params.command}`,
|
|
816
|
+
`usedFallback=${params.usedFallback ? "true" : "false"}`
|
|
817
|
+
].join("\n");
|
|
818
|
+
}
|
|
819
|
+
/**
|
|
820
|
+
* Assembles reflection event payload from validated inputs for deterministic reflection event
|
|
821
|
+
* persistence.
|
|
822
|
+
*/
|
|
823
|
+
function buildReflectionEventPayload(params) {
|
|
824
|
+
const eventId = params.eventId || createReflectionEventId(eventIdentityFromParams(params));
|
|
825
|
+
const metadata = buildReflectionEventMetadata(params, eventId);
|
|
826
|
+
return {
|
|
827
|
+
kind: "episodic-reflection",
|
|
828
|
+
text: renderReflectionEventText(params, eventId),
|
|
829
|
+
metadata
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
//#endregion
|
|
833
|
+
//#region src/engine/reflection/reflection-store-payload-builder.ts
|
|
834
|
+
/** @file reflection-store-payload-builder.ts
|
|
835
|
+
* @purpose Build reflection event, item, and legacy payloads for storage.
|
|
836
|
+
* @boundary Pure payload assembly from parsed reflection text and caller context.
|
|
837
|
+
*/
|
|
838
|
+
function buildReflectionStorePayloads(params) {
|
|
839
|
+
const slices = extractInjectableReflectionSlices(params.reflectionText);
|
|
840
|
+
const eventId = params.eventId || createReflectionEventId({
|
|
841
|
+
runAt: params.runAt,
|
|
842
|
+
sessionKey: params.sessionKey,
|
|
843
|
+
sessionId: params.sessionId,
|
|
844
|
+
agentId: params.agentId,
|
|
845
|
+
command: params.command
|
|
846
|
+
});
|
|
847
|
+
const payloads = [buildReflectionEventPayload({
|
|
848
|
+
eventId,
|
|
849
|
+
scope: params.scope,
|
|
850
|
+
sessionKey: params.sessionKey,
|
|
851
|
+
sessionId: params.sessionId,
|
|
852
|
+
agentId: params.agentId,
|
|
853
|
+
command: params.command,
|
|
854
|
+
toolErrorSignals: params.toolErrorSignals,
|
|
855
|
+
runAt: params.runAt,
|
|
856
|
+
usedFallback: params.usedFallback,
|
|
857
|
+
sourceReflectionPath: params.sourceReflectionPath
|
|
858
|
+
})];
|
|
859
|
+
payloads.push(...buildReflectionItemPayloads({
|
|
860
|
+
items: extractInjectableReflectionSliceItems(params.reflectionText),
|
|
861
|
+
eventId,
|
|
862
|
+
agentId: params.agentId,
|
|
863
|
+
sessionKey: params.sessionKey,
|
|
864
|
+
sessionId: params.sessionId,
|
|
865
|
+
runAt: params.runAt,
|
|
866
|
+
usedFallback: params.usedFallback,
|
|
867
|
+
toolErrorSignals: params.toolErrorSignals,
|
|
868
|
+
sourceReflectionPath: params.sourceReflectionPath
|
|
869
|
+
}));
|
|
870
|
+
if (params.writeLegacyCombined === true && (slices.invariants.length > 0 || slices.derived.length > 0)) payloads.push(buildLegacyCombinedPayload({
|
|
871
|
+
slices,
|
|
872
|
+
scope: params.scope,
|
|
873
|
+
sessionKey: params.sessionKey,
|
|
874
|
+
sessionId: params.sessionId,
|
|
875
|
+
agentId: params.agentId,
|
|
876
|
+
command: params.command,
|
|
877
|
+
toolErrorSignals: params.toolErrorSignals,
|
|
878
|
+
runAt: params.runAt,
|
|
879
|
+
usedFallback: params.usedFallback,
|
|
880
|
+
sourceReflectionPath: params.sourceReflectionPath
|
|
881
|
+
}));
|
|
882
|
+
return {
|
|
883
|
+
eventId,
|
|
884
|
+
slices,
|
|
885
|
+
payloads
|
|
886
|
+
};
|
|
887
|
+
}
|
|
888
|
+
function buildLegacyCombinedPayload(params) {
|
|
889
|
+
const dateYmd = new Date(params.runAt).toISOString().split("T")[0];
|
|
890
|
+
const deriveQuality = computeDerivedLineQuality(params.slices.derived.length);
|
|
891
|
+
const deriveBaseWeight = params.usedFallback ? resolveLegacyDeriveBaseWeight({ usedFallback: true }) : 1;
|
|
892
|
+
return {
|
|
893
|
+
kind: "combined-legacy",
|
|
894
|
+
text: [
|
|
895
|
+
`reflection · ${params.scope} · ${dateYmd}`,
|
|
896
|
+
`Session Reflection (${new Date(params.runAt).toISOString()})`,
|
|
897
|
+
`Session Key: ${params.sessionKey}`,
|
|
898
|
+
`Session ID: ${params.sessionId}`,
|
|
899
|
+
"",
|
|
900
|
+
"Invariants:",
|
|
901
|
+
...params.slices.invariants.length > 0 ? params.slices.invariants.map((x) => `- ${x}`) : ["- (none captured)"],
|
|
902
|
+
"",
|
|
903
|
+
"Derived:",
|
|
904
|
+
...params.slices.derived.length > 0 ? params.slices.derived.map((x) => `- ${x}`) : ["- (none captured)"]
|
|
905
|
+
].join("\n"),
|
|
906
|
+
metadata: {
|
|
907
|
+
type: "memory-reflection",
|
|
908
|
+
stage: "reflect-store",
|
|
909
|
+
reflectionVersion: 3,
|
|
910
|
+
sessionKey: params.sessionKey,
|
|
911
|
+
sessionId: params.sessionId,
|
|
912
|
+
agentId: params.agentId,
|
|
913
|
+
command: params.command,
|
|
914
|
+
storedAt: params.runAt,
|
|
915
|
+
invariants: params.slices.invariants,
|
|
916
|
+
derived: params.slices.derived,
|
|
917
|
+
usedFallback: params.usedFallback,
|
|
918
|
+
errorSignals: params.toolErrorSignals.map((s) => s.signatureHash),
|
|
919
|
+
decayModel: "logistic",
|
|
920
|
+
decayMidpointDays: 3,
|
|
921
|
+
decayK: REFLECTION_DERIVE_LOGISTIC_K,
|
|
922
|
+
deriveBaseWeight,
|
|
923
|
+
deriveQuality,
|
|
924
|
+
deriveSource: params.usedFallback ? "fallback" : "normal",
|
|
925
|
+
...params.sourceReflectionPath ? { sourceReflectionPath: params.sourceReflectionPath } : {}
|
|
926
|
+
}
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
//#endregion
|
|
930
|
+
//#region src/engine/reflection/reflection-store-writer.ts
|
|
931
|
+
/** @file reflection-store-writer.ts
|
|
932
|
+
* @purpose Persist reflection payloads with semantic duplicate protection.
|
|
933
|
+
* @boundary Store embedding, duplicate search, and write orchestration.
|
|
934
|
+
*/
|
|
935
|
+
async function storeReflectionEntries(params) {
|
|
936
|
+
const { eventId, slices, payloads } = buildReflectionStorePayloads(params);
|
|
937
|
+
const storedKinds = [];
|
|
938
|
+
const derivedSources = [];
|
|
939
|
+
const dedupeThreshold = Number.isFinite(params.dedupeThreshold) ? Number(params.dedupeThreshold) : .97;
|
|
940
|
+
for (const payload of payloads) {
|
|
941
|
+
const vector = await params.embed(payload.text);
|
|
942
|
+
const existing = await params.searchSemantic(vector, {
|
|
943
|
+
limit: 12,
|
|
944
|
+
minScore: .1,
|
|
945
|
+
projectIdFilter: [params.scope]
|
|
946
|
+
});
|
|
947
|
+
if (payload.kind === "combined-legacy") {
|
|
948
|
+
const topMatch = existing[0];
|
|
949
|
+
if (topMatch && topMatch.score > dedupeThreshold) continue;
|
|
950
|
+
}
|
|
951
|
+
if (hasDuplicateReflectionPayload(payload, existing)) continue;
|
|
952
|
+
const stored = await params.store({
|
|
953
|
+
text: payload.text,
|
|
954
|
+
category: categoryForPayload(payload.kind),
|
|
955
|
+
projectId: params.scope,
|
|
956
|
+
importance: resolveReflectionImportance(payload.kind),
|
|
957
|
+
metadata: metadataForPayload(payload, params.runAt, params.writerAgentId),
|
|
958
|
+
timestamp: params.runAt
|
|
959
|
+
});
|
|
960
|
+
storedKinds.push(payload.kind);
|
|
961
|
+
if (payload.kind === "item-derived" && stored.factId) derivedSources.push({
|
|
962
|
+
line: payload.text,
|
|
963
|
+
rowId: stored.id,
|
|
964
|
+
factId: stored.factId,
|
|
965
|
+
sourceAgentId: params.agentId,
|
|
966
|
+
memoryKind: stored.category ?? categoryForPayload(payload.kind),
|
|
967
|
+
projectId: stored.projectId ?? params.scope,
|
|
968
|
+
rank: derivedSources.length + 1,
|
|
969
|
+
score: resolveReflectionImportance(payload.kind)
|
|
970
|
+
});
|
|
971
|
+
}
|
|
972
|
+
return {
|
|
973
|
+
stored: storedKinds.length > 0,
|
|
974
|
+
eventId,
|
|
975
|
+
slices,
|
|
976
|
+
storedKinds,
|
|
977
|
+
derivedSources
|
|
978
|
+
};
|
|
979
|
+
}
|
|
980
|
+
function categoryForPayload(kind) {
|
|
981
|
+
return kind === "episodic-reflection" ? "episodic" : "lesson";
|
|
982
|
+
}
|
|
983
|
+
function metadataForPayload(payload, runAt, writerAgentId) {
|
|
984
|
+
const category = categoryForPayload(payload.kind);
|
|
985
|
+
const metadataPatch = {
|
|
986
|
+
...payload.metadata,
|
|
987
|
+
...writerAgentId ? { writer_agent_id: writerAgentId } : {},
|
|
988
|
+
...category === "lesson" ? { anti_pattern_signature: buildReflectionAntiPatternSignature(payload.kind === "combined-legacy" ? "combined-legacy" : "reflection-item", payload.text) } : { event_at: new Date(runAt).toISOString() }
|
|
989
|
+
};
|
|
990
|
+
return stringifyInsightMetadata(buildInsightMetadata({
|
|
991
|
+
text: payload.text,
|
|
992
|
+
category,
|
|
993
|
+
timestamp: runAt
|
|
994
|
+
}, metadataPatch));
|
|
995
|
+
}
|
|
996
|
+
function resolveReflectionImportance(kind) {
|
|
997
|
+
if (kind === "episodic-reflection") return .55;
|
|
998
|
+
if (kind === "item-invariant") return .82;
|
|
999
|
+
if (kind === "item-derived") return .78;
|
|
1000
|
+
return .75;
|
|
1001
|
+
}
|
|
1002
|
+
function hasDuplicateReflectionPayload(payload, matches) {
|
|
1003
|
+
if (payload.kind === "combined-legacy") return false;
|
|
1004
|
+
return matches.some((match) => {
|
|
1005
|
+
const existingMetadata = parseReflectionMetadata(match.entry.metadata);
|
|
1006
|
+
if (payload.kind === "episodic-reflection") {
|
|
1007
|
+
const eventMetadata = payload.metadata;
|
|
1008
|
+
return existingMetadata.type === "memory-reflection-event" && existingMetadata.sessionKey === eventMetadata.sessionKey && existingMetadata.sessionId === eventMetadata.sessionId && existingMetadata.agentId === eventMetadata.agentId && existingMetadata.command === eventMetadata.command;
|
|
1009
|
+
}
|
|
1010
|
+
const itemMetadata = payload.metadata;
|
|
1011
|
+
return existingMetadata.type === "memory-reflection-item" && existingMetadata.sessionId === itemMetadata.sessionId && existingMetadata.agentId === itemMetadata.agentId && existingMetadata.itemKind === itemMetadata.itemKind && match.entry.text === payload.text;
|
|
1012
|
+
});
|
|
1013
|
+
}
|
|
1014
|
+
//#endregion
|
|
1015
|
+
export { loadAgentReflectionSlicesFromEntries as a, buildReflectionMappedMetadata as i, createReflectionEventId as n, extractInjectableReflectionMappedMemoryItems as o, buildReflectionAntiPatternSignature as r, extractReflectionLearningGovernanceCandidates as s, storeReflectionEntries as t };
|