@remnic/core 9.3.717 → 9.3.719
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/dist/access-boundary.d.ts +5 -5
- package/dist/access-boundary.js +9 -9
- package/dist/access-cli.js +23 -23
- package/dist/access-http.d.ts +5 -5
- package/dist/access-http.js +13 -13
- package/dist/access-mcp.d.ts +5 -5
- package/dist/access-mcp.js +12 -12
- package/dist/access-operations-batch.js +10 -10
- package/dist/access-operations.d.ts +5 -5
- package/dist/access-operations.js +11 -11
- package/dist/{access-service-d4Tk-Dlr.d.ts → access-service-CZbnt0t2.d.ts} +3 -3
- package/dist/access-service.d.ts +5 -5
- package/dist/access-service.js +8 -8
- package/dist/access-surface-catalog.d.ts +5 -5
- package/dist/action-confidence.d.ts +1 -1
- package/dist/active-memory-bridge.d.ts +1 -1
- package/dist/active-recall.d.ts +1 -1
- package/dist/active-recall.js +1 -1
- package/dist/behavior-learner.d.ts +1 -1
- package/dist/behavior-signals.d.ts +1 -1
- package/dist/bootstrap.d.ts +4 -4
- package/dist/briefing.d.ts +3 -1
- package/dist/briefing.js +3 -3
- package/dist/buffer-surprise-report.d.ts +1 -1
- package/dist/buffer.d.ts +1 -1
- package/dist/calibration.d.ts +1 -1
- package/dist/capabilities.d.ts +1 -1
- package/dist/{catalog-CbR0CsUw.d.ts → catalog-CEYlMs9X.d.ts} +1 -1
- package/dist/causal-behavior.d.ts +1 -1
- package/dist/causal-consolidation.d.ts +1 -1
- package/dist/causal-consolidation.js +4 -4
- package/dist/{chunk-JEIROMLX.js → chunk-2COL35PK.js} +95 -9
- package/dist/chunk-2COL35PK.js.map +1 -0
- package/dist/{chunk-XZTUMWKQ.js → chunk-2PTBLS2S.js} +2 -2
- package/dist/{chunk-2Y6LMOQQ.js → chunk-2VHMVWPU.js} +2 -2
- package/dist/{chunk-6UU43ZGD.js → chunk-4KZGLDJJ.js} +2 -2
- package/dist/{chunk-K44MIN6D.js → chunk-5RHM43BJ.js} +3 -3
- package/dist/{chunk-2B43BYYZ.js → chunk-72VDBALG.js} +18 -18
- package/dist/{chunk-UY4JMEAK.js → chunk-7EEVXW7X.js} +2 -2
- package/dist/{chunk-XCTDHF7U.js → chunk-A5TUPZ3N.js} +33 -1
- package/dist/chunk-A5TUPZ3N.js.map +1 -0
- package/dist/{chunk-WI4QX7GH.js → chunk-A66YRSOS.js} +2 -2
- package/dist/{chunk-EM22PCQR.js → chunk-ANI5DUAE.js} +8 -6
- package/dist/{chunk-EM22PCQR.js.map → chunk-ANI5DUAE.js.map} +1 -1
- package/dist/{chunk-VZQXJNBD.js → chunk-APUJIMDM.js} +2 -2
- package/dist/{chunk-MPHDVHIB.js → chunk-DIFU33GU.js} +2 -2
- package/dist/{chunk-DXGS5YOQ.js → chunk-EH27LHML.js} +2 -2
- package/dist/{chunk-YAINYEM3.js → chunk-F3PVXKHP.js} +25 -1398
- package/dist/chunk-F3PVXKHP.js.map +1 -0
- package/dist/{chunk-DZYARLJ7.js → chunk-HLIR3RJ7.js} +2 -2
- package/dist/{chunk-6FUJ2VYY.js → chunk-JAKYZGV4.js} +3 -3
- package/dist/{chunk-ZAVTEQFM.js → chunk-JIZGYQYH.js} +3 -3
- package/dist/{chunk-QOIONSOI.js → chunk-KRGC4EDX.js} +2 -2
- package/dist/{chunk-AJOIM6UR.js → chunk-L5ASZA2F.js} +2 -2
- package/dist/{chunk-I56LKMF7.js → chunk-LXSG4L55.js} +2 -2
- package/dist/{chunk-MSVSP5VO.js → chunk-N3DUH6OO.js} +1 -1
- package/dist/chunk-N3DUH6OO.js.map +1 -0
- package/dist/{chunk-CTUWGJRI.js → chunk-NFRBADNR.js} +166 -28
- package/dist/chunk-NFRBADNR.js.map +1 -0
- package/dist/chunk-OJU73BUX.js +1688 -0
- package/dist/chunk-OJU73BUX.js.map +1 -0
- package/dist/{chunk-JVEMUX6L.js → chunk-OZ2KQ7HF.js} +2 -2
- package/dist/{chunk-OUDAU3T5.js → chunk-P5IPFZVH.js} +4 -4
- package/dist/{chunk-KHQ433G5.js → chunk-REWQAFSA.js} +2 -2
- package/dist/{chunk-V7GDTQ6I.js → chunk-S35FX6MU.js} +2 -2
- package/dist/{chunk-MTHNJCOJ.js → chunk-S3OPGGZB.js} +2 -2
- package/dist/{chunk-ZXLSNG3T.js → chunk-U5H7WHTS.js} +6 -4
- package/dist/{chunk-ZXLSNG3T.js.map → chunk-U5H7WHTS.js.map} +1 -1
- package/dist/{chunk-BZAK3RBN.js → chunk-UCJ5CDTK.js} +6 -6
- package/dist/{chunk-BF2426TN.js → chunk-URM3HW2R.js} +2 -2
- package/dist/{chunk-VO4UICII.js → chunk-YTZLBBEB.js} +2 -2
- package/dist/{chunk-OC56UWV5.js → chunk-YYOK4GVF.js} +2 -2
- package/dist/{cli-insNLYs6.d.ts → cli-1orcdXOY.d.ts} +3 -3
- package/dist/cli.d.ts +6 -6
- package/dist/cli.js +27 -27
- package/dist/compounding/engine.d.ts +1 -1
- package/dist/compounding/engine.js +3 -3
- package/dist/compounding/preference-consolidator.d.ts +1 -1
- package/dist/compression-optimizer.d.ts +1 -1
- package/dist/config.d.ts +1 -1
- package/dist/config.js +1 -1
- package/dist/connectors/codex-materialize-runner.d.ts +1 -1
- package/dist/connectors/codex-materialize-runner.js +3 -3
- package/dist/connectors/codex-materialize.d.ts +1 -1
- package/dist/connectors/index.d.ts +1 -1
- package/dist/connectors/index.js +3 -3
- package/dist/consolidation-provenance-check.d.ts +1 -1
- package/dist/consolidation-undo.d.ts +1 -1
- package/dist/contradiction/index.d.ts +1 -1
- package/dist/conversation-index/backend.d.ts +1 -1
- package/dist/conversation-index/chunker.d.ts +1 -1
- package/dist/conversation-index/faiss-adapter.d.ts +1 -1
- package/dist/conversation-index/indexer.d.ts +1 -1
- package/dist/conversation-index/search.d.ts +1 -1
- package/dist/day-summary.d.ts +1 -1
- package/dist/delinearize.d.ts +1 -1
- package/dist/direct-answer-wiring.d.ts +1 -1
- package/dist/direct-answer.d.ts +1 -1
- package/dist/embedding-fallback.d.ts +1 -1
- package/dist/enrichment/index.d.ts +1 -1
- package/dist/entity-retrieval.d.ts +1 -1
- package/dist/entity-retrieval.js +3 -3
- package/dist/entity-schema.d.ts +1 -1
- package/dist/explicit-capture.d.ts +4 -4
- package/dist/extraction-faithfulness.d.ts +1 -1
- package/dist/extraction-judge-telemetry.d.ts +1 -1
- package/dist/extraction-judge-training.d.ts +1 -1
- package/dist/extraction-judge.d.ts +1 -1
- package/dist/extraction.d.ts +1 -1
- package/dist/fallback-llm.d.ts +1 -1
- package/dist/identity-continuity.d.ts +1 -1
- package/dist/importance.d.ts +1 -1
- package/dist/index.d.ts +9 -9
- package/dist/index.js +33 -33
- package/dist/intent.d.ts +1 -1
- package/dist/lcm/engine.d.ts +1 -1
- package/dist/lcm/index.d.ts +1 -1
- package/dist/lcm/tools.d.ts +1 -1
- package/dist/lifecycle.d.ts +1 -1
- package/dist/live-connectors-runner.d.ts +1 -1
- package/dist/local-llm.d.ts +1 -1
- package/dist/maintenance/memory-governance.d.ts +1 -1
- package/dist/maintenance/memory-governance.js +3 -3
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +3 -3
- package/dist/maintenance/rebuild-memory-projection.js +4 -4
- package/dist/mcp-memory-inspector-app.d.ts +5 -5
- package/dist/memory-action-policy.d.ts +1 -1
- package/dist/memory-cache.d.ts +1 -1
- package/dist/memory-lifecycle-ledger-utils.d.ts +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/memory-provenance.d.ts +1 -1
- package/dist/memory-worth-outcomes.d.ts +1 -1
- package/dist/models-json.d.ts +1 -1
- package/dist/namespaces/migrate.d.ts +2 -2
- package/dist/namespaces/migrate.js +4 -4
- package/dist/namespaces/principal.d.ts +1 -1
- package/dist/namespaces/search.d.ts +1 -1
- package/dist/namespaces/storage.d.ts +2 -2
- package/dist/namespaces/storage.js +3 -3
- package/dist/native-knowledge.d.ts +1 -1
- package/dist/operator-toolkit.d.ts +1 -1
- package/dist/operator-toolkit.js +9 -9
- package/dist/orchestration/maintenance.d.ts +2 -2
- package/dist/orchestration/maintenance.js +5 -5
- package/dist/{orchestrator-XPKhY2OV.d.ts → orchestrator-kOxredSr.d.ts} +20 -3
- package/dist/orchestrator.d.ts +4 -4
- package/dist/orchestrator.js +16 -16
- package/dist/patterns-cli.d.ts +1 -1
- package/dist/policy-runtime.d.ts +1 -1
- package/dist/provenance.d.ts +1 -1
- package/dist/qmd-recall-cache.d.ts +1 -1
- package/dist/qmd.d.ts +1 -1
- package/dist/recall-disclosure-escalation.d.ts +1 -1
- package/dist/recall-explain-renderer.d.ts +1 -1
- package/dist/recall-explain-renderer.js +3 -3
- package/dist/recall-planner-llm.d.ts +1 -1
- package/dist/recall-state.d.ts +1 -1
- package/dist/recall-tag-filter.d.ts +1 -1
- package/dist/recall-xray-cli.d.ts +1 -1
- package/dist/recall-xray-cli.js +4 -4
- package/dist/recall-xray-renderer.d.ts +1 -1
- package/dist/recall-xray-renderer.js +3 -3
- package/dist/recall-xray.d.ts +1 -1
- package/dist/recall-xray.js +2 -2
- package/dist/resolve-auth-token.d.ts +1 -1
- package/dist/resume-bundles.js +2 -2
- package/dist/retrieval-agents.d.ts +1 -1
- package/dist/retrieval-tiers.d.ts +1 -1
- package/dist/routing/engine.d.ts +1 -1
- package/dist/routing/store.d.ts +1 -1
- package/dist/schemas.d.ts +22 -22
- package/dist/search/embed-helper.d.ts +1 -1
- package/dist/search/factory.d.ts +1 -1
- package/dist/search/index.d.ts +1 -1
- package/dist/search/lancedb-backend.d.ts +1 -1
- package/dist/search/meilisearch-backend.d.ts +1 -1
- package/dist/search/noop-backend.d.ts +1 -1
- package/dist/search/orama-backend.d.ts +1 -1
- package/dist/search/port.d.ts +1 -1
- package/dist/search/remote-backend.d.ts +1 -1
- package/dist/{semantic-consolidation-DSjMDZ1u.d.ts → semantic-consolidation-B58v3S-a.d.ts} +1 -1
- package/dist/semantic-consolidation.d.ts +2 -2
- package/dist/semantic-consolidation.js +4 -4
- package/dist/semantic-rule-promotion.js +3 -3
- package/dist/semantic-rule-verifier.d.ts +1 -1
- package/dist/semantic-rule-verifier.js +3 -3
- package/dist/session-observer-bands.d.ts +1 -1
- package/dist/session-observer-state.d.ts +1 -1
- package/dist/shared-context/manager.d.ts +1 -1
- package/dist/signal.d.ts +1 -1
- package/dist/storage.d.ts +1 -1
- package/dist/storage.js +2 -2
- package/dist/summarizer.d.ts +1 -1
- package/dist/summary-snapshot.d.ts +1 -1
- package/dist/temporal-supersession.d.ts +1 -1
- package/dist/temporal-validity.d.ts +1 -1
- package/dist/threading.d.ts +1 -1
- package/dist/tier-migration.d.ts +1 -1
- package/dist/tier-routing.d.ts +1 -1
- package/dist/topics.d.ts +1 -1
- package/dist/transcript.d.ts +1 -1
- package/dist/transfer/types.d.ts +12 -12
- package/dist/{types-D9dwzU_x.d.ts → types-ACmDOScJ.d.ts} +36 -0
- package/dist/types.d.ts +1 -1
- package/dist/types.js +1 -1
- package/dist/utility-runtime.d.ts +1 -1
- package/dist/verified-recall.js +3 -3
- package/package.json +2 -2
- package/src/briefing.ts +32 -0
- package/src/config.ts +32 -0
- package/src/correction/index.ts +24 -0
- package/src/correction/passive-capture.test.ts +500 -0
- package/src/correction/passive-capture.ts +335 -0
- package/src/correction/passive-correction-detector.test.ts +263 -0
- package/src/correction/passive-correction-detector.ts +325 -0
- package/src/correction/passive-correction-notifications.ts +123 -0
- package/src/orchestrator.ts +196 -12
- package/src/types.ts +36 -0
- package/dist/chunk-2KF4HDG2.js +0 -24
- package/dist/chunk-2KF4HDG2.js.map +0 -1
- package/dist/chunk-CTUWGJRI.js.map +0 -1
- package/dist/chunk-JEIROMLX.js.map +0 -1
- package/dist/chunk-MSVSP5VO.js.map +0 -1
- package/dist/chunk-XCTDHF7U.js.map +0 -1
- package/dist/chunk-YAINYEM3.js.map +0 -1
- /package/dist/{chunk-XZTUMWKQ.js.map → chunk-2PTBLS2S.js.map} +0 -0
- /package/dist/{chunk-2Y6LMOQQ.js.map → chunk-2VHMVWPU.js.map} +0 -0
- /package/dist/{chunk-6UU43ZGD.js.map → chunk-4KZGLDJJ.js.map} +0 -0
- /package/dist/{chunk-K44MIN6D.js.map → chunk-5RHM43BJ.js.map} +0 -0
- /package/dist/{chunk-2B43BYYZ.js.map → chunk-72VDBALG.js.map} +0 -0
- /package/dist/{chunk-UY4JMEAK.js.map → chunk-7EEVXW7X.js.map} +0 -0
- /package/dist/{chunk-WI4QX7GH.js.map → chunk-A66YRSOS.js.map} +0 -0
- /package/dist/{chunk-VZQXJNBD.js.map → chunk-APUJIMDM.js.map} +0 -0
- /package/dist/{chunk-MPHDVHIB.js.map → chunk-DIFU33GU.js.map} +0 -0
- /package/dist/{chunk-DXGS5YOQ.js.map → chunk-EH27LHML.js.map} +0 -0
- /package/dist/{chunk-DZYARLJ7.js.map → chunk-HLIR3RJ7.js.map} +0 -0
- /package/dist/{chunk-6FUJ2VYY.js.map → chunk-JAKYZGV4.js.map} +0 -0
- /package/dist/{chunk-ZAVTEQFM.js.map → chunk-JIZGYQYH.js.map} +0 -0
- /package/dist/{chunk-QOIONSOI.js.map → chunk-KRGC4EDX.js.map} +0 -0
- /package/dist/{chunk-AJOIM6UR.js.map → chunk-L5ASZA2F.js.map} +0 -0
- /package/dist/{chunk-I56LKMF7.js.map → chunk-LXSG4L55.js.map} +0 -0
- /package/dist/{chunk-JVEMUX6L.js.map → chunk-OZ2KQ7HF.js.map} +0 -0
- /package/dist/{chunk-OUDAU3T5.js.map → chunk-P5IPFZVH.js.map} +0 -0
- /package/dist/{chunk-KHQ433G5.js.map → chunk-REWQAFSA.js.map} +0 -0
- /package/dist/{chunk-V7GDTQ6I.js.map → chunk-S35FX6MU.js.map} +0 -0
- /package/dist/{chunk-MTHNJCOJ.js.map → chunk-S3OPGGZB.js.map} +0 -0
- /package/dist/{chunk-BZAK3RBN.js.map → chunk-UCJ5CDTK.js.map} +0 -0
- /package/dist/{chunk-BF2426TN.js.map → chunk-URM3HW2R.js.map} +0 -0
- /package/dist/{chunk-VO4UICII.js.map → chunk-YTZLBBEB.js.map} +0 -0
- /package/dist/{chunk-OC56UWV5.js.map → chunk-YYOK4GVF.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/briefing.ts"],"sourcesContent":["/**\n * Daily Context Briefing (Issue #370)\n *\n * Produces a focused \"here is what matters right now\" briefing by\n * cross-referencing active entities, recent facts, open commitments,\n * LLM-generated follow-ups, and an optional calendar source.\n *\n * The module exposes:\n * - `parseBriefingWindow(token)` — CLI-friendly window parser.\n * - `buildBriefing(options)` — core builder that returns markdown + JSON.\n * - `FileCalendarSource` — stub CalendarSource implementation that reads\n * a local ICS or JSON file.\n *\n * ALL OpenAI usage in this module goes through the Responses API. Chat\n * Completions is never used.\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport { extractJsonCandidates } from \"./json-extract.js\";\nimport { normalizeEntityName, StorageManager } from \"./storage.js\";\nimport { readEnvVar, resolveHomeDir } from \"./runtime/env.js\";\nimport type {\n BriefingActiveThread,\n BriefingCalendarSourceError,\n BriefingFocus,\n BriefingFollowup,\n BriefingOpenCommitment,\n BriefingRecentEntity,\n BriefingResult,\n BriefingSections,\n CalendarEvent,\n CalendarSource,\n EntityFile,\n MemoryFile,\n} from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────────\n// Window parsing\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Allowed values for the briefing format flag/field. */\nexport const BRIEFING_FORMAT_ALLOWED = [\"markdown\", \"json\"] as const;\n\n/**\n * Default model used for the Responses API follow-up generation call.\n * Mirrors the extraction engine default in config.ts — keep in sync.\n */\nexport const BRIEFING_FOLLOWUP_DEFAULT_MODEL = \"gpt-5.5\";\nexport type BriefingFormatValue = typeof BRIEFING_FORMAT_ALLOWED[number];\n\n/**\n * Validate a user-supplied `--format` flag value.\n * Returns `null` when the value is valid (or `undefined`, meaning the flag\n * was not supplied and the caller should fall back to the configured default).\n * Returns an error message string when the value is explicitly invalid.\n */\nexport function validateBriefingFormat(value: string | undefined): string | null {\n if (value === undefined) return null;\n if ((BRIEFING_FORMAT_ALLOWED as readonly string[]).includes(value)) return null;\n return `Invalid --format value: \"${value}\". Accepted: ${BRIEFING_FORMAT_ALLOWED.join(\", \")}.`;\n}\n\n/** Parsed briefing lookback window. */\nexport interface ParsedBriefingWindow {\n /** Start of the window (inclusive). */\n from: Date;\n /** End of the window (exclusive). */\n to: Date;\n /** Human-readable label. */\n label: string;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/**\n * Maximum allowed lookback offset in milliseconds (100 years).\n * Anything beyond this is almost certainly a typo or abuse — and would\n * overflow to `Invalid Date` for sufficiently large values anyway.\n */\nconst MAX_WINDOW_MS = 100 * 365 * DAY_MS;\n\n/**\n * Parse a CLI-friendly window token into a concrete date range.\n *\n * Accepted forms (case-insensitive):\n * - `yesterday` — the previous UTC calendar day.\n * - `today` — the current UTC calendar day so far.\n * - `NNh` — last N hours (e.g. `24h`, `48h`).\n * - `NNd` — last N calendar days (e.g. `3d`, `7d`).\n * - `NNw` — last N weeks (e.g. `1w`, `2w`).\n *\n * Returns `null` for invalid tokens so callers can surface a clean error.\n */\nexport function parseBriefingWindow(\n token: string,\n now: Date = new Date(),\n): ParsedBriefingWindow | null {\n const raw = typeof token === \"string\" ? token.trim().toLowerCase() : \"\";\n if (raw.length === 0) return null;\n\n if (raw === \"yesterday\") {\n const startOfToday = startOfUtcDay(now);\n const from = new Date(startOfToday.getTime() - DAY_MS);\n return { from, to: startOfToday, label: \"yesterday\" };\n }\n\n if (raw === \"today\") {\n return { from: startOfUtcDay(now), to: now, label: \"today\" };\n }\n\n const match = raw.match(/^(\\d+)\\s*(h|d|w)$/);\n if (!match) return null;\n const value = parseInt(match[1], 10);\n if (!Number.isFinite(value) || value <= 0) return null;\n const unit = match[2];\n let ms = 0;\n if (unit === \"h\") ms = value * 60 * 60 * 1000;\n else if (unit === \"d\") ms = value * DAY_MS;\n else if (unit === \"w\") ms = value * 7 * DAY_MS;\n if (ms === 0) return null;\n // Reject values that exceed the 100-year cap or would overflow to Invalid Date.\n if (ms > MAX_WINDOW_MS || !Number.isFinite(ms)) return null;\n const from = new Date(now.getTime() - ms);\n if (!Number.isFinite(from.getTime())) return null;\n return {\n from,\n to: now,\n label: `last ${value}${unit}`,\n };\n}\n\nfunction startOfUtcDay(date: Date): Date {\n const d = new Date(date.getTime());\n d.setUTCHours(0, 0, 0, 0);\n return d;\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Focus filter\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Parse a CLI `--focus` string into a structured focus filter.\n *\n * Accepted forms:\n * - `person:Jane Doe`\n * - `project:remnic-core`\n * - `topic:retrieval`\n *\n * If no prefix is supplied, falls back to `topic:<value>`.\n */\nexport function parseBriefingFocus(token: string | undefined): BriefingFocus | null {\n if (typeof token !== \"string\") return null;\n const trimmed = token.trim();\n if (trimmed.length === 0) return null;\n const [maybeType, ...rest] = trimmed.split(\":\");\n if (rest.length === 0) {\n return { type: \"topic\", value: maybeType };\n }\n const rawType = maybeType.toLowerCase();\n if (rawType === \"person\" || rawType === \"project\" || rawType === \"topic\") {\n const value = rest.join(\":\").trim();\n if (value.length === 0) return null;\n return { type: rawType, value };\n }\n return { type: \"topic\", value: trimmed };\n}\n\n/**\n * Decide whether a memory/entity matches the given focus filter.\n * Purely deterministic — no LLM, case-insensitive substring match across\n * the most useful surfaces.\n *\n * For typed focus (`person:`, `project:`, `entity:`) we attribute via the\n * canonical-id path below to avoid the substring leak fixed in #682 PR 2/3\n * R-10 (`Alice-Test` substring-hitting `person-alice-test-a1`).\n *\n * For untyped (`topic`) focus there is no type to canonicalize against, so\n * we keep `entityRef` in the raw haystack — otherwise memories that link to\n * an entity only via `frontmatter.entityRef` (no body / tag mention) would\n * silently drop out of an untyped focus filter (codex P2 review on #695).\n */\nexport function focusMatchesMemory(\n memory: MemoryFile,\n focus: BriefingFocus,\n entityAliases?: Readonly<Record<string, string>>,\n): boolean {\n const needle = focus.value.toLowerCase();\n const entityRef = (memory.frontmatter.entityRef ?? \"\").toLowerCase();\n\n // Raw substring match across content and tags. For untyped (`topic`)\n // focus, also include the entityRef so memories linked only via the\n // frontmatter ref still match. For typed focus we deliberately\n // exclude entityRef here and route through the canonical-id path\n // below (see comment above).\n const rawHaystackParts = [\n memory.content,\n ...(memory.frontmatter.tags ?? []),\n ];\n if (focus.type === \"topic\" && entityRef) {\n rawHaystackParts.push(entityRef);\n }\n const rawHaystack = rawHaystackParts.join(\" \").toLowerCase();\n if (rawHaystack.includes(needle)) return true;\n\n // Canonical-id match (#682 PR 2/3 R-10). Normalize BOTH sides through\n // `normalizeEntityName` so:\n // - `entityRef === slug` exact comparison no longer fails when the\n // stored ref is in a non-canonical form (e.g. `person:Alice-Test`\n // vs. `person-alice-test`) — both normalize to the same canonical id.\n // - `entityRef.includes(slug)` substring matching is replaced by\n // equality, so similarly-prefixed entities like\n // `person-alice-test-a1` no longer match a focus on\n // `person:Alice-Test`.\n // This also handles the type-prefix-in-name case the cursor reviewer\n // flagged: `normalizeEntityName` strips a duplicate type prefix so\n // `Project-Alpha` of type `project` canonicalizes to `project-alpha`,\n // and a focus on `project:Project-Alpha` does the same.\n if (!entityRef) return false;\n const focusCanonical = normalizeEntityName(focus.value, focus.type, entityAliases);\n // Strip a leading `<type><delimiter>` prefix from a non-canonical\n // entityRef before normalizing — `normalizeEntityName` only strips\n // `<type>-` so other valid verbatim formats (`person:Alice-Test`,\n // `person/alice-test`, `person_alice_test`, `person Alice Test`)\n // would otherwise double up the type prefix and miss the canonical\n // comparison. Codex P2 review on #695: memory writes persist\n // entityRef strings as provided, so any non-alphanumeric delimiter\n // after the type token must be tolerated here.\n let refForNormalize = entityRef;\n const typeDelimMatch = refForNormalize.match(\n new RegExp(`^${focus.type}[^a-z0-9]+`, \"i\"),\n );\n if (typeDelimMatch) {\n refForNormalize = refForNormalize.slice(typeDelimMatch[0].length);\n }\n const refCanonical = normalizeEntityName(refForNormalize, focus.type, entityAliases);\n return refCanonical === focusCanonical;\n}\n\nexport function focusMatchesEntity(entity: EntityFile, focus: BriefingFocus): boolean {\n const needle = focus.value.toLowerCase();\n if (focus.type === \"person\" && entity.type.toLowerCase() !== \"person\") return false;\n if (focus.type === \"project\" && entity.type.toLowerCase() !== \"project\") return false;\n const haystack = [\n entity.name,\n entity.synthesis || entity.summary || \"\",\n ...entity.facts,\n ...(entity.aliases ?? []),\n ...(entity.structuredSections ?? []).flatMap((section) => [section.title, ...section.facts]),\n ]\n .join(\" \")\n .toLowerCase();\n return haystack.includes(needle);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Calendar source\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Stub `CalendarSource` backed by a single local file. Supports:\n * - JSON files containing an array of `CalendarEvent` records, OR a wrapper\n * `{ events: CalendarEvent[] }` object.\n * - Minimal ICS (`.ics`) files — extracts `VEVENT` blocks with `SUMMARY`,\n * `DTSTART`, `DTEND`, `LOCATION`, `DESCRIPTION`, `UID`.\n *\n * Real calendar integrations (Google, iCloud, Microsoft) can plug into the\n * same `CalendarSource` interface later.\n */\nexport class FileCalendarSource implements CalendarSource {\n constructor(private readonly filePath: string) {}\n\n async eventsForDate(dateIso: string): Promise<CalendarEvent[]> {\n let raw: string;\n try {\n raw = await readFile(this.filePath, \"utf-8\");\n } catch (err) {\n log.warn(`briefing: calendar source unreadable at ${this.filePath}: ${err}`);\n return [];\n }\n\n const events = this.filePath.toLowerCase().endsWith(\".ics\")\n ? parseIcsEvents(raw)\n : parseJsonEvents(raw);\n\n return events.filter((event) => eventFallsOnDate(event, dateIso));\n }\n}\n\nfunction parseJsonEvents(raw: string): CalendarEvent[] {\n try {\n const parsed = JSON.parse(raw) as unknown;\n const arr = Array.isArray(parsed)\n ? parsed\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { events?: unknown }).events)\n ? ((parsed as { events: unknown[] }).events)\n : [];\n const events: CalendarEvent[] = [];\n for (const entry of arr) {\n if (!entry || typeof entry !== \"object\") continue;\n const e = entry as Record<string, unknown>;\n const id = typeof e.id === \"string\" ? e.id : typeof e.uid === \"string\" ? e.uid : cryptoRandomId();\n const title = typeof e.title === \"string\" ? e.title : typeof e.summary === \"string\" ? e.summary : \"\";\n const start = typeof e.start === \"string\" ? e.start : typeof e.dtstart === \"string\" ? e.dtstart : \"\";\n if (!title || !start) continue;\n events.push({\n id,\n title,\n start,\n end: typeof e.end === \"string\" ? e.end : typeof e.dtend === \"string\" ? e.dtend : undefined,\n location: typeof e.location === \"string\" ? e.location : undefined,\n notes: typeof e.notes === \"string\" ? e.notes : typeof e.description === \"string\" ? e.description : undefined,\n });\n }\n return events;\n } catch (err) {\n log.warn(`briefing: calendar JSON parse failed: ${err}`);\n return [];\n }\n}\n\ninterface IcsParsedLine {\n property: string;\n params: Record<string, string>;\n value: string;\n}\n\n/**\n * Parse a single ICS content line into its property, parameters, and value.\n * Returns null if the line is not a well-formed property line.\n *\n * Example:\n * `DTSTART;TZID=America/New_York:20260411T233000`\n * → { property: \"DTSTART\", params: { TZID: \"America/New_York\" }, value: \"20260411T233000\" }\n */\nfunction parseIcsLine(line: string): IcsParsedLine | null {\n // Find the first `:` outside of any parameter value. Per RFC 5545 parameter\n // values may be quoted, but the minimal-parser use case here only needs to\n // handle unquoted TZID values.\n const colonIdx = line.indexOf(\":\");\n if (colonIdx <= 0) return null;\n const head = line.slice(0, colonIdx);\n const value = line.slice(colonIdx + 1).trim();\n // Head is of the form `PROPERTY[;PARAM=val[;PARAM=val]]`.\n const headParts = head.split(\";\");\n const property = headParts[0]!.toUpperCase();\n if (!/^[A-Z0-9-]+$/.test(property)) return null;\n const params: Record<string, string> = {};\n for (let i = 1; i < headParts.length; i++) {\n const segment = headParts[i]!;\n const eqIdx = segment.indexOf(\"=\");\n if (eqIdx <= 0) continue;\n const name = segment.slice(0, eqIdx).toUpperCase();\n let val = segment.slice(eqIdx + 1);\n // Strip surrounding quotes if present (RFC 5545 §3.1).\n if (val.startsWith('\"') && val.endsWith('\"') && val.length >= 2) {\n val = val.slice(1, -1);\n }\n params[name] = val;\n }\n return { property, params, value };\n}\n\ninterface IcsDateField {\n raw: string;\n params: Record<string, string>;\n}\n\n/** @internal — exported for testing only. */\nexport function parseIcsEvents(raw: string): CalendarEvent[] {\n const events: CalendarEvent[] = [];\n // RFC 5545 §3.1 line unfolding: a CRLF (now \\n) followed by a single\n // whitespace character (space or tab) is a fold — remove both characters\n // to join the continuation onto the preceding logical line. This MUST\n // happen after normalising CRLF → \\n and BEFORE splitting on \\n.\n const normalized = raw.replace(/\\r\\n/g, \"\\n\").replace(/\\n[ \\t]/g, \"\");\n const blocks = normalized.split(/BEGIN:VEVENT/i).slice(1);\n for (const block of blocks) {\n const endIdx = block.search(/END:VEVENT/i);\n const body = endIdx === -1 ? block : block.slice(0, endIdx);\n const simpleFields: Record<string, string> = {};\n const dateFields: Record<string, IcsDateField> = {};\n for (const line of body.split(\"\\n\")) {\n const parsed = parseIcsLine(line);\n if (!parsed) continue;\n const { property, params, value } = parsed;\n if (property === \"DTSTART\" || property === \"DTEND\") {\n if (dateFields[property] === undefined) {\n dateFields[property] = { raw: value, params };\n }\n } else if (simpleFields[property] === undefined) {\n simpleFields[property] = value;\n }\n }\n const title = simpleFields.SUMMARY;\n const dtstart = dateFields.DTSTART;\n if (!title || !dtstart) continue;\n const dtend = dateFields.DTEND;\n events.push({\n id: simpleFields.UID ?? cryptoRandomId(),\n title,\n start: normalizeIcsDate(dtstart.raw, dtstart.params),\n end: dtend ? normalizeIcsDate(dtend.raw, dtend.params) : undefined,\n location: simpleFields.LOCATION,\n notes: simpleFields.DESCRIPTION,\n });\n }\n return events;\n}\n\n/**\n * Normalise an ICS date/datetime value (optionally with a `TZID` parameter)\n * into an ISO 8601 string that downstream code can compare unambiguously.\n *\n * Behaviour:\n * - `20260411T150000Z` → `2026-04-11T15:00:00Z`\n * - `20260411` → `2026-04-11T00:00:00Z` (date-only events are day-boundaries)\n * - `20260411T150000` (floating, no Z, no TZID) → `2026-04-11T15:00:00` (floating)\n * - `20260411T233000` with `TZID=America/New_York` → `2026-04-12T03:30:00Z`\n * (applies the zone offset at that wallclock time; DST-aware via Intl)\n * - Unknown TZID falls back to UTC with a logged warning (conservative:\n * the event still appears, but on the UTC date).\n */\nfunction normalizeIcsDate(value: string, params: Record<string, string> = {}): string {\n // Date-time with explicit Z suffix (UTC).\n if (/^\\d{8}T\\d{6}Z$/.test(value)) {\n const y = value.slice(0, 4);\n const m = value.slice(4, 6);\n const d = value.slice(6, 8);\n const hh = value.slice(9, 11);\n const mm = value.slice(11, 13);\n const ss = value.slice(13, 15);\n return `${y}-${m}-${d}T${hh}:${mm}:${ss}Z`;\n }\n // Date-time without Z: may be floating or zoned via TZID.\n if (/^\\d{8}T\\d{6}$/.test(value)) {\n const y = value.slice(0, 4);\n const m = value.slice(4, 6);\n const d = value.slice(6, 8);\n const hh = value.slice(9, 11);\n const mm = value.slice(11, 13);\n const ss = value.slice(13, 15);\n const local = `${y}-${m}-${d}T${hh}:${mm}:${ss}`;\n const tzid = params.TZID;\n if (tzid) {\n const utcIso = icsWallclockToUtc(local, tzid);\n if (utcIso) return utcIso;\n log.warn(\n `briefing: unsupported TZID \"${tzid}\" — treating as UTC for ${local}`,\n );\n return `${local}Z`;\n }\n // No TZID → floating. Downstream compares the date slice directly.\n return local;\n }\n // Date-only (all-day event). Date-only values carry no TZID per RFC 5545.\n if (/^\\d{8}$/.test(value)) {\n return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}T00:00:00Z`;\n }\n return value;\n}\n\n/**\n * Convert a wallclock local datetime in a named IANA timezone to a UTC ISO\n * string. Returns null if the timezone is unsupported by the runtime.\n *\n * Implementation note: this is the standard \"invert the formatter\" technique.\n * We treat the local wallclock as though it were UTC, ask the runtime what\n * time that instant shows in the target zone, and the delta is the zone's\n * offset at that wallclock moment (DST-aware).\n */\nfunction icsWallclockToUtc(local: string, tzid: string): string | null {\n const match = local.match(/^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})$/);\n if (!match) return null;\n const [, y, mo, d, hh, mm, ss] = match;\n // Treat the wallclock as UTC for the first probe.\n const naiveUtcMs = Date.UTC(\n Number(y),\n Number(mo) - 1,\n Number(d),\n Number(hh),\n Number(mm),\n Number(ss),\n );\n if (!Number.isFinite(naiveUtcMs)) return null;\n\n let formatter: Intl.DateTimeFormat;\n try {\n formatter = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: tzid,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hour12: false,\n });\n } catch {\n return null;\n }\n\n const zonedMs = zonedFormatToMs(formatter, new Date(naiveUtcMs));\n if (zonedMs === null) return null;\n // Offset = naiveUtc − zonedAtNaiveUtc (positive for zones east of UTC).\n const offsetMs = naiveUtcMs - zonedMs;\n // Apply the offset once to land on the real UTC instant.\n const realUtcMs = naiveUtcMs + offsetMs;\n // Second pass: offsets can differ when the wallclock crosses a DST boundary.\n const zonedMs2 = zonedFormatToMs(formatter, new Date(realUtcMs));\n if (zonedMs2 !== null) {\n const offsetMs2 = realUtcMs - zonedMs2;\n if (offsetMs2 !== offsetMs) {\n return new Date(naiveUtcMs + offsetMs2).toISOString();\n }\n }\n return new Date(realUtcMs).toISOString();\n}\n\n/**\n * Format a Date in the given timezone and return the absolute ms timestamp\n * of that wallclock time interpreted as if it were UTC. Used only by\n * `icsWallclockToUtc` to compute zone offsets.\n */\nfunction zonedFormatToMs(formatter: Intl.DateTimeFormat, date: Date): number | null {\n const parts = formatter.formatToParts(date);\n const get = (type: string): string | undefined =>\n parts.find((p) => p.type === type)?.value;\n const y = get(\"year\");\n const mo = get(\"month\");\n const d = get(\"day\");\n const hh = get(\"hour\");\n const mm = get(\"minute\");\n const ss = get(\"second\");\n if (!y || !mo || !d || !hh || !mm || !ss) return null;\n // RFC 5545 / Intl edge-case: some runtimes return `hour: \"24\"` for midnight\n // while keeping the same calendar day (instead of returning hour=0 with the\n // next day). Passing 24 straight to Date.UTC would roll the date forward by\n // one day, producing a 24-hour-skewed offset in icsWallclockToUtc and\n // shifting TZID midnight events to the wrong briefing day. Normalise to 0\n // and leave the date component unchanged.\n const normalizedHour = Number(hh) === 24 ? 0 : Number(hh);\n const ms = Date.UTC(Number(y), Number(mo) - 1, Number(d), normalizedHour, Number(mm), Number(ss));\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * Returns true when `isoStr` has an explicit UTC or numeric offset suffix\n * (Z, ±HH:MM, or ±HHMM). Floating datetimes produced by `normalizeIcsDate`\n * have no such suffix.\n */\nfunction isoHasTimezone(isoStr: string): boolean {\n return /(Z|[+-]\\d{2}:?\\d{2})$/.test(isoStr);\n}\n\n/**\n * Parse an ISO datetime string (UTC-aware or floating) to milliseconds since\n * epoch, or `null` if the string is not a valid datetime.\n *\n * - UTC / offset-aware strings are passed directly to `new Date()`.\n * - Floating strings (no timezone suffix) are interpreted as UTC so that\n * interval arithmetic uses the same epoch base as UTC-aware strings.\n * The caller is responsible for using the correct date-boundary constants.\n */\nfunction isoToMs(isoStr: string): number | null {\n if (!isoStr) return null;\n let src = isoStr;\n if (!isoHasTimezone(src)) {\n // Treat floating time as UTC for interval math (append Z).\n src = src + \"Z\";\n }\n const ms = new Date(src).getTime();\n return Number.isFinite(ms) ? ms : null;\n}\n\n/** @internal — exported for testing only. */\nexport function eventFallsOnDate(event: CalendarEvent, dateIso: string): boolean {\n const target = dateIso.slice(0, 10);\n const start = event.start;\n\n // Floating ICS datetime (no Z, no offset): `normalizeIcsDate` produces\n // \"YYYY-MM-DDTHH:MM:SS\" with no timezone. Passing this to `new Date()`\n // causes ECMAScript to parse it as local time, which then round-trips\n // through UTC via `toISOString()` and can shift the calendar date.\n // For floating times we compare date portions directly (no epoch arithmetic).\n const startIsFloating = !isoHasTimezone(start);\n\n if (startIsFloating) {\n // Validate the start timestamp with the same rigour applied to end:\n // 1. Shape check — must match the ISO-8601 date or datetime pattern.\n // 2. Real-date check — round-trip through UTC to reject impossible dates\n // like \"2026-02-30\" that JavaScript silently auto-corrects.\n // 3. Time-component check — reject out-of-range hours/minutes/seconds\n // (e.g. \"2026-04-11T25:99:00\") that JavaScript rolls over to a\n // different day, which would cause the event to be matched against\n // unrelated calendar dates.\n // If start fails any check we skip the event entirely — there is no usable\n // start date to fall back on.\n const startShapeOk =\n typeof start === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?)?$/.test(start);\n if (!startShapeOk) {\n log.debug(`briefing: skipping calendar event with invalid start value: ${JSON.stringify(start)}`);\n return false;\n }\n const startDateStr = start.slice(0, 10);\n const startDateProbe = new Date(startDateStr + \"T00:00:00Z\");\n if (\n Number.isNaN(startDateProbe.getTime()) ||\n startDateProbe.toISOString().slice(0, 10) !== startDateStr\n ) {\n log.warn(\n `briefing: skipping calendar event \"${event.title}\" with impossible start date ${JSON.stringify(startDateStr)}`,\n );\n return false;\n }\n const startRawTime = start.indexOf(\"T\") !== -1 ? start.slice(start.indexOf(\"T\") + 1) : \"\";\n if (startRawTime !== \"\") {\n const startTimeParts = startRawTime.split(\":\").map(Number);\n const shh = startTimeParts[0] ?? 0;\n const smm = startTimeParts[1] ?? 0;\n const sss = Math.floor(startTimeParts[2] ?? 0);\n if (shh > 23 || smm > 59 || sss > 59) {\n log.warn(\n `briefing: skipping calendar event \"${event.title}\" with out-of-range start time ${JSON.stringify(startRawTime)}`,\n );\n return false;\n }\n }\n\n const startDate = startDateStr;\n const end = event.end;\n\n // Point event (no end) — simple date prefix comparison.\n if (!end) return startDate === target;\n\n // Validate that end is a recognisable ISO-8601 date/datetime string before\n // slicing it for lexicographic comparison. A malformed end (e.g. a JSON\n // feed emitting \"end\": \"invalid\") would otherwise produce a non-date prefix\n // from `end.slice(0, 10)` and cause the event to appear on unrelated days.\n // Fallback: treat the event as a single-day event starting on startDate.\n const endIsValid =\n typeof end === \"string\" &&\n /^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?)?$/.test(end);\n if (!endIsValid) {\n log.warn(\n `briefing: event \"${event.title}\" has malformed end timestamp ${JSON.stringify(end)}; treating as single-day event at ${startDate}`,\n );\n // Render the event but only on its start date.\n return startDate === target;\n }\n\n // UhLh: Reject impossible calendar dates that pass the regex (e.g. \"2026-99-99\").\n // The regex only validates the *shape* of the string — it accepts month 99 and\n // day 99. We must additionally verify the date is real by constructing a UTC\n // Date and checking that the ISO round-trip matches the input prefix. If the\n // date is impossible, Date will auto-correct it (e.g. \"2026-01-99\" becomes some\n // later date), so the round-trip will differ. Fall back to single-day semantics.\n const endDate = end.slice(0, 10);\n const endDateProbe = new Date(endDate + \"T00:00:00Z\");\n if (\n Number.isNaN(endDateProbe.getTime()) ||\n endDateProbe.toISOString().slice(0, 10) !== endDate\n ) {\n log.warn(\n `briefing: event \"${event.title}\" has impossible end date ${JSON.stringify(endDate)}; treating as single-day event at ${startDate}`,\n );\n return startDate === target;\n }\n\n // Validate the time components of the end timestamp when present.\n // The regex above only checks the shape (e.g. two digits for hour) but does\n // not enforce numeric ranges. A value like \"2026-04-11T25:99:99\" passes the\n // regex and the date-round-trip check above yet carries an impossible time.\n // JavaScript's Date constructor silently rolls such values over to a later\n // date, which would make the event bleed into unrelated days. Extract the\n // individual time fields and reject anything outside the valid range.\n const rawTime = end.indexOf(\"T\") !== -1 ? end.slice(end.indexOf(\"T\") + 1) : \"\";\n if (rawTime !== \"\") {\n const timeParts = rawTime.split(\":\").map(Number);\n const hh = timeParts[0] ?? 0;\n const mm = timeParts[1] ?? 0;\n // Seconds may carry a fractional component; floor to get the integer part.\n const ss = Math.floor(timeParts[2] ?? 0);\n const timeIsValid = hh <= 23 && mm <= 59 && ss <= 59;\n if (!timeIsValid) {\n log.warn(\n `briefing: event \"${event.title}\" has out-of-range end time ${JSON.stringify(rawTime)}; treating as single-day event at ${startDate}`,\n );\n return startDate === target;\n }\n }\n\n // Span event: include if [start, end) overlaps the target calendar day.\n //\n // We can't use pure YYYY-MM-DD lexicographic comparison because a\n // same-day event (`start=2026-04-11T14:30`, `end=2026-04-11T15:00`)\n // has `startDate === endDate === \"2026-04-11\"`, and a `target < endDate`\n // check would wrongly exclude it. A cross-day event ending at\n // `2026-04-12T00:00:00` (exact midnight) also needs the end day to be\n // treated as exclusive per half-open `[start, end)` semantics.\n //\n // Decide whether the end day is still active on the end date by looking\n // at the time portion: if the end time is strictly after midnight, the\n // event is still running at the start of the end day and should include\n // it; if the end time is exactly midnight, the event ends precisely at\n // the boundary and the end day is excluded. Within-day spans always\n // have a non-zero end time and so correctly include their own date.\n //\n // UhLg: A date-only end value (no \"T\" separator) produces an empty\n // endTime string. The regex above does not match empty string, so\n // endAtExactMidnight would be false and the event would incorrectly\n // appear on the end date. Date-only end values carry [start, end)\n // semantics (the end date is exclusive), so we treat them as midnight.\n const endTime = end.slice(11); // \"HH:MM\", \"HH:MM:SS\", \"HH:MM:SS.mmm\", or \"\" (date-only)\n // Treat any end time that is exactly midnight — or absent (date-only) — as\n // day-exclusive per [start, end) semantics.\n // Cases covered:\n // \"\" — date-only end (UhLg fix: exclusive like midnight)\n // \"00:00\" — HH:MM form (valid floating-time ISO value, no seconds)\n // \"00:00:00\" — HH:MM:SS form\n // \"00:00:00.000...\" — with fractional seconds (any number of trailing zeros)\n // A bare `>` string comparison incorrectly treats \"00:00:00.000\" as > \"00:00:00\"\n // because the fractional suffix makes the string lexicographically longer.\n const endIsDateOnly = endTime === \"\";\n const endAtExactMidnight = endIsDateOnly || /^00(:00){1,2}(\\.0+)?$/.test(endTime);\n const endActiveOnEndDay = !endAtExactMidnight;\n if (endActiveOnEndDay) {\n return startDate <= target && target <= endDate;\n }\n return startDate <= target && target < endDate;\n }\n\n // UTC or offset-aware ISO string: parse and normalise to UTC milliseconds,\n // then check whether the event's [start, end) interval overlaps the target\n // UTC day [dayStart, dayEnd).\n const startMs = isoToMs(start);\n if (startMs === null) {\n log.debug(`briefing: skipping calendar event with invalid start value: ${JSON.stringify(start)}`);\n return false;\n }\n\n // Boundaries of the target UTC day (half-open: [dayStart, dayEnd)).\n const dayStart = Date.UTC(\n Number(target.slice(0, 4)),\n Number(target.slice(5, 7)) - 1,\n Number(target.slice(8, 10)),\n );\n const dayEnd = dayStart + 86_400_000; // +24 h\n\n const end = event.end;\n if (!end) {\n // Point event: included iff start falls within [dayStart, dayEnd).\n return startMs >= dayStart && startMs < dayEnd;\n }\n\n const endMs = isoToMs(end);\n if (endMs === null) {\n // Unparseable end — fall back to point-event semantics.\n return startMs >= dayStart && startMs < dayEnd;\n }\n\n // Interval event: overlaps day iff start < dayEnd AND end > dayStart.\n // Using strict > for end so that an event ending exactly at midnight\n // (dayEnd of previous day) is NOT counted on the next day.\n return startMs < dayEnd && endMs > dayStart;\n}\n\nfunction cryptoRandomId(): string {\n // Keep dependency-free: Math.random is fine for synthetic fixture IDs.\n return `evt-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// buildBriefing\n// ──────────────────────────────────────────────────────────────────────────\n\n/** Dependency-injection hook for LLM follow-up generation (used in tests). */\nexport type BriefingFollowupGenerator = (\n prompt: {\n sections: BriefingSections;\n windowLabel: string;\n maxFollowups: number;\n },\n) => Promise<BriefingFollowup[]>;\n\n/** Options accepted by `buildBriefing`. */\nexport interface BuildBriefingOptions {\n /** Workspace-scoped storage. Tests pass a temp dir. */\n storage: StorageManager;\n /** Parsed window. If omitted, a default 1-day window is used. */\n window?: ParsedBriefingWindow;\n /** Optional focus filter. */\n focus?: BriefingFocus | null;\n /** Optional namespace hint for logging. */\n namespace?: string;\n /** Calendar source. Section omitted entirely when undefined. */\n calendarSource?: CalendarSource;\n /** Maximum LLM follow-ups (0 to disable the section). */\n maxFollowups?: number;\n /** Whether the module is allowed to invoke the Responses API. */\n allowLlm?: boolean;\n /** OpenAI API key. If absent the follow-up section is gracefully omitted. */\n openaiApiKey?: string;\n /** OpenAI-compatible base URL (for Azure or proxied endpoints). */\n openaiBaseUrl?: string;\n /** Model id for the Responses call. */\n model?: string;\n /** Injected follow-up generator. Overrides real LLM call (tests). */\n followupGenerator?: BriefingFollowupGenerator;\n /** Injected \"now\" — makes tests deterministic. */\n now?: Date;\n}\n\nconst MAX_ACTIVE_THREADS = 8;\nconst MAX_RECENT_ENTITIES = 8;\nconst MAX_OPEN_COMMITMENTS = 8;\n\n/**\n * Build the daily context briefing.\n *\n * Never throws on LLM failures — the suggested follow-ups section is simply\n * omitted and `followupsUnavailableReason` is set.\n */\nexport async function buildBriefing(options: BuildBriefingOptions): Promise<BriefingResult> {\n const now = options.now ?? new Date();\n const window = options.window ?? defaultWindow(now);\n const maxFollowups = clampFollowups(options.maxFollowups);\n const focus = options.focus ?? null;\n\n const [allMemories, allEntities] = await Promise.all([\n safeReadMemories(options.storage),\n safeReadEntities(options.storage),\n ]);\n\n const memoriesInWindow = filterMemoriesByWindow(allMemories, window);\n const focusedMemories = focus\n ? memoriesInWindow.filter((m) => focusMatchesMemory(m, focus, options.storage.entityAliases))\n : memoriesInWindow;\n\n const activeThreads = buildActiveThreads(focusedMemories);\n const recentEntities = buildRecentEntities(allEntities, window, focus);\n // TODO(#370): openCommitments only covers memories inside the lookback window.\n // Still-open commitments (pending tag, commitment category) that pre-date the\n // window are silently omitted. A separate query over allMemories filtered to\n // open-status entries would surface these. Deferred to avoid scope creep here.\n const openCommitments = buildOpenCommitments(focusedMemories);\n\n const calendarLoadResult = options.calendarSource\n ? await loadTodayCalendar(options.calendarSource, now)\n : undefined;\n\n const calendarSourceErrors: BriefingCalendarSourceError[] =\n calendarLoadResult?.error ? [calendarLoadResult.error] : [];\n\n const sectionsBase: BriefingSections = {\n activeThreads,\n recentEntities,\n openCommitments,\n suggestedFollowups: [],\n todayCalendar: calendarLoadResult?.events,\n };\n\n let followups: BriefingFollowup[] = [];\n let followupsUnavailableReason: string | undefined;\n\n if (maxFollowups === 0 || options.allowLlm === false) {\n followupsUnavailableReason = \"LLM follow-ups disabled by configuration\";\n } else if (!options.openaiApiKey && !options.followupGenerator) {\n followupsUnavailableReason =\n 'no LLM configured for follow-ups (set OPENAI_API_KEY, enable a local LLM, or use modelSource \"gateway\")';\n } else {\n try {\n const generator = options.followupGenerator ?? buildOpenAiFollowupGenerator({\n apiKey: options.openaiApiKey!,\n model: options.model ?? BRIEFING_FOLLOWUP_DEFAULT_MODEL,\n baseURL: options.openaiBaseUrl,\n });\n const generated = await generator({\n sections: sectionsBase,\n windowLabel: window.label,\n maxFollowups,\n });\n followups = generated.slice(0, maxFollowups);\n } catch (err) {\n const errMsg = stringifyError(err);\n const modelName = options.model ?? BRIEFING_FOLLOWUP_DEFAULT_MODEL;\n // Detect \"model not found / invalid\" errors from the Responses API and\n // produce a user-friendly message that surfaces the problematic identifier.\n if (\n /model/i.test(errMsg) &&\n (/not found/i.test(errMsg) || /does not exist/i.test(errMsg) || /invalid/i.test(errMsg))\n ) {\n followupsUnavailableReason =\n `configured follow-up model '${modelName}' is not available in the Responses API`;\n } else {\n followupsUnavailableReason = `LLM follow-ups failed: ${errMsg}`;\n }\n log.warn(`briefing: ${followupsUnavailableReason}`);\n }\n }\n\n const sections: BriefingSections = {\n ...sectionsBase,\n suggestedFollowups: followups,\n };\n\n const windowIso = { from: window.from.toISOString(), to: window.to.toISOString() };\n const markdown = renderBriefingMarkdown({\n sections,\n windowLabel: window.label,\n focus,\n followupsUnavailableReason,\n generatedAt: now,\n namespace: options.namespace,\n });\n\n const json: Record<string, unknown> = {\n generatedAt: now.toISOString(),\n window: windowIso,\n focus,\n namespace: options.namespace ?? null,\n sections,\n followupsUnavailableReason: followupsUnavailableReason ?? null,\n calendarSourceErrors: calendarSourceErrors.length > 0 ? calendarSourceErrors : null,\n };\n\n const result: BriefingResult = {\n markdown,\n json,\n sections,\n followupsUnavailableReason,\n window: windowIso,\n };\n\n if (calendarSourceErrors.length > 0) {\n result.calendarSourceErrors = calendarSourceErrors;\n }\n\n return result;\n}\n\nfunction clampFollowups(value: number | undefined): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return 5;\n return Math.max(0, Math.min(10, Math.floor(value)));\n}\n\nfunction defaultWindow(now: Date): ParsedBriefingWindow {\n const parsed = parseBriefingWindow(\"yesterday\", now);\n if (parsed) return parsed;\n return { from: new Date(now.getTime() - DAY_MS), to: now, label: \"yesterday\" };\n}\n\nasync function safeReadMemories(storage: StorageManager): Promise<MemoryFile[]> {\n try {\n return await storage.readAllMemories();\n } catch (err) {\n log.warn(`briefing: readAllMemories failed: ${err}`);\n return [];\n }\n}\n\nasync function safeReadEntities(storage: StorageManager): Promise<EntityFile[]> {\n try {\n return await storage.readAllEntityFiles();\n } catch (err) {\n log.warn(`briefing: readAllEntityFiles failed: ${err}`);\n return [];\n }\n}\n\nfunction memoryTimestamp(memory: MemoryFile): number {\n const raw = memory.frontmatter.updated || memory.frontmatter.created;\n if (!raw) return 0;\n const t = Date.parse(raw);\n return Number.isFinite(t) ? t : 0;\n}\n\n/** @internal — exported for testing only. */\nexport function filterMemoriesByWindow(memories: MemoryFile[], window: ParsedBriefingWindow): MemoryFile[] {\n const fromMs = window.from.getTime();\n const toMs = window.to.getTime();\n return memories.filter((m) => {\n // Exclude explicitly retired statuses so commitments overridden within the\n // window don't appear as open. In addition to `superseded` / `archived`\n // (temporal retirement), also exclude `rejected` and `quarantined`, which\n // come from governance/disposition workflows: those memories have been\n // explicitly marked unsafe or invalid and must NOT flow into active\n // threads, open commitments, or follow-up generation, even if they\n // fall within the briefing window. Surfacing them would reintroduce\n // quarantined content into downstream automation as actionable context.\n //\n // `pending_review` memories are awaiting human review — not invalidated —\n // and must be included so reviewers see them in the briefing.\n const status = m.frontmatter.status;\n if (\n status === \"superseded\" ||\n status === \"archived\" ||\n status === \"rejected\" ||\n status === \"quarantined\" ||\n status === \"forgotten\"\n ) {\n return false;\n }\n const ts = memoryTimestamp(m);\n return ts >= fromMs && ts < toMs;\n });\n}\n\n/** @internal — exported for testing only. */\nexport function buildActiveThreads(memories: MemoryFile[]): BriefingActiveThread[] {\n const buckets = new Map<string, BriefingActiveThread>();\n for (const memory of memories) {\n const threadKey = extractThreadKey(memory);\n const updatedAt = memory.frontmatter.updated || memory.frontmatter.created || \"\";\n const existing = buckets.get(threadKey);\n if (!existing || updatedAt > existing.updatedAt) {\n buckets.set(threadKey, {\n id: threadKey,\n title: summarizeContentTitle(memory),\n updatedAt,\n // Always derive reason from the newest memory so the description\n // reflects the most-recent activity type, not the first memory seen.\n reason: describeReason(memory),\n });\n }\n }\n return Array.from(buckets.values())\n .sort((a, b) => {\n if (a.updatedAt > b.updatedAt) return -1;\n if (a.updatedAt < b.updatedAt) return 1;\n // Tiebreaker: lexicographic order by id ensures a deterministic, stable\n // result when multiple threads share the same updatedAt timestamp (e.g.\n // after a batch extraction run).\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n })\n .slice(0, MAX_ACTIVE_THREADS);\n}\n\nfunction extractThreadKey(memory: MemoryFile): string {\n const entityRef = memory.frontmatter.entityRef?.trim();\n if (entityRef) return `entity:${entityRef}`;\n const tags = memory.frontmatter.tags ?? [];\n const topicTag = tags.find((t) => t.startsWith(\"topic:\"));\n if (topicTag) return topicTag;\n if (tags.length > 0) return `tag:${tags[0]}`;\n return `memory:${memory.frontmatter.id}`;\n}\n\nfunction summarizeContentTitle(memory: MemoryFile): string {\n const firstLine = (memory.content || \"\").split(\"\\n\").find((line) => line.trim().length > 0) ?? \"\";\n const trimmed = firstLine.trim();\n if (trimmed.length === 0) return memory.frontmatter.id;\n return trimmed.length > 120 ? `${trimmed.slice(0, 117)}...` : trimmed;\n}\n\nfunction describeReason(memory: MemoryFile): string {\n const cat = memory.frontmatter.category;\n if (cat === \"commitment\") return \"open commitment\";\n if (cat === \"decision\") return \"recent decision\";\n if (cat === \"correction\") return \"recent correction\";\n return \"recent activity\";\n}\n\n/** @internal — exported for testing only. */\nexport function buildRecentEntities(\n entities: EntityFile[],\n window: ParsedBriefingWindow,\n focus: BriefingFocus | null,\n): BriefingRecentEntity[] {\n const fromMs = window.from.getTime();\n const scored: BriefingRecentEntity[] = [];\n const now = window.to;\n for (const entity of entities) {\n if (focus && !focusMatchesEntity(entity, focus)) continue;\n const toMs = window.to.getTime();\n const updatedMs = entity.updated ? Date.parse(entity.updated) : 0;\n if (!Number.isFinite(updatedMs) || updatedMs < fromMs || updatedMs >= toMs) continue;\n const score = StorageManager.scoreEntity(entity, now);\n scored.push({\n name: entity.name,\n type: entity.type,\n updatedAt: entity.updated,\n score: Number(score.toFixed(4)),\n summary: entity.synthesis || entity.summary,\n });\n }\n return scored\n .sort((a, b) => {\n const scoreDiff = b.score - a.score;\n if (scoreDiff !== 0) return scoreDiff;\n if (a.updatedAt > b.updatedAt) return -1;\n if (a.updatedAt < b.updatedAt) return 1;\n return 0;\n })\n .slice(0, MAX_RECENT_ENTITIES);\n}\n\nfunction buildOpenCommitments(memories: MemoryFile[]): BriefingOpenCommitment[] {\n const commitments: BriefingOpenCommitment[] = [];\n\n for (const memory of memories) {\n const tags = memory.frontmatter.tags ?? [];\n const isPending = tags.some((t) => t.toLowerCase() === \"pending\");\n const isCommitment = memory.frontmatter.category === \"commitment\";\n const isUnresolvedQuestion = /(?:\\?$|\\bfollow[- ]up\\b|\\btodo\\b)/i.test(memory.content);\n\n if (isPending || isCommitment || isUnresolvedQuestion) {\n const kind: BriefingOpenCommitment[\"kind\"] = isCommitment\n ? \"commitment\"\n : isUnresolvedQuestion\n ? \"question\"\n : \"pending_memory\";\n commitments.push({\n id: memory.frontmatter.id,\n kind,\n text: summarizeContentTitle(memory),\n source: memory.frontmatter.source,\n createdAt: memory.frontmatter.created,\n });\n }\n }\n\n return commitments\n .sort((a, b) => {\n // Missing timestamps sort last (highest comparator value).\n if (!a.createdAt && !b.createdAt) return 0;\n if (!a.createdAt) return 1;\n if (!b.createdAt) return -1;\n if (a.createdAt > b.createdAt) return -1;\n if (a.createdAt < b.createdAt) return 1;\n return 0;\n })\n .slice(0, MAX_OPEN_COMMITMENTS);\n}\n\ninterface CalendarLoadResult {\n events: CalendarEvent[] | undefined;\n error: BriefingCalendarSourceError | undefined;\n}\n\nasync function loadTodayCalendar(\n source: CalendarSource,\n now: Date,\n): Promise<CalendarLoadResult> {\n const sourceLabel = (source as { filePath?: string }).filePath ?? \"calendar\";\n try {\n const dateIso = now.toISOString().slice(0, 10);\n const events = await source.eventsForDate(dateIso);\n // Return the events array (possibly empty for a legitimately empty calendar).\n // An empty array is distinct from `undefined`: empty means \"source responded\n // with no events today\"; undefined means \"source failed\".\n return { events, error: undefined };\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n log.warn(`briefing: calendar source error (${sourceLabel}): ${message}`);\n // Return undefined events (not []) to signal an error so callers can\n // distinguish \"no events today\" from \"the calendar source threw\".\n return {\n events: undefined,\n error: { source: sourceLabel, error: message },\n };\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Follow-ups (Responses API)\n// ──────────────────────────────────────────────────────────────────────────\n\nfunction buildOpenAiFollowupGenerator(cfg: {\n apiKey: string;\n model: string;\n baseURL?: string;\n}): BriefingFollowupGenerator {\n return async ({ sections, windowLabel, maxFollowups }) => {\n // Lazy import keeps the module dependency-free when LLM path is unused.\n const { OpenAI } = (await import(\"openai\")) as {\n OpenAI: new (opts: { apiKey: string; baseURL?: string }) => unknown;\n };\n const clientOpts: { apiKey: string; baseURL?: string } = { apiKey: cfg.apiKey };\n if (cfg.baseURL) clientOpts.baseURL = cfg.baseURL;\n const client = new OpenAI(clientOpts) as {\n responses: {\n create: (args: {\n model: string;\n instructions: string;\n input: string;\n max_output_tokens?: number;\n }) => Promise<{ output_text?: string }>;\n };\n };\n\n const prompt = buildFollowupPrompt(sections, windowLabel, maxFollowups);\n const response = await client.responses.create({\n model: cfg.model,\n instructions: FOLLOWUP_INSTRUCTIONS,\n input: prompt,\n max_output_tokens: 512,\n });\n\n const text = typeof response.output_text === \"string\" ? response.output_text : \"\";\n return parseFollowupResponse(text, maxFollowups);\n };\n}\n\n/**\n * Minimal chat-completion surface shared by `FallbackLlmClient` (gateway\n * model chain) and `LocalLlmClient` (Ollama / OpenAI-compatible local\n * endpoints). Matches `Orchestrator.fastLlmForRerank` so briefing\n * follow-ups can ride the same routing as other fast-tier operations.\n */\nexport interface BriefingChainLlmClient {\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: {\n temperature?: number;\n maxTokens?: number;\n timeoutMs?: number;\n operation?: string;\n priority?: \"background\" | \"recall-critical\";\n },\n ): Promise<{ content: string } | null>;\n}\n\n/**\n * Build a follow-up generator backed by the configured LLM chain\n * (gateway model source or local LLM) instead of a direct OpenAI key.\n *\n * Local models frequently wrap JSON in code fences or prose, so the\n * response is run through `extractJsonCandidates` and the first candidate\n * that parses into a valid `{ followups: [...] }` shape wins. Throws when\n * the chain returns nothing or no candidate parses — `buildBriefing`\n * catches and surfaces the message via `followupsUnavailableReason`.\n */\nexport function buildChainFollowupGenerator(\n client: BriefingChainLlmClient,\n): BriefingFollowupGenerator {\n return async ({ sections, windowLabel, maxFollowups }) => {\n const prompt = buildFollowupPrompt(sections, windowLabel, maxFollowups);\n const response = await client.chatCompletion(\n [\n { role: \"system\", content: FOLLOWUP_INSTRUCTIONS },\n { role: \"user\", content: prompt },\n ],\n {\n temperature: 0.2,\n maxTokens: 512,\n operation: \"briefing-followups\",\n priority: \"background\",\n },\n );\n if (!response?.content) {\n throw new Error(\"LLM chain returned no response\");\n }\n const candidates = extractJsonCandidates(response.content);\n let lastError: unknown;\n for (const candidate of candidates) {\n try {\n return parseFollowupResponse(candidate, maxFollowups);\n } catch (err) {\n lastError = err;\n }\n }\n throw new Error(\n `LLM chain response contained no valid followups JSON: ${stringifyError(lastError ?? \"no JSON candidates found\")}`,\n );\n };\n}\n\nconst FOLLOWUP_INSTRUCTIONS = `You suggest short follow-up prompts for a daily context briefing.\nReturn strict JSON of the form { \"followups\": [{ \"text\": \"...\", \"rationale\": \"...\" }] }.\nRules:\n- Never invent facts absent from the input.\n- Keep each \"text\" under 140 characters.\n- Prefer concrete, action-oriented phrasing.\n- Omit duplicates. Avoid filler.`;\n\nfunction buildFollowupPrompt(\n sections: BriefingSections,\n windowLabel: string,\n maxFollowups: number,\n): string {\n const lines: string[] = [];\n lines.push(`Window: ${windowLabel}`);\n lines.push(`Desired follow-ups: ${maxFollowups}`);\n lines.push(\"\");\n lines.push(\"Active threads:\");\n for (const t of sections.activeThreads) lines.push(`- ${t.title} (${t.reason})`);\n lines.push(\"\");\n lines.push(\"Recent entities:\");\n for (const e of sections.recentEntities) lines.push(`- ${e.name} [${e.type}]`);\n lines.push(\"\");\n lines.push(\"Open commitments:\");\n for (const c of sections.openCommitments) lines.push(`- [${c.kind}] ${c.text}`);\n return lines.join(\"\\n\");\n}\n\nfunction parseFollowupResponse(raw: string, max: number): BriefingFollowup[] {\n // JSON.parse throws on invalid JSON — let the caller catch it so the outer\n // try/catch in buildBriefing can set followupsUnavailableReason rather than\n // silently returning an empty array that masks the parse failure.\n const candidates = extractJsonCandidates(raw);\n let lastError: unknown;\n for (const candidate of candidates) {\n try {\n const parsed = JSON.parse(candidate) as unknown;\n if (!parsed || typeof parsed !== \"object\") {\n throw new Error(`LLM returned non-object JSON: ${typeof parsed}`);\n }\n const arr = (parsed as { followups?: unknown }).followups;\n if (!Array.isArray(arr)) {\n throw new Error(`LLM response missing \"followups\" array`);\n }\n const out: BriefingFollowup[] = [];\n for (const entry of arr) {\n if (!entry || typeof entry !== \"object\") continue;\n const text = (entry as Record<string, unknown>).text;\n if (typeof text !== \"string\" || text.trim().length === 0) continue;\n const rationale = (entry as Record<string, unknown>).rationale;\n out.push({\n text: text.trim(),\n rationale: typeof rationale === \"string\" ? rationale.trim() : undefined,\n });\n if (out.length >= max) break;\n }\n return out;\n } catch (err) {\n lastError = err;\n }\n }\n if (lastError) throw lastError;\n throw new Error(\"LLM response contained no JSON candidates\");\n}\n\nfunction stringifyError(err: unknown): string {\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Markdown rendering\n// ──────────────────────────────────────────────────────────────────────────\n\ninterface RenderContext {\n sections: BriefingSections;\n windowLabel: string;\n focus: BriefingFocus | null;\n followupsUnavailableReason?: string;\n generatedAt: Date;\n namespace?: string;\n}\n\nexport function renderBriefingMarkdown(ctx: RenderContext): string {\n const lines: string[] = [];\n lines.push(`# Daily Context Briefing`);\n lines.push(\"\");\n lines.push(`_Generated ${ctx.generatedAt.toISOString()} (window: ${ctx.windowLabel})_`);\n if (ctx.focus) {\n lines.push(`_Focus: ${ctx.focus.type}:${ctx.focus.value}_`);\n }\n if (ctx.namespace) {\n lines.push(`_Namespace: ${ctx.namespace}_`);\n }\n lines.push(\"\");\n\n lines.push(`## Active threads`);\n if (ctx.sections.activeThreads.length === 0) {\n lines.push(`_No active threads in window._`);\n } else {\n for (const t of ctx.sections.activeThreads) {\n lines.push(`- **${t.title}** — ${t.reason} (updated ${t.updatedAt})`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Recent entities`);\n if (ctx.sections.recentEntities.length === 0) {\n lines.push(`_No entities updated in window._`);\n } else {\n for (const e of ctx.sections.recentEntities) {\n const summary = e.summary ? ` — ${e.summary}` : \"\";\n lines.push(`- **${e.name}** (${e.type}, score ${e.score})${summary}`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Open commitments`);\n if (ctx.sections.openCommitments.length === 0) {\n lines.push(`_No open commitments detected._`);\n } else {\n for (const c of ctx.sections.openCommitments) {\n lines.push(`- [${c.kind}] ${c.text}`);\n }\n }\n lines.push(\"\");\n\n lines.push(`## Suggested follow-ups`);\n if (ctx.followupsUnavailableReason) {\n lines.push(`_Unavailable: ${ctx.followupsUnavailableReason}_`);\n } else if (ctx.sections.suggestedFollowups.length === 0) {\n lines.push(`_No follow-ups suggested._`);\n } else {\n for (const f of ctx.sections.suggestedFollowups) {\n const rationale = f.rationale ? ` _(${f.rationale})_` : \"\";\n lines.push(`- ${f.text}${rationale}`);\n }\n }\n lines.push(\"\");\n\n if (ctx.sections.todayCalendar !== undefined) {\n lines.push(`## Today's calendar`);\n if (ctx.sections.todayCalendar.length === 0) {\n lines.push(`_No events on the calendar today._`);\n } else {\n for (const ev of ctx.sections.todayCalendar) {\n const end = ev.end ? ` → ${ev.end}` : \"\";\n const loc = ev.location ? ` @ ${ev.location}` : \"\";\n lines.push(`- **${ev.title}** (${ev.start}${end})${loc}`);\n }\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\").trimEnd() + \"\\n\";\n}\n\n// ──────────────────────────────────────────────────────────────────────────\n// Save helpers\n// ──────────────────────────────────────────────────────────────────────────\n\n/**\n * Resolve the directory where `--save` writes dated briefings.\n * Respects the following precedence:\n * 1. explicit `configOverride` argument\n * 2. `$REMNIC_HOME/briefings/`\n * 3. `$HOME/.remnic/briefings/`\n */\nexport function resolveBriefingSaveDir(\n configOverride: string | null | undefined,\n env?: NodeJS.ProcessEnv,\n): string {\n if (typeof configOverride === \"string\" && configOverride.trim().length > 0) {\n return path.resolve(configOverride.trim());\n }\n const remnicHome = (env === undefined ? readEnvVar(\"REMNIC_HOME\") : env.REMNIC_HOME)?.trim();\n if (remnicHome && remnicHome.length > 0) {\n return path.join(remnicHome, \"briefings\");\n }\n const home = env === undefined\n ? resolveHomeDir()\n : env.HOME ?? env.USERPROFILE ?? os.homedir();\n return path.join(home, \".remnic\", \"briefings\");\n}\n\n/** Format the dated filename for a given briefing. */\nexport function briefingFilename(date: Date, format: \"markdown\" | \"json\" = \"markdown\"): string {\n const day = date.toISOString().slice(0, 10);\n return format === \"json\" ? `${day}.json` : `${day}.md`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAS,gBAAgB;AACzB,OAAO,QAAQ;AACf,OAAO,UAAU;AAyBV,IAAM,0BAA0B,C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M,OAAO,QAAQ,SACjB,eAAe,IACf,IAAI,QAAQ,IAAI,eAAe,GAAG,QAAQ;AAC9C,SAAO,KAAK,KAAK,MAAM,WAAW,WAAW;AAC/C;AAGO,SAAS,iBAAiB,MAAY,SAA8B,YAAoB;AAC7F,QAAM,MAAM,KAAK,YAAY,EAAE,MAAM,GAAG,EAAE;AAC1C,SAAO,WAAW,SAAS,GAAG,GAAG,UAAU,GAAG,GAAG;AACnD;","names":["from","end"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["export type ReasoningEffort = \"none\" | \"low\" | \"medium\" | \"high\";\nexport type TriggerMode = \"smart\" | \"every_n\" | \"time_based\";\nexport type SignalLevel = \"none\" | \"low\" | \"medium\" | \"high\";\nexport type MemoryCategory = \"fact\" | \"preference\" | \"correction\" | \"entity\" | \"decision\" | \"relationship\" | \"principle\" | \"commitment\" | \"moment\" | \"skill\" | \"rule\" | \"procedure\" | \"reasoning_trace\";\nexport type ConsolidationAction = \"ADD\" | \"MERGE\" | \"UPDATE\" | \"INVALIDATE\" | \"SKIP\";\nexport type ConfidenceTier = \"explicit\" | \"implied\" | \"inferred\" | \"speculative\";\nexport type PrincipalFromSessionKeyMode = \"map\" | \"prefix\" | \"regex\";\nexport type RecallPlanMode = \"no_recall\" | \"minimal\" | \"full\" | \"graph_mode\";\nexport type CronRecallMode = \"all\" | \"none\" | \"allowlist\";\nexport type CronConversationRecallMode = \"auto\" | \"always\" | \"never\";\nexport type IdentityInjectionMode = \"recovery_only\" | \"minimal\" | \"full\";\nexport type CaptureMode = \"implicit\" | \"explicit\" | \"hybrid\";\nexport type MemoryOsPresetName = \"conservative\" | \"balanced\" | \"research-max\" | \"local-llm-heavy\";\nexport type ExtractionPassSource = \"base\" | \"proactive\";\n/**\n * Scope classification for extracted facts (issue #XXX).\n *\n * - `\"project\"` — knowledge specific to one codebase: file paths, environment\n * configs, deployment details, project-specific workarounds, team/stakeholder\n * info tied to one project.\n * - `\"global\"` — knowledge that applies across projects: core framework bugs,\n * library behavior, API patterns, user preferences, tool configurations,\n * general coding patterns, infrastructure knowledge.\n *\n * Default is `\"project\"` when a coding context is active, `\"global\"` when no\n * coding context is present.\n */\nexport type MemoryScope = \"project\" | \"global\";\nexport type SlotMismatchMode = \"error\" | \"warn\" | \"silent\";\nexport type CodexCompactionFlushMode = \"signal\" | \"heuristic\" | \"auto\";\nexport type DreamingNarrativePromptStyle = \"reflective\" | \"diary\" | \"analytical\";\nexport type HeartbeatDetectionMode = \"runtime-signal\" | \"heuristic\" | \"auto\";\nexport type ActiveRecallQueryMode = \"message\" | \"recent\" | \"full\";\nexport type ActiveRecallPromptStyle =\n | \"balanced\"\n | \"strict\"\n | \"contextual\"\n | \"recall-heavy\"\n | \"precision-heavy\"\n | \"preference-only\";\nexport type ActiveRecallThinking =\n | \"off\"\n | \"minimal\"\n | \"low\"\n | \"medium\"\n | \"high\"\n | \"xhigh\"\n | \"adaptive\";\nexport type ActiveRecallChatType = \"direct\" | \"group\" | \"channel\";\nexport type ActiveRecallModelFallbackPolicy = \"default-remote\" | \"resolved-only\";\n\n/**\n * Retrieval tier ladder (issue #518). Identifies which tier served a recall\n * result. Ordered top-to-bottom by cost, but routing is not strictly\n * sequential — callers may jump straight to a lower tier when eligibility\n * does not hold.\n */\nexport type RetrievalTier =\n | \"exact-cache\"\n | \"fuzzy-cache\"\n | \"direct-answer\"\n | \"hybrid\"\n | \"rerank-graph\"\n | \"agentic\";\n\n/**\n * Per-recall annotation describing which retrieval tier served a result,\n * why that tier was chosen, and what was filtered along the way. Added as\n * part of issue #518 (direct-answer tier + `query --explain`).\n *\n * Not to be confused with the existing `recallExplain` operation\n * (graph-path explanation) — that is a user-invoked RPC; this is a\n * per-result annotation that can be attached to any recall response.\n */\nexport interface RecallTierExplain {\n tier: RetrievalTier;\n tierReason: string;\n filteredBy: string[];\n candidatesConsidered: number;\n latencyMs: number;\n sourceAnchors?: Array<{ path: string; lineRange?: [number, number] }>;\n}\n\n/**\n * Recall disclosure depth (issue #677). Selects how much content each\n * recall result returns:\n *\n * - `\"chunk\"` — semantic chunk excerpt (cheapest; default).\n * - `\"section\"` — full markdown section / memory body (current pre-#677 behavior).\n * - `\"raw\"` — raw transcript / archive excerpts from `lcm/` when present.\n *\n * Disclosure is **orthogonal** to the retrieval-tier ladder\n * (`RetrievalTier` / `RETRIEVAL_TIERS`). The tier ladder controls *which\n * pipeline stage served a result*; disclosure controls *how deep into the\n * underlying memory the result reaches*. A request can mix any retrieval\n * tier with any disclosure depth.\n *\n * Default is `\"chunk\"` when the caller omits the field; this preserves the\n * existing recall behavior because callers that did not request a disclosure\n * level continue to receive the same chunk-shaped previews they always had.\n * Surfaces (CLI / HTTP / MCP) and downstream telemetry are wired in later\n * PRs of #677.\n */\nexport type RecallDisclosure = \"chunk\" | \"section\" | \"raw\";\n\n/**\n * Ordered list of disclosure levels, cheapest to most expensive. Used for\n * validation, escalation policy comparisons, and future telemetry rollups.\n * Treat this as the single source of truth — do not hard-code disclosure\n * strings elsewhere.\n */\nexport const RECALL_DISCLOSURE_LEVELS: readonly RecallDisclosure[] = [\n \"chunk\",\n \"section\",\n \"raw\",\n] as const;\n\n/**\n * Default disclosure level when a caller omits `disclosure`. Set to `chunk`\n * so callers that did not opt in to deeper disclosure see the same\n * preview-shaped behavior as before #677.\n */\nexport const DEFAULT_RECALL_DISCLOSURE: RecallDisclosure = \"chunk\";\n\nexport function isRecallDisclosure(value: unknown): value is RecallDisclosure {\n return typeof value === \"string\"\n && (RECALL_DISCLOSURE_LEVELS as readonly string[]).includes(value);\n}\n\nexport interface RecallSectionConfig {\n id: string;\n enabled?: boolean;\n maxChars?: number | null;\n maxHints?: number;\n maxSupportingFacts?: number;\n maxRelatedEntities?: number;\n consolidateTriggerLines?: number;\n consolidateTargetLines?: number;\n maxEntities?: number;\n maxResults?: number;\n recentTurns?: number;\n maxTurns?: number;\n maxTokens?: number;\n lookbackHours?: number;\n maxCount?: number;\n topK?: number;\n timeoutMs?: number;\n maxPatterns?: number;\n maxRubrics?: number;\n forceGeneric?: boolean;\n}\n\nexport interface RecallPipelineConfig {\n recallBudgetChars: number;\n pipeline: RecallSectionConfig[];\n}\n\nexport interface SessionObserverBandConfig {\n maxBytes: number;\n triggerDeltaBytes: number;\n triggerDeltaTokens: number;\n}\n\nexport interface FileHygieneConfig {\n enabled: boolean;\n // Lint (warn before truncation risk)\n lintEnabled: boolean;\n lintBudgetBytes: number;\n lintWarnRatio: number;\n lintPaths: string[];\n // Rotation/splitting\n rotateEnabled: boolean;\n rotateMaxBytes: number;\n rotateKeepTailChars: number;\n rotatePaths: string[];\n archiveDir: string;\n // Cadence\n runMinIntervalMs: number;\n // Optional warnings log (future-proofed)\n warningsLogEnabled: boolean;\n warningsLogPath: string;\n // Optional index file (future-proofed)\n indexEnabled: boolean;\n indexPath: string;\n}\n\nexport interface NativeKnowledgeConfig {\n enabled: boolean;\n includeFiles: string[];\n maxChunkChars: number;\n maxResults: number;\n maxChars: number;\n stateDir: string;\n obsidianVaults: NativeKnowledgeObsidianVaultConfig[];\n openclawWorkspace?: NativeKnowledgeOpenClawWorkspaceConfig;\n}\n\nexport interface NativeKnowledgeFolderRuleConfig {\n pathPrefix: string;\n namespace?: string;\n privacyClass?: string;\n}\n\nexport interface NativeKnowledgeObsidianVaultConfig {\n id: string;\n rootDir: string;\n includeGlobs: string[];\n excludeGlobs: string[];\n namespace?: string;\n privacyClass?: string;\n folderRules: NativeKnowledgeFolderRuleConfig[];\n dailyNotePatterns: string[];\n materializeBacklinks: boolean;\n}\n\nexport interface NativeKnowledgeOpenClawWorkspaceConfig {\n enabled: boolean;\n bootstrapFiles: string[];\n handoffGlobs: string[];\n dailySummaryGlobs: string[];\n automationNoteGlobs: string[];\n workspaceDocGlobs: string[];\n excludeGlobs: string[];\n sharedSafeGlobs: string[];\n}\n\n/**\n * OpenClaw SecretRef shape (issue #757).\n *\n * OpenClaw resolves these at runtime via its built-in secret resolver\n * (e.g. exec providers like `kc_*` for macOS Keychain). Plugins receive\n * the raw object in `pluginConfig` and must call the gateway's resolver\n * before using the value. Standalone Remnic does NOT resolve SecretRefs;\n * operators must use plain strings or `${ENV_VAR}` expansion instead.\n */\nexport interface SecretRef {\n source: string;\n provider?: string;\n id?: string;\n command?: unknown;\n [key: string]: unknown;\n}\n\nexport type AgentAccessAuthToken = string | SecretRef;\n\nexport interface AgentAccessHttpConfig {\n enabled: boolean;\n host: string;\n port: number;\n /**\n * Bearer token. Either a literal string (env-expanded) or an unresolved\n * SecretRef object preserved verbatim from openclaw.json — resolved at\n * service-start time via {@link resolveAgentAccessAuthToken}.\n */\n authToken?: AgentAccessAuthToken;\n principal?: string;\n maxBodyBytes: number;\n}\n\nexport interface DreamingConfig {\n enabled: boolean;\n journalPath: string;\n maxEntries: number;\n injectRecentCount: number;\n minIntervalMinutes: number;\n narrativeModel: string | null;\n narrativePromptStyle: DreamingNarrativePromptStyle;\n watchFile: boolean;\n}\n\n/**\n * Light-sleep phase config (issue #678 PR 2/4).\n *\n * Groups existing top-level lifecycle-policy gates under a unified namespace.\n * When `dreams.phases.lightSleep.*` keys are set they WIN over the legacy\n * top-level keys; the legacy keys remain readable for backward compatibility.\n *\n * Light sleep: recent activity scoring + clustering (tier-routing value score,\n * observation ledger, buffer state — `runLifecyclePolicyPass` in orchestrator).\n */\nexport interface DreamsLightSleepConfig {\n /** Phase master switch. Mirrors `lifecyclePolicyEnabled` when not set explicitly. */\n enabled: boolean;\n /** Minimum interval between light-sleep passes in milliseconds. */\n cadenceMs: number;\n /** Value score above which a memory is treated as hot. Mirrors `lifecyclePromoteHeatThreshold`. */\n promoteHeatThreshold: number;\n /** Value score below which a memory starts to decay. Mirrors `lifecycleStaleDecayThreshold`. */\n staleDecayThreshold: number;\n /** Value score below which a memory is eligible for archive. Mirrors `lifecycleArchiveDecayThreshold`. */\n archiveDecayThreshold: number;\n /** Whether stale memories are filtered from recall. Mirrors `lifecycleFilterStaleEnabled`. */\n filterStaleEnabled: boolean;\n}\n\n/**\n * REM phase config (issue #678 PR 2/4).\n *\n * Groups existing top-level semantic-consolidation and supersession gates.\n * When `dreams.phases.rem.*` keys are set they WIN over the legacy top-level\n * keys.\n *\n * REM: cross-session synthesis, supersession resolution, semantic consolidation\n * (`runSemanticConsolidation` in orchestrator).\n */\nexport interface DreamsRemConfig {\n /** Phase master switch. Mirrors `semanticConsolidationEnabled` when not set explicitly. */\n enabled: boolean;\n /**\n * How often the REM pass runs, in milliseconds.\n * Derived from `semanticConsolidationIntervalHours` (×3 600 000) when not set explicitly.\n */\n cadenceMs: number;\n /** Cosine-similarity threshold for cluster membership. Mirrors `semanticConsolidationThreshold`. */\n similarityThreshold: number;\n /** Minimum cluster size before consolidation runs. Mirrors `semanticConsolidationMinClusterSize`. */\n minClusterSize: number;\n /** Max cluster operations per run. Mirrors `semanticConsolidationMaxPerRun`. */\n maxPerRun: number;\n /** Minimum gap between consolidation passes (ms). Mirrors `consolidationMinIntervalMs`. */\n minIntervalMs: number;\n}\n\n/**\n * Deep-sleep phase config (issue #678 PR 2/4).\n *\n * Groups existing versioning and tier-migration gates.\n * When `dreams.phases.deepSleep.*` keys are set they WIN over the legacy\n * top-level keys.\n *\n * Deep sleep: promotion to durable memory, hot→cold tier migration,\n * page-version snapshots, archive (`engram-nightly-governance` cron,\n * `tier-migration.ts`, `page-versioning.ts`, `hygiene.ts`).\n */\nexport interface DreamsDeepSleepConfig {\n /**\n * Phase master switch. No single direct legacy mirror; defaults false unless\n * an existing deep-sleep surface such as nightly governance auto-registration,\n * tier migration, or page versioning is explicitly enabled. Set to `false`\n * to disable those surfaces without removing legacy config keys.\n */\n enabled: boolean;\n /** True only when dreams.phases.deepSleep.enabled was explicitly configured. */\n enabledExplicitlySet?: boolean;\n /**\n * Minimum interval between deep-sleep passes in milliseconds.\n * Informational only in PR 2; PR 4 will wire this into the cron scheduler.\n */\n cadenceMs: number;\n /** Enable page-version snapshots on every overwrite. Mirrors `versioningEnabled`. */\n versioningEnabled: boolean;\n /** Max snapshots per page. Mirrors `versioningMaxPerPage`. */\n versioningMaxPerPage: number;\n}\n\n/**\n * Unified dreams phases config block (issue #678 PR 2/4).\n *\n * Operators set `dreams.phases.{lightSleep,rem,deepSleep}.*` in their plugin\n * config. Values under this block WIN over the equivalent legacy top-level keys\n * when both are set. Legacy keys continue to be parsed so existing configs do\n * not need to change.\n *\n * This block is intentionally separate from `DreamingConfig` which controls the\n * diary surface (`surfaces/dreams.ts`) — a different feature. See docs/dreams.md.\n */\nexport interface DreamsPhasesConfig {\n lightSleep: DreamsLightSleepConfig;\n rem: DreamsRemConfig;\n deepSleep: DreamsDeepSleepConfig;\n}\n\n/** Procedural memory (issue #519): mining + recall gates. All sub-features default off. */\nexport interface ProceduralConfig {\n enabled: boolean;\n /** Minimum cluster size before emitting a candidate; `0` disables mining (`minOccurrences_zero`). */\n minOccurrences: number;\n /** Minimum success rate from trajectory outcomes in [0, 1]. */\n successFloor: number;\n /** When auto-promotion is enabled, promote pending_review → active after this many occurrences. */\n autoPromoteOccurrences: number;\n autoPromoteEnabled: boolean;\n lookbackDays: number;\n /** When true, installer may register the nightly procedural mining cron (default off). */\n proceduralMiningCronAutoRegister: boolean;\n /** Max procedure memories to inject on task-initiation recall (1–10). */\n recallMaxProcedures: number;\n}\n\n/**\n * Claim-level provenance spans (issue #1575). Controls whether extracted\n * facts carry verbatim source-utterance excerpts and the strength tag that\n * downstream features (faithfulness gate #1576, correction UX #1580/#1583,\n * tombstone matching #1579, TrustScore #1577) consume.\n *\n * PR 1 parses the block + schema only; the extraction prompt and validator\n * land in PR 2. When `enabled` is false, extraction prompt/output are\n * byte-identical to pre-feature behavior (rule 39).\n */\nexport interface ProvenanceConfig {\n /** Emit provenance spans on new extractions. Default true. */\n enabled: boolean;\n /** Maximum characters stored per quote; longer quotes truncate at a word boundary. Default 300. */\n maxQuoteChars: number;\n /**\n * When true, facts whose quote cannot be located are routed to\n * `pending_review` instead of `active`. Stays false until #1576 lands and\n * the bench shows the gate is safe (rule 48).\n */\n requireSpans: boolean;\n}\n\n/**\n * Coding-agent mode config (issue #569).\n *\n * When the connector provides a `CodingContext` (see below), Remnic overlays\n * a project- and/or branch-scoped namespace on top of the principal's default\n * namespace so that memories written while working on project A do not surface\n * while working on project B.\n *\n * Both flags default off-for-branch / on-for-project. Per CLAUDE.md #30 every\n * filter or transform needs an escape hatch: set `projectScope: false` to\n * exactly restore pre-#569 behaviour.\n */\nexport interface CodingModeConfig {\n /**\n * When true (default), a session with a resolved `CodingContext` uses a\n * project-scoped namespace. When false, the principal's default namespace\n * is used unchanged (pre-#569 behaviour).\n */\n projectScope: boolean;\n /**\n * When true, recall/write also overlay the current branch on top of the\n * project namespace. Default false — branch-scope is opt-in because active\n * development typically wants recall across branches. (Wired by PR 3 of\n * issue #569; declared here so the schema ships in one slice.)\n */\n branchScope: boolean;\n /**\n * When true (default), project-scoped and branch-scoped sessions include\n * the root/default namespace in their read fallbacks so globally useful\n * memories remain visible from any project. When false, project-scoped\n * sessions only see their own namespace (strict isolation).\n *\n * CLAUDE.md #30: configuration gate for the recall fan-out to the root\n * namespace. Does not affect writes — those always go to the project\n * namespace only.\n */\n globalFallback: boolean;\n}\n\n// CodingKnowledgeConfig — Track A (issue #1548) durable coding-knowledge\n// surface. Master gate plus per-feature switches. Off by default.\nexport interface CodingKnowledgeConfig {\n /** Master gate. Off = byte-for-byte pre-feature behaviour on every path. */\n enabled: boolean;\n /** Decision-record surfaces + briefing titles (effective only under the master gate). */\n decisionRecords: boolean;\n /** Architecture-card build/refresh + briefing injection. */\n architectureCard: boolean;\n /** Last-seen-head persistence + delta briefing line. */\n sessionDelta: boolean;\n /** Opt-in LLM summary pass (costs tokens — default off, per rule 48). */\n architectureCardLlmSummary: boolean;\n /**\n * Structural-context provider selection.\n * - `\"none\"` (default): no provider consulted — review-context runs\n * file-path-only boosting, identical to pre-feature behaviour.\n * - `\"subprocess\"`: shells out to `structuralProviderCommand` via\n * `execFile` (argv-array, never shell-string — rule 10).\n * - `\"native\"`: the `@remnic/coding-graph` engine, when installed.\n */\n structuralProvider: \"none\" | \"subprocess\" | \"native\";\n /**\n * Absolute path to the subprocess binary when `structuralProvider =\n * \"subprocess\"`. Empty string = no command configured (consumer must\n * reject the empty case at the wiring site). Rule 24: `statSync` file\n * check at boot, not at every call.\n */\n structuralProviderCommand: string;\n /**\n * Gate for the 14 codegraph parity tools (issue #1554). Off by default --\n * tools/list, HTTP routes, and CLI help are byte-identical to pre-feature\n * until this is true. The runtime also requires the @remnic/coding-graph\n * package to be installed (rule 39: single gate predicate\n * codegraphSurfaceVisible(config) && isCodingGraphInstalled()).\n */\n codegraphTools: boolean;\n /**\n * Root directory for per-project graph SQLite DBs. Empty string = derive\n * from memoryDir (<memoryDir>/codegraph/<principal>/<projectId>.sqlite).\n * Absolute path required when set explicitly (rule 11 -- no relative paths).\n */\n codegraphDbDir: string;\n}\n\n// ChatConfig — conversational memory inspection and correction (issue #1583).\n// Off by default — spawns LLM calls so explicit opt-in (rule 48).\nexport interface ChatConfig {\n /** Master gate. Off = no tools/endpoints/CLI registered (byte-identical, rule 39). */\n enabled: boolean;\n /** Routing override for the chat LLM (empty = use the default chain). */\n model: string;\n /** Max tool calls per user turn before partial-reply fallback (rule 34). */\n maxToolCallsPerTurn: number;\n /** Hours after which idle chat session state is cleaned up. */\n sessionTtlHours: number;\n}\n\n/**\n * Session-scoped coding context. Produced by `resolveGitContext()` in the\n * connector layer and attached to a session so that recall + write paths can\n * compute an overlay namespace.\n *\n * All fields mirror `GitContext` from `./coding/git-context.ts`; kept as a\n * separate interface because `types.ts` must stay dependency-free (it is\n * imported by every other module).\n */\nexport interface CodingContext {\n projectId: string;\n branch: string | null;\n rootPath: string;\n defaultBranch: string | null;\n}\n\nexport type ScopeProfileLayerId =\n | \"userProject\"\n | \"teamProject\"\n | \"userGlobal\"\n | \"serverShared\";\n\nexport type ScopeProfilePromotionTarget =\n | ScopeProfileLayerId\n | \"serverShared\"\n | \"teamProject\"\n | \"userGlobal\";\n\nexport interface ScopeProfileTeamProjectConfig {\n /**\n * Namespace template for team-project layers. Supported placeholders:\n * `{teamId}`, `{principal}`, `{projectId}`, `{projectHash}`, and\n * `{projectNamespace}`. The resolved namespace is validated at use time.\n */\n namespaceTemplate?: string;\n /**\n * Optional trusted team id for this profile. When omitted, the resolver uses\n * the first configured team whose principal lists include the caller.\n */\n teamId?: string;\n}\n\nexport interface ScopeProfileAutoPromoteConfig {\n enabled: boolean;\n targets: ScopeProfilePromotionTarget[];\n categories: Array<\"fact\" | \"correction\" | \"decision\" | \"preference\" | \"rule\" | \"procedure\">;\n minConfidenceTier: ConfidenceTier;\n}\n\nexport interface ScopeProfileConfig {\n readOrder: ScopeProfileLayerId[];\n writeDefault: ScopeProfileLayerId;\n promotionTargets: ScopeProfilePromotionTarget[];\n teamProject?: ScopeProfileTeamProjectConfig;\n autoPromote: ScopeProfileAutoPromoteConfig;\n}\n\nexport interface ScopeTeamConfig {\n principals: string[];\n projectNamespaceTemplate?: string;\n read: string[];\n write: string[];\n promote: string[];\n}\n\n/** Configuration for the nightly contradiction-scan cron (issue #520). */\nexport interface ContradictionScanConfig {\n /** Master switch for the contradiction scan cron. Default true. */\n enabled: boolean;\n /** Embedding cosine similarity floor for candidate pair generation. Default 0.82. */\n similarityFloor: number;\n /** Minimum topic-token Jaccard overlap for unstructured pairs. Default 0.4. */\n topicOverlapFloor: number;\n /** Cap on candidate pairs evaluated per cron run. Default 500. */\n maxPairsPerRun: number;\n /** Cooldown in days before re-evaluating a pair judged independent/both-valid. Default 14. */\n cooldownDays: number;\n /** When true, pairs judged \"duplicates\" are auto-flagged for dedup (still need user approval). Default false. */\n autoMergeDuplicates: boolean;\n}\n\nexport interface HeartbeatConfig {\n enabled: boolean;\n journalPath: string;\n maxPreviousRuns: number;\n watchFile: boolean;\n detectionMode: HeartbeatDetectionMode;\n gateExtractionDuringHeartbeat: boolean;\n}\n\nexport interface SlotBehaviorConfig {\n requireExclusiveMemorySlot: boolean;\n onSlotMismatch: SlotMismatchMode;\n}\n\nexport interface CodexCompatConfig {\n enabled: boolean;\n threadIdBufferKeying: boolean;\n compactionFlushMode: CodexCompactionFlushMode;\n fingerprintDedup: boolean;\n}\n\nexport function confidenceTier(score: number): ConfidenceTier {\n if (score >= 0.95) return \"explicit\";\n if (score >= 0.70) return \"implied\";\n if (score >= 0.40) return \"inferred\";\n return \"speculative\";\n}\n\n/** Default TTL in days for speculative memories (auto-expire if unconfirmed) */\nexport const SPECULATIVE_TTL_DAYS = 30;\n\n/**\n * Shape for semantic chunking config overrides stored in PluginConfig.\n * Mirrors SemanticChunkingConfig from semantic-chunking.ts without creating\n * a circular import (types.ts is imported by everything).\n */\nexport interface SemanticChunkingConfigShape {\n targetTokens: number;\n minTokens: number;\n maxTokens: number;\n smoothingWindowSize: number;\n boundaryThresholdStdDevs: number;\n embeddingBatchSize: number;\n fallbackToRecursive: boolean;\n}\n\nexport interface PluginConfig {\n openaiApiKey: string | undefined;\n openaiBaseUrl: string | undefined;\n model: string;\n reasoningEffort: ReasoningEffort;\n triggerMode: TriggerMode;\n bufferMaxTurns: number;\n bufferMaxMinutes: number;\n /**\n * Surprise-gated buffer flush (issue #563, D-MEM).\n *\n * When enabled, every turn added to the smart buffer is scored against a\n * configurable window of recent memories using an embedding-distance proxy\n * for novelty (see `buffer-surprise.ts`). A turn whose surprise score\n * exceeds `bufferSurpriseThreshold` triggers an immediate extract flush,\n * even if the existing signal/turn-count/time triggers would otherwise keep\n * buffering. Disabled by default — when `false`, buffer behavior is\n * identical to pre-#563 code. Additive only: existing triggers are never\n * suppressed by this flag.\n */\n bufferSurpriseTriggerEnabled: boolean;\n /**\n * Threshold in `[0, 1]` above which a surprise score causes an immediate\n * flush. `0.35` is a conservative default chosen to favor precision over\n * recall during the opt-in phase. Ignored unless\n * `bufferSurpriseTriggerEnabled` is `true`.\n */\n bufferSurpriseThreshold: number;\n /**\n * Number of nearest neighbors to average over when computing the surprise\n * score (see `computeSurprise`). Default `5`. Clamped to the recent-memory\n * window size at call time.\n */\n bufferSurpriseK: number;\n /**\n * Maximum number of recent memories to sample when computing the surprise\n * score. Bounds embedding cost per turn. Default `20`. Set to `0` to\n * disable the trigger even when the flag is on (no memories to compare\n * against → treat as not-applicable rather than maximally surprising).\n */\n bufferSurpriseRecentMemoryCount: number;\n /**\n * Hard timeout (ms) for the surprise probe. If the probe does not\n * resolve within this window, the buffer treats the probe as failed,\n * logs at debug, and falls through to the existing triggers. Ensures\n * a slow or hung embedder cannot stall the turn-append path. Default\n * `2000` (2s).\n */\n bufferSurpriseProbeTimeoutMs: number;\n consolidateEveryN: number;\n highSignalPatterns: string[];\n maxMemoryTokens: number;\n memoryOsPreset?: MemoryOsPresetName;\n qmdEnabled: boolean;\n qmdCollection: string;\n qmdMaxResults: number;\n qmdColdTierEnabled?: boolean;\n qmdColdCollection?: string;\n qmdColdMaxResults?: number;\n qmdTierMigrationEnabled: boolean;\n qmdTierDemotionMinAgeDays: number;\n qmdTierDemotionValueThreshold: number;\n qmdTierPromotionValueThreshold: number;\n qmdTierParityGraphEnabled: boolean;\n qmdTierParityHiMemEnabled: boolean;\n qmdTierAutoBackfillEnabled: boolean;\n qmdSupportedVersion: string;\n qmdAutoUpgradeEnabled: boolean;\n qmdAutoUpgradeCheckIntervalMs: number;\n qmdChunkStrategy: \"auto\" | \"regex\";\n qmdCandidateLimit?: number;\n qmdQueryRerankEnabled: boolean;\n // Daemon search plan; \"hybrid\" (default) = lex+vec+hyde. Issue #1335.\n qmdSearchStrategy: \"hybrid\" | \"lex-vec\" | \"lex\";\n // Subprocess fallback command; \"query\" (default) keeps LLM expansion. Issue #1335.\n qmdSubprocessStrategy: \"query\" | \"search\";\n // Per-call daemon search timeout in ms; default 8000. Issue #1335.\n qmdDaemonTimeoutMs: number;\n qmdIndexName?: string;\n qmdForceCpu: boolean;\n qmdGpuBackend?: \"auto\" | \"metal\" | \"cuda\" | \"vulkan\" | \"false\";\n qmdEmbedParallelism?: number;\n qmdEmbedModel?: string;\n qmdRerankModel?: string;\n qmdGenerateModel?: string;\n embeddingFallbackEnabled: boolean;\n embeddingFallbackProvider: \"auto\" | \"openai\" | \"local\";\n /**\n * Host adapters may register an embedding provider scoped to this memoryDir.\n * Core remains host-agnostic: when no provider is registered, the existing\n * OpenAI/local fallback path is used.\n */\n hostEmbeddingProviderEnabled: boolean;\n hostEmbeddingProviderId?: string;\n hostEmbeddingProviderModel?: string;\n /**\n * Optional model identifier for local embedding fallback requests.\n *\n * Local chat/completion models and local embedding models are often\n * different LM Studio/Ollama model IDs. When unset, Remnic preserves the\n * legacy behavior and falls back to `localLlmModel`.\n */\n embeddingFallbackModel: string;\n /** Optional absolute path to qmd binary. If unset, PATH/fallback discovery is used. */\n qmdPath?: string;\n memoryDir: string;\n debug: boolean;\n identityEnabled: boolean;\n identityContinuityEnabled: boolean;\n identityInjectionMode: IdentityInjectionMode;\n identityMaxInjectChars: number;\n continuityIncidentLoggingEnabled: boolean;\n continuityAuditEnabled: boolean;\n sessionObserverEnabled?: boolean;\n sessionObserverDebounceMs?: number;\n sessionObserverBands?: SessionObserverBandConfig[];\n injectQuestions: boolean;\n commitmentDecayDays: number;\n workspaceDir: string;\n captureMode: CaptureMode;\n fileHygiene?: FileHygieneConfig;\n nativeKnowledge?: NativeKnowledgeConfig;\n agentAccessHttp: AgentAccessHttpConfig;\n // Access tracking (Phase 1A)\n accessTrackingEnabled: boolean;\n accessTrackingBufferMaxSize: number;\n // Retrieval options\n recencyWeight: number;\n boostAccessCount: boolean;\n /** Record empty recall impressions (memoryIds: []) when no memories are injected. Disabled by default. */\n recordEmptyRecallImpressions: boolean;\n // v2.2 Advanced Retrieval\n queryExpansionEnabled: boolean;\n queryExpansionMaxQueries: number;\n /** Minimum token length to consider for query expansion. */\n queryExpansionMinTokenLen: number;\n rerankEnabled: boolean;\n /** Rerank provider. \"local\" uses Local LLM only; \"cloud\" uses gateway fallback chain. */\n rerankProvider: \"local\" | \"cloud\";\n rerankMaxCandidates: number;\n rerankTimeoutMs: number;\n rerankCacheEnabled: boolean;\n rerankCacheTtlMs: number;\n feedbackEnabled: boolean;\n // v2.2 Negative Examples (safe defaults: off unless enabled)\n /** If true, allow recording negative examples and apply a soft penalty during ranking. */\n negativeExamplesEnabled: boolean;\n /** Score penalty per \"not useful\" hit (typical QMD scores ~0-1). Keep small. */\n negativeExamplesPenaltyPerHit: number;\n /** Maximum penalty applied from negative examples. */\n negativeExamplesPenaltyCap: number;\n // Chunking (Phase 2A)\n chunkingEnabled: boolean;\n chunkingTargetTokens: number;\n chunkingMinTokens: number;\n chunkingOverlapSentences: number;\n // Semantic Chunking (Issue #368)\n /** Enable semantic chunking with embedding-based topic boundary detection. Default: false. */\n semanticChunkingEnabled: boolean;\n /** Optional overrides for the semantic chunking algorithm. */\n semanticChunkingConfig: Partial<SemanticChunkingConfigShape>;\n // Contradiction Detection (Phase 2B)\n contradictionDetectionEnabled: boolean;\n contradictionSimilarityThreshold: number;\n contradictionMinConfidence: number;\n contradictionAutoResolve: boolean;\n /** Nightly contradiction-scan cron config (issue #520). */\n contradictionScan: ContradictionScanConfig;\n // Temporal Supersession (issue #375)\n /**\n * When enabled, writes that carry `structuredAttributes` mark any older\n * fact with the same `entityRef + attribute_name` supersession key and a\n * conflicting value as `status: \"superseded\"`.\n */\n temporalSupersessionEnabled: boolean;\n /**\n * When enabled, superseded memories are still returned by recall (useful\n * for audit/history queries). Default: false — superseded memories are\n * filtered out.\n */\n temporalSupersessionIncludeInRecall: boolean;\n /**\n * Bi-temporal validity master gate (issue #1578). When `false` (default),\n * the recall validity-injection filter and `asOf` semantics behave\n * byte-identically to pre-#1578.\n *\n * Turn on to exclude validity-expired facts from default injection\n * candidates (they remain findable by explicit search and `as_of`\n * queries). Storage round-trips `observedAt`/`eventTimeSource`; the\n * extraction prompt emits an optional per-fact `eventTime` expression\n * and `resolveFactEventTime` resolves it against the source turn\n * timestamp at write time (#1578 PR2).\n */\n temporalBiTemporal: boolean;\n /**\n * Escape hatch for the bi-temporal injection filter (issue #1578). When\n * `true`, facts whose `[valid_at, invalid_at)` interval ended before now\n * are kept in injection candidates even with `temporalBiTemporal` on — some\n * deployments prefer the older (always-inject) behavior. Default `false`.\n */\n temporalExpiredInInjection: boolean;\n /**\n * Correction Contract (issue #1580) — one plan/apply pipeline for memory\n * corrections. Master visibility + enforcement gate for the\n * `memory_correct_plan` / `memory_correct_apply` tools. Default `true`:\n * planning is read-only (locates candidates + drafts a pending plan file)\n * and safe to ship on; `false` hides the tools and rejects runtime calls so\n * the surface cannot drift out of sync. Parsed from `correction.enabled`\n * (nested) or `correctionEnabled` (flat legacy).\n */\n correctionEnabled: boolean;\n /**\n * Whether `memory_correct_apply` requires an explicit `confirm: true` to\n * mutate memories. Default `true` (least-privileged). Parsed from\n * `correction.applyRequiresConfirm` / `correctionApplyRequiresConfirm`.\n */\n correctionApplyRequiresConfirm: boolean;\n /**\n * Max memories a single correction plan may touch; over-limit plans are\n * rejected, never silently truncated (review thread). Default `10`. Parsed\n * from `correction.maxAffected` / `correctionMaxAffected`.\n */\n correctionMaxAffected: number;\n /**\n * Plan time-to-live in hours; expired plans are rejected at apply. Default\n * `24`. Parsed from `correction.planTtlHours` / `correctionPlanTtlHours`.\n */\n correctionPlanTtlHours: number;\n // Tombstones — non-resurrection invariant (issue #1579).\n /**\n * Master gate for the tombstone non-resurrection invariant. When `true`\n * (default), a fact that matches an active tombstone at the storage\n * chokepoint is persisted as `status: \"pending_review\"` + `blockedBy`\n * instead of becoming active — visible, never a silent drop (rule 34).\n * When `false`, pre-feature behavior: the chokepoint check is a no-op and\n * retired facts can resurrect through re-extraction / import / consolidation\n * / dreams / pattern-reinforcement. Off = rollback safety (rule 30).\n */\n tombstonesEnabled: boolean;\n /**\n * Tier-4 semantic tombstone matching (issue #1579). Off by default — ships\n * dark until MemCorrect (#1584) shows an acceptable false-block rate\n * (rule 48). When `true`, the tombstone lookup also checks embedding cosine\n * similarity against tombstoned normalized text.\n */\n tombstonesSemanticMatch: boolean;\n /**\n * Cosine threshold for tier-4 semantic tombstone matching. Default `0.9`.\n * Only consulted when `tombstonesSemanticMatch` is `true`.\n */\n tombstonesSemanticThreshold: number;\n // Direct-answer retrieval tier (issue #518)\n /**\n * When true, recall checks whether a single validated memory in a\n * high-trust taxonomy bucket can answer the query before invoking QMD.\n * Default false — enable explicitly after bench validation.\n */\n recallDirectAnswerEnabled: boolean;\n /**\n * Disclosure auto-escalation policy (issue #677 PR 4/4). When set to\n * `\"auto\"`, recalls without an explicit caller-supplied disclosure\n * escalate from `chunk` to `section` if the top-K confidence falls\n * below {@link recallDisclosureEscalationThreshold}. `raw` is never\n * auto-selected — it requires an explicit caller request. Default\n * `\"manual\"` preserves pre-#677 behavior.\n */\n recallDisclosureEscalation: \"manual\" | \"auto\";\n /**\n * Top-K confidence threshold (in `[0, 1]`) below which auto-escalation\n * promotes `chunk` → `section`. Only consulted when\n * {@link recallDisclosureEscalation} is `\"auto\"`. Default `0.5`.\n */\n recallDisclosureEscalationThreshold: number;\n /**\n * Graph-based retrieval tier via Personalized PageRank (issue #559 PR 4).\n * When true, recall builds a retrieval graph from memory frontmatter\n * and runs PPR, merging the result with QMD via MMR. Default false —\n * ships off pending the retrieval-graph bench in PR 5.\n */\n recallGraphEnabled: boolean;\n /** PPR damping factor used when `recallGraphEnabled` is true. */\n recallGraphDamping: number;\n /** PPR power-iteration cap used when `recallGraphEnabled` is true. */\n recallGraphIterations: number;\n /**\n * Max memories returned by the graph tier before MMR. Set to 0 to\n * disable the graph tier's contribution without flipping the flag.\n */\n recallGraphTopK: number;\n /**\n * Minimum token-overlap ratio (query tokens ∩ memory tokens / query tokens)\n * required for direct-answer eligibility. Set to 0 to disable the gate.\n */\n recallDirectAnswerTokenOverlapFloor: number;\n /**\n * Minimum calibrated importance score required for direct-answer\n * eligibility. Set to 0 to disable the gate.\n */\n recallDirectAnswerImportanceFloor: number;\n /**\n * Ambiguity margin: if the second-best candidate scores within this\n * ratio of the top candidate, direct-answer defers to the hybrid tier.\n */\n recallDirectAnswerAmbiguityMargin: number;\n /**\n * Taxonomy category IDs eligible for direct-answer routing. Memories\n * whose resolved taxonomy category is not in this list never qualify.\n */\n recallDirectAnswerEligibleTaxonomyBuckets: string[];\n /**\n * Cross-namespace query-budget limiter (issue #565 PR 4/5). When true,\n * a principal that issues a burst of recalls against namespaces other\n * than their own is throttled once its per-window count crosses\n * `recallCrossNamespaceBudgetHardLimit`. Default false — ships disabled.\n */\n recallCrossNamespaceBudgetEnabled: boolean;\n /** Rolling window in milliseconds over which cross-namespace reads are counted. */\n recallCrossNamespaceBudgetWindowMs: number;\n /**\n * Soft threshold — the first point at which the limiter flags a burst.\n * Calls are still allowed; anomaly detection (issue #565 PR 5) will\n * surface the warning.\n */\n recallCrossNamespaceBudgetSoftLimit: number;\n /** Hard threshold — calls past this count are denied in the window. */\n recallCrossNamespaceBudgetHardLimit: number;\n // Memory Worth recall filter (issue #560 PR 4)\n /**\n * When true, recall multiplies candidate scores by the Memory Worth\n * factor computed from `mw_success` / `mw_fail` counters on each\n * memory's frontmatter (see `computeMemoryWorth`). Memories with a\n * history of failed sessions sink; neutral / uninstrumented memories\n * are untouched (multiplier 1.0). Default false — flip to true in PR 5\n * once the benchmark shows precision tie-or-win.\n */\n recallMemoryWorthFilterEnabled: boolean;\n /**\n * Recall-audit anomaly detector (issue #565 PR 5/5). When true,\n * access surfaces run the anomaly detector over a tail of the audit\n * trail after each recall and surface any flags via logs / metrics.\n * Ships disabled.\n */\n recallAuditAnomalyDetectionEnabled: boolean;\n /** Rolling window over which audit entries are analyzed. */\n recallAuditAnomalyWindowMs: number;\n /** Threshold for the `repeat-query` flag. */\n recallAuditAnomalyRepeatQueryLimit: number;\n /** Threshold for the `namespace-walk` flag (distinct namespaces). */\n recallAuditAnomalyNamespaceWalkLimit: number;\n /** Threshold for the `high-cardinality-return` flag. */\n recallAuditAnomalyHighCardinalityLimit: number;\n /** Threshold for the `rapid-fire` flag. */\n recallAuditAnomalyRapidFireLimit: number;\n /**\n * Optional half-life for Memory Worth decay, in milliseconds. When\n * positive, older outcome observations are exponentially decayed toward\n * the uniform prior. Set to 0 (default) to disable decay and use raw\n * counter values.\n */\n recallMemoryWorthHalfLifeMs: number;\n // Memory Linking (Phase 3A)\n memoryLinkingEnabled: boolean;\n // Conversation Threading (Phase 3B)\n threadingEnabled: boolean;\n threadingGapMinutes: number;\n // Memory Summarization (Phase 4A)\n summarizationEnabled: boolean;\n summarizationTriggerCount: number;\n summarizationRecentToKeep: number;\n summarizationImportanceThreshold: number;\n summarizationProtectedTags: string[];\n // Topic Extraction (Phase 4B)\n topicExtractionEnabled: boolean;\n topicExtractionTopN: number;\n // Transcript & Context Preservation (v2.0)\n // Transcript archive\n transcriptEnabled: boolean;\n transcriptRetentionDays: number;\n /** Channel types to skip from transcript logging (e.g., [\"cron\"]) */\n transcriptSkipChannelTypes: string[];\n // Transcript injection\n transcriptRecallHours: number;\n maxTranscriptTurns: number;\n maxTranscriptTokens: number;\n // Checkpoint\n checkpointEnabled: boolean;\n checkpointTurns: number;\n // Compaction reset: trigger session reset after compaction instead of continuing degraded.\n // Requires OC fork with PR #29985 (api.resetSession).\n compactionResetEnabled: boolean;\n beforeResetTimeoutMs: number;\n initGateTimeoutMs: number;\n flushOnResetEnabled: boolean;\n commandsListEnabled: boolean;\n openclawToolsEnabled: boolean;\n openclawToolSnippetMaxChars: number;\n openclawMessageReceivedCaptureEnabled: boolean;\n openclawReplyMetadataCaptureEnabled: boolean;\n openclawReplyMetadataExtractionHintsEnabled: boolean;\n openclawChannelEnvelopeCleaningEnabled: boolean;\n sessionTogglesEnabled: boolean;\n verboseRecallVisibility: boolean;\n recallTranscriptsEnabled: boolean;\n recallTranscriptRetentionDays: number;\n respectBundledActiveMemoryToggle: boolean;\n activeRecallEnabled: boolean;\n activeRecallAgents: string[] | null;\n activeRecallAllowedChatTypes: ActiveRecallChatType[];\n activeRecallQueryMode: ActiveRecallQueryMode;\n activeRecallPromptStyle: ActiveRecallPromptStyle;\n activeRecallCustomInstruction: string | null;\n activeRecallPromptAppend: string | null;\n activeRecallMaxSummaryChars: number;\n activeRecallRecentUserTurns: number;\n activeRecallRecentAssistantTurns: number;\n activeRecallRecentUserChars: number;\n activeRecallRecentAssistantChars: number;\n activeRecallThinking: ActiveRecallThinking;\n activeRecallTimeoutMs: number;\n activeRecallCacheTtlMs: number;\n activeRecallModel: string | null;\n activeRecallModelFallbackPolicy: ActiveRecallModelFallbackPolicy;\n activeRecallPersistTranscripts: boolean;\n activeRecallTranscriptDir: string;\n activeRecallEntityGraphDepth: number;\n activeRecallIncludeCausalTrajectories: boolean;\n activeRecallIncludeDaySummary: boolean;\n activeRecallAttachRecallExplain: boolean;\n activeRecallAllowChainedActiveMemory: boolean;\n dreaming: DreamingConfig;\n /**\n * Unified dreams-phases config block (issue #678 PR 2/4).\n * Groups existing lifecycle, REM, and deep-sleep gates under one namespace.\n * Values here WIN over equivalent legacy top-level keys when set. See docs/dreams.md.\n */\n dreamsPhases: DreamsPhasesConfig;\n procedural: ProceduralConfig;\n /**\n * Claim-level provenance spans (issue #1575). Parsed from the\n * `provenance` config block; see `ProvenanceConfig` for the documented\n * defaults. PR 1 parses + persists only; extraction wiring lands in PR 2.\n */\n provenance: ProvenanceConfig;\n /**\n * Wearable transcript ingestion (Limitless / Bee / Omi connectors).\n * Disabled by default; see docs/wearables.md.\n */\n wearables: import(\"./wearables/types.js\").WearablesConfig;\n /**\n * At-rest encryption configuration (issue #690 PR 3/4).\n *\n * When `secureStoreEnabled` is true, `StorageManager` reads and\n * writes memory files through the `secure-fs` encryption layer.\n * The store must be unlocked via `remnic secure-store unlock` before\n * any recall or store operations will succeed.\n *\n * When `secureStoreEncryptOnWrite` is true (the default when enabled),\n * every new memory write is encrypted. Set to false to pause new\n * encryptions while still being able to decrypt existing files.\n */\n secureStoreEnabled: boolean;\n /** Encrypt new writes when the secure-store is unlocked. Default true. */\n secureStoreEncryptOnWrite: boolean;\n // Coding-agent project/branch scoping (issue #569)\n codingMode: CodingModeConfig;\n // Coding-knowledge durable memory surface (issue #1548 Track A). Off\n // by default — byte-for-byte pre-feature behaviour when `enabled === false`\n // (rule 39).\n codingKnowledge: CodingKnowledgeConfig;\n heartbeat: HeartbeatConfig;\n // Conversational memory inspection and correction (issue #1583). Off by\n // default — byte-identical pre-feature when enabled === false (rule 39).\n chat: ChatConfig;\n slotBehavior: SlotBehaviorConfig;\n codexCompat: CodexCompatConfig;\n /**\n * When true (default), the extraction prompt instructs the LLM to classify\n * each fact as `\"project\"` or `\"global\"` scope. Global-scoped facts are\n * promoted to the shared namespace so they are visible across all projects.\n * When false, all facts go to whatever namespace the session is in (pre-\n * scope-classification behavior). Rule 30: configuration gate.\n */\n extractionScopeClassificationEnabled: boolean;\n // Extraction judge (issue #376)\n /** Enable the LLM-as-judge fact-worthiness gate on extracted facts. Default false (opt-in). */\n extractionJudgeEnabled: boolean;\n /** Model override for the judge LLM. Empty string means use the local model. */\n extractionJudgeModel: string;\n /** Maximum number of candidate facts per judge LLM batch call. */\n extractionJudgeBatchSize: number;\n /** Shadow mode: log judge verdicts but do not filter facts. Default false. */\n extractionJudgeShadow: boolean;\n /**\n * Maximum number of times the same candidate text may be deferred before\n * the judge forcibly converts the verdict to `\"reject\"`. Prevents\n * pathological LLM responses from looping forever on ambiguous facts.\n * Defaults to 2 (issue #562, PR 2).\n */\n extractionJudgeMaxDeferrals: number;\n /**\n * Emit structured telemetry rows to\n * `state/observation-ledger/extraction-judge-verdicts.jsonl` on every\n * judge verdict. Off by default; enable to collect defer-rate / latency\n * metrics for operator dashboards (issue #562, PR 3).\n */\n extractionJudgeTelemetryEnabled: boolean;\n /**\n * Collect `(candidate_text, verdict_kind, reason)` tuples into\n * `~/.remnic/judge-training/<date>.jsonl` for use by a future GRPO\n * training pipeline (issue #562, PR 4). Off by default. Rows live in\n * the user's home directory rather than the shared memory directory so\n * they are not committed, sync'd, or bundled into memory exports.\n */\n collectJudgeTrainingPairs: boolean;\n /**\n * Override directory for judge training-pair collection. Empty string\n * means use the default (`~/.remnic/judge-training`). Primarily for\n * tests and for operators who want the output to land in a specific\n * location.\n */\n judgeTrainingDir: string;\n // Extraction faithfulness gate (issue #1576). Entailment-verification of\n // extracted facts against their verified source spans from #1575.\n /** Gate mode: \"off\" (default, byte-identical pre-feature), \"shadow\" (record only), \"enforce\" (route to pending_review). */\n extractionFaithfulnessGate: \"off\" | \"shadow\" | \"enforce\";\n /** Override model/endpoint; empty string = default routing chain. */\n extractionFaithfulnessModel: string;\n /** Context window (chars) around the quote sent to the verifier. Default 400. */\n extractionFaithfulnessContextChars: number;\n /** Per-batch timeout in ms; timeout → tagged error, never blocks writes. Default 8000. */\n extractionFaithfulnessTimeoutMs: number;\n // Hourly summaries\n hourlySummariesEnabled: boolean;\n daySummaryEnabled: boolean;\n /** Timezone override for the day summary cron (issue #1475). */\n daySummaryTimezone?: string;\n /** If true, Engram may attempt to auto-register an hourly summary cron job (default off). */\n hourlySummaryCronAutoRegister: boolean;\n /** If true, Engram may attempt to auto-register the nightly governance cron job (default off). */\n nightlyGovernanceCronAutoRegister: boolean;\n summaryRecallHours: number;\n maxSummaryCount: number;\n summaryModel: string;\n // v2.4 Extended hourly summaries\n hourlySummariesExtendedEnabled: boolean;\n hourlySummariesIncludeToolStats: boolean;\n hourlySummariesIncludeSystemMessages: boolean;\n hourlySummariesMaxTurnsPerRun: number;\n // v2.4 Conversation index (optional)\n conversationIndexEnabled: boolean;\n conversationIndexBackend: \"qmd\" | \"faiss\";\n conversationIndexQmdCollection: string;\n conversationIndexRetentionDays: number;\n conversationIndexMinUpdateIntervalMs: number;\n conversationIndexEmbedOnUpdate: boolean;\n conversationIndexFaissScriptPath?: string;\n conversationIndexFaissPythonBin?: string;\n conversationIndexFaissModelId: string;\n conversationIndexFaissIndexDir: string;\n conversationIndexFaissUpsertTimeoutMs: number;\n conversationIndexFaissSearchTimeoutMs: number;\n conversationIndexFaissHealthTimeoutMs: number;\n conversationIndexFaissMaxBatchSize: number;\n conversationIndexFaissMaxSearchK: number;\n conversationRecallTopK: number;\n conversationRecallMaxChars: number;\n conversationRecallTimeoutMs: number;\n // Evaluation harness foundation\n evalHarnessEnabled: boolean;\n evalShadowModeEnabled: boolean;\n benchmarkBaselineSnapshotsEnabled: boolean;\n benchmarkDeltaReporterEnabled: boolean;\n benchmarkStoredBaselineEnabled: boolean;\n evalStoreDir: string;\n // Objective-state memory foundation\n objectiveStateMemoryEnabled: boolean;\n objectiveStateSnapshotWritesEnabled: boolean;\n objectiveStateRecallEnabled: boolean;\n objectiveStateStoreDir: string;\n // Causal trajectory memory foundation\n causalTrajectoryMemoryEnabled: boolean;\n causalTrajectoryStoreDir: string;\n causalTrajectoryRecallEnabled: boolean;\n actionGraphRecallEnabled: boolean;\n // Trust-zone memory foundation\n trustZonesEnabled: boolean;\n quarantinePromotionEnabled: boolean;\n trustZoneStoreDir: string;\n trustZoneRecallEnabled: boolean;\n memoryPoisoningDefenseEnabled: boolean;\n memoryRedTeamBenchEnabled: boolean;\n // Harmonic retrieval foundation\n harmonicRetrievalEnabled: boolean;\n abstractionAnchorsEnabled: boolean;\n abstractionNodeStoreDir: string;\n // Episodic/semantic split foundation\n verifiedRecallEnabled: boolean;\n semanticRulePromotionEnabled: boolean;\n semanticRuleVerificationEnabled: boolean;\n semanticConsolidationEnabled: boolean;\n semanticConsolidationModel: string;\n semanticConsolidationThreshold: number;\n semanticConsolidationMinClusterSize: number;\n semanticConsolidationExcludeCategories: string[];\n semanticConsolidationIntervalHours: number;\n semanticConsolidationMaxPerRun: number;\n /**\n * When true (default), semantic-consolidation prompts the LLM with an\n * operator-aware format asking for JSON `{operator, output}` and records\n * the resulting SPLIT/MERGE/UPDATE operator on `derived_via`. When\n * false, falls back to the legacy plain-text prompt — `derived_via` is\n * still populated via the cluster-shape heuristic in\n * `chooseConsolidationOperator`. Issue #561 PR 3.\n */\n operatorAwareConsolidationEnabled: boolean;\n // Pattern reinforcement (issue #687 PR 2/4)\n /**\n * When true, the pattern-reinforcement maintenance job runs on its\n * configured cadence and clusters duplicate non-procedural memories\n * by normalized content. Clusters with `>= patternReinforcementMinCount`\n * members produce a canonical (most-recent) memory tagged with\n * `reinforcement_count` + `last_reinforced_at`; the older duplicates\n * are marked `superseded` and pointed at the canonical. Default\n * `false` — opt-in until bench validation lands.\n */\n patternReinforcementEnabled: boolean;\n /**\n * Minimum interval (ms) between pattern-reinforcement runs. Default\n * `7 * 24 * 60 * 60 * 1000` (7 days). Set to `0` to disable cadence\n * gating (useful for tests / manual invocation).\n */\n patternReinforcementCadenceMs: number;\n /**\n * Minimum cluster size before pattern reinforcement promotes a\n * canonical and supersedes duplicates. Default `3`. Clamped to\n * `>= 2` at config-parse time — a \"cluster of 1\" is just a single\n * memory and a \"cluster of 0\" is meaningless.\n */\n patternReinforcementMinCount: number;\n /**\n * Memory categories the pattern-reinforcement job considers.\n * Default `[\"preference\", \"fact\", \"decision\"]`. The job\n * intentionally skips procedural memories so it stays disjoint from\n * the procedural mining pipeline.\n */\n patternReinforcementCategories: string[];\n /** issue #687 PR 3/4: opt-in recall score boost for reinforced memories. Default false. */\n reinforcementRecallBoostEnabled: boolean;\n /** Score bonus per unit of reinforcement_count. Range [0, 1]. Default 0.05. */\n reinforcementRecallBoostWeight: number;\n /** Maximum additive reinforcement boost per result. Range [0, 1]. Default 0.3. */\n reinforcementRecallBoostMax: number;\n /**\n * Async peer profile reasoner — issue #679 PR 2/5.\n *\n * Default `false` (opt-in). When enabled, the reasoner runs after\n * `runSemanticConsolidation` (the REM phase of the dreams pipeline)\n * and updates per-peer profile.md files with provenance-tagged\n * field updates derived from the peer's interaction log.\n */\n peerProfileReasonerEnabled: boolean;\n /**\n * Model identifier used by the peer profile reasoner. Logged for\n * telemetry only — actual dispatch is via the same FallbackLlmClient\n * the orchestrator uses for semantic consolidation. Default `gpt-5.5`.\n */\n peerProfileReasonerModel: string;\n /**\n * Minimum new interaction-log entries a peer must accumulate since\n * the previous reasoner run before being processed again. Default 5.\n * Setting to 0 forces every run to consider every peer.\n */\n peerProfileReasonerMinInteractions: number;\n /**\n * Hard cap on the total number of profile fields the reasoner will\n * apply across all peers in a single run. Default 8.\n */\n peerProfileReasonerMaxFieldsPerRun: number;\n /**\n * When true, inject the active peer's profile fields into the recall\n * context as a \"## Peer Profile\" section. Default false (opt-in,\n * Gotcha #30/#48 — least-privileged default). Requires the session's\n * peer ID to be registered via `setPeerIdForSession` before recall.\n */\n peerProfileRecallEnabled: boolean;\n /**\n * Maximum number of peer profile fields to inject per recall. Only\n * the most-recently-updated N fields are included to keep the context\n * budget predictable. Default 5. Setting to 0 disables field\n * injection even when `peerProfileRecallEnabled` is true.\n */\n peerProfileRecallMaxFields: number;\n // Creation-memory foundation\n creationMemoryEnabled: boolean;\n memoryUtilityLearningEnabled: boolean;\n promotionByOutcomeEnabled: boolean;\n commitmentLedgerEnabled: boolean;\n commitmentLifecycleEnabled: boolean;\n commitmentStaleDays: number;\n commitmentLedgerDir: string;\n resumeBundlesEnabled: boolean;\n resumeBundleDir: string;\n workProductRecallEnabled: boolean;\n workProductLedgerDir: string;\n workTasksEnabled: boolean;\n workProjectsEnabled: boolean;\n workTasksDir: string;\n workProjectsDir: string;\n workIndexEnabled: boolean;\n workIndexDir: string;\n workTaskIndexEnabled: boolean;\n workProjectIndexEnabled: boolean;\n workIndexAutoRebuildEnabled: boolean;\n workIndexAutoRebuildDebounceMs: number;\n // Local LLM Provider (v2.1)\n localLlmEnabled: boolean;\n localLlmUrl: string;\n localLlmModel: string;\n /** Optional API key for authenticated OpenAI-compatible endpoints. */\n localLlmApiKey?: string;\n /** Additional headers for local/compatible endpoint requests. */\n localLlmHeaders?: Record<string, string>;\n /** If false, do not send Authorization header even when localLlmApiKey is set. */\n localLlmAuthHeader: boolean;\n localLlmFallback: boolean;\n /** Optional home directory override for local LLM helpers (LM Studio settings, CLI PATH). */\n localLlmHomeDir?: string;\n /** Optional absolute path to LMS CLI binary (preferred over auto-detection). */\n localLmsCliPath?: string;\n /** Optional bin directory prepended to PATH for LMS CLI execution. */\n localLmsBinDir?: string;\n /** Hard timeout for local LLM and gateway fallback requests (ms). */\n localLlmTimeoutMs: number;\n /** Max context window for local LLM (override auto-detection). Set lower if your LLM server defaults to smaller contexts. */\n localLlmMaxContext?: number;\n // Observability\n /** If true, log slow operations (local LLM + related I/O) with durations and metadata (no content). */\n slowLogEnabled: boolean;\n /**\n * If true, include the full recalled memory text in `RecallTraceEvent.recalledContent`.\n * Disabled by default — enable only when you want external trace subscribers (e.g. Langfuse)\n * to see the exact memory context injected into each conversation turn.\n * This adds payload to trace events but does not log to files or the gateway log.\n */\n traceRecallContent: boolean;\n /** Threshold for slow operation logging (ms). */\n slowLogThresholdMs: number;\n // Performance profiling (opt-in)\n /** If true, collect and persist timing traces for recall and extraction pipelines. */\n profilingEnabled: boolean;\n /** Directory for profiling trace JSONL files. Defaults to <memoryDir>/profiling. */\n profilingStorageDir: string;\n /** Maximum number of trace files to keep (rolling window). */\n profilingMaxTraces: number;\n // Extraction stability guards (P0/P1)\n extractionDedupeEnabled: boolean;\n extractionDedupeWindowMs: number;\n extractionMinChars: number;\n extractionMinUserTurns: number;\n /**\n * When true, skip semantic memory extraction for mechanical action/state\n * telemetry transcripts that have no durable-memory cue. Raw transcript\n * storage/recall still runs; this only prevents expensive low-value fact\n * extraction over state logs. Default true.\n */\n extractionTelemetryPrefilterEnabled: boolean;\n /**\n * When true, LCM uses deterministic compression instead of semantic LLM\n * summarization for mechanical action/state telemetry transcripts with no\n * durable-memory cue. Raw transcript storage/recall still runs. Default true.\n */\n lcmTelemetryPrefilterEnabled: boolean;\n extractionMaxTurnChars: number;\n extractionMaxFactsPerRun: number;\n extractionMaxEntitiesPerRun: number;\n extractionMaxQuestionsPerRun: number;\n extractionMaxProfileUpdatesPerRun: number;\n /**\n * Minimum importance level required to persist an extracted fact. Facts\n * whose locally-scored level falls below this threshold are dropped before\n * write and counted toward the `importance_gated` metric. Defaults to\n * \"low\" so trivial content (greetings, single-word replies, filler) is\n * silently dropped while everything else still passes.\n */\n extractionMinImportanceLevel: ImportanceLevel;\n /**\n * Inline source attribution (issue #369).\n * When enabled, extracted facts carry a compact provenance tag (agent,\n * session, timestamp) inlined into the fact text — not just in YAML\n * frontmatter — so the citation survives hostile memory text, copy/paste,\n * and LLM quoting. Off by default to preserve backwards compatibility\n * with existing downstream consumers that expect raw fact text.\n */\n inlineSourceAttributionEnabled: boolean;\n /**\n * Template used when injecting inline citations. Supported placeholders:\n * `{agent}`, `{session}`, `{sessionId}`, `{ts}`, `{date}`. Defaults to\n * `[Source: agent={agent}, session={sessionId}, ts={ts}]`.\n */\n inlineSourceAttributionFormat: string;\n consolidationRequireNonZeroExtraction: boolean;\n consolidationMinIntervalMs: number;\n // QMD maintenance (debounced singleflight)\n qmdMaintenanceEnabled: boolean;\n qmdMaintenanceDebounceMs: number;\n /**\n * Namespace-aware maintenance fanout (issue #1500). When namespaces are\n * enabled, background maintenance jobs use the rebuildable namespace catalog\n * to discover dynamic project/team namespaces rather than only processing the\n * configured default/shared/policy set.\n */\n maintenanceNamespaceFanoutEnabled: boolean;\n maintenanceMaxNamespacesPerCycle: number;\n maintenanceIncludeProjectNamespaces: boolean;\n maintenanceIncludeBranchNamespaces: boolean;\n maintenanceIncludeTeamProjectNamespaces: boolean;\n maintenanceNamespaceLockStaleMs: number;\n qmdAutoEmbedEnabled: boolean;\n qmdEmbedMinIntervalMs: number;\n qmdUpdateTimeoutMs: number;\n qmdUpdateMinIntervalMs: number;\n // Local LLM resilience\n localLlmRetry5xxCount: number;\n localLlmRetryBackoffMs: number;\n localLlm400TripThreshold: number;\n localLlm400CooldownMs: number;\n // Local LLM fast tier (v9.1) — smaller model for quick ops\n localLlmFastEnabled: boolean;\n localLlmFastModel: string;\n localLlmFastUrl: string;\n localLlmFastTimeoutMs: number;\n /**\n * Suppress chain-of-thought / thinking mode on the main local LLM\n * (issue #548). When true, Remnic injects\n * `chat_template_kwargs: { enable_thinking: false }` on every\n * request so thinking-capable models (Qwen 3.5, Gemma 4, DeepSeek,\n * etc.) skip reasoning tokens that structured-output tasks like\n * extraction and consolidation cannot benefit from. Default: true\n * — the dominant localLlm use case is JSON-shaped extraction where\n * thinking is pure latency tax and a common cause of 60s timeouts.\n * Set to false to restore thinking for narrative tasks.\n *\n * The fast-tier client (`fastLlm`) always disables thinking; that\n * contract is baked into \"fast tier\" and is unaffected by this flag.\n */\n localLlmDisableThinking: boolean;\n // Gateway config for fallback AI\n gatewayConfig?: GatewayConfig;\n /**\n * Optional host-supplied resolver for provider API keys. Core never discovers\n * host runtimes directly; adapters inject their native secret resolver here.\n */\n providerApiKeyResolver?: (params: {\n provider: string;\n cfg?: unknown;\n agentDir?: string;\n }) => Promise<{ apiKey?: string; source?: string; mode?: string } | null>;\n /**\n * Optional host-supplied resolver for request-ready model auth, including\n * provider transforms such as OAuth token exchange or base URL overrides.\n */\n runtimeAuthForModelResolver?: (params: {\n model: { provider: string; id: string; api?: string; baseUrl?: string };\n cfg?: unknown;\n workspaceDir?: string;\n }) => Promise<{\n apiKey?: string;\n baseUrl?: string;\n source?: string;\n mode?: string;\n profileId?: string;\n } | null>;\n // Gateway model source (v9.2) — route LLM calls through gateway agent model chain\n modelSource: \"plugin\" | \"gateway\";\n gatewayAgentId: string;\n fastGatewayAgentId: string;\n /**\n * Optional task-specific model chain for Remnic's background LLM work —\n * extraction, the extraction judge, fact/profile/identity consolidation,\n * summarization, semantic consolidation, calibration, and causal\n * consolidation. When set, this chain is resolved through gateway providers\n * instead of using gatewayAgentId or agents.defaults.model. All task paths\n * route through the shared `gatewayTaskChainOptions` helper.\n * LCM summarization is the one fast-tier exception: if `fastGatewayAgentId`\n * is configured, LCM uses that persona before falling back to this chain.\n *\n * Only takes effect when `modelSource: \"gateway\"`; ignored (with a startup\n * warning) under `modelSource: \"plugin\"`. See issue #1365 / PR #1370.\n */\n taskModelChain?: AgentPersonaModelConfig;\n\n // v3.0 Multi-agent memory (namespaces)\n namespacesEnabled: boolean;\n /**\n * Enable the rebuildable namespace catalog (issue #1499). When enabled and\n * `namespacesEnabled` is also true, storage resolution and read/write paths\n * record cheap, failure-tolerant namespace touches in\n * `<memoryDir>/state/namespaces.jsonl`. The catalog is downstream metadata —\n * filesystem memory remains the source of truth, and the catalog is fully\n * rebuildable from disk via `remnic namespaces rebuild`. The catalog is inert\n * (a no-op that enumerates nothing) whenever `namespacesEnabled` is false, so\n * existing single-namespace behavior is unchanged. Default on.\n */\n namespaceCatalogEnabled: boolean;\n defaultNamespace: string;\n sharedNamespace: string;\n principalFromSessionKeyMode: PrincipalFromSessionKeyMode;\n principalFromSessionKeyRules: PrincipalRule[];\n namespacePolicies: NamespacePolicy[];\n defaultRecallNamespaces: Array<\"self\" | \"shared\">;\n scopeProfiles: Record<string, ScopeProfileConfig>;\n defaultScopeProfile: string | undefined;\n teams: Record<string, ScopeTeamConfig>;\n cronRecallMode: CronRecallMode;\n cronRecallAllowlist: string[];\n cronRecallPolicyEnabled: boolean;\n cronRecallNormalizedQueryMaxChars: number;\n cronRecallInstructionHeavyTokenCap: number;\n cronConversationRecallMode: CronConversationRecallMode;\n autoPromoteToSharedEnabled: boolean;\n autoPromoteToSharedCategories: Array<\"fact\" | \"correction\" | \"decision\" | \"preference\">;\n autoPromoteMinConfidenceTier: ConfidenceTier;\n routingRulesEnabled: boolean;\n routingRulesStateFile: string;\n\n // v4.0 Shared-context (cross-agent shared intelligence)\n sharedContextEnabled: boolean;\n sharedContextDir?: string;\n sharedContextMaxInjectChars: number;\n crossSignalsSemanticEnabled: boolean;\n crossSignalsSemanticTimeoutMs: number;\n sharedCrossSignalSemanticEnabled?: boolean;\n sharedCrossSignalSemanticTimeoutMs?: number;\n sharedCrossSignalSemanticMaxCandidates?: number;\n\n // v5.0 Compounding engine\n compoundingEnabled: boolean;\n compoundingWeeklyCronEnabled: boolean;\n compoundingSemanticEnabled: boolean;\n compoundingSynthesisTimeoutMs: number;\n compoundingInjectEnabled: boolean;\n\n // IRC (Inductive Rule Consolidation) — preference synthesis\n ircEnabled: boolean;\n ircMaxPreferences: number;\n ircIncludeCorrections: boolean;\n ircMinConfidence: number;\n\n // CMC (Causal Memory Consolidation) — cross-session causal reasoning\n cmcEnabled: boolean;\n cmcStitchLookbackDays: number;\n cmcStitchMinScore: number;\n cmcStitchMaxEdgesPerTrajectory: number;\n cmcConsolidationEnabled: boolean;\n cmcConsolidationMinRecurrence: number;\n cmcConsolidationMinSessions: number;\n cmcConsolidationSuccessThreshold: number;\n cmcRetrievalEnabled: boolean;\n cmcRetrievalMaxDepth: number;\n cmcRetrievalMaxChars: number;\n cmcRetrievalCounterfactualBoost: number;\n cmcBehaviorLearningEnabled: boolean;\n cmcBehaviorMinFrequency: number;\n cmcBehaviorMinSessions: number;\n cmcBehaviorConfidenceThreshold: number;\n cmcLifecycleCausalImpactWeight: number;\n\n // PEDC (Prediction-Error-Driven Calibration) — model-user alignment\n calibrationEnabled: boolean;\n calibrationMaxRulesPerRecall: number;\n calibrationMaxChars: number;\n\n // Search backend abstraction\n searchBackend?: \"qmd\" | \"remote\" | \"noop\" | \"lancedb\" | \"meilisearch\" | \"orama\";\n remoteSearchBaseUrl?: string;\n remoteSearchApiKey?: string;\n remoteSearchTimeoutMs?: number;\n\n // LanceDB backend\n lancedbEnabled: boolean;\n lanceDbPath?: string;\n lanceEmbeddingDimension?: number;\n\n // Meilisearch backend\n meilisearchEnabled: boolean;\n meilisearchHost?: string;\n meilisearchApiKey?: string;\n meilisearchTimeoutMs?: number;\n meilisearchAutoIndex?: boolean;\n\n // Orama backend\n oramaEnabled: boolean;\n oramaDbPath?: string;\n oramaEmbeddingDimension?: number;\n\n // QMD daemon mode\n qmdDaemonEnabled: boolean;\n qmdDaemonUrl: string;\n qmdDaemonRecheckIntervalMs: number;\n qmdIntentHintsEnabled: boolean;\n qmdExplainEnabled: boolean;\n\n // v7.0 Knowledge Graph Enhancement\n knowledgeIndexEnabled: boolean;\n knowledgeIndexMaxEntities: number;\n knowledgeIndexMaxChars: number;\n entityRetrievalEnabled: boolean;\n entityRetrievalMaxChars: number;\n entityRetrievalMaxHints: number;\n entityRetrievalMaxSupportingFacts: number;\n entityRetrievalMaxRelatedEntities: number;\n entityRetrievalRecentTurns: number;\n entitySchemas?: Record<string, EntitySchemaDefinition>;\n // Recall assembly controls\n recallBudgetChars: number;\n recallOuterTimeoutMs: number;\n recallCoreDeadlineMs: number;\n recallEnrichmentDeadlineMs: number;\n recallPipeline: RecallSectionConfig[];\n /** Apply Maximal Marginal Relevance to the final recall selection per-section. */\n recallMmrEnabled: boolean;\n /** MMR λ parameter. 1.0 = pure relevance, 0.0 = pure diversity. Default 0.7. */\n recallMmrLambda: number;\n /** MMR is applied over the top N candidates per section. Default 40. */\n recallMmrTopN: number;\n /**\n * Boost stored `reasoning_trace` memories in recall results when the\n * incoming query reads like a problem-solving ask (e.g. \"how do I…\",\n * \"step by step\", \"walk me through…\"). Default false — opt in after\n * benchmarking (issue #564 PR 3).\n */\n recallReasoningTraceBoostEnabled: boolean;\n /**\n * Issue #1582 — append stable short handles (`[m:4f2a]`) to injected memory\n * lines at recall render time. Default false: off = byte-identical injection\n * (rule 39). Token cost ~9 chars/memory; flip the default only with #1574\n * evidence that answer quality is unaffected (rule 55).\n */\n recallMemoryHandles: boolean;\n /**\n * Issue #1582 — how many recent per-session recall snapshots (newest first)\n * handle resolution searches. Older-than-N snapshots are not searched and a\n * miss is tagged rather than widening the window.\n */\n recallHandleSnapshotDepth: number;\n qmdRecallCacheTtlMs: number;\n qmdRecallCacheStaleTtlMs: number;\n qmdRecallCacheMaxEntries: number;\n entityRelationshipsEnabled: boolean;\n entityActivityLogEnabled: boolean;\n entityActivityLogMaxEntries: number;\n entityAliasesEnabled: boolean;\n entitySummaryEnabled: boolean;\n entitySynthesisMaxTokens: number;\n\n // v6.0 Fact deduplication & archival\n /** Enable content-hash deduplication to prevent storing semantically identical facts. */\n factDeduplicationEnabled: boolean;\n /**\n * Issue #373 — Write-time semantic similarity guard. When enabled (default),\n * the orchestrator embeds each candidate fact and queries the existing\n * embedding index for its top-K nearest neighbors. If the best cosine\n * similarity is at or above `semanticDedupThreshold`, the fact is dropped\n * as a near-duplicate. Fails open (keeps the fact) if the embedding backend\n * is unavailable.\n */\n semanticDedupEnabled: boolean;\n /** Cosine similarity threshold in [0, 1] above which a candidate fact is skipped. */\n semanticDedupThreshold: number;\n /** Number of nearest-neighbor candidates to consider during semantic dedup. */\n semanticDedupCandidates: number;\n /** Enable automatic archival of old, low-importance, rarely-accessed facts. */\n factArchivalEnabled: boolean;\n /** Minimum age in days before a fact is eligible for archival. */\n factArchivalAgeDays: number;\n /** Maximum importance score for archival eligibility (0-1). Only facts below this are archived. */\n factArchivalMaxImportance: number;\n /** Maximum access count for archival eligibility. Only rarely-accessed facts are archived. */\n factArchivalMaxAccessCount: number;\n /** Tags that protect a fact from archival regardless of other criteria. */\n factArchivalProtectedCategories: string[];\n // v8.3 Lifecycle policy engine\n lifecyclePolicyEnabled: boolean;\n lifecycleFilterStaleEnabled: boolean;\n lifecyclePromoteHeatThreshold: number;\n lifecycleStaleDecayThreshold: number;\n lifecycleArchiveDecayThreshold: number;\n lifecycleProtectedCategories: MemoryCategory[];\n lifecycleMetricsEnabled: boolean;\n // v8.3 proactive + policy learning\n proactiveExtractionEnabled: boolean;\n contextCompressionActionsEnabled: boolean;\n compressionGuidelineLearningEnabled: boolean;\n compressionGuidelineSemanticRefinementEnabled: boolean;\n compressionGuidelineSemanticTimeoutMs: number;\n maxProactiveQuestionsPerExtraction: number;\n proactiveExtractionTimeoutMs: number;\n proactiveExtractionMaxTokens: number;\n extractionMaxOutputTokens: number;\n proactiveExtractionCategoryAllowlist?: MemoryCategory[];\n maxCompressionTokensPerHour: number;\n behaviorLoopAutoTuneEnabled: boolean;\n behaviorLoopLearningWindowDays: number;\n behaviorLoopMinSignalCount: number;\n behaviorLoopMaxDeltaPerCycle: number;\n behaviorLoopProtectedParams: string[];\n // v8.0 Phase 1: recall planner + intent routing + verbatim artifacts\n recallPlannerEnabled: boolean;\n /**\n * Opt-in gate for LLM-based recall planning (issue #1367 / Option C). When\n * false (the default) recall mode is decided by the regex heuristic\n * `planRecallMode()`. When true, the planner consults an LLM (routed through\n * the gateway/fallback chain — provider-agnostic) and falls back to the\n * heuristic on timeout/error/unavailable. `recallPlannerShadowMode` runs the\n * LLM for telemetry only without changing the effective mode.\n */\n recallPlannerLlmEnabled: boolean;\n recallPlannerModel: string;\n recallPlannerTimeoutMs: number;\n recallPlannerUseResponsesApi: boolean;\n recallPlannerMaxPromptChars: number;\n recallPlannerMaxMemoryHints: number;\n recallPlannerShadowMode: boolean;\n recallPlannerTelemetryEnabled: boolean;\n recallPlannerMaxQmdResultsMinimal: number;\n recallPlannerMaxQmdResultsFull: number;\n intentRoutingEnabled: boolean;\n intentRoutingBoost: number;\n verbatimArtifactsEnabled: boolean;\n verbatimArtifactsMinConfidence: number;\n verbatimArtifactsMaxRecall: number;\n verbatimArtifactCategories: MemoryCategory[];\n // v8.0 Phase 2A: Memory Boxes + Trace Weaving\n memoryBoxesEnabled: boolean;\n /** Jaccard overlap threshold below which a topic shift triggers box sealing (0-1, default 0.35) */\n boxTopicShiftThreshold: number;\n /** Time gap in ms before an open box is sealed (default 30 min) */\n boxTimeGapMs: number;\n /** Max memories per box before forced seal */\n boxMaxMemories: number;\n traceWeaverEnabled: boolean;\n /** Days back to search for trace links */\n traceWeaverLookbackDays: number;\n /** Minimum Jaccard overlap to assign the same traceId (0-1, default 0.4) */\n traceWeaverOverlapThreshold: number;\n /** Number of recent days of boxes to inject during recall */\n boxRecallDays: number;\n // v8.0 Phase 2B: Episode/Note dual store (HiMem)\n /** Classify extracted memories as episode or note and tag with memoryKind */\n episodeNoteModeEnabled: boolean;\n // v8.1 Temporal + Tag Indexes (SwiftMem-inspired)\n /** Build and maintain temporal (state/index_time.json) and tag (state/index_tags.json) indexes */\n queryAwareIndexingEnabled: boolean;\n /** Max candidate paths returned from index prefilter (0 = no cap) */\n queryAwareIndexingMaxCandidates: number;\n temporalIndexWindowDays: number;\n temporalIndexMaxEntries: number;\n temporalBoostRecentDays: number;\n temporalBoostScore: number;\n temporalDecayEnabled: boolean;\n tagMemoryEnabled: boolean;\n tagMaxPerMemory: number;\n tagIndexMaxEntries: number;\n tagRecallBoost: number;\n tagRecallMaxMatches: number;\n // v8.2 multi-graph memory (PR 18)\n multiGraphMemoryEnabled: boolean;\n // v8.2 PR 19A: graph recall planner gating\n graphRecallEnabled: boolean;\n graphRecallMaxExpansions: number;\n graphRecallMaxPerSeed: number;\n graphRecallMinEdgeWeight: number;\n graphRecallShadowEnabled: boolean;\n graphRecallSnapshotEnabled: boolean;\n graphRecallShadowSampleRate: number;\n graphRecallExplainToolEnabled: boolean;\n graphRecallStoreColdMirror: boolean;\n graphRecallColdMirrorCollection?: string;\n graphRecallColdMirrorMinAgeDays: number;\n graphRecallUseEntityPriors: boolean;\n graphRecallEntityPriorBoost: number;\n graphRecallPreferHubSeeds: boolean;\n graphRecallHubBias: number;\n graphRecallRecencyHalfLifeDays: number;\n graphRecallDampingFactor: number;\n graphRecallMaxSeedNodes: number;\n graphRecallMaxExpandedNodes: number;\n graphRecallMaxTrailPerNode: number;\n graphRecallMinSeedScore: number;\n graphRecallExpansionScoreThreshold: number;\n graphRecallExplainMaxPaths: number;\n graphRecallExplainMaxChars: number;\n graphRecallExplainEdgeLimit: number;\n graphRecallExplainEnabled: boolean;\n graphRecallEntityHintsEnabled: boolean;\n graphRecallEntityHintMax: number;\n graphRecallEntityHintMaxChars: number;\n graphRecallSnapshotDir: string;\n graphRecallEnableTrace: boolean;\n graphRecallEnableDebug: boolean;\n /** Allow graph_mode escalation for broader causal/timeline phrasing beyond strict keywords. */\n graphExpandedIntentEnabled?: boolean;\n /** Run bounded graph expansion in full mode when enough recall seeds exist. */\n graphAssistInFullModeEnabled?: boolean;\n /** In full mode, compute graph assist for telemetry/snapshotting but do not inject merged results. */\n graphAssistShadowEvalEnabled?: boolean;\n /** Minimum seed results required before full-mode graph assist runs. */\n graphAssistMinSeedResults?: number;\n entityGraphEnabled: boolean;\n timeGraphEnabled: boolean;\n /** When true, write fallback temporal adjacency edges for consecutive extracted memories. */\n graphWriteSessionAdjacencyEnabled?: boolean;\n causalGraphEnabled: boolean;\n maxGraphTraversalSteps: number;\n graphActivationDecay: number;\n /** Weight of graph activation score when blending with seed QMD score (0-1). */\n graphExpansionActivationWeight: number;\n /** Lower bound for blended graph-expanded recall scores (0-1). */\n graphExpansionBlendMin: number;\n /** Upper bound for blended graph-expanded recall scores (0-1). */\n graphExpansionBlendMax: number;\n maxEntityGraphEdgesPerMemory: number;\n /** SimpleMem-inspired de-linearization: resolve pronouns and anchor relative dates after extraction. */\n delinearizeEnabled: boolean;\n /** Synapse-inspired confidence gate — skip memory injection when top score is below threshold. */\n recallConfidenceGateEnabled: boolean;\n recallConfidenceGateThreshold: number;\n /** PlugMem-inspired causal rule extraction: mine IF→THEN rules during consolidation. */\n causalRuleExtractionEnabled: boolean;\n /** E-Mem-inspired memory reconstruction: targeted retrieval for missing entity context. */\n memoryReconstructionEnabled: boolean;\n /** Maximum number of entity expansions per recall. */\n memoryReconstructionMaxExpansions: number;\n /** Synapse-inspired lateral inhibition to suppress hub-node dominance. */\n graphLateralInhibitionEnabled: boolean;\n /** Inhibition strength (default 0.15). Higher = more suppression. */\n graphLateralInhibitionBeta: number;\n /** Number of top competing nodes considered for inhibition (default 7). */\n graphLateralInhibitionTopM: number;\n\n // Issue #681 PR 2/3 — graph-edge confidence decay maintenance.\n /** Enable the periodic graph-edge confidence decay job. Default false (opt-in). */\n graphEdgeDecayEnabled: boolean;\n /** Cadence in milliseconds at which the cron triggers the decay job. Default 7d. */\n graphEdgeDecayCadenceMs: number;\n /** Decay window passed through to `decayEdgeConfidence`. Default 90 days. */\n graphEdgeDecayWindowMs: number;\n /** Per-window confidence drop. Default 0.1. */\n graphEdgeDecayPerWindow: number;\n /** Floor confidence will not decay below. Default 0.1. */\n graphEdgeDecayFloor: number;\n /** Confidence threshold for the \"below visibility\" telemetry counter. Default 0.2. */\n graphEdgeDecayVisibilityThreshold: number;\n\n /**\n * Issue #681 PR 3/3 — minimum edge confidence required for an edge to be\n * traversed during spreading activation. Edges with `confidence` below this\n * floor are pruned and contribute neither activation nor downstream\n * neighbors. Legacy edges without `confidence` are treated as 1.0 so they\n * always pass the floor. Range `[0, 1]`; default `0.2`.\n */\n graphTraversalConfidenceFloor: number;\n /**\n * Issue #681 PR 3/3 — number of PageRank-style refinement iterations applied\n * on top of the BFS spreading-activation scores. Each iteration redistributes\n * a node's confidence-weighted activation along its outgoing edges. Set to 0\n * to disable refinement and use raw BFS scores. Default `8`.\n */\n graphTraversalPageRankIterations: number;\n // v8.2: Temporal Memory Tree\n temporalMemoryTreeEnabled: boolean;\n tmtHourlyMinMemories: number;\n tmtSummaryMaxTokens: number;\n // Explicit cue recall\n /** Front-load exact stored evidence for query-visible cues like turns, dates, ids, files, and tools. */\n explicitCueRecallEnabled: boolean;\n /** Character budget for the explicit cue evidence section. */\n explicitCueRecallMaxChars: number;\n /** Maximum query-visible cues expanded per recall. */\n explicitCueRecallMaxReferences: number;\n /** Enable targeted fact evidence recall for direct answer questions. */\n targetedFactRecallEnabled: boolean;\n /** Character budget for the targeted fact evidence section. */\n targetedFactRecallMaxChars: number;\n /** Maximum recalled items for targeted fact evidence. */\n targetedFactRecallMaxResults: number;\n /** Recent-turn scan window for targeted fact evidence. */\n targetedFactRecallScanWindowTurns: number;\n /** Recent-token scan window for targeted fact evidence. */\n targetedFactRecallScanWindowTokens: number;\n /** Enable focused list evidence recall for count, relation, and recommendation questions. */\n focusedListRecallEnabled: boolean;\n /** Character budget for the focused list evidence section. */\n focusedListRecallMaxChars: number;\n /** Maximum recalled items for focused list evidence. */\n focusedListRecallMaxResults: number;\n /** Recent-turn scan window for focused list evidence. */\n focusedListRecallScanWindowTurns: number;\n /** Recent-token scan window for focused list evidence. */\n focusedListRecallScanWindowTokens: number;\n /** Enable response guidance recall for user answer-shape preferences. */\n responseGuidanceRecallEnabled: boolean;\n /** Character budget for the response guidance recall section. */\n responseGuidanceRecallMaxChars: number;\n /** Maximum recalled items for response guidance. */\n responseGuidanceRecallMaxResults: number;\n /** Recent-turn scan window for response guidance. */\n responseGuidanceRecallScanWindowTurns: number;\n /** Recent-token scan window for response guidance. */\n responseGuidanceRecallScanWindowTokens: number;\n /** Enable event-order evidence recall for chronology questions. */\n eventOrderRecallEnabled: boolean;\n /** Character budget for the event-order evidence section. */\n eventOrderRecallMaxChars: number;\n /** Maximum recalled items for event-order evidence. */\n eventOrderRecallMaxResults: number;\n /** Recent-turn scan window for event-order evidence. */\n eventOrderRecallScanWindowTurns: number;\n /** Recent-token scan window for event-order evidence. */\n eventOrderRecallScanWindowTokens: number;\n // Lossless Context Management (LCM)\n lcmEnabled: boolean;\n lcmLeafBatchSize: number;\n lcmRollupFanIn: number;\n lcmFreshTailTurns: number;\n lcmMaxDepth: number;\n lcmRecallBudgetShare: number;\n lcmDeterministicMaxTokens: number;\n lcmArchiveRetentionDays: number;\n /** Max independent LCM observe jobs to process concurrently. Default 1. */\n lcmObserveConcurrency: number;\n /** Opt-in structured message-part capture/recall sidecar for LCM. Default false. */\n messagePartsEnabled: boolean;\n /** Max structured file/tool matches injected into recall. */\n messagePartsRecallMaxResults: number;\n\n // v9.1 Parallel Specialized Retrieval (ASMR-inspired)\n /** Enable three-agent parallel retrieval (DirectFact + Contextual + Temporal). Default false. */\n parallelRetrievalEnabled: boolean;\n /** Per-agent source weights for score blending during merge. */\n parallelAgentWeights: { direct: number; contextual: number; temporal: number };\n /** Max results fetched per agent before merge. */\n parallelMaxResultsPerAgent: number;\n\n // Daily Context Briefing (Issue #370)\n /** Briefing configuration knobs — see BriefingConfig for field docs. */\n briefing: BriefingConfig;\n\n // Codex CLI connector settings (install-time)\n codex: CodexConnectorConfig;\n\n // Live connectors (issue #683). Concrete implementations live under\n // packages/remnic-core/src/connectors/live/. Each child block maps to one\n // connector. All defaults are off — operators opt in.\n connectors: LiveConnectorsConfig;\n\n // MECE Taxonomy (#366)\n /** Enable the MECE taxonomy knowledge directory. Default false. */\n taxonomyEnabled: boolean;\n /** Auto-regenerate RESOLVER.md when taxonomy changes. Default true. */\n taxonomyAutoGenResolver: boolean;\n\n // Codex CLI — native memory materialization (#378)\n /** Materialize Remnic memories into Codex's expected ~/.codex/memories/ layout. Default true. */\n codexMaterializeMemories: boolean;\n /** Namespace to materialize; \"auto\" derives from the connector context. Default \"auto\". */\n codexMaterializeNamespace: string;\n /** Max whitespace-tokenized size of memory_summary.md. Default 4500. */\n codexMaterializeMaxSummaryTokens: number;\n /** Max age in days for rollout_summaries/*.md before pruning. Default 30. */\n codexMaterializeRolloutRetentionDays: number;\n /** Run materialization after semantic/causal consolidation completes. Default true. */\n codexMaterializeOnConsolidation: boolean;\n /** Run materialization at Codex session-end hook. Default true. */\n codexMaterializeOnSessionEnd: boolean;\n /** Enable Codex marketplace integration. Default true. */\n codexMarketplaceEnabled: boolean;\n\n // Page-level versioning (issue #371)\n /** Enable page-level versioning with sidecar snapshots. Default false. */\n versioningEnabled: boolean;\n /** Maximum number of version snapshots to keep per page. Default 50. Set to 0 to disable pruning. */\n versioningMaxPerPage: number;\n /** Name of the sidecar directory inside memoryDir. Default \".versions\". */\n versioningSidecarDir: string;\n\n // Binary file lifecycle management (#367)\n /** Enable binary file lifecycle management (mirror, redirect, clean). Default: false. */\n binaryLifecycleEnabled: boolean;\n /** Grace period in days before a mirrored binary is eligible for local cleanup. Default: 7. */\n binaryLifecycleGracePeriodDays: number;\n /** Storage backend type: \"filesystem\" copies to a local dir, \"none\" is no-op. Default: \"none\". */\n binaryLifecycleBackendType: \"filesystem\" | \"s3\" | \"none\";\n /** Base path for the filesystem backend. Required when backendType is \"filesystem\". */\n binaryLifecycleBackendPath: string;\n\n /**\n * Advertise legacy `engram_*` / `engram.*` MCP tool aliases alongside the\n * canonical `remnic_*` names (issue #1427). Default true for backward\n * compatibility. Set false to halve the advertised MCP `tools/list` surface;\n * tools stay callable under both names regardless. Also settable via\n * `REMNIC_EMIT_LEGACY_TOOLS` (falls back to `ENGRAM_EMIT_LEGACY_TOOLS`).\n */\n emitLegacyTools: boolean;\n // Codex citation parity (issue #379)\n /** Enable oai-mem-citation blocks in recall responses. Default false. */\n citationsEnabled: boolean;\n /** Auto-enable citations when the Codex adapter is detected. Default true. */\n citationsAutoDetect: boolean;\n\n // External enrichment pipeline (issue #365)\n /** Enable the external enrichment pipeline. Default false. */\n enrichmentEnabled: boolean;\n /** Automatically enrich new entities on creation. Default false. */\n enrichmentAutoOnCreate: boolean;\n /** Max candidates accepted per entity per enrichment run. Default 20. */\n enrichmentMaxCandidatesPerEntity: number;\n\n // Memory extensions discovery (#382)\n /** Whether third-party memory extensions are discovered and injected into consolidation. Default true. */\n memoryExtensionsEnabled: boolean;\n /**\n * Root directory for memory extensions. Empty string means derive from\n * memoryDir: go up to the Remnic home dir and append memory_extensions.\n */\n memoryExtensionsRoot: string;\n}\n\n/** Runtime configuration for the daily context briefing feature. */\nexport interface BriefingConfig {\n /** Whether `remnic briefing` CLI and MCP tool are enabled. */\n enabled: boolean;\n /** Default lookback window token (e.g. \"yesterday\", \"3d\", \"1w\", \"24h\"). */\n defaultWindow: string;\n /** Default output format for the CLI. */\n defaultFormat: \"markdown\" | \"json\";\n /** Maximum number of LLM-generated suggested follow-ups. */\n maxFollowups: number;\n /** Optional path to an ICS or JSON calendar file. null disables the section. */\n calendarSource: string | null;\n /** If true, CLI writes a dated briefing file by default. */\n saveByDefault: boolean;\n /** Override directory for saved briefings. null → $REMNIC_HOME/briefings/. */\n saveDir: string | null;\n /** Whether to call the Responses API for follow-up suggestions. */\n llmFollowups: boolean;\n}\n\n/** Parsed representation of a briefing lookback window. */\nexport type BriefingWindow = \"yesterday\" | \"today\" | string;\n\n/** Filter the briefing to a single entity / project / topic. */\nexport interface BriefingFocus {\n type: \"person\" | \"project\" | \"topic\";\n value: string;\n}\n\n/** Calendar event surfaced by a CalendarSource implementation. */\nexport interface CalendarEvent {\n /** Stable identifier for dedupe / linking. */\n id: string;\n /** Event title (short). */\n title: string;\n /** ISO 8601 start timestamp. */\n start: string;\n /** Optional ISO 8601 end timestamp. */\n end?: string;\n /** Optional freeform location. */\n location?: string;\n /** Optional short notes. */\n notes?: string;\n}\n\n/** Abstraction over any calendar backend. Concrete implementations: `FileCalendarSource`. */\nexport interface CalendarSource {\n /** Return events that fall on the given UTC date (YYYY-MM-DD). */\n eventsForDate(dateIso: string): Promise<CalendarEvent[]>;\n}\n\n/** A single \"active thread\" surfaced in a briefing. */\nexport interface BriefingActiveThread {\n id: string;\n title: string;\n updatedAt: string;\n reason: string;\n}\n\n/** A single \"recent entity\" entry. */\nexport interface BriefingRecentEntity {\n name: string;\n type: string;\n updatedAt: string;\n score: number;\n summary?: string;\n}\n\n/** A single unresolved commitment or open question. */\nexport interface BriefingOpenCommitment {\n id: string;\n kind: \"question\" | \"commitment\" | \"pending_memory\";\n text: string;\n source?: string;\n createdAt?: string;\n}\n\n/** An LLM-generated short follow-up suggestion. */\nexport interface BriefingFollowup {\n text: string;\n rationale?: string;\n}\n\n/** Structured sections of a briefing result. */\nexport interface BriefingSections {\n activeThreads: BriefingActiveThread[];\n recentEntities: BriefingRecentEntity[];\n openCommitments: BriefingOpenCommitment[];\n suggestedFollowups: BriefingFollowup[];\n /** Only populated when a calendar source is configured and returns events. */\n todayCalendar?: CalendarEvent[];\n}\n\n/** A calendar source failure recorded when a CalendarSource throws during briefing generation. */\nexport interface BriefingCalendarSourceError {\n /** Human-readable description of the source (e.g. file path or source name). */\n source: string;\n /** Stringified error message from the failed source. */\n error: string;\n}\n\n/** Result returned by `buildBriefing`. */\nexport interface BriefingResult {\n markdown: string;\n json: Record<string, unknown>;\n sections: BriefingSections;\n /** Reason why suggested follow-ups were omitted (e.g. missing API key, LLM error). */\n followupsUnavailableReason?: string;\n /** Effective lookback window (ISO date range) used for this briefing. */\n window: { from: string; to: string };\n /**\n * Calendar sources that failed during this briefing run.\n * Only present (non-empty) when at least one source threw.\n * Allows callers to distinguish \"no events today\" from \"source unavailable\".\n */\n calendarSourceErrors?: BriefingCalendarSourceError[];\n}\n\n/**\n * Settings for the Codex CLI connector. These are consumed by\n * `remnic connectors install codex-cli` to decide where the phase-2 memory\n * extension is dropped and whether to install it at all.\n */\nexport interface CodexConnectorConfig {\n /**\n * Whether to install the Remnic memory extension into\n * `<codex_home>/memories_extensions/remnic/` when the `codex-cli`\n * connector is installed. Default `true`. Set to `false` for users who\n * self-manage the Codex memory extensions folder.\n */\n installExtension: boolean;\n /**\n * Optional override for the Codex home directory. When `null`, the\n * connector reads `$CODEX_HOME` and falls back to `~/.codex`. Setting\n * this is useful for integration tests and non-default installs.\n */\n codexHome: string | null;\n}\n\n/**\n * Container for live-connector config blocks (issue #683 PR 2/N).\n *\n * Lives at `connectors.*` rather than the top level so future connectors\n * (Notion, Gmail, GitHub) can slot in without bloating `PluginConfig`.\n *\n * Every child block must default to `enabled: false` per CLAUDE.md gotcha\n * #30 (escape hatch by default) and gotcha #48 (least-privileged enum\n * defaults). Concrete connectors are also expected to short-circuit at\n * registration time when their credentials are not populated.\n */\nexport interface LiveConnectorsConfig {\n /** Google Drive live connector (issue #683 PR 2/N). */\n googleDrive: GoogleDriveLiveConnectorConfig;\n /** Notion live connector (issue #683 PR 3/N). */\n notion: NotionLiveConnectorConfig;\n /** Gmail live connector (issue #683 PR 4/6). */\n gmail: GmailLiveConnectorConfig;\n /** GitHub live connector (issue #683 PR 5/6). */\n github: GitHubLiveConnectorConfig;\n}\n\n/**\n * Operator-facing config for the Google Drive live connector. The connector\n * module itself defines a separate, *validated* `GoogleDriveConnectorConfig`\n * shape (frozen, post-validation). This interface is the pre-validation\n * shape that `parseConfig` round-trips through.\n *\n * `clientId` / `clientSecret` / `refreshToken` are stored as strings here so\n * the schema can ship in `openclaw.plugin.json` and operators can populate\n * them from a secret store (e.g. an env-substituted plist or systemd\n * EnvironmentFile). They MUST NEVER be committed to source. The repo-wide\n * privacy policy in CLAUDE.md applies.\n */\nexport interface GoogleDriveLiveConnectorConfig {\n /** Master gate. Default false — operators must opt in explicitly. */\n enabled: boolean;\n /** OAuth2 client id. Populate from a secret store; never commit. */\n clientId: string;\n /** OAuth2 client secret. Populate from a secret store; never commit. */\n clientSecret: string;\n /** OAuth2 refresh token. Populate from a secret store; never commit. */\n refreshToken: string;\n /** Poll interval in ms. Default 300000 (5 min); min 1000; max 86400000 (24h). */\n pollIntervalMs: number;\n /** Optional folder-id scope. Empty array = all accessible files. */\n folderIds: string[];\n}\n\n/**\n * Operator-facing config for the Notion live connector (issue #683 PR 3/N).\n * The connector module defines a separate validated `NotionConnectorConfig`\n * shape (frozen, post-validation). This interface is the pre-validation shape\n * that `parseConfig` round-trips through.\n *\n * `token` is stored as a string here so operators can populate it from a\n * secret store (e.g. an env-substituted plist or systemd EnvironmentFile).\n * It MUST NEVER be committed to source. The repo-wide privacy policy in\n * CLAUDE.md applies.\n */\nexport interface NotionLiveConnectorConfig {\n /** Master gate. Default false — operators must opt in explicitly. */\n enabled: boolean;\n /** Notion integration token. Starts with `secret_`. Populate from a secret store; never commit. */\n token: string;\n /** Array of Notion database ids to import pages from. Empty = connector is a no-op. */\n databaseIds: string[];\n /** Poll interval in ms. Default 300000 (5 min); min 1000; max 86400000 (24h). */\n pollIntervalMs: number;\n}\n\n/**\n * Operator-facing config for the Gmail live connector (issue #683 PR 4/6).\n * The connector module defines a separate validated `GmailConnectorConfig`\n * shape (frozen, post-validation). This interface is the pre-validation shape\n * that `parseConfig` round-trips through.\n *\n * OAuth2 credentials are stored as strings here so operators can populate\n * them from a secret store (e.g. env-substituted plist or systemd\n * EnvironmentFile). They MUST NEVER be committed to source. The repo-wide\n * privacy policy in CLAUDE.md applies.\n */\nexport interface GmailLiveConnectorConfig {\n /** Master gate. Default false — operators must opt in explicitly. */\n enabled: boolean;\n /** OAuth2 client id. Populate from a secret store; never commit. */\n clientId: string;\n /** OAuth2 client secret. Populate from a secret store; never commit. */\n clientSecret: string;\n /** OAuth2 refresh token issued for the Gmail scope. Populate from a secret store; never commit. */\n refreshToken: string;\n /** Gmail userId. Defaults to \"me\" (the authenticated user). */\n userId: string;\n /** Gmail search query applied in addition to the watermark filter. Default \"in:inbox\". */\n query: string;\n /** Poll interval in ms. Default 300000 (5 min); min 1000; max 86400000 (24h). */\n pollIntervalMs: number;\n}\n\n/**\n * Operator-facing config for the GitHub live connector (issue #683 PR 5/6).\n * The connector module defines a separate validated `GitHubConnectorConfig`\n * shape (frozen, post-validation). This interface is the pre-validation shape\n * that `parseConfig` round-trips through.\n *\n * `token` is stored as a string here so operators can populate it from a\n * secret store (e.g. an env-substituted plist or systemd EnvironmentFile).\n * It MUST NEVER be committed to source. The repo-wide privacy policy in\n * CLAUDE.md applies.\n */\nexport interface GitHubLiveConnectorConfig {\n /** Master gate. Default false — operators must opt in explicitly. */\n enabled: boolean;\n /** GitHub personal access token. Populate from a secret store; never commit. */\n token: string;\n /** GitHub login of the user whose comments will be imported. Required. */\n userLogin: string;\n /** Repos to poll in \"owner/repo\" format. Empty = connector is a no-op. */\n repos: string[];\n /** Poll interval in ms. Default 300000 (5 min); min 1000; max 86400000 (24h). */\n pollIntervalMs: number;\n /** Whether to fetch Discussion comments in addition to issue/PR comments. Default false. */\n includeDiscussions: boolean;\n}\n\nexport interface BootstrapOptions {\n dryRun?: boolean;\n sessionsDir?: string;\n limit?: number;\n since?: Date;\n}\n\nexport interface BootstrapResult {\n sessionsScanned: number;\n turnsProcessed: number;\n highSignalTurns: number;\n memoriesCreated: number;\n skipped: number;\n}\n\nexport interface PrincipalRule {\n match: string;\n principal: string;\n}\n\nexport interface NamespacePolicy {\n name: string;\n readPrincipals: string[];\n writePrincipals: string[];\n includeInRecallByDefault?: boolean;\n}\n\nexport interface RelevanceFeedback {\n up: number;\n down: number;\n lastUpdatedAt: string;\n notes?: string[];\n}\n\nexport interface BufferTurn {\n role: \"user\" | \"assistant\";\n content: string;\n timestamp: string;\n sourceValidAt?: string;\n sessionKey?: string;\n logicalSessionKey?: string;\n providerThreadId?: string | null;\n turnFingerprint?: string;\n persistProcessedFingerprint?: boolean;\n extractionContextOnly?: boolean;\n parts?: import(\"./message-parts/index.js\").LcmMessagePartInput[];\n rawContent?: unknown;\n sourceFormat?: import(\"./message-parts/index.js\").MessagePartSourceFormat;\n importProvenance?: import(\"./bulk-import/types.js\").ImportTurnProvenance;\n}\n\nexport interface BufferEntryState {\n turns: BufferTurn[];\n lastExtractionAt: string | null;\n extractionCount: number;\n /**\n * Turns retained across `clearAfterExtraction` so a later extraction pass\n * sees the context that caused a defer verdict (issue #562, PR 2). Bounded\n * to the configured retention cap by `retainDeferredTurns`. Empty / absent\n * means no retention in effect.\n */\n retainedTurns?: BufferTurn[];\n}\n\nexport interface BufferState {\n turns: BufferTurn[];\n lastExtractionAt: string | null;\n extractionCount: number;\n entries?: Record<string, BufferEntryState>;\n}\n\nexport interface BehaviorLoopAdjustment {\n parameter: string;\n previousValue: number;\n nextValue: number;\n delta: number;\n evidenceCount: number;\n confidence: number;\n reason: string;\n appliedAt: string;\n}\n\nexport interface BehaviorLoopPolicyState {\n version: number;\n windowDays: number;\n minSignalCount: number;\n maxDeltaPerCycle: number;\n protectedParams: string[];\n adjustments: BehaviorLoopAdjustment[];\n updatedAt: string;\n}\n\nexport type BehaviorSignalType = \"correction_override\" | \"preference_affinity\" | \"topic_revisitation\" | \"action_pattern\" | \"outcome_preference\" | \"phrasing_style\";\nexport type BehaviorSignalDirection = \"positive\" | \"negative\";\n\nexport interface BehaviorSignalEvent {\n timestamp: string;\n namespace: string;\n memoryId: string;\n category: Extract<MemoryCategory, \"correction\" | \"preference\">;\n signalType: BehaviorSignalType;\n direction: BehaviorSignalDirection;\n confidence: number;\n signalHash: string;\n source: \"extraction\" | \"correction\";\n}\n\n/**\n * One row of the buffer-surprise telemetry ledger (issue #563 PR 3).\n *\n * Emitted by `SmartBuffer` each time the surprise probe produces a score\n * for an incoming turn (i.e. the feature flag is on and the existing\n * trigger-logic path called through to the probe). Not written when the\n * probe is skipped — the absence of a row is meaningful and matches the\n * \"probe was not consulted\" state.\n *\n * The ledger is intentionally lean: we record the score, the threshold in\n * force, whether the turn caused a flush, and the turn count so operators\n * can re-derive precision/recall without replaying traffic. Turn content\n * is never persisted — this ledger is safe to commit to shared storage.\n */\nexport interface BufferSurpriseEvent {\n /** Literal tag to simplify multiplexed log consumers. */\n event: \"BUFFER_SURPRISE\";\n /** ISO timestamp when the decision was made. Server-side, not turn ts. */\n timestamp: string;\n /** Buffer identifier (session / thread). Opaque string. */\n bufferKey: string;\n /** Session key if available; null when the turn has no session binding. */\n sessionKey: string | null;\n /** Role of the scored turn. */\n turnRole: \"user\" | \"assistant\";\n /** Surprise score in `[0, 1]`, already clamped. */\n surpriseScore: number;\n /** Threshold in force when the decision was made. */\n threshold: number;\n /** Whether this turn upgraded `keep_buffering` → `extract_now`. */\n triggeredFlush: boolean;\n /** Number of turns in the buffer (including the current turn). */\n turnCountInWindow: number;\n}\n\n/** Memory status for lifecycle management */\nexport type MemoryStatus =\n | \"active\"\n | \"pending_review\"\n | \"rejected\"\n | \"quarantined\"\n | \"superseded\"\n | \"archived\"\n /**\n * Operator explicitly forgot the memory (issue #686 PR 4/6). Soft\n * delete: the file stays on disk and a page-version snapshot is kept\n * so the act is reversible during a configurable retention window\n * (default 90 days), but the memory is excluded from recall, browse,\n * and entity attribution. After the retention window passes, a\n * future maintenance cron will hard-delete forgotten memories.\n */\n | \"forgotten\";\nexport type LifecycleState = \"candidate\" | \"validated\" | \"active\" | \"stale\" | \"archived\";\nexport type VerificationState = \"unverified\" | \"user_confirmed\" | \"system_inferred\" | \"disputed\";\nexport type PolicyClass = \"ephemeral\" | \"durable\" | \"protected\";\n\n/** Importance level tiers */\nexport type ImportanceLevel = \"critical\" | \"high\" | \"normal\" | \"low\" | \"trivial\";\n\n/** Importance scoring result */\nexport interface ImportanceScore {\n /** Numeric score 0-1 */\n score: number;\n /** Tier level */\n level: ImportanceLevel;\n /** Reasons for this score */\n reasons: string[];\n /** Salient keywords extracted */\n keywords: string[];\n}\n\nexport interface MemoryFrontmatter {\n id: string;\n category: MemoryCategory;\n created: string;\n updated: string;\n source: string;\n confidence: number;\n confidenceTier: ConfidenceTier;\n tags: string[];\n entityRef?: string;\n supersedes?: string;\n /** ISO 8601 date — memory expires and gets cleaned up after this date */\n expiresAt?: string;\n /** IDs of parent memories this was derived from (lineage tracking) */\n lineage?: string[];\n /** Memory status: active (default), pending_review, rejected, quarantined, superseded, archived, or forgotten */\n status?: MemoryStatus;\n /**\n * Tombstone block marker (issue #1579). When a new fact matches an active\n * tombstone at the storage chokepoint, it is persisted with\n * `status: \"pending_review\"` and this field set to the tombstone id — making\n * the block VISIBLE (rule 34: never a silent drop) rather than silently\n * discarding the extraction. Approving the memory through the review queue\n * emits a revocation that re-allows the content.\n */\n blockedBy?: string;\n /** Which tombstone tier matched (`exact`/`normalized`/`keyed`/`semantic`). */\n tombstoneBlockTier?: \"exact\" | \"normalized\" | \"keyed\" | \"semantic\";\n /** ID of memory that superseded this one */\n supersededBy?: string;\n /** Timestamp when superseded */\n supersededAt?: string;\n /** Timestamp when archived */\n archivedAt?: string;\n /**\n * Explicit fact validity start (issue #680). ISO 8601 timestamp.\n *\n * When present, marks the moment at which the fact begins being\n * \"true\" / authoritative. When absent at read time, callers fall\n * back to `created` so legacy memories written before #680 still\n * participate in `as_of` recall filtering without a migration.\n */\n valid_at?: string;\n /**\n * Explicit fact validity end (issue #680). ISO 8601 timestamp.\n *\n * Set automatically by the temporal-supersession pipeline when a\n * newer fact supersedes this one — the value is the superseder's\n * `valid_at` (or `created` if no `valid_at` was set). May also be\n * set manually for facts that are known to expire at a specific\n * point in time.\n */\n invalid_at?: string;\n /**\n * Ingestion time (issue #1578) — when Remnic *learned* this fact.\n * Distinct from `created` (file creation) and `valid_at` (event-time\n * start). Aligns with the source turn timestamp (#1575\n * `sources[].observedAt`). When `eventTimeSource === \"assumed\"`,\n * `valid_at` is copied from this value.\n */\n observedAt?: string;\n /**\n * Provenance of the event-time interval (issue #1578).\n * - `\"extracted\"` — a per-fact `eventTime` expression was resolved\n * against the source turn's timestamp and produced `valid_at` /\n * `invalid_at`.\n * - `\"assumed\"` — no resolvable expression; `valid_at` was copied from\n * `observedAt` (the ingestion anchor).\n * Absent on memories written before #1578; readers treat absent as\n * `\"assumed\"` for display purposes.\n */\n eventTimeSource?: \"extracted\" | \"assumed\";\n /**\n * Timestamp when the operator explicitly forgot this memory\n * (issue #686 PR 4/6). Set by `remnic forget <id>`. Memories with\n * `status === \"forgotten\"` are excluded from recall, browse, and\n * entity attribution; the file remains on disk until the retention\n * window passes.\n */\n forgottenAt?: string;\n /** Optional human-readable reason captured by `remnic forget --reason`. */\n forgottenReason?: string;\n /** Policy-driven lifecycle state used for retrieval eligibility/ranking. */\n lifecycleState?: LifecycleState;\n /** Verification provenance used by lifecycle policy. */\n verificationState?: VerificationState;\n /** Policy class used by lifecycle guardrails. */\n policyClass?: PolicyClass;\n /** Last lifecycle validation timestamp (ISO 8601). */\n lastValidatedAt?: string;\n /** Lifecycle decay score in [0,1]. */\n decayScore?: number;\n /** Lifecycle heat score in [0,1]. */\n heatScore?: number;\n // Access tracking (Phase 1A)\n /** Number of times this memory has been retrieved */\n accessCount?: number;\n /** Last time this memory was accessed (ISO 8601) */\n lastAccessed?: string;\n // Memory Worth counters (issue #560)\n //\n // Per-fact outcome counters used to derive a dynamic utility score —\n // `p(success | retrieved)` — as a complement to the static `importance`\n // field. Absent on legacy memories written before #560; readers must treat\n // `undefined` as zero observations (uniform Beta(1,1) prior).\n //\n // Both values must be non-negative integers on write. PR 1 wires only the\n // schema + storage round-trip — no increments, scoring, or filtering yet.\n /** Number of sessions where this memory was retrieved and the outcome was judged a success. */\n mw_success?: number;\n /** Number of sessions where this memory was retrieved and the outcome was judged a failure. */\n mw_fail?: number;\n // Importance scoring (Phase 1B)\n /** Importance score with level, reasons, and keywords */\n importance?: ImportanceScore;\n // Chunking (Phase 2A)\n /** Parent memory ID if this is a chunk */\n parentId?: string;\n /** Chunk index within parent (0-based) */\n chunkIndex?: number;\n /** Total number of chunks for this parent */\n chunkTotal?: number;\n // Memory Linking (Phase 3A)\n /** Links to other memories */\n links?: MemoryLink[];\n // Intent-grounded memory routing (v8.0 phase 1)\n intentGoal?: string;\n intentActionType?: string;\n intentEntityTypes?: string[];\n // Verbatim artifact lineage (v8.0 phase 1)\n artifactType?: \"decision\" | \"constraint\" | \"todo\" | \"definition\" | \"commitment\" | \"correction\" | \"fact\";\n sourceMemoryId?: string;\n sourceTurnId?: string;\n // v8.0 Phase 2B: HiMem episode/note classification\n /** episode = time-specific event; note = stable belief/preference/decision */\n memoryKind?: \"episode\" | \"note\" | \"box\" | \"dream\" | \"procedural\";\n /** Structured key-value attributes extracted from the content (e.g., product attributes, dates, quantities). */\n structuredAttributes?: Record<string, string>;\n /**\n * SHA-256 (via ContentHashIndex.computeHash) of the raw content that was\n * used as the dedup key at write time. Persists through archive and\n * consolidation so the hash can be removed from the index even if the stored\n * content has been transformed (e.g. an inline citation was appended).\n *\n * When present, archive/consolidation paths use this directly instead of\n * calling stripCitation(memory.content), which only handles the default\n * [Source: ...] format and silently fails for custom citation templates.\n */\n contentHash?: string;\n /**\n * Consolidation provenance — pointers to the page-versioning snapshots\n * that this memory was derived from (issue #561). Each entry is a\n * `\"<memory-path>:<version-number>\"` string (e.g.\n * `\"facts/preferences.md:3\"`) referencing a snapshot recorded by\n * `page-versioning.ts`.\n *\n * PR 1 introduces this field as read-through only — storage preserves\n * it verbatim but no code produces it yet. PR 2 populates it on\n * consolidation writes; PR 4 adds a `remnic doctor` integrity check\n * that validates each referent actually exists.\n */\n derived_from?: string[];\n /**\n * Which consolidation operator produced this memory (issue #561,\n * extended in #687). See `ConsolidationOperator` in\n * `semantic-consolidation.ts` for the operator algebra. Absent on\n * memories that were not produced by a consolidation pass.\n *\n * `\"pattern-reinforcement\"` (issue #687 PR 2/4) tags memories that\n * were promoted to canonical by the pattern-reinforcement\n * maintenance job after observing the same content across\n * multiple sessions.\n */\n derived_via?: \"split\" | \"merge\" | \"update\" | \"pattern-reinforcement\";\n /**\n * Number of source memories that reinforced this canonical memory\n * (issue #687 PR 2/4). Set by the pattern-reinforcement\n * maintenance job when it clusters duplicate memories and promotes\n * the most recent member to canonical. Counts the cluster size at\n * the time of the run; subsequent runs update this monotonically.\n *\n * Always a positive integer when present. Absent on memories that\n * have not been touched by pattern reinforcement.\n */\n reinforcement_count?: number;\n /**\n * ISO 8601 timestamp recording the most recent pattern-reinforcement\n * run that touched this memory (issue #687 PR 2/4). Updated each\n * time the cluster size grows. Absent when `reinforcement_count`\n * is absent.\n */\n last_reinforced_at?: string;\n // Claim-level provenance spans (issue #1575).\n //\n // Verbatim source-utterance excerpts that ground each extracted fact, plus\n // a coarse `provenance` tag recording whether the span was located in the\n // buffered turn text. Absent on legacy memories written before #1575;\n // readers MUST treat both `undefined` (legacy) and `provenance: \"none\"`\n // uniformly — never crash, never drop the fact (rule 34 spirit).\n //\n // `charStart` / `charEnd` are best-effort debugging aids — consumers MUST\n // tolerate their absence (turn text is not persisted forever). The span\n // interval is half-open [charStart, charEnd) per rule 35.\n //\n // PR 1 wires only the schema + storage round-trip — no extraction prompt,\n // validator, or read surfaces yet.\n /** Literal source-utterance excerpts backing this fact (issue #1575). */\n sources?: ProvenanceSource[];\n /**\n * Coarse provenance strength: `\"verified\"` (span located in source text),\n * `\"unverified\"` (span present but not locatable), or `\"none\"` (no span\n * recorded). Readers treat absent as `\"none\"` for legacy memories.\n */\n provenance?: \"verified\" | \"unverified\" | \"none\";\n\n // Faithfulness gate (issue #1576). When the extraction faithfulness gate\n // runs (mode \"shadow\" or \"enforce\"), this field records the verdict. Absent\n // when the gate is off or the fact predates #1576 — readers MUST treat\n // absent as \"not checked\" (rule 34 spirit).\n //\n // This field is its own frontmatter island — it never feeds mw_*/trust\n // fields. Consumed by #1577 (TrustScore) as one input among many.\n /** Entailment verdict from the faithfulness gate (issue #1576). */\n faithfulness?: FaithfulnessFrontmatter;\n}\n\n/**\n * Faithfulness gate frontmatter (issue #1576).\n *\n * Serialized as a single JSON line so it round-trips through the existing\n * YAML parser. `verdict: \"unchecked\"` marks a fact that entered the gate but\n * could not be evaluated (backend failure, timeout). `verdict:\n * \"skipped_no_span\"` marks a legacy fact without a verified source span.\n * Both are distinct from the field being absent (gate was off entirely).\n */\nexport interface FaithfulnessFrontmatter {\n verdict: \"entailed\" | \"contradicted\" | \"unsupported\" | \"unchecked\" | \"skipped_no_span\";\n /** Model/endpoint that produced the verdict, when known. */\n model?: string;\n /** One-sentence rationale from the verifier. */\n rationale?: string;\n /** ISO-8601 timestamp the check ran. */\n at?: string;\n}\n\n/** Memory link relationship types */\nexport type MemoryLinkType = \"follows\" | \"references\" | \"contradicts\" | \"supports\" | \"related\";\n\n/** A link between memories */\nexport interface MemoryLink {\n targetId: string;\n linkType: MemoryLinkType;\n strength: number;\n reason?: string;\n}\n\n/**\n * A verbatim source-utterance excerpt that grounds an extracted fact\n * (issue #1575). Emitted by the PR 2 extraction validator; round-tripped\n * through storage in PR 1.\n *\n * `quote` is the only strictly-required field — without it the entry is\n * meaningless and is dropped on read. `charStart` / `charEnd` are\n * best-effort offsets within the buffered turn text at write time and\n * form a half-open interval [charStart, charEnd) (rule 35).\n */\nexport interface ProvenanceSource {\n /** Session key of the source turn (e.g. `project/<name>/<ts>`). */\n sessionKey: string;\n /** Host-supplied turn identifier, when one was provided. */\n turnId?: string;\n /** ISO 8601 timestamp of the source turn. */\n observedAt: string;\n /** Verbatim utterance excerpt, capped at `provenance.maxQuoteChars`. */\n quote: string;\n /** Offset within the buffered turn text where the quote begins, when located. */\n charStart?: number;\n /** Half-open end offset within the buffered turn text (rule 35). */\n charEnd?: number;\n}\n\n// Conversation Threading (Phase 3B)\nexport interface ConversationThread {\n id: string;\n title: string;\n createdAt: string;\n updatedAt: string;\n sessionKey?: string;\n episodeIds: string[];\n linkedThreadIds: string[];\n}\n\n// Memory Summarization (Phase 4A)\nexport interface MemorySummary {\n id: string;\n createdAt: string;\n timeRangeStart: string;\n timeRangeEnd: string;\n summaryText: string;\n keyFacts: string[];\n keyEntities: string[];\n sourceEpisodeIds: string[];\n}\n\nexport interface DaySummaryResult {\n summary: string;\n bullets: string[];\n next_actions: string[];\n risks_or_open_loops: string[];\n}\n\n// Topic Extraction (Phase 4B)\nexport interface TopicScore {\n term: string;\n score: number;\n count: number;\n}\n\nexport interface MemoryFile {\n path: string;\n frontmatter: MemoryFrontmatter;\n content: string;\n}\n\n/**\n * Public type representing the **Observation** stage in the\n * Trace → Observation → Primitive pipeline (issue #685).\n *\n * - **Trace**: raw conversation turns captured in `buffer.ts`. Noisy,\n * verbose, ephemeral.\n * - **Observation** (this type): post-extraction, importance-scored\n * fact candidate emitted by `extraction.ts` / `extraction-judge.ts`.\n * Already distilled — but not yet consolidated against the corpus.\n * - **Primitive**: the durable `MemoryFile` written by `storage.ts`,\n * reinforced over time by `compounding/engine.ts`.\n *\n * `MemoryObservation` is the named handle on the intermediate stage\n * the codebase has always produced but never publicly typed. It lets\n * callers (telemetry, doctor surfaces, tests, downstream tooling)\n * inspect the post-extraction shape without reaching into extraction\n * internals.\n *\n * Naming note: this is intentionally NOT the same as the existing\n * `state/observation-ledger/` directory, which is telemetry storage\n * for the extraction pipeline (turn-count aggregates rebuilt by\n * `maintenance/rebuild-observations.ts` and judge verdict events\n * appended by `extraction-judge-telemetry.ts`). Lifecycle events on\n * primitives — status flips, supersessions, archival, forget — live\n * in `state/memory-lifecycle-ledger.jsonl`, written by\n * `StorageManager`. A `MemoryObservation` describes the in-flight\n * candidate that became (or didn't become) a primitive; the ledger\n * directory is how the pipeline reports on itself. See\n * `docs/trace-to-primitive.md` for the full pipeline walkthrough.\n */\nexport interface MemoryObservation {\n /** Stable id for this observation, distinct from any primitive id. */\n id: string;\n /** Source session id the trace came from. */\n sessionId?: string;\n /** ISO timestamp the observation was emitted. */\n observedAt: string;\n /** The extracted fact candidate (category, content, confidence, tags, etc.). */\n fact: ExtractedFact;\n /** Importance score in [0,1], from `importance.ts`. */\n importance?: number;\n /**\n * Whether the observation passed the extraction judge\n * (`extraction-judge.ts`). When `false`, the observation was\n * captured for telemetry but not persisted as a primitive.\n */\n judgeAccepted?: boolean;\n /** Optional reason the judge gave when rejecting. */\n judgeRejectionReason?: string;\n /**\n * Id of the resulting `MemoryFile` primitive once consolidation runs.\n * Absent until consolidation decides to ADD/MERGE/UPDATE the\n * observation into the corpus.\n */\n resultingPrimitiveId?: string;\n}\n\n/** Ordered step for extracted procedure memories (issue #519). */\nexport interface ExtractedProcedureStep {\n order: number;\n intent: string;\n toolCall?: { kind: string; signature: string };\n expectedOutcome?: string;\n optional?: boolean;\n}\n\nexport interface ExtractedFact {\n category: MemoryCategory;\n content: string;\n confidence: number;\n tags: string[];\n entityRef?: string;\n source?: ExtractionPassSource;\n /**\n * Claim-level provenance spans backing this fact (issue #1575).\n * Populated by the PR 2 extraction validator when `provenance.enabled`\n * is true. Absent for legacy extractions — downstream consumers (the\n * faithfulness gate #1576, TrustScore #1577) MUST treat absent as\n * \"no verified span\" and skip gracefully.\n */\n sources?: ProvenanceSource[];\n /**\n * Coarse provenance strength tag (issue #1575 PR 2). Set by the extraction\n * validator: \"verified\" when the quote was located in source turns,\n * \"unverified\" when the quote survived but no offsets were recoverable.\n * Absent when `provenance.enabled` is false or no quote was provided —\n * readers treat absent as \"none\" (rule 34 spirit).\n */\n provenance?: \"verified\" | \"unverified\" | \"none\";\n /**\n * Transient LLM-provided supporting quote (issue #1575 PR 2). Consumed by\n * the post-parse validator to build `sources`, then stripped before the\n * fact reaches persistence. NEVER included in content-hash dedup (rule 23 /\n * checklist §13). Absent on facts that have already passed the validator.\n */\n quote?: string;\n /**\n * Transient requireSpans signal (issue #1575 PR 2). Set by the provenance\n * validator (`ProvenanceBuildResult.requireSpansPending`) when\n * `provenance.requireSpans` is enabled and the quote could not be located\n * in any source turn. Read by the persist path to route the fact to\n * `pending_review` instead of `active`. Stripped before persistence —\n * it never reaches frontmatter (chatgpt-codex-connector thread 4xB).\n */\n requireSpansPending?: boolean;\n promptedByQuestion?: string;\n /**\n * Whether this fact is project-scoped or globally applicable.\n * When `extractionScopeClassificationEnabled` is true, the extraction LLM\n * classifies each fact. Default is `\"project\"` when a coding context is\n * active, `\"global\"` when no coding context is present.\n */\n scope?: MemoryScope;\n /** Structured key-value attributes extracted from the content (e.g., product attributes, dates, quantities). */\n structuredAttributes?: Record<string, string>;\n /** When category is `procedure`, ordered steps with intents (persisted under procedures/). */\n procedureSteps?: ExtractedProcedureStep[];\n /**\n * When category is `reasoning_trace`, the stored solution chain the user\n * walked through. Persisted under reasoning-traces/.\n */\n reasoningTrace?: ExtractedReasoningTrace;\n /**\n * Optional event-time expression for bi-temporal validity (#1578 PR2).\n * Verbatim temporal anchor extracted from the conversation (\"2025-03-01\",\n * \"last March\", \"since 2024\", \"until 2025-06-01\"). Resolved against the\n * source turn timestamp at write time by `resolveFactEventTime` — never\n * re-resolved at read. Absent when the fact carries no temporal anchor or\n * when `temporal.biTemporal` is off.\n */\n eventTime?: string;\n}\n\nexport interface ExtractedReasoningTraceStep {\n order: number;\n description: string;\n}\n\nexport interface ExtractedReasoningTrace {\n steps: ExtractedReasoningTraceStep[];\n finalAnswer: string;\n observedOutcome?: string;\n}\n\nexport interface MemoryIntent {\n goal: string;\n actionType: string;\n entityTypes: string[];\n /** True when the prompt reads like starting a concrete task (ship/deploy/tests/PR, etc.). */\n taskInitiation?: boolean;\n}\n\nexport interface ExtractedQuestion {\n question: string;\n context: string;\n priority: number;\n}\n\nexport interface QuestionEntry {\n id: string;\n question: string;\n context: string;\n priority: number; // 0-1, higher = more important\n created: string;\n resolved: boolean;\n resolvedAt?: string;\n}\n\nexport interface ExtractionResult {\n facts: ExtractedFact[];\n profileUpdates: string[];\n entities: EntityMention[];\n questions: ExtractedQuestion[];\n identityReflection?: string;\n relationships?: ExtractedRelationship[];\n extractionFailure?: string;\n}\n\nexport interface EntityMention {\n name: string;\n type: \"person\" | \"project\" | \"tool\" | \"company\" | \"place\" | \"other\";\n facts: string[];\n structuredSections?: EntityStructuredSection[];\n source?: ExtractionPassSource;\n promptedByQuestion?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Knowledge Graph Enhancement (Entity Relationships, Activity, Scoring)\n// ---------------------------------------------------------------------------\n\nexport interface EntityRelationship {\n target: string;\n label: string;\n}\n\nexport interface EntityActivityEntry {\n date: string;\n note: string;\n}\n\nexport interface EntityTimelineEntry {\n timestamp: string;\n text: string;\n source?: string;\n sessionKey?: string;\n principal?: string;\n}\n\nexport interface EntityStructuredSection {\n key: string;\n title: string;\n facts: string[];\n}\n\nexport interface EntitySchemaSectionDefinition {\n key: string;\n title: string;\n description: string;\n aliases?: string[];\n}\n\nexport interface EntitySchemaDefinition {\n sections: EntitySchemaSectionDefinition[];\n}\n\nexport interface EntityFile {\n name: string;\n type: string;\n created?: string;\n updated: string;\n extraFrontmatterLines?: string[];\n preSectionLines?: string[];\n facts: string[];\n summary?: string;\n synthesis?: string;\n synthesisUpdatedAt?: string;\n synthesisTimelineCount?: number;\n synthesisStructuredFactCount?: number;\n synthesisStructuredFactDigest?: string;\n synthesisVersion?: number;\n timeline: EntityTimelineEntry[];\n structuredSections?: EntityStructuredSection[];\n relationships: EntityRelationship[];\n activity: EntityActivityEntry[];\n aliases: string[];\n extraSections?: Array<{\n title: string;\n lines: string[];\n }>;\n}\n\nexport interface ScoredEntity {\n name: string;\n type: string;\n score: number;\n factCount: number;\n summary?: string;\n topRelationships: string[];\n}\n\nexport interface ExtractedRelationship {\n source: string;\n target: string;\n label: string;\n extractionSource?: ExtractionPassSource;\n promptedByQuestion?: string;\n}\n\nexport interface ConsolidationItem {\n existingId: string;\n action: ConsolidationAction;\n mergeWith?: string;\n updatedContent?: string;\n reason: string;\n}\n\nexport interface ConsolidationResult {\n items: ConsolidationItem[];\n profileUpdates: string[];\n entityUpdates: EntityMention[];\n}\n\nexport interface ConsolidationObservation {\n runAt: string;\n recentMemories: MemoryFile[];\n existingMemories: MemoryFile[];\n profile: string;\n result: ConsolidationResult;\n merged: number;\n invalidated: number;\n}\n\nexport interface QmdSearchResult {\n docid: string;\n path: string;\n snippet: string;\n score: number;\n line?: number;\n explain?: QmdSearchExplain;\n transport?: \"daemon\" | \"subprocess\" | \"hybrid\" | \"scoped_prefilter\";\n}\n\nexport interface QmdSearchExplain {\n ftsScores?: number[];\n vectorScores?: number[];\n /** QMD 2.5 nested RRF `totalScore`, or legacy numeric RRF score. */\n rrf?: number;\n rrfRank?: number;\n rrfPositionScore?: number;\n rrfBaseScore?: number;\n rrfTopRankBonus?: number;\n rerankScore?: number;\n blendedScore?: number;\n /** Additive boost applied from `reinforcement_count` frontmatter (issue #687 PR 3/4). */\n reinforcementBoost?: number;\n}\n\nexport interface MetaState {\n extractionCount: number;\n lastExtractionAt: string | null;\n lastConsolidationAt: string | null;\n totalMemories: number;\n totalEntities: number;\n processedExtractionFingerprints?: Array<{\n fingerprint: string;\n observedAt: string;\n }>;\n}\n\nexport type MemoryActionType =\n | \"store_episode\"\n | \"store_note\"\n | \"update_note\"\n | \"create_artifact\"\n | \"summarize_node\"\n | \"discard\"\n | \"link_graph\";\n\nexport type MemoryActionOutcome = \"applied\" | \"skipped\" | \"failed\";\n\nexport type MemoryActionPolicyDecision = \"allow\" | \"defer\" | \"deny\";\n\nexport type MemoryActionStatus = \"validated\" | \"applied\" | \"rejected\";\n\nexport type MemoryActionEligibilitySource =\n | \"extraction\"\n | \"consolidation\"\n | \"replay\"\n | \"manual\"\n | \"unknown\";\n\nexport interface MemoryActionEligibilityContext {\n confidence: number;\n lifecycleState: LifecycleState;\n importance: number;\n source: MemoryActionEligibilitySource;\n}\n\nexport interface MemoryActionPolicyResult {\n action: MemoryActionType;\n decision: MemoryActionPolicyDecision;\n rationale: string;\n eligibility: MemoryActionEligibilityContext;\n}\n\nexport interface MemoryActionEvent {\n schemaVersion?: number;\n actionId?: string;\n timestamp: string;\n action: MemoryActionType;\n outcome: MemoryActionOutcome;\n status?: MemoryActionStatus;\n actor?: string;\n subsystem?: string;\n reason?: string;\n memoryId?: string;\n namespace?: string;\n sessionKey?: string;\n sourceSessionKey?: string;\n checkpointCapturedAt?: string;\n checkpointTtl?: string;\n checkpointTurnCount?: number;\n inputSummary?: string;\n outputMemoryIds?: string[];\n dryRun?: boolean;\n policyVersion?: string;\n promptHash?: string;\n policyDecision?: MemoryActionPolicyDecision;\n policyRationale?: string;\n policyEligibility?: MemoryActionEligibilityContext;\n}\n\nexport type MemoryLifecycleEventType =\n | \"created\"\n | \"updated\"\n | \"superseded\"\n | \"archived\"\n | \"rejected\"\n | \"restored\"\n | \"merged\"\n | \"imported\"\n | \"promoted\"\n | \"explicit_capture_accepted\"\n | \"explicit_capture_queued\";\n\nexport interface MemoryLifecycleStateSummary {\n category?: MemoryCategory;\n path?: string;\n status?: MemoryStatus;\n lifecycleState?: LifecycleState;\n}\n\nexport interface MemoryLifecycleEvent {\n eventId: string;\n memoryId: string;\n eventType: MemoryLifecycleEventType;\n timestamp: string;\n actor: string;\n reasonCode?: string;\n ruleVersion: string;\n relatedMemoryIds?: string[];\n before?: MemoryLifecycleStateSummary;\n after?: MemoryLifecycleStateSummary;\n correlationId?: string;\n}\n\nexport interface MemoryProjectionCurrentState {\n memoryId: string;\n category: MemoryCategory;\n status: MemoryStatus;\n lifecycleState?: LifecycleState;\n path: string;\n pathRel: string;\n created: string;\n updated: string;\n archivedAt?: string;\n supersededAt?: string;\n entityRef?: string;\n source: string;\n confidence: number;\n confidenceTier: ConfidenceTier;\n memoryKind?: MemoryFrontmatter[\"memoryKind\"];\n accessCount?: number;\n lastAccessed?: string;\n tags?: string[];\n preview?: string;\n}\n\nexport interface CompressionGuidelineOptimizerSourceWindow {\n from: string;\n to: string;\n}\n\nexport interface CompressionGuidelineOptimizerEventCounts {\n total: number;\n applied: number;\n skipped: number;\n failed: number;\n}\n\nexport type CompressionGuidelineActivationState = \"draft\" | \"active\";\n\nexport interface CompressionGuidelineOptimizerActionSummary {\n action: MemoryActionType;\n total: number;\n outcomes: Record<MemoryActionOutcome, number>;\n quality: {\n good: number;\n poor: number;\n unknown: number;\n };\n}\n\nexport interface CompressionGuidelineOptimizerRuleUpdate {\n action: MemoryActionType;\n delta: number;\n direction: \"increase\" | \"decrease\" | \"hold\";\n confidence: \"low\" | \"medium\" | \"high\";\n notes: string[];\n}\n\nexport interface CompressionGuidelineOptimizerState {\n version: number;\n updatedAt: string;\n sourceWindow: CompressionGuidelineOptimizerSourceWindow;\n eventCounts: CompressionGuidelineOptimizerEventCounts;\n guidelineVersion: number;\n contentHash?: string;\n activationState?: CompressionGuidelineActivationState;\n actionSummaries?: CompressionGuidelineOptimizerActionSummary[];\n ruleUpdates?: CompressionGuidelineOptimizerRuleUpdate[];\n}\n\nexport type ContinuityIncidentState = \"open\" | \"closed\";\n\nexport interface ContinuityIncidentRecord {\n id: string;\n state: ContinuityIncidentState;\n openedAt: string;\n updatedAt: string;\n triggerWindow?: string;\n symptom: string;\n suspectedCause?: string;\n fixApplied?: string;\n verificationResult?: string;\n preventiveRule?: string;\n closedAt?: string;\n filePath?: string;\n}\n\nexport interface ContinuityIncidentOpenInput {\n triggerWindow?: string;\n symptom: string;\n suspectedCause?: string;\n}\n\nexport interface ContinuityIncidentCloseInput {\n fixApplied: string;\n verificationResult: string;\n preventiveRule?: string;\n}\n\nexport type ContinuityLoopCadence = \"daily\" | \"weekly\" | \"monthly\" | \"quarterly\";\nexport type ContinuityLoopStatus = \"active\" | \"paused\" | \"retired\";\n\nexport interface ContinuityImprovementLoop {\n id: string;\n cadence: ContinuityLoopCadence;\n purpose: string;\n status: ContinuityLoopStatus;\n killCondition: string;\n lastReviewed: string;\n notes?: string;\n}\n\nexport interface ContinuityLoopUpsertInput {\n id: string;\n cadence: ContinuityLoopCadence;\n purpose: string;\n status: ContinuityLoopStatus;\n killCondition: string;\n lastReviewed?: string;\n notes?: string;\n}\n\nexport interface ContinuityLoopReviewInput {\n status?: ContinuityLoopStatus;\n notes?: string;\n reviewedAt?: string;\n}\n\n/** Entry in the access tracking buffer (batched updates) */\nexport interface AccessTrackingEntry {\n memoryId: string;\n newCount: number;\n lastAccessed: string;\n}\n\nexport interface SignalScanResult {\n level: SignalLevel;\n patterns: string[];\n}\n\n// ============================================================================\n// LLM Trace Callback (for external observability plugins)\n// ============================================================================\n\nexport interface LlmTraceEvent {\n kind: \"llm_start\" | \"llm_end\" | \"llm_error\";\n traceId: string;\n model: string;\n operation: \"extraction\" | \"consolidation\" | \"profile_consolidation\" | \"identity_consolidation\" | \"day_summary\";\n input?: string;\n output?: string;\n durationMs?: number;\n error?: string;\n tokenUsage?: { input?: number; output?: number; total?: number };\n}\n\nexport interface RecallTraceEvent {\n kind: \"recall_summary\";\n traceId: string;\n operation: \"recall\";\n sessionKey?: string;\n promptHash: string;\n promptLength: number;\n retrievalQueryHash: string;\n retrievalQueryLength: number;\n recallMode: RecallPlanMode;\n recallResultLimit: number;\n qmdEnabled: boolean;\n qmdAvailable: boolean;\n recallNamespaces: string[];\n source: \"none\" | \"hot_qmd\" | \"hot_embedding\" | \"cold_fallback\" | \"recent_scan\";\n recalledMemoryCount: number;\n injected: boolean;\n contextChars: number;\n policyVersion?: string;\n identityInjectionMode?: IdentityInjectionMode | \"none\";\n identityInjectedChars?: number;\n identityInjectionTruncated?: boolean;\n durationMs: number;\n timings?: Record<string, string>;\n /**\n * The full recalled memory context added to the runtime context.\n * Only populated when `traceRecallContent` config option is `true`.\n * Omitted by default to avoid sending potentially sensitive memory content\n * to external trace collectors unless explicitly opted in.\n */\n recalledContent?: string;\n}\n\nexport type EngramTraceEvent = LlmTraceEvent | RecallTraceEvent;\nexport type LlmTraceCallback = (event: EngramTraceEvent) => void;\n\n// ============================================================================\n// Gateway Configuration Types (for fallback AI)\n// ============================================================================\n\nexport type ModelApi =\n | \"openai-completions\"\n | \"anthropic-messages\"\n | \"google-generative\"\n | \"codex-cli\"\n | string;\nexport type CodexCliReasoningEffort = \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\nexport type ModelProviderAuthMode = \"bearer\" | \"header\" | \"query\";\n\nexport interface ModelDefinitionConfig {\n id: string;\n name?: string;\n contextWindow?: number;\n maxOutputTokens?: number;\n costPer1MInput?: number;\n costPer1MOutput?: number;\n aliases?: string[];\n}\n\nexport interface ModelProviderConfig {\n baseUrl: string;\n apiKey?: string | Record<string, unknown>;\n auth?: ModelProviderAuthMode;\n api?: ModelApi;\n headers?: Record<string, string>;\n authHeader?: boolean;\n disableThinking?: boolean;\n executable?: string;\n reasoningEffort?: CodexCliReasoningEffort;\n codexCliExecutable?: string;\n codexCliReasoningEffort?: CodexCliReasoningEffort;\n retryOptions?: {\n timeoutMs?: number;\n };\n models: ModelDefinitionConfig[];\n}\n\nexport interface AgentDefaultsConfig {\n model?: {\n primary?: string;\n backup?: string;\n fallbacks?: string[];\n };\n thinking?: {\n mode?: \"off\" | \"on\" | \"adaptive\";\n budget?: number;\n };\n}\n\nexport interface AgentPersonaModelConfig {\n primary?: string;\n fallbacks?: string[];\n}\n\nexport interface AgentPersona {\n id: string;\n name?: string;\n model?: AgentPersonaModelConfig;\n}\n\nexport interface GatewayConfig {\n agents?: {\n defaults?: AgentDefaultsConfig;\n list?: AgentPersona[];\n };\n models?: {\n providers?: Record<string, ModelProviderConfig>;\n };\n}\n\n// ============================================================================\n// Transcript & Context Preservation (v2.0)\n// ============================================================================\n\nexport interface TranscriptEntry {\n timestamp: string;\n role: \"user\" | \"assistant\";\n content: string;\n sessionKey: string;\n turnId: string;\n metadata?: {\n compactAfter?: boolean;\n compactionId?: string | null;\n messageId?: string;\n threadId?: string;\n replyToId?: string;\n replyToBody?: string;\n replyToSender?: string;\n };\n}\n\nexport interface Checkpoint {\n sessionKey: string;\n capturedAt: string;\n turns: TranscriptEntry[];\n ttl: string; // ISO timestamp when checkpoint expires\n}\n\nexport interface HourlySummary {\n hour: string; // \"2026-02-08T14:00:00Z\"\n sessionKey: string;\n bullets: string[];\n turnCount: number;\n generatedAt: string;\n}\n\n// ============================================================================\n// Dreams Pipeline Telemetry (issue #678 PR 3/4)\n// ============================================================================\n\n// Re-export from the authoritative source to avoid duplicate definitions.\n// dreams-ledger.ts is the single source of truth; types.ts re-exports so\n// callers that import from types.js continue to work unchanged.\nexport type {\n DreamsPhase,\n DreamsPhaseStatus,\n DreamsStatusResult,\n DreamsRunResult,\n} from \"./maintenance/dreams-ledger.js\";\n"],"mappings":";AA+GO,IAAM,2BAAwD;AAAA,EACnE;AAAA,EACA;AAAA,EACA;AACF;AAOO,IAAM,4BAA8C;AAEpD,SAAS,mBAAmB,OAA2C;AAC5E,SAAO,OAAO,UAAU,YAClB,yBAA+C,SAAS,KAAK;AACrE;AAoeO,SAAS,eAAe,OAA+B;AAC5D,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,SAAS,IAAM,QAAO;AAC1B,MAAI,SAAS,IAAM,QAAO;AAC1B,SAAO;AACT;AAGO,IAAM,uBAAuB;","names":[]}
|