@remnic/core 1.1.3 → 1.1.4
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-cli.js +14 -14
- package/dist/access-http.d.ts +2 -2
- package/dist/access-http.js +8 -7
- package/dist/access-mcp.d.ts +2 -2
- package/dist/access-mcp.js +7 -6
- package/dist/{access-service-_AEUMVyX.d.ts → access-service-CtXFnprR.d.ts} +59 -7
- package/dist/access-service.d.ts +2 -2
- package/dist/access-service.js +6 -5
- package/dist/bootstrap.d.ts +1 -1
- package/dist/briefing.d.ts +1 -1
- package/dist/briefing.js +3 -3
- package/dist/buffer.d.ts +1 -1
- package/dist/causal-consolidation.js +3 -3
- package/dist/{chunk-Y3WQ4ZWK.js → chunk-52PDY6GD.js} +2 -2
- package/dist/{chunk-BOUYNNYD.js → chunk-67YLUWLG.js} +32 -13
- package/dist/{chunk-BOUYNNYD.js.map → chunk-67YLUWLG.js.map} +1 -1
- package/dist/{chunk-DR7MCMPS.js → chunk-AEMBDV7M.js} +210 -5
- package/dist/chunk-AEMBDV7M.js.map +1 -0
- package/dist/{chunk-55FXRRSJ.js → chunk-AGZHRWPT.js} +2 -2
- package/dist/{chunk-AKUCB2OG.js → chunk-CUI2STX6.js} +5 -4
- package/dist/{chunk-AKUCB2OG.js.map → chunk-CUI2STX6.js.map} +1 -1
- package/dist/{chunk-DHRQHX36.js → chunk-EGEPUGN4.js} +2 -2
- package/dist/{chunk-LZRYQK6L.js → chunk-F5VQOQ2E.js} +2 -2
- package/dist/{chunk-ZGXSCMQN.js → chunk-HIRKCQGF.js} +12 -12
- package/dist/{chunk-34F3PLWZ.js → chunk-MUELDH4F.js} +2 -2
- package/dist/{chunk-IM3JSE73.js → chunk-NZS2BLTP.js} +20 -14
- package/dist/{chunk-IM3JSE73.js.map → chunk-NZS2BLTP.js.map} +1 -1
- package/dist/{chunk-7GCMLT7J.js → chunk-TIFRGAKO.js} +4 -4
- package/dist/{chunk-R2L7SUX2.js → chunk-V7TEH5I2.js} +2 -2
- package/dist/{chunk-L5IIGA5V.js → chunk-W7WWT4FJ.js} +2 -2
- package/dist/{chunk-N7X62G74.js → chunk-X6VBWOVZ.js} +4 -4
- package/dist/{chunk-LVYGDT5V.js → chunk-XQ4EJLUD.js} +10 -12
- package/dist/chunk-XQ4EJLUD.js.map +1 -0
- package/dist/{chunk-4PLGJRBV.js → chunk-XRCYKJ3V.js} +130 -3
- package/dist/{chunk-4PLGJRBV.js.map → chunk-XRCYKJ3V.js.map} +1 -1
- package/dist/{chunk-DCE6SQLA.js → chunk-Y4A6M3B6.js} +2 -2
- package/dist/{chunk-SS253RXF.js → chunk-ZIBOQULP.js} +2 -2
- package/dist/{cli-x2APT9a6.d.ts → cli-lMql2FCr.d.ts} +2 -2
- package/dist/cli.d.ts +3 -3
- package/dist/cli.js +14 -13
- package/dist/consolidation-provenance-check.d.ts +1 -1
- package/dist/consolidation-undo.d.ts +1 -1
- package/dist/{engine-ICC2DSQF.js → engine-O6YWKQM3.js} +6 -4
- package/dist/entity-retrieval.d.ts +1 -1
- package/dist/entity-retrieval.js +3 -3
- package/dist/explicit-capture.d.ts +1 -1
- package/dist/extraction.js +2 -2
- package/dist/index.d.ts +17 -5
- package/dist/index.js +25 -19
- package/dist/index.js.map +1 -1
- package/dist/{memory-governance-KG52RITE.js → memory-governance-JZHZDOLN.js} +4 -4
- package/dist/{memory-projection-store-D3vBHS4J.d.ts → memory-projection-store-CY8TU40w.d.ts} +1 -1
- package/dist/memory-projection-store.d.ts +1 -1
- package/dist/memory-projection-store.js +1 -1
- package/dist/memory-worth-outcomes.d.ts +1 -1
- package/dist/operator-toolkit.d.ts +1 -1
- package/dist/operator-toolkit.js +5 -5
- package/dist/orchestrator.d.ts +1 -1
- package/dist/orchestrator.js +11 -11
- package/dist/schemas.d.ts +22 -22
- package/dist/semantic-consolidation.js +3 -3
- package/dist/semantic-rule-promotion.js +3 -3
- package/dist/semantic-rule-verifier.js +3 -3
- package/dist/storage.d.ts +1 -1
- package/dist/storage.js +2 -2
- package/dist/temporal-supersession.d.ts +1 -1
- package/dist/tier-migration.d.ts +1 -1
- package/dist/verified-recall.js +3 -3
- package/package.json +6 -3
- package/scripts/ensure-better-sqlite3.mjs +124 -0
- package/dist/chunk-DR7MCMPS.js.map +0 -1
- package/dist/chunk-LVYGDT5V.js.map +0 -1
- /package/dist/{chunk-Y3WQ4ZWK.js.map → chunk-52PDY6GD.js.map} +0 -0
- /package/dist/{chunk-55FXRRSJ.js.map → chunk-AGZHRWPT.js.map} +0 -0
- /package/dist/{chunk-DHRQHX36.js.map → chunk-EGEPUGN4.js.map} +0 -0
- /package/dist/{chunk-LZRYQK6L.js.map → chunk-F5VQOQ2E.js.map} +0 -0
- /package/dist/{chunk-ZGXSCMQN.js.map → chunk-HIRKCQGF.js.map} +0 -0
- /package/dist/{chunk-34F3PLWZ.js.map → chunk-MUELDH4F.js.map} +0 -0
- /package/dist/{chunk-7GCMLT7J.js.map → chunk-TIFRGAKO.js.map} +0 -0
- /package/dist/{chunk-R2L7SUX2.js.map → chunk-V7TEH5I2.js.map} +0 -0
- /package/dist/{chunk-L5IIGA5V.js.map → chunk-W7WWT4FJ.js.map} +0 -0
- /package/dist/{chunk-N7X62G74.js.map → chunk-X6VBWOVZ.js.map} +0 -0
- /package/dist/{chunk-DCE6SQLA.js.map → chunk-Y4A6M3B6.js.map} +0 -0
- /package/dist/{chunk-SS253RXF.js.map → chunk-ZIBOQULP.js.map} +0 -0
- /package/dist/{engine-ICC2DSQF.js.map → engine-O6YWKQM3.js.map} +0 -0
- /package/dist/{memory-governance-KG52RITE.js.map → memory-governance-JZHZDOLN.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/access-service.ts","../src/work/storage.ts","../src/work/board.ts","../src/procedural/procedure-miner.ts","../src/procedural/procedure-stats.ts"],"sourcesContent":["import { stat } from \"node:fs/promises\";\nimport * as nodeFs from \"node:fs/promises\";\nimport { constants as fsConstants } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { ZodError } from \"zod\";\nimport { AccessIdempotencyStore, hashAccessIdempotencyPayload } from \"./access-idempotency.js\";\nimport { AccessAuditAdapter, type AccessAuditConfig, type AccessAuditResult } from \"./access-audit.js\";\nimport type { AnomalyDetectorResult } from \"./recall-audit-anomaly.js\";\nimport { resolveGitContext } from \"./coding/git-context.js\";\nimport { WorkStorage } from \"./work/storage.js\";\nimport {\n exportWorkBoardMarkdown,\n exportWorkBoardSnapshot,\n importWorkBoardSnapshot,\n} from \"./work/board.js\";\nimport { wrapWorkLayerContext } from \"./work/boundary.js\";\nimport {\n persistExplicitCapture,\n queueExplicitCaptureForReview,\n validateExplicitCaptureInput,\n type ExplicitCaptureInput,\n type ValidExplicitCapture,\n} from \"./explicit-capture.js\";\nimport { CrossNamespaceBudget, type BudgetDecision } from \"./cross-namespace-budget.js\";\nimport { log } from \"./logger.js\";\nimport {\n buildQualityScore,\n buildProposedActions,\n groupActionsByStatus,\n listMemoryGovernanceRuns,\n readMemoryGovernanceRunArtifact,\n runMemoryGovernance,\n} from \"./maintenance/memory-governance.js\";\nimport { runProcedureMining } from \"./procedural/procedure-miner.js\";\nimport type { PatternReinforcementResult } from \"./maintenance/pattern-reinforcement.js\";\nimport type { LiveConnectorsRunSummary } from \"./live-connectors-runner.js\";\nimport {\n computeProcedureStats,\n type ProcedureStatsReport,\n} from \"./procedural/procedure-stats.js\";\nimport {\n normalizeProjectionPreview,\n normalizeProjectionTags,\n} from \"./memory-projection-format.js\";\nimport {\n inferMemoryStatus,\n toMemoryPathRel,\n} from \"./memory-lifecycle-ledger-utils.js\";\nimport { getMemoryProjectionPath } from \"./memory-projection-store.js\";\nimport { canReadNamespace, canWriteNamespace, defaultNamespaceForPrincipal, recallNamespacesForPrincipal, resolvePrincipal } from \"./namespaces/principal.js\";\nimport type { LastRecallSnapshot } from \"./recall-state.js\";\nimport type {\n GraphRecallSnapshot,\n IntentDebugSnapshot,\n Orchestrator,\n RecallInvocationOptions,\n} from \"./orchestrator.js\";\nimport { parseEntityFile, StorageManager } from \"./storage.js\";\nimport {\n buildGraphSnapshot,\n type GraphSnapshotRequest,\n type GraphSnapshotResponse,\n type GraphSnapshotNodeMetadata,\n} from \"./graph-snapshot.js\";\nimport * as nodePath from \"node:path\";\nimport {\n buildBriefing,\n FileCalendarSource,\n parseBriefingFocus,\n parseBriefingWindow,\n} from \"./briefing.js\";\nimport {\n getTrustZoneStoreStatus,\n isTrustZoneName,\n listTrustZoneRecords,\n promoteTrustZoneRecord,\n scoreTrustZoneProvenance,\n seedTrustZoneDemoDataset,\n summarizeTrustZonePromotionReadiness,\n type TrustZoneDemoSeedResult,\n type TrustZoneName,\n type TrustZonePromotionResult,\n type TrustZoneProvenanceScore,\n type TrustZoneRecord,\n type TrustZoneRecordKind,\n type TrustZoneSourceClass,\n type TrustZoneStoreStatus,\n} from \"./trust-zones.js\";\nimport type {\n EntityFile,\n MemoryFile,\n MemoryActionOutcome,\n MemoryActionType,\n MemoryLifecycleEvent,\n MemoryStatus,\n PluginConfig,\n RecallDisclosure,\n RecallPlanMode,\n} from \"./types.js\";\nimport { DEFAULT_RECALL_DISCLOSURE, isRecallDisclosure } from \"./types.js\";\nimport { estimateRecallTokens } from \"./recall-xray.js\";\nimport {\n applyTagFilter,\n normalizeTags,\n parseTagMatch,\n type TagMatchMode,\n} from \"./recall-tag-filter.js\";\nimport { decideDisclosureEscalation } from \"./recall-disclosure-escalation.js\";\nimport type { LocalLlmClient } from \"./local-llm.js\";\nimport type { FallbackLlmClient } from \"./fallback-llm.js\";\nimport type { SemanticDedupLookup } from \"./dedup/semantic.js\";\nimport { toRecallExplainJson } from \"./recall-explain-renderer.js\";\nimport {\n recordMemoryOutcome,\n type MemoryOutcomeKind,\n type RecordMemoryOutcomeResult,\n} from \"./memory-worth-outcomes.js\";\nimport {\n importCapsule as importCapsuleFn,\n type ImportCapsuleOptions,\n type ImportCapsuleResult,\n} from \"./transfer/capsule-import.js\";\nimport {\n exportCapsule as exportCapsuleFn,\n type ExportCapsuleOptions,\n type ExportCapsuleResult,\n} from \"./transfer/capsule-export.js\";\nimport {\n defaultCapsulesDir,\n type CapsuleListEntry,\n} from \"./capsule-cli.js\";\nimport { formatProfileTraceAscii } from \"./profiling.js\";\n\nexport class EngramAccessInputError extends Error {}\n\ntype AccessProfilingReportRequest = {\n format?: string;\n limit?: number;\n};\n\ntype AccessProfilingReportResponse = {\n enabled: boolean;\n format?: \"ascii\" | \"json\";\n report?: string;\n traces?: unknown[];\n stats?: unknown;\n bottleneck?: string | null;\n reason?: string;\n message?: string;\n};\n\nlet cachedPackageVersion: string | null = null;\n\nasync function getPackageVersion(): Promise<string> {\n if (cachedPackageVersion !== null) return cachedPackageVersion;\n try {\n const raw = await nodeFs.readFile(new URL(\"../package.json\", import.meta.url), \"utf-8\");\n const parsed = JSON.parse(raw) as { version?: unknown };\n cachedPackageVersion = typeof parsed.version === \"string\" && parsed.version.length > 0\n ? parsed.version\n : \"unknown\";\n } catch {\n cachedPackageVersion = \"unknown\";\n }\n return cachedPackageVersion;\n}\n\nfunction normalizeTrustZoneInputError(error: unknown): EngramAccessInputError | null {\n const message = error instanceof Error ? error.message : null;\n if (!message) {\n return null;\n }\n if (\n /^sourceRecordId must /.test(message) ||\n /^promotionReason must /.test(message) ||\n /^recordedAt must /.test(message) ||\n /^trust zone promotion requires /.test(message) ||\n /^source trust-zone record not found: /.test(message) ||\n /^trust-zone promotion denied: /.test(message) ||\n /^trust zone demo seed requires /.test(message) ||\n /^unsupported trust-zone demo scenario: /.test(message)\n ) {\n return new EngramAccessInputError(message);\n }\n return null;\n}\n\nexport const ENGRAM_ACCESS_WRITE_SCHEMA_VERSION = 1;\n\nexport interface EngramAccessHealthResponse {\n ok: true;\n memoryDir: string;\n namespacesEnabled: boolean;\n defaultNamespace: string;\n searchBackend: string;\n qmdEnabled: boolean;\n nativeKnowledgeEnabled: boolean;\n projectionAvailable: boolean;\n}\n\nexport interface EngramAccessRecallRequest {\n query: string;\n sessionKey?: string;\n namespace?: string;\n topK?: number;\n mode?: RecallPlanMode | \"auto\";\n includeDebug?: boolean;\n /**\n * Recall disclosure depth (issue #677). Selects how much content each\n * result returns: `\"chunk\"` (default), `\"section\"`, or `\"raw\"`. Omitting\n * this field is equivalent to passing `\"chunk\"` and preserves pre-#677\n * behavior. Surfaces (CLI / HTTP / MCP) and per-level token telemetry\n * are wired in subsequent PRs of #677.\n */\n disclosure?: RecallDisclosure;\n /**\n * Coding-agent context (issue #569). When a connector resolves a git\n * context for the session's cwd, it passes it here and the access service\n * attaches it to the orchestrator before recall so project- / branch-\n * scoped namespace overlays apply.\n *\n * Keyed by `sessionKey`; ignored when `sessionKey` is absent.\n */\n codingContext?: {\n projectId: string;\n branch: string | null;\n rootPath: string;\n defaultBranch: string | null;\n } | null;\n /**\n * Working directory of the calling agent session. When provided and no\n * `codingContext` is already attached to the session, the service resolves\n * git context from this path and attaches it automatically. This enables\n * Claude Code hooks (and any connector that knows its cwd) to get\n * project-scoped memory without explicitly constructing a `codingContext`.\n */\n cwd?: string;\n /**\n * Arbitrary project tag for non-git-based project scoping. When provided,\n * creates a `CodingContext` with `projectId: \"tag:<projectTag>\"`.\n * Useful for OpenClaw sessions where the whole workspace is one git repo\n * but different conversations correspond to different client projects.\n * Takes precedence over `cwd`-based git resolution but NOT over an\n * explicit `codingContext`.\n */\n projectTag?: string;\n /**\n * Historical recall pin (issue #680). ISO 8601 timestamp. When set,\n * the orchestrator filters out memories whose `valid_at` is after this\n * instant OR whose `invalid_at` is at-or-before this instant, so the\n * caller sees the corpus as it existed at `asOf`. Invalid values are\n * rejected here with `EngramAccessInputError` (CLAUDE.md rule 51).\n */\n asOf?: string;\n /**\n * Free-form recall tag filter (issue #689). When non-empty, recall results\n * whose frontmatter `tags` do not match are removed from the response.\n * Comparison is case-sensitive exact match against tags stored on each\n * memory's frontmatter (see `storage.ts` and `docs/tags.md`).\n */\n tags?: string[];\n /**\n * Match mode for `tags` (issue #689). `\"any\"` (default when omitted)\n * admits results that carry at least one filter tag. `\"all\"` requires\n * every filter tag to be present. Ignored when `tags` is absent or empty.\n */\n tagMatch?: \"any\" | \"all\";\n /**\n * Issue #681 — when `true`, bypasses the configured\n * `graphTraversalConfidenceFloor` for this recall and includes graph edges\n * below the floor in traversal. Useful for diagnostic queries that need to\n * surface results pruned by confidence decay. Default `false`.\n */\n includeLowConfidence?: boolean;\n}\n\n/**\n * Standalone request to attach / clear the coding context for a session\n * without performing a recall. Used by the Claude Code / Codex connectors\n * at session start, and by the `remnic.set_coding_context` MCP tool (PR 7).\n */\nexport interface EngramAccessSetCodingContextRequest {\n sessionKey: string;\n codingContext: {\n projectId: string;\n branch: string | null;\n rootPath: string;\n defaultBranch: string | null;\n } | null;\n}\n\nexport interface EngramAccessRecallResponse {\n query: string;\n sessionKey?: string;\n namespace: string;\n context: string;\n count: number;\n memoryIds: string[];\n results: EngramAccessMemorySummary[];\n recordedAt?: string;\n traceId?: string;\n plannerMode?: RecallPlanMode;\n fallbackUsed: boolean;\n sourcesUsed: string[];\n /**\n * Disclosure depth applied to this recall (issue #677). Reflects the\n * caller-requested level after defaulting; useful for surfaces that want\n * to render a \"served at depth X\" hint without re-deriving it. PR 1 of\n * #677 wires this end-to-end for plumbing only — section/raw payload\n * shaping ships in later PRs.\n */\n disclosure: RecallDisclosure;\n budgetsApplied?: LastRecallSnapshot[\"budgetsApplied\"];\n auditAnomalies?: AnomalyDetectorResult;\n budgetWarning?: BudgetDecision;\n latencyMs?: number;\n debug?: {\n snapshot?: LastRecallSnapshot;\n intent?: IntentDebugSnapshot | null;\n graph?: GraphRecallSnapshot | null;\n };\n}\n\nexport interface EngramAccessRecallExplainRequest {\n sessionKey?: string;\n namespace?: string;\n}\n\nexport interface EngramAccessRecallExplainResponse {\n found: boolean;\n snapshot?: LastRecallSnapshot;\n intent?: IntentDebugSnapshot | null;\n graph?: GraphRecallSnapshot | null;\n}\n\nexport interface EngramAccessDaySummaryRequest {\n memories?: string;\n sessionKey?: string;\n namespace?: string;\n}\n\n/** Inputs accepted by the `remnic_briefing` MCP tool. */\nexport interface EngramAccessBriefingRequest {\n since?: string;\n focus?: string;\n namespace?: string;\n format?: \"markdown\" | \"json\";\n maxFollowups?: number;\n /** Caller principal for namespace access checks. Transport-bound — never from untrusted payloads. */\n principal?: string;\n}\n\n/** Response for `remnic_briefing`. */\nexport interface EngramAccessBriefingResponse {\n format: \"markdown\" | \"json\";\n window: { from: string; to: string };\n namespace: string;\n markdown: string;\n json: Record<string, unknown>;\n followupsUnavailableReason?: string;\n}\n\nexport interface EngramAccessMemoryRecord {\n id: string;\n path: string;\n category: string;\n status?: string;\n created?: string;\n updated?: string;\n content: string;\n frontmatter: MemoryFile[\"frontmatter\"];\n}\n\nexport interface EngramAccessMemorySummary {\n id: string;\n path: string;\n category: string;\n status: string;\n created?: string;\n updated?: string;\n tags: string[];\n entityRef?: string;\n preview: string;\n /**\n * Disclosure depth at which this result was served (issue #677). Set by\n * recall paths; omitted on non-recall surfaces (e.g. memory browse) where\n * the concept does not apply. PR 1 of #677 always reports the\n * request-level disclosure on recall results; per-result divergence is\n * reserved for the auto-escalation policy that ships in PR 4/4.\n */\n disclosure?: RecallDisclosure;\n /**\n * Full memory content (markdown body) — populated when `disclosure` is\n * `\"section\"` or `\"raw\"` (issue #677 PR 2/4). At `\"chunk\"` depth callers\n * only receive the short `preview`, preserving the cheap-by-default\n * recall payload. Browse/non-recall paths leave `content` undefined.\n */\n content?: string;\n /**\n * Raw transcript excerpts surfaced from the LCM archive when `disclosure`\n * is `\"raw\"` and the LCM engine is enabled (issue #677 PR 2/4). Each\n * entry is a per-message excerpt sized by the LCM archive's\n * configured excerpt window. Empty array when LCM is disabled or has\n * no matching transcript content. Always omitted at chunk/section.\n */\n rawExcerpts?: Array<{\n turnIndex: number;\n role: string;\n content: string;\n sessionId: string;\n }>;\n}\n\nexport interface EngramAccessMemoryBrowseRequest {\n query?: string;\n status?: string;\n category?: string;\n namespace?: string;\n sort?: \"updated_desc\" | \"updated_asc\" | \"created_desc\" | \"created_asc\";\n limit?: number;\n offset?: number;\n}\n\nexport interface EngramAccessMemoryBrowseResponse {\n namespace: string;\n sort: \"updated_desc\" | \"updated_asc\" | \"created_desc\" | \"created_asc\";\n total: number;\n count: number;\n limit: number;\n offset: number;\n memories: EngramAccessMemorySummary[];\n}\n\nexport interface EngramAccessMemoryResponse {\n found: boolean;\n namespace: string;\n memory?: EngramAccessMemoryRecord;\n}\n\nexport interface EngramAccessTimelineResponse {\n found: boolean;\n namespace: string;\n count: number;\n timeline: MemoryLifecycleEvent[];\n}\n\nexport interface EngramAccessEntitySummary {\n name: string;\n type: string;\n updated: string;\n summary?: string;\n aliases: string[];\n}\n\nexport interface EngramAccessEntityListResponse {\n namespace: string;\n total: number;\n count: number;\n limit: number;\n offset: number;\n entities: EngramAccessEntitySummary[];\n}\n\nexport interface EngramAccessEntityResponse {\n found: boolean;\n namespace: string;\n entity?: EntityFile;\n}\n\nexport interface EngramAccessReviewQueueResponse {\n found: boolean;\n namespace?: string;\n runId?: string;\n summary?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"summary\"];\n metrics?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"metrics\"];\n qualityScore?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"qualityScore\"];\n reviewQueue?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"reviewQueue\"];\n appliedActions?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"appliedActions\"];\n transitionReport?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"transitionReport\"];\n report?: string;\n}\n\nexport interface EngramAccessMaintenanceResponse {\n namespace: string;\n health: EngramAccessHealthResponse;\n latestGovernanceRun: EngramAccessReviewQueueResponse;\n}\n\nexport interface EngramAccessTrustZoneStatusResponse {\n namespace: string;\n status: TrustZoneStoreStatus;\n}\n\nexport interface EngramAccessTrustZoneRecordSummary {\n recordId: string;\n filePath: string;\n zone: TrustZoneName;\n recordedAt: string;\n kind: TrustZoneRecordKind;\n summary: string;\n sourceClass: TrustZoneSourceClass;\n sessionKey?: string;\n sourceId?: string;\n evidenceHashPresent: boolean;\n anchored: boolean;\n entityRefs: string[];\n tags: string[];\n metadata?: Record<string, string>;\n trustScore?: TrustZoneProvenanceScore;\n nextPromotionTarget?: TrustZoneName;\n nextPromotionAllowed: boolean;\n nextPromotionReasons: string[];\n corroborationCount?: number;\n corroborationSourceClasses?: TrustZoneSourceClass[];\n}\n\nexport interface EngramAccessTrustZoneBrowseRequest {\n query?: string;\n zone?: TrustZoneName;\n kind?: TrustZoneRecordKind;\n sourceClass?: TrustZoneSourceClass;\n namespace?: string;\n limit?: number;\n offset?: number;\n}\n\nexport interface EngramAccessTrustZoneBrowseResponse {\n namespace: string;\n total: number;\n count: number;\n limit: number;\n offset: number;\n records: EngramAccessTrustZoneRecordSummary[];\n}\n\nexport interface EngramAccessTrustZonePromoteRequest {\n recordId: string;\n targetZone: TrustZoneName;\n promotionReason: string;\n recordedAt?: string;\n summary?: string;\n dryRun?: boolean;\n namespace?: string;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessTrustZonePromoteResponse extends TrustZonePromotionResult {\n namespace: string;\n dryRun: boolean;\n}\n\nexport interface EngramAccessTrustZoneDemoSeedRequest {\n scenario?: string;\n recordedAt?: string;\n dryRun?: boolean;\n namespace?: string;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessTrustZoneDemoSeedResponse extends TrustZoneDemoSeedResult {\n namespace: string;\n}\n\nexport interface EngramAccessQualityResponse {\n namespace: string;\n totalMemories: number;\n statusCounts: Record<string, number>;\n categoryCounts: Record<string, number>;\n confidenceTierCounts: Record<string, number>;\n ageBucketCounts: Record<string, number>;\n archivePressure: {\n pendingReview: number;\n quarantined: number;\n archived: number;\n staleActive: number;\n lowConfidenceActive: number;\n };\n latestGovernanceRun: {\n found: boolean;\n runId?: string;\n qualityScore?: EngramAccessReviewQueueResponse[\"qualityScore\"];\n reviewQueueCount: number;\n };\n}\n\nexport interface EngramAccessCapsuleListResponse {\n namespace: string;\n capsulesDir: string;\n capsules: CapsuleListEntry[];\n}\n\nasync function buildProjectedGovernanceProposedActions(\n storage: Awaited<ReturnType<Orchestrator[\"getStorage\"]>>,\n projected: NonNullable<Awaited<ReturnType<Awaited<ReturnType<Orchestrator[\"getStorage\"]>>[\"getProjectedGovernanceRecord\"]>>>,\n): Promise<Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"appliedActions\"]> {\n const reviewQueue = projected.reviewQueueRows.map((row) => ({\n entryId: row.entryId,\n memoryId: row.memoryId,\n path: row.path,\n reasonCode: row.reasonCode,\n severity: row.severity,\n suggestedAction: row.suggestedAction,\n suggestedStatus: row.suggestedStatus,\n relatedMemoryIds: row.relatedMemoryIds,\n })) as Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"reviewQueue\"];\n const memories = (await Promise.all(projected.reviewQueueRows.map((row) => storage.getMemoryById(row.memoryId))))\n .filter((memory): memory is MemoryFile => Boolean(memory));\n return buildProposedActions(reviewQueue, memories);\n}\n\nfunction hasGroupedGovernanceActions(\n grouped?: Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"transitionReport\"][\"proposed\"],\n): boolean {\n if (!grouped) return false;\n return Object.values(grouped).some((actions) => Array.isArray(actions) && actions.length > 0);\n}\n\nexport interface EngramAccessReviewDispositionRequest {\n memoryId: string;\n status: MemoryStatus | \"archived\";\n reasonCode: string;\n namespace?: string;\n /**\n * Trusted transport-bound principal. This must never come from untrusted client payloads.\n * When present, write authorization is evaluated against this principal instead of sessionKey.\n */\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessReviewDispositionResponse {\n ok: boolean;\n namespace: string;\n memoryId: string;\n status: MemoryStatus | \"archived\";\n previousStatus: MemoryStatus;\n currentPath?: string;\n}\n\nexport interface EngramAccessWriteEnvelope {\n schemaVersion?: number;\n idempotencyKey?: string;\n dryRun?: boolean;\n sessionKey?: string;\n /**\n * Trusted transport-bound principal. This must never come from untrusted client payloads.\n * When present, write authorization is evaluated against this principal instead of sessionKey.\n */\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessMemoryStoreRequest extends EngramAccessWriteEnvelope, ExplicitCaptureInput {}\n\nexport interface EngramAccessSuggestionSubmitRequest extends EngramAccessWriteEnvelope, ExplicitCaptureInput {}\n\nexport interface EngramAccessWriteResponse {\n schemaVersion: 1;\n operation: \"memory_store\" | \"suggestion_submit\";\n namespace: string;\n dryRun: boolean;\n accepted: boolean;\n queued: boolean;\n status: \"validated\" | \"stored\" | \"duplicate\" | \"queued_for_review\";\n memoryId?: string;\n duplicateOf?: string;\n idempotencyKey?: string;\n idempotencyReplay?: boolean;\n}\n\nexport interface EngramAccessObserveRequest {\n sessionKey: string;\n messages: Array<{ role: \"user\" | \"assistant\"; content: string }>;\n namespace?: string;\n authenticatedPrincipal?: string;\n skipExtraction?: boolean;\n /**\n * Working directory of the calling agent session (issue #569 wiring).\n * When provided and no `codingContext` is attached for this session,\n * resolves git context from the path and attaches it so writes route to\n * the correct project namespace.\n */\n cwd?: string;\n /**\n * Arbitrary project tag for non-git-based project scoping (issue #569).\n * Creates a `CodingContext` with `projectId: \"tag:<projectTag>\"`.\n */\n projectTag?: string;\n}\n\nexport interface EngramAccessObserveResponse {\n accepted: number;\n sessionKey: string;\n namespace: string;\n lcmArchived: boolean;\n extractionQueued: boolean;\n}\n\nexport interface EngramAccessLcmSearchRequest {\n query: string;\n sessionKey?: string;\n namespace?: string;\n limit?: number;\n authenticatedPrincipal?: string;\n}\n\nexport interface EngramAccessLcmSearchResponse {\n query: string;\n namespace: string;\n results: Array<{ sessionId: string; content: string; turnIndex?: number }>;\n count: number;\n lcmEnabled: boolean;\n}\n\nexport interface EngramAccessLcmStatusResponse {\n enabled: boolean;\n archiveAvailable: boolean;\n stats?: { totalTurns?: number };\n}\n\ntype EngramAccessIdempotencyStatus = \"miss\" | \"replay\" | \"conflict\";\n\nfunction normalizePagination(limit?: number, offset?: number): { limit: number; offset: number } {\n const normalizedLimit = Number.isFinite(limit) ? Math.max(1, Math.min(200, Math.floor(limit ?? 50))) : 50;\n const normalizedOffset = Number.isFinite(offset) ? Math.max(0, Math.floor(offset ?? 0)) : 0;\n return { limit: normalizedLimit, offset: normalizedOffset };\n}\n\nfunction normalizeBrowseSort(\n sort?: EngramAccessMemoryBrowseRequest[\"sort\"],\n): NonNullable<EngramAccessMemoryBrowseRequest[\"sort\"]> {\n switch (sort) {\n case \"updated_asc\":\n case \"created_desc\":\n case \"created_asc\":\n return sort;\n case \"updated_desc\":\n default:\n return \"updated_desc\";\n }\n}\n\nfunction bucketMemoryAge(referenceIso: string | undefined, nowMs: number): string {\n const referenceMs = referenceIso ? Date.parse(referenceIso) : Number.NaN;\n if (!Number.isFinite(referenceMs)) return \"unknown\";\n const ageDays = Math.floor((nowMs - referenceMs) / 86_400_000);\n if (ageDays <= 7) return \"0_7_days\";\n if (ageDays <= 30) return \"8_30_days\";\n if (ageDays <= 90) return \"31_90_days\";\n return \"91_plus_days\";\n}\n\nfunction incrementCount(counts: Record<string, number>, key: string): void {\n counts[key] = (counts[key] ?? 0) + 1;\n}\n\nfunction summarizeTrustZoneRecord(\n record: TrustZoneRecord,\n filePath: string,\n allRecords: TrustZoneRecord[],\n poisoningDefenseEnabled: boolean,\n trustZonesEnabled: boolean,\n promotionEnabled: boolean,\n): EngramAccessTrustZoneRecordSummary {\n const trustScore = poisoningDefenseEnabled ? scoreTrustZoneProvenance(record) : undefined;\n const readiness = summarizeTrustZonePromotionReadiness({\n record,\n allRecords,\n poisoningDefenseEnabled,\n });\n const promotionReasons = [...readiness.reasons];\n const promotionAllowed = readiness.allowed && trustZonesEnabled === true && promotionEnabled === true;\n if (trustZonesEnabled !== true) {\n promotionReasons.push(\"trust zone promotion requires trustZonesEnabled=true\");\n }\n if (promotionEnabled !== true) {\n promotionReasons.push(\"trust zone promotion requires quarantinePromotionEnabled=true\");\n }\n return {\n recordId: record.recordId,\n filePath,\n zone: record.zone,\n recordedAt: record.recordedAt,\n kind: record.kind,\n summary: record.summary,\n sourceClass: record.provenance.sourceClass,\n sessionKey: record.provenance.sessionKey,\n sourceId: record.provenance.sourceId,\n evidenceHashPresent: typeof record.provenance.evidenceHash === \"string\",\n anchored: Boolean(record.provenance.sourceId && record.provenance.evidenceHash),\n entityRefs: [...(record.entityRefs ?? [])],\n tags: [...(record.tags ?? [])],\n metadata: record.metadata,\n trustScore,\n nextPromotionTarget: readiness.nextTargetZone,\n nextPromotionAllowed: promotionAllowed,\n nextPromotionReasons: promotionReasons,\n corroborationCount: readiness.requiresCorroboration ? readiness.corroborationCount : undefined,\n corroborationSourceClasses: readiness.requiresCorroboration ? readiness.corroborationSourceClasses : undefined,\n };\n}\n\nfunction compareBrowseMemory(\n sort: NonNullable<EngramAccessMemoryBrowseRequest[\"sort\"]>,\n left: MemoryFile,\n right: MemoryFile,\n): number {\n const leftUpdated = left.frontmatter.updated ?? left.frontmatter.created ?? \"\";\n const rightUpdated = right.frontmatter.updated ?? right.frontmatter.created ?? \"\";\n const leftCreated = left.frontmatter.created ?? \"\";\n const rightCreated = right.frontmatter.created ?? \"\";\n\n switch (sort) {\n case \"updated_asc\":\n return (\n leftUpdated.localeCompare(rightUpdated) ||\n leftCreated.localeCompare(rightCreated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n case \"created_desc\":\n return (\n rightCreated.localeCompare(leftCreated) ||\n rightUpdated.localeCompare(leftUpdated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n case \"created_asc\":\n return (\n leftCreated.localeCompare(rightCreated) ||\n leftUpdated.localeCompare(rightUpdated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n case \"updated_desc\":\n default:\n return (\n rightUpdated.localeCompare(leftUpdated) ||\n rightCreated.localeCompare(leftCreated) ||\n left.frontmatter.id.localeCompare(right.frontmatter.id)\n );\n }\n}\n\n/**\n * Pure helper that shapes a {@link EngramAccessMemorySummary} from a\n * {@link MemoryFile} based on the requested disclosure depth (issue #677\n * PR 2/4). Extracted so the shaping invariants — chunk emits preview\n * only, section attaches `content`, raw also surfaces `rawExcerpts` when\n * the caller passes them — can be unit-tested without booting an\n * orchestrator.\n *\n * Browse / non-recall paths pass `disclosure === undefined` so the\n * `disclosure`, `content`, and `rawExcerpts` fields are all omitted —\n * preserving the cheap-by-default browse projection.\n */\nexport function shapeMemorySummary(\n memory: MemoryFile,\n baseDir: string,\n disclosure?: RecallDisclosure,\n rawExcerpts?: EngramAccessMemorySummary[\"rawExcerpts\"],\n): EngramAccessMemorySummary {\n const includeFullContent =\n disclosure === \"section\" || disclosure === \"raw\";\n return {\n id: memory.frontmatter.id,\n path: memory.path,\n category: memory.frontmatter.category,\n status: inferMemoryStatus(memory.frontmatter, toMemoryPathRel(baseDir, memory.path)),\n created: memory.frontmatter.created,\n updated: memory.frontmatter.updated,\n tags: normalizeProjectionTags(memory.frontmatter.tags),\n entityRef: memory.frontmatter.entityRef,\n preview: normalizeProjectionPreview(memory.content),\n ...(disclosure !== undefined ? { disclosure } : {}),\n ...(includeFullContent ? { content: memory.content } : {}),\n ...(disclosure === \"raw\" && rawExcerpts !== undefined\n ? { rawExcerpts }\n : {}),\n };\n}\n\nexport class EngramAccessService {\n private readonly idempotency: AccessIdempotencyStore;\n private readonly idempotencyLocks = new Map<string, Promise<void>>();\n private readonly budget: CrossNamespaceBudget;\n private readonly auditAdapter: AccessAuditAdapter | null;\n\n constructor(private readonly orchestrator: Orchestrator) {\n this.idempotency = new AccessIdempotencyStore(orchestrator.config.memoryDir);\n this.budget = new CrossNamespaceBudget({\n enabled: orchestrator.config.recallCrossNamespaceBudgetEnabled,\n windowMs: orchestrator.config.recallCrossNamespaceBudgetWindowMs,\n softLimit: orchestrator.config.recallCrossNamespaceBudgetSoftLimit,\n hardLimit: orchestrator.config.recallCrossNamespaceBudgetHardLimit,\n });\n\n const auditEnabled = orchestrator.config.recallAuditAnomalyDetectionEnabled === true;\n const auditLogEnabled = false; // Audit JSONL logging — off until wired to a directory\n if (auditEnabled || auditLogEnabled) {\n const auditConfig: AccessAuditConfig = {\n audit: {\n enabled: auditLogEnabled,\n rootDir: orchestrator.config.memoryDir,\n },\n detection: {\n enabled: auditEnabled,\n windowMs: orchestrator.config.recallAuditAnomalyWindowMs,\n repeatQueryLimit: orchestrator.config.recallAuditAnomalyRepeatQueryLimit,\n namespaceWalkLimit: orchestrator.config.recallAuditAnomalyNamespaceWalkLimit,\n highCardinalityReturnLimit: orchestrator.config.recallAuditAnomalyHighCardinalityLimit,\n rapidFireLimit: orchestrator.config.recallAuditAnomalyRapidFireLimit,\n },\n };\n this.auditAdapter = new AccessAuditAdapter(auditConfig);\n } else {\n this.auditAdapter = null;\n }\n }\n\n get briefingEnabled(): boolean {\n return this.orchestrator.config.briefing?.enabled === true;\n }\n\n private resolveNamespace(namespace?: string): string {\n const requested = namespace?.trim();\n if (!requested) return this.orchestrator.config.defaultNamespace;\n if (!this.orchestrator.config.namespacesEnabled && requested !== this.orchestrator.config.defaultNamespace) {\n throw new EngramAccessInputError(`unsupported namespace: ${requested}`);\n }\n return requested;\n }\n\n private normalizeRecallMode(mode?: RecallPlanMode | \"auto\"): RecallPlanMode | undefined {\n if (!mode || mode === \"auto\") return undefined;\n if (mode === \"no_recall\" || mode === \"minimal\" || mode === \"full\" || mode === \"graph_mode\") {\n return mode;\n }\n throw new EngramAccessInputError(`unsupported recall mode: ${mode}`);\n }\n\n private resolveRecallNamespace(namespace: string | undefined, sessionKey: string | undefined): string | undefined {\n const requested = namespace?.trim();\n if (!requested) return undefined;\n const resolved = this.resolveNamespace(requested);\n const principal = resolvePrincipal(sessionKey, this.orchestrator.config);\n if (!canReadNamespace(principal, resolved, this.orchestrator.config)) {\n throw new EngramAccessInputError(`namespace override is not readable: ${resolved}`);\n }\n return resolved;\n }\n\n private resolveWritePrincipal(sessionKey: string | undefined, authenticatedPrincipal?: string): string {\n const trusted = authenticatedPrincipal?.trim();\n if (trusted) return trusted;\n return resolvePrincipal(sessionKey, this.orchestrator.config);\n }\n\n private resolveWritableNamespace(\n namespace: string | undefined,\n sessionKey: string | undefined,\n authenticatedPrincipal?: string,\n ): string {\n const resolved = this.resolveNamespace(namespace);\n const principal = this.resolveWritePrincipal(sessionKey, authenticatedPrincipal);\n if (!canWriteNamespace(principal, resolved, this.orchestrator.config)) {\n throw new EngramAccessInputError(`namespace is not writable: ${resolved}`);\n }\n return resolved;\n }\n\n private resolveReadableNamespace(namespace: string | undefined, principal?: string): string {\n const resolved = this.resolveNamespace(namespace);\n const namespacesEnabled = this.orchestrator.config.namespacesEnabled;\n\n if (!namespacesEnabled) {\n // Namespaces are disabled globally — no ACL needed for any caller.\n return resolved;\n }\n\n // Namespaces are enabled. An absent principal means the caller is\n // unauthenticated. Unauthenticated callers must NOT be allowed to read\n // arbitrary namespaces: that would bypass all readPrincipals policies.\n if (!principal) {\n throw new EngramAccessInputError(\n \"authentication required: namespaces are enabled and no principal was supplied\",\n );\n }\n\n // Authenticated caller — enforce the namespace ACL as normal.\n if (!canReadNamespace(principal, resolved, this.orchestrator.config)) {\n throw new EngramAccessInputError(`namespace is not readable: ${resolved}`);\n }\n return resolved;\n }\n\n private async buildRecallDebug(\n snapshot: LastRecallSnapshot | null,\n namespace: string,\n includeDebug: boolean,\n sessionKey?: string,\n ): Promise<EngramAccessRecallResponse[\"debug\"] | undefined> {\n if (!includeDebug) return undefined;\n if (!sessionKey?.trim()) return undefined;\n const [intent, graph] = await Promise.all([\n this.orchestrator.getLastIntentSnapshot(namespace),\n this.orchestrator.getLastGraphRecallSnapshot(namespace),\n ]);\n return snapshot || intent || graph\n ? {\n snapshot: snapshot ?? undefined,\n intent,\n graph,\n }\n : undefined;\n }\n\n private async serializeRecallResults(\n snapshot: LastRecallSnapshot | null,\n disclosure: RecallDisclosure,\n rawContext: { query: string; sessionKey?: string } | null = null,\n ): Promise<EngramAccessMemorySummary[]> {\n if (!snapshot) return [];\n const namespace = snapshot.namespace ? this.resolveNamespace(snapshot.namespace) : this.orchestrator.config.defaultNamespace;\n const storage = await this.orchestrator.getStorage(namespace);\n const storageDir = storage.dir;\n const results: EngramAccessMemorySummary[] = [];\n const seen = new Set<string>();\n\n // Pre-fetch raw excerpts once when `disclosure === \"raw\"` so we don't\n // hit the LCM archive per-result (issue #677 PR 2/4). Excerpts are\n // attached to the first result; per-result attribution is reserved\n // for a future PR if/when the LCM index can be joined to memory ids.\n // Coerce `null` (non-raw disclosure) to `undefined` so the optional\n // serializer field is never explicitly `null`.\n // Pass the resolved namespace so the LCM lookup can mirror the\n // `${namespace}:${sessionKey}` prefix that `observe()` writes.\n const rawExcerptsResult = await this.fetchRawExcerpts(\n disclosure,\n rawContext ? { ...rawContext, namespace } : null,\n );\n const rawExcerpts = rawExcerptsResult ?? undefined;\n\n for (const memoryPath of snapshot.resultPaths ?? []) {\n if (!memoryPath || seen.has(memoryPath)) continue;\n const memory = await storage.readMemoryByPath(memoryPath);\n if (!memory) continue;\n seen.add(memoryPath);\n results.push(\n this.serializeMemorySummary(\n memory,\n storageDir,\n disclosure,\n // Attach the (possibly empty) raw excerpts to the first raw\n // result; subsequent results do not duplicate the array.\n results.length === 0 ? rawExcerpts : undefined,\n ),\n );\n }\n\n if (results.length > 0) return results;\n\n for (const memoryId of snapshot.memoryIds) {\n const memory = await storage.getMemoryById(memoryId);\n if (!memory || seen.has(memory.path)) continue;\n seen.add(memory.path);\n results.push(\n this.serializeMemorySummary(\n memory,\n storageDir,\n disclosure,\n results.length === 0 ? rawExcerpts : undefined,\n ),\n );\n }\n return results;\n }\n\n /**\n * Fetch raw transcript excerpts from the LCM archive for `disclosure ===\n * \"raw\"` recalls (issue #677 PR 2/4). Returns `null` for non-raw recall\n * depths, an empty array when LCM is disabled / not initialized / has no\n * matches, and an array of LCM-side excerpts otherwise. Errors are\n * swallowed and treated as \"no excerpts\" so a failing LCM never breaks\n * the recall response.\n *\n * Namespace handling: LCM archival prefixes non-default-namespace\n * sessions with `${namespace}:${sessionKey}` (see `observe()` around\n * line 2498), so the lookup must mirror that prefix or raw recalls in\n * non-default namespaces miss their own excerpts.\n */\n private async fetchRawExcerpts(\n disclosure: RecallDisclosure,\n context: { query: string; sessionKey?: string; namespace?: string } | null,\n ): Promise<EngramAccessMemorySummary[\"rawExcerpts\"] | null> {\n if (disclosure !== \"raw\") return null;\n if (!context || !context.query) return [];\n // Privacy guard: raw disclosure must be session-scoped. Without a\n // sessionKey, `lcm.searchContextFull(query, n, undefined)` searches\n // across every archived session in the LCM store and would return\n // excerpts from unrelated sessions (potentially crossing namespaces\n // via their `${namespace}:${sessionKey}` prefix encoding). Treat a\n // missing sessionKey as \"no excerpts\" — callers asking for raw\n // disclosure outside a session get an empty list, not a leak.\n if (!context.sessionKey) return [];\n const lcm = this.orchestrator.lcmEngine;\n if (!lcm || !lcm.enabled) return [];\n try {\n const lcmSessionKey =\n context.namespace &&\n context.namespace !== this.orchestrator.config.defaultNamespace\n ? `${context.namespace}:${context.sessionKey}`\n : context.sessionKey;\n const rows = await lcm.searchContextFull(\n context.query,\n // Cap the excerpt fanout so recall responses stay bounded. Five\n // matches is enough to anchor the model in the raw transcript\n // without ballooning token spend; raw is meant as the escape\n // hatch, not the default.\n 5,\n lcmSessionKey,\n );\n return rows.map((r) => ({\n turnIndex: r.turn_index,\n role: r.role,\n content: r.content,\n sessionId: r.session_id,\n }));\n } catch {\n // CLAUDE.md rule 13: never let an external subsystem (LCM/SQLite)\n // crash the primary recall flow.\n return [];\n }\n }\n\n private async handleIdempotentWrite<T extends EngramAccessWriteResponse>(options: {\n operation: T[\"operation\"];\n idempotencyKey?: string;\n requestFingerprint: unknown;\n skip?: boolean;\n execute: () => Promise<T>;\n }): Promise<T> {\n if (options.skip === true) {\n return options.execute();\n }\n const key = options.idempotencyKey?.trim();\n if (!key) {\n return options.execute();\n }\n return this.withIdempotencyLock(key, async () => {\n return this.idempotency.withKeyLock(key, async () => {\n const requestHash = hashAccessIdempotencyPayload({\n operation: options.operation,\n request: options.requestFingerprint,\n });\n const existing = await this.idempotency.get(key, requestHash);\n if (existing.conflict) {\n throw new EngramAccessInputError(`idempotencyKey reuse conflict: ${key}`);\n }\n if (existing.response) {\n return {\n ...(existing.response as T),\n idempotencyReplay: true,\n };\n }\n const response = await options.execute();\n await this.idempotency.put(key, requestHash, response);\n return response;\n });\n });\n }\n\n private async peekIdempotentWrite(options: {\n operation: EngramAccessWriteResponse[\"operation\"];\n idempotencyKey?: string;\n requestFingerprint: unknown;\n skip?: boolean;\n }): Promise<EngramAccessIdempotencyStatus> {\n if (options.skip === true) {\n return \"miss\";\n }\n const key = options.idempotencyKey?.trim();\n if (!key) {\n return \"miss\";\n }\n return this.withIdempotencyLock(key, async () => {\n return this.idempotency.withKeyLock(key, async () => {\n const requestHash = hashAccessIdempotencyPayload({\n operation: options.operation,\n request: options.requestFingerprint,\n });\n const existing = await this.idempotency.get(key, requestHash);\n if (existing.conflict) {\n return \"conflict\";\n }\n return existing.response ? \"replay\" : \"miss\";\n });\n });\n }\n\n private async withIdempotencyLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const previous = this.idempotencyLocks.get(key) ?? Promise.resolve();\n let release!: () => void;\n const current = new Promise<void>((resolve) => {\n release = resolve;\n });\n const queued = previous.then(() => current, () => current);\n this.idempotencyLocks.set(key, queued);\n\n await previous.catch(() => {});\n try {\n return await fn();\n } finally {\n release();\n if (this.idempotencyLocks.get(key) === queued) {\n this.idempotencyLocks.delete(key);\n }\n }\n }\n\n async health(namespace?: string): Promise<EngramAccessHealthResponse> {\n const resolvedNamespace = this.resolveNamespace(namespace);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n let projectionAvailable = false;\n try {\n await stat(getMemoryProjectionPath(storage.dir));\n projectionAvailable = true;\n } catch {\n projectionAvailable = false;\n }\n\n return {\n ok: true,\n memoryDir: storage.dir,\n namespacesEnabled: this.orchestrator.config.namespacesEnabled === true,\n defaultNamespace: this.orchestrator.config.defaultNamespace,\n searchBackend: this.orchestrator.config.searchBackend ?? \"qmd\",\n qmdEnabled: this.orchestrator.config.qmdEnabled === true,\n nativeKnowledgeEnabled: this.orchestrator.config.nativeKnowledge?.enabled === true,\n projectionAvailable,\n };\n }\n\n async daySummary(\n request: EngramAccessDaySummaryRequest,\n ): Promise<import(\"./types.js\").DaySummaryResult | null> {\n if (!this.orchestrator.config.daySummaryEnabled) {\n throw new EngramAccessInputError(\"day summary is disabled\");\n }\n\n const memories = (request.memories ?? \"\").trim();\n const namespace = this.resolveRecallNamespace(request.namespace, request.sessionKey);\n\n if (memories.length === 0) {\n // Auto-gather today's facts from the resolved namespace\n return this.orchestrator.generateDaySummaryAuto(namespace);\n }\n return this.orchestrator.generateDaySummary(memories);\n }\n\n /**\n * Build a daily context briefing. Gracefully degrades when the OpenAI key\n * or Responses API is unavailable — never throws for LLM-related problems.\n */\n async briefing(\n request: EngramAccessBriefingRequest,\n ): Promise<EngramAccessBriefingResponse> {\n const config = this.orchestrator.config;\n if (!config.briefing.enabled) {\n throw new EngramAccessInputError(\"briefing is disabled\");\n }\n\n const namespace = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(namespace);\n\n const token = typeof request.since === \"string\" && request.since.trim().length > 0\n ? request.since.trim()\n : config.briefing.defaultWindow;\n const window = parseBriefingWindow(token);\n if (!window) {\n throw new EngramAccessInputError(`invalid briefing window: ${token}`);\n }\n\n // Validate focus: only treat undefined / empty strings as \"no filter\".\n // Anything else that parses to null (e.g. \"project:\", \"topic:\") is malformed\n // and must be rejected so a templating miss never silently broadens the\n // briefing from a targeted project view to all memories.\n const rawFocus = typeof request.focus === \"string\" ? request.focus.trim() : \"\";\n let focus = null;\n if (rawFocus.length > 0) {\n focus = parseBriefingFocus(rawFocus);\n if (!focus) {\n throw new EngramAccessInputError(\n `invalid briefing focus filter: ${request.focus}`,\n );\n }\n }\n\n // Reject unsupported format values explicitly. Programmatic callers that\n // bypass CLI/MCP pre-validation (which already use validateBriefingFormat)\n // could otherwise send a typo like \"jsno\" and silently receive a response\n // in the default format, masking the client bug and breaking format-dependent\n // automation. Only undefined / absent format falls through to the default.\n const SUPPORTED_FORMATS = [\"markdown\", \"json\"] as const;\n if (\n typeof request.format === \"string\" &&\n !(SUPPORTED_FORMATS as readonly string[]).includes(request.format)\n ) {\n throw new EngramAccessInputError(\n `unsupported briefing format: \"${request.format}\". Accepted: ${SUPPORTED_FORMATS.join(\", \")}.`,\n );\n }\n const format: \"markdown\" | \"json\" = request.format === \"json\"\n ? \"json\"\n : request.format === \"markdown\"\n ? \"markdown\"\n : config.briefing.defaultFormat;\n\n const maxFollowups = typeof request.maxFollowups === \"number\" && Number.isFinite(request.maxFollowups)\n ? Math.max(0, Math.min(10, Math.floor(request.maxFollowups)))\n : config.briefing.maxFollowups;\n\n const calendarSource = config.briefing.calendarSource\n ? new FileCalendarSource(config.briefing.calendarSource)\n : undefined;\n\n const result = await buildBriefing({\n storage,\n namespace,\n window,\n focus,\n calendarSource,\n maxFollowups,\n allowLlm: config.briefing.llmFollowups,\n openaiApiKey: config.openaiApiKey,\n openaiBaseUrl: config.openaiBaseUrl,\n model: config.model,\n });\n\n return {\n format,\n window: result.window,\n namespace,\n markdown: result.markdown,\n json: result.json,\n followupsUnavailableReason: result.followupsUnavailableReason,\n };\n }\n\n /**\n * Attach a coding context to a session (issue #569). Used by the Claude\n * Code / Codex / generic-MCP connectors at session start so that recall +\n * write paths can route to a project- / branch-scoped namespace.\n *\n * Validates the input shape and rejects malformed payloads rather than\n * silently accepting them (CLAUDE.md #51). Pass `codingContext: null` to\n * clear.\n */\n setCodingContext(request: EngramAccessSetCodingContextRequest): void {\n const sessionKey = typeof request.sessionKey === \"string\" ? request.sessionKey.trim() : \"\";\n if (!sessionKey) {\n throw new EngramAccessInputError(\"sessionKey is required for setCodingContext\");\n }\n if (request.codingContext === null) {\n this.orchestrator.setCodingContextForSession(sessionKey, null);\n return;\n }\n const ctx = request.codingContext;\n if (!ctx || typeof ctx !== \"object\") {\n throw new EngramAccessInputError(\"codingContext must be an object or null\");\n }\n if (typeof ctx.projectId !== \"string\" || ctx.projectId.trim().length === 0) {\n throw new EngramAccessInputError(\"codingContext.projectId must be a non-empty string\");\n }\n // Whitespace-only rootPath must be rejected just like whitespace-only\n // projectId — otherwise a payload like `{ rootPath: \" \" }` slips past\n // validation and produces a session whose rootPath is meaningless for\n // `remnic doctor` output and for downstream namespace decisions.\n if (typeof ctx.rootPath !== \"string\" || ctx.rootPath.trim().length === 0) {\n throw new EngramAccessInputError(\"codingContext.rootPath must be a non-empty string\");\n }\n if (ctx.branch !== null && typeof ctx.branch !== \"string\") {\n throw new EngramAccessInputError(\"codingContext.branch must be a string or null\");\n }\n if (ctx.defaultBranch !== null && typeof ctx.defaultBranch !== \"string\") {\n throw new EngramAccessInputError(\"codingContext.defaultBranch must be a string or null\");\n }\n this.orchestrator.setCodingContextForSession(sessionKey, {\n projectId: ctx.projectId,\n branch: ctx.branch,\n rootPath: ctx.rootPath,\n defaultBranch: ctx.defaultBranch,\n });\n }\n\n /**\n * Auto-resolve and attach a coding context for a session when one is not\n * already present. Resolves from `projectTag` (highest priority after\n * explicit `codingContext`), then from `cwd` via git detection.\n *\n * This is a no-op when:\n * - `sessionKey` is missing\n * - the session already has a coding context attached\n * - codingMode.projectScope is disabled (CLAUDE.md #30)\n * - neither `cwd` nor `projectTag` is provided\n *\n * Never throws — git resolution failures are silently ignored because not\n * being in a repo is a normal runtime state.\n */\n private async maybeAttachCodingContext(\n sessionKey: string | undefined,\n options: { cwd?: string; projectTag?: string },\n ): Promise<void> {\n if (!sessionKey) return;\n // Respect the configuration gate (CLAUDE.md #30).\n if (!this.orchestrator.config.codingMode?.projectScope) return;\n // Don't overwrite an already-attached context.\n if (this.orchestrator.getCodingContextForSession(sessionKey)) return;\n // projectTag takes priority over cwd.\n if (typeof options.projectTag === \"string\" && options.projectTag.trim().length > 0) {\n const tag = options.projectTag.trim();\n this.orchestrator.setCodingContextForSession(sessionKey, {\n projectId: `tag:${tag}`,\n branch: null,\n rootPath: `tag:${tag}`,\n defaultBranch: null,\n });\n return;\n }\n // cwd → git resolution\n if (typeof options.cwd === \"string\" && options.cwd.trim().length > 0) {\n try {\n const gitCtx = await resolveGitContext(options.cwd);\n if (gitCtx) {\n this.setCodingContext({\n sessionKey,\n codingContext: {\n projectId: gitCtx.projectId,\n branch: gitCtx.branch,\n rootPath: gitCtx.rootPath,\n defaultBranch: gitCtx.defaultBranch,\n },\n });\n }\n } catch {\n // Silently ignore git resolution failures — not being in a repo\n // is normal. resolveGitContext itself never throws, but the\n // setCodingContext validation might reject edge-case rootPaths.\n }\n }\n }\n\n async recall(request: EngramAccessRecallRequest): Promise<EngramAccessRecallResponse> {\n const query = request.query.trim();\n if (query.length === 0) {\n throw new EngramAccessInputError(\"query is required\");\n }\n // Disclosure depth (issue #677). Default to `\"chunk\"` when omitted so\n // pre-#677 callers see unchanged behavior. Reject explicitly invalid\n // string values per CLAUDE.md rule 51 (do not silently fall back).\n const callerProvidedDisclosure =\n request.disclosure !== undefined && request.disclosure !== null;\n const requestedDisclosure: RecallDisclosure = (() => {\n if (!callerProvidedDisclosure) {\n return DEFAULT_RECALL_DISCLOSURE;\n }\n if (!isRecallDisclosure(request.disclosure)) {\n throw new EngramAccessInputError(\n `disclosure must be one of: chunk, section, raw (got: ${String(request.disclosure)})`,\n );\n }\n return request.disclosure;\n })();\n // Attach any coding context shipped with the recall request BEFORE\n // namespace resolution so the overlay applies to this recall (issue #569).\n if (request.codingContext !== undefined && request.sessionKey) {\n this.setCodingContext({\n sessionKey: request.sessionKey,\n codingContext: request.codingContext,\n });\n }\n // Auto-resolve coding context from cwd/projectTag when no explicit\n // codingContext was supplied (issue #569 wiring). This allows Claude\n // Code hooks and OpenClaw connectors to get project-scoped memory\n // transparently.\n if (request.codingContext === undefined && request.sessionKey) {\n await this.maybeAttachCodingContext(request.sessionKey, {\n cwd: request.cwd,\n projectTag: request.projectTag,\n });\n }\n const namespaceOverride = this.resolveRecallNamespace(request.namespace, request.sessionKey);\n const namespace = namespaceOverride ?? this.orchestrator.config.defaultNamespace;\n // Normalize mode early so that no_recall / invalid modes skip budget\n // accounting (Codex P1: budget recorded before mode validation).\n const mode = this.normalizeRecallMode(request.mode);\n const principal = resolvePrincipal(request.sessionKey, this.orchestrator.config);\n const principalNamespace = defaultNamespaceForPrincipal(principal, this.orchestrator.config);\n // Skip budget checks for modes that never perform a cross-namespace read.\n const modeSkipsBudget = mode === \"no_recall\";\n // Derive the full set of namespaces the orchestrator will actually search.\n // When no explicit override is provided, `recallNamespacesForPrincipal()` may\n // expand to shared / policy-default namespaces. Budget must be checked\n // against every cross-namespace entry in the effective set so that omitting\n // `namespace` cannot bypass the limiter (Cursor/Codex review feedback).\n //\n // NOTE: coding overlays (branch/project scope) are resolved inside\n // orchestrator.recall() AFTER this check. The access-service does not\n // duplicate that resolution here to avoid tight coupling. Coding-overlay\n // namespaces are a second-layer defense covered by the anomaly detector\n // (PR 5/5 of issue #565).\n const effectiveNamespaces = namespaceOverride\n ? [namespaceOverride]\n : recallNamespacesForPrincipal(principal, this.orchestrator.config);\n let budgetDecision: BudgetDecision;\n if (modeSkipsBudget) {\n budgetDecision = {\n allowed: true as const,\n reason: \"allowed-same-namespace\" as const,\n count: 0,\n limit: {\n softLimit: this.orchestrator.config.recallCrossNamespaceBudgetSoftLimit ?? 10,\n hardLimit: this.orchestrator.config.recallCrossNamespaceBudgetHardLimit ?? 30,\n windowMs: this.orchestrator.config.recallCrossNamespaceBudgetWindowMs ?? 60_000,\n },\n };\n } else {\n // Peek at every effective namespace to determine whether ANY would be\n // cross-namespace WITHOUT recording side effects (Cursor review:\n // multi-count bug). Record a single budget event only when at least\n // one effective namespace differs from the principal's self namespace.\n let anyCrossNamespace = false;\n let denied: BudgetDecision | null = null;\n for (const ns of effectiveNamespaces) {\n const peek = this.budget.peek({\n principal,\n principalNamespace,\n queryNamespace: ns,\n });\n if (peek.reason !== \"allowed-same-namespace\") {\n anyCrossNamespace = true;\n }\n if (!peek.allowed) {\n denied = peek;\n break;\n }\n }\n if (denied) {\n // The peek projected a denial — deny without recording so the\n // bucket is not inflated by rejected attempts.\n budgetDecision = denied;\n } else if (anyCrossNamespace) {\n budgetDecision = this.budget.record(principal);\n } else {\n budgetDecision = {\n allowed: true as const,\n reason: \"allowed-same-namespace\" as const,\n count: 0,\n limit: {\n softLimit: this.orchestrator.config.recallCrossNamespaceBudgetSoftLimit ?? 10,\n hardLimit: this.orchestrator.config.recallCrossNamespaceBudgetHardLimit ?? 30,\n windowMs: this.orchestrator.config.recallCrossNamespaceBudgetWindowMs ?? 60_000,\n },\n };\n }\n if (!budgetDecision.allowed) {\n throw new EngramAccessInputError(\n `recall denied: cross-namespace budget exceeded (${budgetDecision.count}/${budgetDecision.limit.hardLimit} in ${budgetDecision.limit.windowMs}ms window)`,\n );\n }\n // Prune expired principal buckets to prevent unbounded Map growth from\n // high-cardinality / transient principals (Codex P2 review feedback).\n this.budget.gc();\n }\n const topK = Number.isFinite(request.topK) ? Math.max(0, Math.floor(request.topK ?? 0)) : undefined;\n // Issue #680 — historical recall pin. Validate at the input\n // boundary so a malformed `asOf` is rejected with a structured\n // 400 instead of silently flooring at NaN inside the orchestrator\n // (CLAUDE.md rule 51, gotcha #51). Empty / undefined is fine —\n // means \"no pin\".\n let asOf: string | undefined;\n if (request.asOf !== undefined && request.asOf !== null) {\n if (typeof request.asOf !== \"string\" || request.asOf.trim().length === 0) {\n throw new EngramAccessInputError(\n \"asOf must be a non-empty ISO 8601 timestamp string\",\n );\n }\n const parsed = Date.parse(request.asOf);\n if (!Number.isFinite(parsed)) {\n throw new EngramAccessInputError(\n `asOf must be a parseable ISO 8601 timestamp (got: \"${request.asOf}\")`,\n );\n }\n asOf = request.asOf;\n }\n const recallOptions: RecallInvocationOptions = {\n namespace: namespaceOverride,\n topK,\n mode,\n ...(asOf !== undefined ? { asOf } : {}),\n ...(request.includeLowConfidence === true ? { includeLowConfidence: true } : {}),\n };\n const startedAt = Date.now();\n const context = await this.orchestrator.recall(query, request.sessionKey, recallOptions);\n const snapshot = request.sessionKey\n ? this.orchestrator.lastRecall.get(request.sessionKey)\n : null;\n const effectiveNamespace = snapshot?.namespace\n ? this.resolveNamespace(snapshot.namespace)\n : namespace;\n // Auto-escalation policy (issue #677 PR 4/4). When the operator\n // configured `recallDisclosureEscalation: \"auto\"` AND the caller\n // did not explicitly choose a disclosure level AND recall produced\n // a low-confidence result set (proxied by fill ratio: results\n // returned / topK requested), we escalate the default `chunk`\n // shape to `section` so the LLM gets richer context to compensate\n // for ambiguous retrieval. Manual mode and explicit caller\n // disclosure both bypass the policy. Documented in\n // `recall-disclosure-escalation.ts` and unit-tested there.\n // Confidence-proxy denominator: priority order is\n // 1. `snapshot.budgetsApplied.appliedTopK` (ALWAYS wins) — this is\n // the limit the orchestrator actually applied after planner /\n // minimal-mode / section-cap narrowing. Codex P1 rounds 2+3\n // on #705 emphasize that even a caller's explicit `request.topK`\n // is wrong when the orchestrator caps below it (e.g. topK=50\n // but appliedTopK=3 makes a 2-hit recall actually 0.67, not\n // 0.04).\n // 2. The caller's explicit `topK` when the snapshot lacks\n // `budgetsApplied` (early-return paths, error cases).\n // 3. Config `qmdMaxResults` as a last-resort fallback.\n // Floor at observed-results so the ratio stays in [0, 1] even if\n // any of the signals drifts below the actual hit count.\n const resultsReturned = snapshot?.memoryIds?.length ?? 0;\n const appliedTopK = snapshot?.budgetsApplied?.appliedTopK;\n const configMaxResults =\n typeof this.orchestrator.config.qmdMaxResults === \"number\" &&\n Number.isFinite(this.orchestrator.config.qmdMaxResults) &&\n this.orchestrator.config.qmdMaxResults > 0\n ? this.orchestrator.config.qmdMaxResults\n : 0;\n const topKDenominator =\n typeof appliedTopK === \"number\" &&\n Number.isFinite(appliedTopK) &&\n appliedTopK > 0\n ? Math.max(appliedTopK, resultsReturned)\n : typeof topK === \"number\" && topK > 0\n ? Math.max(topK, resultsReturned)\n : Math.max(configMaxResults, resultsReturned, 1);\n // When the recall produced no snapshot (sessionless / namespace\n // mismatch / early-return path), there is no confidence signal to\n // base escalation on. Pass `undefined` so the helper takes its\n // `no-top-k-confidence` branch instead of computing 0/N=0 and\n // forcing auto-escalation on every sessionless caller (Codex P2\n // review on PR #705).\n const topKConfidence =\n snapshot && topKDenominator > 0\n ? Math.min(1, resultsReturned / topKDenominator)\n : undefined;\n const escalationDecision = decideDisclosureEscalation({\n mode: this.orchestrator.config.recallDisclosureEscalation,\n threshold: this.orchestrator.config.recallDisclosureEscalationThreshold,\n originalDisclosure: requestedDisclosure,\n callerProvidedDisclosure,\n topKConfidence,\n });\n const disclosure = escalationDecision.effective;\n let results = await this.serializeRecallResults(snapshot, disclosure, {\n query,\n sessionKey: request.sessionKey,\n });\n\n // Tag filter (issue #689). Applied post-recall, post-serialization so\n // the actual frontmatter tags are already loaded onto each result. When\n // `tags` is absent or empty the filter is a no-op; an invalid `tagMatch`\n // throws via `parseTagMatch` (CLAUDE.md rule 51).\n const filterTags = normalizeTags(request.tags);\n let tagMatchMode: TagMatchMode | undefined;\n try {\n tagMatchMode = parseTagMatch(request.tagMatch);\n } catch (err) {\n throw new EngramAccessInputError(\n err instanceof Error ? err.message : String(err),\n );\n }\n let effectiveContext = context;\n if (filterTags && filterTags.length > 0) {\n const beforeIds = results.map((r) => r.id);\n const { results: admitted } = applyTagFilter(results, {\n tags: filterTags,\n tagMatch: tagMatchMode,\n });\n results = admitted;\n // Codex P1: `context` was generated by orchestrator.recall(...)\n // BEFORE the tag filter ran, so it can contain memories that don't\n // match the requested tags. Surfaces consuming `context` (the\n // prompt-injection string) would leak excluded content into the\n // LLM. When the filter actually drops any result, rebuild context\n // from the admitted set so excluded content is unreachable through\n // any field of the response. The rebuilt context concatenates each\n // admitted result's available text (full content at section/raw\n // disclosure, otherwise the preview) — a different wire format\n // than the orchestrator's native context, but a strict subset\n // safe to inject.\n const admittedIds = new Set(results.map((r) => r.id));\n const droppedAny = beforeIds.some((id) => !admittedIds.has(id));\n if (droppedAny) {\n effectiveContext = results\n .map((r) => {\n const content =\n typeof (r as { content?: unknown }).content === \"string\"\n ? ((r as { content?: string }).content ?? \"\")\n : \"\";\n const preview =\n typeof (r as { preview?: unknown }).preview === \"string\"\n ? ((r as { preview?: string }).preview ?? \"\")\n : \"\";\n return content || preview;\n })\n .filter((s) => s.length > 0)\n .join(\"\\n\\n\");\n }\n }\n const filteredMemoryIds = filterTags && filterTags.length > 0\n ? results.map((r) => r.id)\n : (snapshot?.memoryIds ?? []);\n const debug = await this.buildRecallDebug(\n snapshot,\n effectiveNamespace,\n request.includeDebug === true,\n request.sessionKey,\n );\n\n // Fire-and-forget audit recording. Must never block or crash recall.\n let auditAnomalies: AccessAuditResult[\"anomalies\"] | undefined;\n if (this.auditAdapter) {\n try {\n const resolvedAgentId = resolvePrincipal(\n request.sessionKey,\n this.orchestrator.config,\n );\n const auditEntry = {\n ts: new Date().toISOString(),\n sessionKey: request.sessionKey ?? \"\",\n agentId: resolvedAgentId,\n trigger: \"access-surface\",\n queryText: query,\n candidateMemoryIds: snapshot?.memoryIds ?? [],\n // Audit must reflect what was actually injected, not what\n // recall produced before the tag filter. Using `context`\n // (pre-filter) overstates injectedChars and can leak content\n // from excluded memories into the audit summary (cursor\n // Medium on PR #712).\n summary: effectiveContext.slice(0, 200) || null,\n injectedChars: effectiveContext.length,\n toggleState: \"enabled\" as const,\n latencyMs: Date.now() - startedAt,\n plannerMode: snapshot?.plannerMode ?? mode,\n requestedMode: mode,\n fallbackUsed: snapshot?.fallbackUsed ?? false,\n };\n const auditResult = await this.auditAdapter.record(\n resolvedAgentId || \"__anonymous__\",\n auditEntry,\n );\n auditAnomalies = auditResult.anomalies;\n } catch {\n // Audit failures must never crash the recall path.\n }\n }\n\n return {\n query,\n sessionKey: request.sessionKey,\n namespace: effectiveNamespace,\n context: effectiveContext,\n count: filterTags && filterTags.length > 0\n ? results.length\n : (snapshot?.memoryIds.length ?? results.length),\n memoryIds: filteredMemoryIds,\n results,\n recordedAt: snapshot?.recordedAt,\n traceId: snapshot?.traceId,\n plannerMode: snapshot?.plannerMode ?? mode,\n fallbackUsed: snapshot?.fallbackUsed ?? false,\n sourcesUsed: snapshot?.sourcesUsed ?? [],\n disclosure,\n budgetsApplied: snapshot?.budgetsApplied,\n auditAnomalies,\n budgetWarning: budgetDecision.reason === \"warn-over-soft\" ? budgetDecision : undefined,\n latencyMs: snapshot?.latencyMs ?? (Date.now() - startedAt),\n debug,\n };\n }\n\n async recallExplain(\n request: EngramAccessRecallExplainRequest = {},\n ): Promise<EngramAccessRecallExplainResponse> {\n const requestedNamespace = request.namespace?.trim()\n ? this.resolveNamespace(request.namespace)\n : undefined;\n if (requestedNamespace) {\n const principal = resolvePrincipal(request.sessionKey, this.orchestrator.config);\n if (!canReadNamespace(principal, requestedNamespace, this.orchestrator.config)) {\n return { found: false };\n }\n }\n const snapshot = request.sessionKey\n ? (() => {\n const candidate = this.orchestrator.lastRecall.get(request.sessionKey);\n if (!candidate) return null;\n if (!requestedNamespace) return candidate;\n return candidate.namespace === requestedNamespace ? candidate : null;\n })()\n : (() => {\n const candidate = this.orchestrator.lastRecall.getMostRecent();\n if (!candidate) return null;\n if (!requestedNamespace) return candidate;\n return candidate.namespace === requestedNamespace ? candidate : null;\n })();\n const namespace = requestedNamespace ?? snapshot?.namespace ?? this.orchestrator.config.defaultNamespace;\n const [intent, graph] = await Promise.all([\n this.orchestrator.getLastIntentSnapshot(namespace),\n this.orchestrator.getLastGraphRecallSnapshot(namespace),\n ]);\n if (!snapshot && !intent && !graph) return { found: false };\n return { found: true, snapshot: snapshot ?? undefined, intent, graph };\n }\n\n async recallTierExplain(\n sessionKey?: string,\n namespace?: string,\n authenticatedPrincipal?: string,\n ) {\n const namespacesEnabled = this.orchestrator.config.namespacesEnabled;\n const requestedNamespace = namespace?.trim()\n ? this.resolveNamespace(namespace)\n : undefined;\n const principal = authenticatedPrincipal?.trim()\n || resolvePrincipal(sessionKey, this.orchestrator.config);\n\n if (requestedNamespace) {\n if (!canReadNamespace(principal, requestedNamespace, this.orchestrator.config)) {\n return toRecallExplainJson(null);\n }\n } else if (namespacesEnabled && !authenticatedPrincipal?.trim() && !sessionKey?.trim()) {\n return toRecallExplainJson(null);\n }\n\n const candidate = sessionKey\n ? this.orchestrator.lastRecall.get(sessionKey)\n : this.orchestrator.lastRecall.getMostRecent();\n\n const snapshot = (() => {\n if (!candidate) return null;\n if (requestedNamespace) {\n return candidate.namespace === requestedNamespace ? candidate : null;\n }\n if (!namespacesEnabled) return candidate;\n const snapshotNs = candidate.namespace\n ?? this.orchestrator.config.defaultNamespace;\n return canReadNamespace(principal, snapshotNs, this.orchestrator.config)\n ? candidate\n : null;\n })();\n\n return toRecallExplainJson(snapshot);\n }\n\n /**\n * Recall X-ray (issue #570). Runs a recall with `xrayCapture: true`\n * and returns the resulting snapshot as structured JSON so every\n * surface (CLI / HTTP / MCP) gets the same payload. Namespace scope\n * is enforced before the recall fires (CLAUDE.md rule 42 — read and\n * write paths must resolve through the same namespace layer) so an\n * unauthorized principal cannot capture an x-ray for a namespace it\n * cannot read.\n */\n async recallXray(request: {\n query: string;\n sessionKey?: string;\n namespace?: string;\n budget?: number;\n authenticatedPrincipal?: string;\n /**\n * Disclosure depth used to shape per-result payload (issue #677\n * PR 3/4). When set, each X-ray result is decorated with the\n * matching `disclosure` field and `estimatedTokens` computed from\n * the actual rendered content at that depth, so the renderer's\n * \"Token spend by disclosure\" summary reflects real spend rather\n * than staying empty when no caller wires the depth knob through.\n */\n disclosure?: RecallDisclosure;\n /**\n * Free-form recall tag filter (issue #689). Mirrors the field on\n * `EngramAccessRecallRequest`. When non-empty, the captured X-ray\n * snapshot's `results` are filtered down to memories whose\n * frontmatter tags satisfy `tagMatch` (\"any\" by default), and a\n * `tag-filter` entry is appended to `filters`.\n */\n tags?: string[];\n /** Match mode for `tags`. See `EngramAccessRecallRequest.tagMatch`. */\n tagMatch?: \"any\" | \"all\";\n }): Promise<{\n snapshotFound: boolean;\n snapshot?: import(\"./recall-xray.js\").RecallXraySnapshot;\n }> {\n const query = typeof request.query === \"string\" ? request.query : \"\";\n if (query.trim().length === 0) {\n // Match the CLI contract (CLAUDE.md rule 51): reject empty\n // input with an explicit error rather than silently producing\n // an empty snapshot.\n throw new Error(\"recallXray: query is required and must be non-empty\");\n }\n // Validate disclosure UP FRONT — before recall executes, before\n // the xray queue mutex is acquired, before namespace resolution.\n // A bad value should fail fast rather than after we've burned\n // cycles on an irreversible recall (Cursor Medium review on PR\n // #699).\n if (\n request.disclosure !== undefined &&\n !isRecallDisclosure(request.disclosure)\n ) {\n throw new EngramAccessInputError(\n `recallXray: disclosure must be one of: chunk, section, raw (got: ${String(request.disclosure)})`,\n );\n }\n\n const namespacesEnabled = this.orchestrator.config.namespacesEnabled;\n const requestedNamespace = request.namespace?.trim()\n ? this.resolveNamespace(request.namespace)\n : undefined;\n const authenticatedPrincipal = request.authenticatedPrincipal?.trim();\n const principal =\n authenticatedPrincipal\n || resolvePrincipal(request.sessionKey, this.orchestrator.config);\n\n if (requestedNamespace) {\n if (\n !canReadNamespace(\n principal,\n requestedNamespace,\n this.orchestrator.config,\n )\n ) {\n return { snapshotFound: false };\n }\n } else if (\n namespacesEnabled\n && !authenticatedPrincipal\n && !request.sessionKey?.trim()\n ) {\n // Namespaces enabled but no identity supplied — reject rather\n // than scanning the global namespace (CLAUDE.md rule 48:\n // least-privileged default).\n return { snapshotFound: false };\n }\n\n // Optional `--budget` override must be a positive integer. Invalid\n // values throw rather than silently defaulting (CLAUDE.md rule 51).\n let budgetOverride: number | undefined;\n if (request.budget !== undefined && request.budget !== null) {\n const parsed =\n typeof request.budget === \"number\"\n ? request.budget\n : Number(request.budget);\n if (\n !Number.isFinite(parsed)\n || parsed <= 0\n || !Number.isInteger(parsed)\n ) {\n throw new Error(\n `recallXray: budget expects a positive integer; got ${JSON.stringify(request.budget)}`,\n );\n }\n budgetOverride = parsed;\n }\n\n // Serialize x-ray invocations behind a per-service mutex so the\n // per-process `getLastXraySnapshot()` slot cannot be clobbered by\n // a concurrent capturing call before this caller reads it back.\n // Budget and principal are now threaded through\n // `RecallInvocationOptions`, so global config mutation is gone\n // (CLAUDE.md rule 47: no shared mutable state across async\n // boundaries). The mutex stays only for the snapshot-slot\n // ordering guarantee.\n const previousQueue = this.xrayQueue;\n let release: () => void = () => {};\n this.xrayQueue = new Promise<void>((resolve) => {\n release = resolve;\n });\n await previousQueue;\n\n try {\n // Clear any prior snapshot so a capture failure surfaces as\n // `{snapshotFound: false}` rather than returning stale data\n // from an earlier call on the same orchestrator.\n this.orchestrator.clearLastXraySnapshot();\n await this.orchestrator.recall(query, request.sessionKey?.trim() || undefined, {\n xrayCapture: true,\n ...(requestedNamespace ? { namespace: requestedNamespace } : {}),\n ...(budgetOverride !== undefined\n ? { budgetCharsOverride: budgetOverride }\n : {}),\n // When the caller supplies an authenticated principal, forward\n // it via the dedicated override channel so orchestrator-side\n // ACL decisions use the SAME principal the access-surface\n // pre-check above authorized. Threading an\n // `authenticatedPrincipal` through `sessionKey` would be wrong:\n // `resolvePrincipal(sessionKey)` only maps configured raw\n // session keys and otherwise collapses to `\"default\"`, which\n // in namespace-enabled deployments produces false denials /\n // wrong-scope serving despite the pre-check passing\n // (CLAUDE.md rule 42).\n ...(authenticatedPrincipal\n ? { principalOverride: authenticatedPrincipal }\n : {}),\n });\n\n const rawSnapshot = this.orchestrator.getLastXraySnapshot();\n if (!rawSnapshot) return { snapshotFound: false };\n // Re-check namespace after capture: the recall may have served\n // from a different namespace than the caller requested. Drop\n // the snapshot rather than leak cross-tenant data (CLAUDE.md\n // rules 42 + 47). The comparison is strict so a snapshot whose\n // namespace is `undefined` cannot bypass the scope the caller\n // asked for.\n if (requestedNamespace && rawSnapshot.namespace !== requestedNamespace) {\n return { snapshotFound: false };\n }\n // Tag filter (issue #689). Mirrors `recall()` semantics — applied\n // post-capture by reading each result's frontmatter tags and\n // dropping non-matching results. Filter activity surfaces as a\n // `tag-filter` entry in `snapshot.filters` so X-ray consumers can\n // see the \"considered → admitted\" delta.\n let snapshot = rawSnapshot;\n const xrayFilterTags = normalizeTags(request.tags);\n let xrayTagMatch: TagMatchMode | undefined;\n try {\n xrayTagMatch = parseTagMatch(request.tagMatch);\n } catch (err) {\n throw new EngramAccessInputError(\n err instanceof Error ? err.message : String(err),\n );\n }\n if (xrayFilterTags && xrayFilterTags.length > 0) {\n const namespace = snapshot.namespace\n ? this.resolveNamespace(snapshot.namespace)\n : this.orchestrator.config.defaultNamespace;\n const tagsByIndex = await Promise.all(\n snapshot.results.map(async (result) => {\n try {\n const storage = await this.orchestrator.getStorage(namespace);\n const memory = await storage.readMemoryByPath(result.path);\n const t = memory?.frontmatter?.tags;\n // Normalize identically to the recall path\n // (`normalizeProjectionTags`): trim and drop empty strings\n // so X-ray tag matching stays consistent with the recall\n // surface. Without this, a frontmatter tag like \" draft \"\n // would match in recall but not in X-ray (cursor review).\n return Array.isArray(t) ? normalizeProjectionTags(t) : [];\n } catch {\n return [];\n }\n }),\n );\n const tagged = snapshot.results.map((result, index) => ({\n result,\n tags: tagsByIndex[index] ?? [],\n }));\n const { results: admittedTagged, trace } = applyTagFilter(tagged, {\n tags: xrayFilterTags,\n tagMatch: xrayTagMatch,\n });\n const admittedResults = admittedTagged.map((entry) => entry.result);\n const filters = trace ? [...snapshot.filters, trace] : snapshot.filters;\n snapshot = { ...snapshot, results: admittedResults, filters };\n }\n // Decorate per-result disclosure + token estimate when the caller\n // wired a depth knob (issue #677 PR 3/4 — codex review on #699\n // flagged that the renderer's per-disclosure summary stays empty\n // until callers populate these fields). Estimate tokens from\n // the actual rendered payload at the requested depth so the\n // summary reflects real spend; chunk uses the preview, section\n // and raw use full content. Best-effort only — a missing\n // memory or read failure is silently dropped (CLAUDE.md rule 13).\n if (request.disclosure !== undefined) {\n // Disclosure already validated up front; pin to the narrowed\n // type here. Re-validation inside the queue would be dead code.\n const disclosure: RecallDisclosure = request.disclosure;\n const namespace = snapshot.namespace\n ? this.resolveNamespace(snapshot.namespace)\n : this.orchestrator.config.defaultNamespace;\n // Pre-fetch raw excerpts ONCE so the first raw-disclosure\n // result's token estimate includes the LCM-side excerpt spend\n // that `shapeMemorySummary` actually attaches in the recall\n // response. Without this, raw recalls systematically\n // undercounted spend on the first result (Cursor Medium review\n // on PR #699). Excerpts are scoped to the same session +\n // namespace as the recall.\n // Trim sessionKey to match what `orchestrator.recall(...)`\n // already does (`request.sessionKey?.trim() || undefined`),\n // otherwise a whitespace-padded key drives recall under one\n // identity but probes LCM under a different prefix and\n // misses stored excerpts (Cursor Low review on PR #699).\n const trimmedSessionKey = request.sessionKey?.trim() || undefined;\n const rawExcerpts =\n disclosure === \"raw\"\n ? await this.fetchRawExcerpts(disclosure, {\n query,\n ...(trimmedSessionKey ? { sessionKey: trimmedSessionKey } : {}),\n namespace,\n })\n : null;\n const rawExcerptText =\n rawExcerpts && rawExcerpts.length > 0\n ? rawExcerpts.map((e) => e.content).join(\"\\n\")\n : \"\";\n // Pre-load every memory in parallel so we can:\n // (a) re-attribute raw excerpts to the *first readable* result\n // rather than always to index 0 (Cursor Low review on PR\n // #699: a missing/unreadable result[0] orphaned the excerpt\n // budget); and\n // (b) include the metadata fields `shapeMemorySummary` actually\n // emits at every depth (id, path, category, status, created,\n // updated, tags, entityRef) in the token estimate, so the\n // summary reflects real spend rather than only payload-body\n // spend (Cursor Low review on PR #699).\n const memoryByIndex = await Promise.all(\n snapshot.results.map(async (result) => {\n try {\n const storage = await this.orchestrator.getStorage(namespace);\n return await storage.readMemoryByPath(result.path);\n } catch {\n return null;\n }\n }),\n );\n const firstReadableIndex = memoryByIndex.findIndex((m) => m !== null);\n const baseDir =\n (await this.orchestrator.getStorage(namespace)).dir;\n const decorated = snapshot.results.map((result, index) => {\n const memory = memoryByIndex[index];\n if (!memory) {\n // Unreadable result: attach the disclosure tag anyway so\n // the per-disclosure summary classifies it correctly,\n // but skip the token estimate since we don't have the\n // content to measure. Without the disclosure tag the\n // result silently flows into the `unspecified` bucket\n // even though the caller explicitly requested a depth\n // (Cursor Low review on PR #699).\n return { ...result, disclosure };\n }\n // Build a representative shaped summary so the estimate\n // counts every field `shapeMemorySummary` actually emits.\n // The serialized JSON form is a close-enough proxy for the\n // wire payload size.\n const shaped = shapeMemorySummary(\n memory,\n baseDir,\n disclosure,\n disclosure === \"raw\" &&\n index === firstReadableIndex &&\n rawExcerpts &&\n rawExcerpts.length > 0\n ? rawExcerpts\n : undefined,\n );\n return {\n ...result,\n disclosure,\n estimatedTokens: estimateRecallTokens(JSON.stringify(shaped)),\n };\n });\n // Edge case: every result was unreadable but rawExcerpts\n // still has content — credit that spend to result[0] rather\n // than dropping it on the floor. Without this, the raw row\n // in the per-disclosure summary under-reports spend whenever\n // every memory file is missing/unreadable.\n if (\n disclosure === \"raw\" &&\n firstReadableIndex === -1 &&\n rawExcerptText.length > 0 &&\n decorated.length > 0\n ) {\n decorated[0] = {\n ...decorated[0]!,\n disclosure,\n estimatedTokens: estimateRecallTokens(rawExcerptText),\n };\n }\n return {\n snapshotFound: true,\n snapshot: { ...snapshot, results: decorated },\n };\n }\n return { snapshotFound: true, snapshot };\n } finally {\n release();\n }\n }\n // Sequence lock for `recallXray` — see comment inside the method.\n // Lives on the instance so every x-ray call on the same service\n // shares it, and so separate services in the same process (e.g.\n // per-tenant) do not block each other.\n private xrayQueue: Promise<void> = Promise.resolve();\n\n async memoryStore(request: EngramAccessMemoryStoreRequest): Promise<EngramAccessWriteResponse> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n const execute = async (): Promise<EngramAccessWriteResponse> => {\n const candidate = this.validateWriteCandidate(request, namespace);\n if (request.dryRun === true) {\n return {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"memory_store\",\n namespace,\n dryRun: true,\n accepted: true,\n queued: false,\n status: \"validated\",\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n }\n const result = await persistExplicitCapture(this.orchestrator, candidate, \"memory_store\");\n const response: EngramAccessWriteResponse = {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"memory_store\",\n namespace,\n dryRun: false,\n accepted: true,\n queued: false,\n status: result.duplicateOf ? \"duplicate\" : \"stored\",\n memoryId: result.id,\n duplicateOf: result.duplicateOf,\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n log.info(\n `access-write op=memory_store namespace=${namespace} dryRun=false status=${response.status} memoryId=${response.memoryId ?? \"-\"} idempotency=${response.idempotencyKey ? \"yes\" : \"no\"}`,\n );\n return response;\n };\n return this.handleIdempotentWrite({\n operation: \"memory_store\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n execute,\n });\n }\n\n async peekMemoryStoreIdempotency(request: EngramAccessMemoryStoreRequest): Promise<EngramAccessIdempotencyStatus> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n return this.peekIdempotentWrite({\n operation: \"memory_store\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n });\n }\n\n async suggestionSubmit(request: EngramAccessSuggestionSubmitRequest): Promise<EngramAccessWriteResponse> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n const execute = async (): Promise<EngramAccessWriteResponse> => {\n const candidate = this.validateWriteCandidate(request, namespace);\n if (request.dryRun === true) {\n return {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"suggestion_submit\",\n namespace,\n dryRun: true,\n accepted: true,\n queued: true,\n status: \"validated\",\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n }\n const result = await queueExplicitCaptureForReview(\n this.orchestrator,\n candidate,\n \"suggestion_submit\",\n new Error(request.sourceReason?.trim() || \"submitted via engram suggestion_submit\"),\n );\n const response: EngramAccessWriteResponse = {\n schemaVersion: ENGRAM_ACCESS_WRITE_SCHEMA_VERSION,\n operation: \"suggestion_submit\",\n namespace,\n dryRun: false,\n accepted: true,\n queued: true,\n status: \"queued_for_review\",\n memoryId: result.id,\n duplicateOf: result.duplicateOf,\n idempotencyKey: request.idempotencyKey?.trim() || undefined,\n };\n log.info(\n `access-write op=suggestion_submit namespace=${namespace} dryRun=false status=${response.status} memoryId=${response.memoryId ?? \"-\"} idempotency=${response.idempotencyKey ? \"yes\" : \"no\"}`,\n );\n return response;\n };\n return this.handleIdempotentWrite({\n operation: \"suggestion_submit\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n execute,\n });\n }\n\n async peekSuggestionSubmitIdempotency(\n request: EngramAccessSuggestionSubmitRequest,\n ): Promise<EngramAccessIdempotencyStatus> {\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n const schemaVersion = request.schemaVersion ?? ENGRAM_ACCESS_WRITE_SCHEMA_VERSION;\n if (schemaVersion !== ENGRAM_ACCESS_WRITE_SCHEMA_VERSION) {\n throw new EngramAccessInputError(`unsupported schemaVersion: ${schemaVersion}`);\n }\n return this.peekIdempotentWrite({\n operation: \"suggestion_submit\",\n idempotencyKey: request.idempotencyKey,\n requestFingerprint: {\n schemaVersion,\n content: request.content,\n category: request.category,\n confidence: request.confidence,\n namespace,\n tags: request.tags,\n entityRef: request.entityRef,\n ttl: request.ttl,\n sourceReason: request.sourceReason,\n },\n skip: request.dryRun === true,\n });\n }\n\n private validateWriteCandidate(\n request: EngramAccessMemoryStoreRequest | EngramAccessSuggestionSubmitRequest,\n namespace: string,\n ): ValidExplicitCapture {\n try {\n return validateExplicitCaptureInput(\n {\n ...request,\n namespace,\n },\n \"legacy_tool\",\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new EngramAccessInputError(message);\n }\n }\n\n async memoryGet(memoryId: string, namespace?: string, principal?: string): Promise<EngramAccessMemoryResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const memory = await storage.getMemoryById(memoryId);\n if (!memory) {\n return { found: false, namespace: resolvedNamespace };\n }\n return {\n found: true,\n namespace: resolvedNamespace,\n memory: this.serializeMemory(memory),\n };\n }\n\n async memoryBrowse(\n request: EngramAccessMemoryBrowseRequest = {},\n ): Promise<EngramAccessMemoryBrowseResponse> {\n const storage = await this.orchestrator.getStorage(request.namespace);\n const resolvedNamespace = request.namespace?.trim() || this.orchestrator.config.defaultNamespace;\n const { limit, offset } = normalizePagination(request.limit, request.offset);\n const sort = normalizeBrowseSort(request.sort);\n const query = request.query?.trim().toLowerCase() ?? \"\";\n const statusFilter = request.status?.trim().toLowerCase();\n const categoryFilter = request.category?.trim().toLowerCase();\n\n const projected = await storage.browseProjectedMemories({\n query,\n status: statusFilter,\n category: categoryFilter,\n sort,\n limit,\n offset,\n });\n if (projected) {\n return {\n namespace: resolvedNamespace,\n sort,\n total: projected.total,\n count: projected.memories.length,\n limit,\n offset,\n memories: projected.memories.map((row) => ({ ...row })),\n };\n }\n\n let memories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()];\n memories = memories.filter((memory) => {\n const status = inferMemoryStatus(memory.frontmatter, toMemoryPathRel(storage.dir, memory.path)).toLowerCase();\n if (statusFilter && status !== statusFilter) return false;\n if (categoryFilter && memory.frontmatter.category.toLowerCase() !== categoryFilter) return false;\n if (!query) return true;\n const haystack = [\n memory.frontmatter.id,\n memory.path,\n memory.content,\n memory.frontmatter.entityRef ?? \"\",\n ...memory.frontmatter.tags,\n ].join(\"\\n\").toLowerCase();\n return haystack.includes(query);\n });\n\n memories.sort((left, right) => compareBrowseMemory(sort, left, right));\n\n const page = memories\n .slice(offset, offset + limit)\n .map((memory) => this.serializeMemorySummary(memory, storage.dir));\n return {\n namespace: resolvedNamespace,\n sort,\n total: memories.length,\n count: page.length,\n limit,\n offset,\n memories: page,\n };\n }\n\n async memoryTimeline(\n memoryId: string,\n namespace?: string,\n limit: number = 200,\n principal?: string,\n ): Promise<EngramAccessTimelineResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const timeline = await storage.getMemoryTimeline(memoryId, limit);\n return {\n found: timeline.length > 0,\n namespace: resolvedNamespace,\n count: timeline.length,\n timeline,\n };\n }\n\n async entityList(options: {\n namespace?: string;\n query?: string;\n limit?: number;\n offset?: number;\n } = {}): Promise<EngramAccessEntityListResponse> {\n const storage = await this.orchestrator.getStorage(options.namespace);\n const resolvedNamespace = options.namespace?.trim() || this.orchestrator.config.defaultNamespace;\n const { limit, offset } = normalizePagination(options.limit, options.offset);\n const query = options.query?.trim().toLowerCase() ?? \"\";\n\n const names = await storage.listEntityNames();\n const entities: EngramAccessEntitySummary[] = [];\n for (const name of names) {\n const raw = await storage.readEntity(name);\n if (!raw) continue;\n const entity = parseEntityFile(raw, this.orchestrator.config.entitySchemas);\n if (query) {\n const haystack = [\n entity.name,\n entity.type,\n entity.synthesis || entity.summary || \"\",\n ...entity.aliases,\n ...entity.facts,\n ...(entity.structuredSections ?? []).flatMap((section) => [section.title, ...section.facts]),\n ].join(\"\\n\").toLowerCase();\n if (!haystack.includes(query)) continue;\n }\n entities.push({\n name: entity.name,\n type: entity.type,\n updated: entity.updated,\n summary: entity.synthesis || entity.summary,\n aliases: entity.aliases,\n });\n }\n\n entities.sort((left, right) => left.name.localeCompare(right.name));\n const page = entities.slice(offset, offset + limit);\n return {\n namespace: resolvedNamespace,\n total: entities.length,\n count: page.length,\n limit,\n offset,\n entities: page,\n };\n }\n\n async entityGet(name: string, namespace?: string): Promise<EngramAccessEntityResponse> {\n const storage = await this.orchestrator.getStorage(namespace);\n const resolvedNamespace = namespace?.trim() || this.orchestrator.config.defaultNamespace;\n const raw = await storage.readEntity(name);\n if (!raw) return { found: false, namespace: resolvedNamespace };\n return {\n found: true,\n namespace: resolvedNamespace,\n entity: parseEntityFile(raw, this.orchestrator.config.entitySchemas),\n };\n }\n\n async reviewQueue(runId?: string, namespace?: string, principal?: string): Promise<EngramAccessReviewQueueResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const projected = await storage.getProjectedGovernanceRecord();\n if (projected && (!runId || projected.runId === runId.trim())) {\n const projectedAppliedActions = projected.appliedActionRows.map((row) => ({\n action: row.action,\n memoryId: row.memoryId,\n reasonCode: row.reasonCode,\n beforeStatus: row.beforeStatus,\n afterStatus: row.afterStatus,\n originalPath: row.originalPath,\n currentPath: row.currentPath,\n })) as Awaited<\n ReturnType<typeof readMemoryGovernanceRunArtifact>\n >[\"appliedActions\"];\n const projectedProposedActions = await buildProjectedGovernanceProposedActions(storage, projected);\n const projectedArtifact = await (async () => {\n try {\n return await readMemoryGovernanceRunArtifact(storage.dir, projected.runId);\n } catch {\n return null;\n }\n })();\n const metrics = projected.metrics as Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"metrics\"];\n const fallbackTransitionReport = {\n proposed: groupActionsByStatus(projectedProposedActions),\n applied: groupActionsByStatus(projectedAppliedActions),\n };\n const transitionReport = projectedArtifact?.transitionReport\n ? {\n proposed:\n hasGroupedGovernanceActions(projectedArtifact.transitionReport.proposed) || projectedProposedActions.length === 0\n ? projectedArtifact.transitionReport.proposed\n : fallbackTransitionReport.proposed,\n applied:\n hasGroupedGovernanceActions(projectedArtifact.transitionReport.applied) || projectedAppliedActions.length === 0\n ? projectedArtifact.transitionReport.applied\n : fallbackTransitionReport.applied,\n }\n : fallbackTransitionReport;\n const qualityScore = projectedArtifact?.qualityScore ?? metrics?.qualityScore ?? buildQualityScore(metrics?.reviewReasons ?? {\n exact_duplicate: 0,\n semantic_duplicate_candidate: 0,\n disputed_memory: 0,\n speculative_low_confidence: 0,\n archive_candidate: 0,\n explicit_capture_review: 0,\n malformed_import: 0,\n });\n const effectiveMetrics = metrics ? { ...metrics, qualityScore: metrics.qualityScore ?? qualityScore } : metrics;\n\n return {\n found: true,\n namespace: resolvedNamespace,\n runId: projected.runId,\n summary: projected.summary as Awaited<ReturnType<typeof readMemoryGovernanceRunArtifact>>[\"summary\"],\n metrics: effectiveMetrics,\n qualityScore,\n reviewQueue: projected.reviewQueueRows.map((row) => ({\n entryId: row.entryId,\n memoryId: row.memoryId,\n path: row.path,\n reasonCode: row.reasonCode,\n severity: row.severity,\n suggestedAction: row.suggestedAction,\n suggestedStatus: row.suggestedStatus,\n relatedMemoryIds: row.relatedMemoryIds,\n })) as Awaited<\n ReturnType<typeof readMemoryGovernanceRunArtifact>\n >[\"reviewQueue\"],\n appliedActions: projectedAppliedActions,\n transitionReport,\n report: projected.report,\n };\n }\n\n const resolvedRunId = runId?.trim() || (await listMemoryGovernanceRuns(storage.dir))[0];\n if (!resolvedRunId) return { found: false, namespace: resolvedNamespace };\n const artifact = await readMemoryGovernanceRunArtifact(storage.dir, resolvedRunId);\n return {\n found: true,\n namespace: resolvedNamespace,\n runId: resolvedRunId,\n summary: artifact.summary,\n metrics: artifact.metrics,\n qualityScore: artifact.qualityScore,\n reviewQueue: artifact.reviewQueue,\n appliedActions: artifact.appliedActions,\n transitionReport: artifact.transitionReport,\n report: artifact.report,\n };\n }\n\n async maintenance(namespace?: string, principal?: string): Promise<EngramAccessMaintenanceResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n return {\n namespace: resolvedNamespace,\n health: await this.health(resolvedNamespace),\n latestGovernanceRun: await this.reviewQueue(undefined, resolvedNamespace, principal),\n };\n }\n\n async quality(namespace?: string, principal?: string): Promise<EngramAccessQualityResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const governance = await this.reviewQueue(undefined, resolvedNamespace, principal);\n const nowMs = Date.now();\n const statusCounts: Record<string, number> = {};\n const categoryCounts: Record<string, number> = {};\n const confidenceTierCounts: Record<string, number> = {};\n const ageBucketCounts: Record<string, number> = {};\n let staleActive = 0;\n let lowConfidenceActive = 0;\n\n const memories = [...await storage.readAllMemories(), ...await storage.readArchivedMemories()];\n for (const memory of memories) {\n const status = inferMemoryStatus(memory.frontmatter, toMemoryPathRel(storage.dir, memory.path)).toLowerCase();\n const confidenceTier = memory.frontmatter.confidenceTier ?? \"unknown\";\n const ageBucket = bucketMemoryAge(memory.frontmatter.updated ?? memory.frontmatter.created, nowMs);\n\n incrementCount(statusCounts, status);\n incrementCount(categoryCounts, memory.frontmatter.category);\n incrementCount(confidenceTierCounts, confidenceTier);\n incrementCount(ageBucketCounts, ageBucket);\n\n if (status === \"active\") {\n if (ageBucket === \"91_plus_days\") staleActive += 1;\n if ((memory.frontmatter.confidence ?? 0) < 0.6) lowConfidenceActive += 1;\n }\n }\n\n return {\n namespace: resolvedNamespace,\n totalMemories: memories.length,\n statusCounts,\n categoryCounts,\n confidenceTierCounts,\n ageBucketCounts,\n archivePressure: {\n pendingReview: statusCounts.pending_review ?? 0,\n quarantined: statusCounts.quarantined ?? 0,\n archived: statusCounts.archived ?? 0,\n staleActive,\n lowConfidenceActive,\n },\n latestGovernanceRun: {\n found: governance.found,\n runId: governance.runId,\n qualityScore: governance.qualityScore ?? governance.metrics?.qualityScore,\n reviewQueueCount: governance.reviewQueue?.length ?? 0,\n },\n };\n }\n\n async governanceRun(\n request: {\n namespace?: string;\n mode?: \"shadow\" | \"apply\";\n recentDays?: number;\n maxMemories?: number;\n batchSize?: number;\n authenticatedPrincipal?: string;\n },\n principal?: string,\n ): Promise<{\n namespace: string;\n runId: string;\n traceId: string;\n mode: \"shadow\" | \"apply\";\n reviewQueueCount: number;\n proposedActionCount: number;\n appliedActionCount: number;\n summaryPath: string;\n reportPath: string;\n }> {\n const deepSleep = this.orchestrator.config.dreamsPhases.deepSleep;\n if (deepSleep.enabled === false && deepSleep.enabledExplicitlySet === true) {\n throw new Error(\"memory governance is disabled by dreams.phases.deepSleep.enabled=false\");\n }\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const mode = request.mode === \"apply\" ? \"apply\" : \"shadow\";\n const boundedBatchSize =\n typeof request.batchSize === \"number\" && Number.isFinite(request.batchSize)\n ? Math.max(1, Math.floor(request.batchSize))\n : undefined;\n const result = await runMemoryGovernance({\n memoryDir: storage.dir,\n mode,\n recentDays:\n typeof request.recentDays === \"number\" && Number.isFinite(request.recentDays)\n ? Math.max(1, Math.floor(request.recentDays))\n : undefined,\n maxMemories:\n typeof request.maxMemories === \"number\" && Number.isFinite(request.maxMemories)\n ? Math.max(1, Math.floor(request.maxMemories))\n : undefined,\n batchSize: boundedBatchSize,\n });\n if (mode === \"apply\") {\n try {\n await this.orchestrator.processEntitySynthesisQueue(\n resolvedNamespace,\n Math.min(boundedBatchSize ?? 5, 5),\n );\n } catch (error) {\n log.debug(`governanceRun: entity synthesis refresh failed after governance apply: ${error}`);\n }\n }\n\n return {\n namespace: resolvedNamespace,\n runId: result.runId,\n traceId: result.traceId,\n mode: result.mode,\n reviewQueueCount: result.reviewQueue.length,\n proposedActionCount: result.proposedActions.length,\n appliedActionCount: result.appliedActions.length,\n summaryPath: result.summaryPath,\n reportPath: result.reportPath,\n };\n }\n\n async procedureMiningRun(\n request: {\n namespace?: string;\n authenticatedPrincipal?: string;\n },\n principal?: string,\n ): Promise<{\n namespace: string;\n clustersProcessed: number;\n proceduresWritten: number;\n skippedReason?: string;\n }> {\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const result = await runProcedureMining({\n memoryDir: storage.dir,\n storage,\n config: this.orchestrator.config,\n });\n return {\n namespace: resolvedNamespace,\n clustersProcessed: result.clustersProcessed,\n proceduresWritten: result.proceduresWritten,\n skippedReason: result.skippedReason,\n };\n }\n\n async liveConnectorsRun(\n request: {\n authenticatedPrincipal?: string;\n force?: boolean;\n } = {},\n principal?: string,\n ): Promise<LiveConnectorsRunSummary> {\n this.resolveWritableNamespace(\n undefined,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n return this.orchestrator.runLiveConnectors({\n force: request.force === true,\n });\n }\n\n /**\n * Run the pattern-reinforcement maintenance job (issue #687 PR 2/4).\n *\n * Cluster duplicate non-procedural memories and reinforce the\n * canonical (most-recent) member. Gated on\n * `patternReinforcementEnabled` — when disabled, returns\n * `{ ran: false, skippedReason: \"disabled\" }` so the cron payload\n * surface in CI logs cleanly.\n *\n * Resolves the namespace via the same writable path used by\n * `procedureMiningRun` so cross-tenant writes are impossible\n * (CLAUDE.md rule 42).\n *\n * Delegates the run to `orchestrator.runPatternReinforcement` so\n * the cadence floor (`patternReinforcementCadenceMs`) is enforced\n * uniformly across cron + MCP paths (PR #730 review feedback,\n * Codex P2). Accepts `force: true` for ad-hoc operator runs that\n * must bypass the cadence floor — mirrors the pattern used by\n * other maintenance MCP tools.\n */\n async patternReinforcementRun(\n request: {\n namespace?: string;\n authenticatedPrincipal?: string;\n force?: boolean;\n } = {},\n principal?: string,\n ): Promise<{\n namespace: string;\n ran: boolean;\n skippedReason?: \"disabled\" | \"cadence\";\n clustersFound: number;\n canonicalsUpdated: number;\n duplicatesSuperseded: number;\n result?: PatternReinforcementResult;\n }> {\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal ?? principal,\n );\n const outcome = await this.orchestrator.runPatternReinforcement({\n namespace: resolvedNamespace,\n force: request.force === true,\n });\n if (!outcome.ran) {\n return {\n namespace: resolvedNamespace,\n ran: false,\n skippedReason: outcome.skippedReason,\n clustersFound: 0,\n canonicalsUpdated: 0,\n duplicatesSuperseded: 0,\n };\n }\n const result = outcome.result!;\n return {\n namespace: resolvedNamespace,\n ran: true,\n clustersFound: result.clustersFound,\n canonicalsUpdated: result.canonicalsUpdated,\n duplicatesSuperseded: result.duplicatesSuperseded,\n result,\n };\n }\n\n /**\n * Procedural memory stats (issue #567 PR 5/5). Read-only — resolves the\n * namespace via the same path used by `recallExplain` / `trustZoneStatus`\n * so cross-tenant reads are impossible (CLAUDE.md rule 42).\n */\n async procedureStats(\n request: { namespace?: string } = {},\n principal?: string,\n ): Promise<ProcedureStatsReport & { namespace: string }> {\n const resolvedNamespace = this.resolveReadableNamespace(\n request.namespace,\n principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const report = await computeProcedureStats({\n storage,\n config: this.orchestrator.config,\n });\n return { namespace: resolvedNamespace, ...report };\n }\n\n async memorySummarizeHourly(): Promise<{\n ok: true;\n message: string;\n }> {\n await this.orchestrator.summarizer.runHourly();\n return {\n ok: true,\n message: \"Hourly summarization completed. Check the summaries directory for results.\",\n };\n }\n\n async conversationIndexUpdate(\n request: {\n sessionKey?: string;\n hours?: number;\n embed?: boolean;\n } = {},\n ): Promise<{\n enabled: boolean;\n sessionKey?: string;\n sessions: number;\n chunks: number;\n skipped: number;\n skippedSessionKeys: string[];\n embeddedRuns: number;\n reason?: string;\n retryAfterMs?: number;\n }> {\n if (!this.orchestrator.config.conversationIndexEnabled) {\n return {\n enabled: false,\n sessions: 0,\n chunks: 0,\n skipped: 0,\n skippedSessionKeys: [],\n embeddedRuns: 0,\n reason: \"disabled\",\n };\n }\n\n const hours =\n typeof request.hours === \"number\" && Number.isFinite(request.hours)\n ? Math.max(1, Math.floor(request.hours))\n : 24;\n\n let sessionKey: string | undefined;\n if (request.sessionKey !== undefined) {\n if (typeof request.sessionKey !== \"string\" || request.sessionKey.trim().length === 0) {\n throw new EngramAccessInputError(\"sessionKey must be a non-empty string when provided\");\n }\n sessionKey = request.sessionKey.trim();\n }\n\n if (sessionKey) {\n const result = await this.orchestrator.updateConversationIndex(\n sessionKey,\n hours,\n { embed: request.embed },\n );\n return {\n enabled: true,\n sessionKey,\n sessions: 1,\n chunks: result.chunks,\n skipped: result.skipped ? 1 : 0,\n skippedSessionKeys: result.skipped ? [sessionKey] : [],\n embeddedRuns: result.embedded ? 1 : 0,\n reason: result.reason,\n retryAfterMs: result.retryAfterMs,\n };\n }\n\n const sessionKeys = await this.orchestrator.transcript.listSessionKeys();\n let chunks = 0;\n let skipped = 0;\n const skippedSessionKeys: string[] = [];\n let embeddedRuns = 0;\n\n for (const sessionKey of sessionKeys) {\n const result = await this.orchestrator.updateConversationIndex(\n sessionKey,\n hours,\n { embed: request.embed },\n );\n chunks += result.chunks;\n if (result.skipped) {\n skipped += 1;\n skippedSessionKeys.push(sessionKey);\n }\n if (result.embedded) {\n embeddedRuns += 1;\n }\n }\n\n return {\n enabled: true,\n sessions: sessionKeys.length,\n chunks,\n skipped,\n skippedSessionKeys,\n embeddedRuns,\n };\n }\n\n async profilingReport(\n request: AccessProfilingReportRequest = {},\n ): Promise<AccessProfilingReportResponse> {\n const profiler = this.orchestrator.profiler;\n if (!profiler.isEnabled) {\n return {\n enabled: false,\n reason: \"disabled\",\n message: \"Profiling is disabled. Set profilingEnabled: true in your plugin config to enable.\",\n };\n }\n\n const format = request.format ?? \"ascii\";\n if (format !== \"ascii\" && format !== \"json\") {\n throw new EngramAccessInputError(\"format must be one of: ascii, json\");\n }\n\n const limit = request.limit ?? 5;\n if (!Number.isInteger(limit) || limit < 1 || limit > 20) {\n throw new EngramAccessInputError(\"limit must be an integer between 1 and 20\");\n }\n\n const traces = profiler.getRecentTraces(limit);\n const stats = profiler.getStats();\n const bottleneck = profiler.identifyBottleneck();\n\n if (format === \"json\") {\n return {\n enabled: true,\n format,\n traces,\n stats,\n bottleneck,\n };\n }\n\n const lines: string[] = [];\n lines.push(\"Engram Profiling Report\");\n lines.push(\"=\".repeat(60));\n lines.push(\"\");\n\n type BucketEntry = { count: number; avgMs: number; p50Ms: number; p95Ms: number; maxMs: number };\n const allBuckets: Array<[string, Record<string, BucketEntry>]> = [\n [\"byKind\", stats.byKind],\n [\"bySpan\", stats.bySpan],\n ];\n const hasStats = allBuckets.some(([, entries]) => Object.keys(entries).length > 0);\n if (hasStats) {\n lines.push(\"Aggregate Stats (all retained traces):\");\n for (const [bucket, entries] of allBuckets) {\n for (const [key, summary] of Object.entries(entries)) {\n lines.push(\n ` ${bucket}/${key}: avg=${summary.avgMs}ms p50=${summary.p50Ms}ms p95=${summary.p95Ms}ms max=${summary.maxMs}ms (n=${summary.count})`,\n );\n }\n }\n lines.push(\"\");\n }\n\n if (bottleneck) {\n lines.push(`Bottleneck: ${bottleneck}`);\n lines.push(\"\");\n }\n\n if (traces.length === 0) {\n lines.push(\"No traces recorded yet. Trigger a recall or extraction to see timing data.\");\n } else {\n for (const trace of traces) {\n lines.push(formatProfileTraceAscii(trace));\n lines.push(\"\");\n }\n }\n\n return {\n enabled: true,\n format,\n report: lines.join(\"\\n\"),\n };\n }\n\n async trustZoneStatus(namespace?: string, principal?: string): Promise<EngramAccessTrustZoneStatusResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n return {\n namespace: resolvedNamespace,\n status: await getTrustZoneStoreStatus({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n enabled: this.orchestrator.config.trustZonesEnabled === true,\n promotionEnabled: this.orchestrator.config.quarantinePromotionEnabled === true,\n poisoningDefenseEnabled: this.orchestrator.config.memoryPoisoningDefenseEnabled === true,\n }),\n };\n }\n\n async trustZoneBrowse(\n request: EngramAccessTrustZoneBrowseRequest,\n principal?: string,\n ): Promise<EngramAccessTrustZoneBrowseResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(request.namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const result = await listTrustZoneRecords({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n query: request.query,\n zone: request.zone,\n kind: request.kind,\n sourceClass: request.sourceClass,\n limit: request.limit,\n offset: request.offset,\n });\n return {\n namespace: resolvedNamespace,\n total: result.total,\n count: result.count,\n limit: result.limit,\n offset: result.offset,\n records: result.records.map((entry) =>\n summarizeTrustZoneRecord(\n entry.record,\n entry.filePath,\n result.allRecords,\n this.orchestrator.config.memoryPoisoningDefenseEnabled === true,\n this.orchestrator.config.trustZonesEnabled === true,\n this.orchestrator.config.quarantinePromotionEnabled === true,\n )),\n };\n }\n\n async trustZonePromote(\n request: EngramAccessTrustZonePromoteRequest,\n ): Promise<EngramAccessTrustZonePromoteResponse> {\n if (!isTrustZoneName(request.targetZone)) {\n throw new EngramAccessInputError(`unsupported trust-zone target: ${String(request.targetZone)}`);\n }\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n let result: TrustZonePromotionResult;\n try {\n result = await promoteTrustZoneRecord({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n enabled: this.orchestrator.config.trustZonesEnabled === true,\n promotionEnabled: this.orchestrator.config.quarantinePromotionEnabled === true,\n poisoningDefenseEnabled: this.orchestrator.config.memoryPoisoningDefenseEnabled === true,\n sourceRecordId: request.recordId,\n targetZone: request.targetZone,\n recordedAt: request.recordedAt ?? new Date().toISOString(),\n promotionReason: request.promotionReason,\n summary: request.summary,\n dryRun: request.dryRun === true,\n });\n } catch (error) {\n throw normalizeTrustZoneInputError(error) ?? error;\n }\n return {\n namespace: resolvedNamespace,\n ...result,\n dryRun: request.dryRun === true,\n };\n }\n\n async trustZoneDemoSeed(\n request: EngramAccessTrustZoneDemoSeedRequest,\n ): Promise<EngramAccessTrustZoneDemoSeedResponse> {\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n let result: TrustZoneDemoSeedResult;\n try {\n result = await seedTrustZoneDemoDataset({\n memoryDir: storage.dir,\n trustZoneStoreDir: this.orchestrator.config.trustZoneStoreDir,\n enabled: this.orchestrator.config.trustZonesEnabled === true,\n scenario: request.scenario,\n recordedAt: request.recordedAt,\n dryRun: request.dryRun === true,\n });\n } catch (error) {\n throw normalizeTrustZoneInputError(error) ?? error;\n }\n return {\n namespace: resolvedNamespace,\n ...result,\n };\n }\n\n async reviewDisposition(\n request: EngramAccessReviewDispositionRequest,\n ): Promise<EngramAccessReviewDispositionResponse> {\n const memoryId = request.memoryId.trim();\n const reasonCode = request.reasonCode.trim();\n if (memoryId.length === 0) {\n throw new EngramAccessInputError(\"memoryId is required\");\n }\n if (reasonCode.length === 0) {\n throw new EngramAccessInputError(\"reasonCode is required\");\n }\n\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n undefined,\n request.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const memory = await storage.getMemoryById(memoryId);\n if (!memory) {\n throw new EngramAccessInputError(`memory not found: ${memoryId}`);\n }\n\n const previousStatus = memory.frontmatter.status ?? \"active\";\n const updatedAt = new Date().toISOString();\n const lifecycle = {\n actor: \"admin-console.review-disposition\",\n reasonCode,\n ruleVersion: \"memory-governance.v1\",\n };\n\n if (request.status === \"archived\") {\n const archivedPath = await storage.archiveMemory(memory, {\n at: new Date(updatedAt),\n ...lifecycle,\n });\n if (!archivedPath) {\n throw new Error(`failed to archive memory disposition: ${memoryId}`);\n }\n return {\n ok: true,\n namespace: resolvedNamespace,\n memoryId,\n status: \"archived\",\n previousStatus,\n currentPath: archivedPath,\n };\n }\n\n const updated = await storage.writeMemoryFrontmatter(memory, {\n status: request.status,\n updated: updatedAt,\n }, lifecycle);\n if (!updated) {\n throw new Error(`failed to update memory disposition: ${memoryId}`);\n }\n return {\n ok: true,\n namespace: resolvedNamespace,\n memoryId,\n status: request.status,\n previousStatus,\n currentPath: memory.path,\n };\n }\n\n private serializeMemory(memory: MemoryFile): EngramAccessMemoryRecord {\n return {\n id: memory.frontmatter.id,\n path: memory.path,\n category: memory.frontmatter.category,\n status: memory.frontmatter.status,\n created: memory.frontmatter.created,\n updated: memory.frontmatter.updated,\n content: memory.content,\n frontmatter: memory.frontmatter,\n };\n }\n\n private serializeMemorySummary(\n memory: MemoryFile,\n baseDir: string,\n disclosure?: RecallDisclosure,\n rawExcerpts?: EngramAccessMemorySummary[\"rawExcerpts\"],\n ): EngramAccessMemorySummary {\n return shapeMemorySummary(memory, baseDir, disclosure, rawExcerpts);\n }\n\n async observe(request: EngramAccessObserveRequest): Promise<EngramAccessObserveResponse> {\n if (!request.sessionKey || typeof request.sessionKey !== \"string\" || request.sessionKey.trim().length === 0) {\n throw new EngramAccessInputError(\"sessionKey is required and must be a non-empty string\");\n }\n if (!Array.isArray(request.messages) || request.messages.length === 0) {\n throw new EngramAccessInputError(\"messages is required and must be a non-empty array\");\n }\n for (const msg of request.messages) {\n if (!msg || typeof msg !== \"object\" || typeof msg.role !== \"string\" || typeof msg.content !== \"string\") {\n throw new EngramAccessInputError(\"each message must have a string 'role' and 'content'\");\n }\n if (msg.role !== \"user\" && msg.role !== \"assistant\") {\n throw new EngramAccessInputError(`invalid message role: ${msg.role} (expected 'user' or 'assistant')`);\n }\n }\n\n // Validate namespace authorization BEFORE attaching coding context so\n // a failed auth check doesn't leave orphaned context on the session\n // (Codex review P2).\n const namespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.authenticatedPrincipal,\n );\n\n // Auto-resolve coding context from cwd/projectTag so observe writes\n // route to the correct project namespace (rule 42: same namespace layer\n // as recall).\n await this.maybeAttachCodingContext(request.sessionKey, {\n cwd: request.cwd,\n projectTag: request.projectTag,\n });\n\n // Prefix sessionKey with namespace for LCM archival so turns are namespace-scoped.\n // This ensures multi-tenant isolation in the LCM archive.\n const lcmSessionKey = namespace !== this.orchestrator.config.defaultNamespace\n ? `${namespace}:${request.sessionKey}`\n : request.sessionKey;\n\n // lcmArchived in the response means \"LCM archival was queued\" (not\n // \"completed\"), matching extractionQueued semantics. Both run async.\n let lcmArchived = false;\n if (this.orchestrator.lcmEngine && this.orchestrator.lcmEngine.enabled) {\n // Fire-and-forget: LCM archival writes to SQLite and builds summary\n // DAGs, which can take tens of seconds for large sessions. Don't\n // block the HTTP response — the caller only needs acknowledgment.\n try {\n this.orchestrator.lcmEngine.enqueueObserveMessages(lcmSessionKey, request.messages);\n lcmArchived = true;\n } catch (err) {\n log.error(`access-observe LCM enqueue failed: ${err}`);\n }\n }\n\n let extractionQueued = false;\n if (request.skipExtraction !== true) {\n const turns = request.messages.map((m) => ({\n source: \"openclaw\" as const,\n sessionKey: lcmSessionKey,\n role: m.role,\n content: m.content,\n timestamp: new Date().toISOString(),\n }));\n // Fire-and-forget: queue extraction in the background so the HTTP\n // response returns immediately. LCM archival (above) is also\n // enqueue-only; extraction involves LLM calls that can take\n // minutes under load and should not block the caller.\n //\n // Backpressure: the orchestrator's own extraction queue already\n // limits concurrency (one extraction at a time per session via\n // queueBufferedExtraction). Fire-and-forget here just decouples\n // the HTTP response from the queue drain.\n try {\n const extractionPromise = this.orchestrator.ingestReplayBatch(turns);\n extractionPromise.catch((err) => {\n log.error(`access-observe background extraction failed: ${err}`);\n });\n extractionQueued = true;\n } catch (err) {\n // Synchronous enqueue failure (e.g. orchestrator disposed)\n log.error(`access-observe extraction enqueue failed: ${err}`);\n }\n }\n\n log.info(\n `access-observe namespace=${namespace} sessionKey=${request.sessionKey} messages=${request.messages.length} lcm=${lcmArchived} extraction=${extractionQueued}`,\n );\n\n return {\n accepted: request.messages.length,\n sessionKey: request.sessionKey,\n namespace,\n lcmArchived,\n extractionQueued,\n };\n }\n\n async lcmSearch(request: EngramAccessLcmSearchRequest): Promise<EngramAccessLcmSearchResponse> {\n if (!request.query || typeof request.query !== \"string\" || request.query.trim().length === 0) {\n throw new EngramAccessInputError(\"query is required and must be a non-empty string\");\n }\n\n const principal = this.resolveWritePrincipal(request.sessionKey, request.authenticatedPrincipal);\n const namespace = this.resolveReadableNamespace(request.namespace, principal);\n\n if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {\n return {\n query: request.query,\n namespace,\n results: [],\n count: 0,\n lcmEnabled: false,\n };\n }\n\n const limit = Math.max(1, Math.min(request.limit ?? 10, 100));\n const lcmSessionKey = request.sessionKey && namespace !== this.orchestrator.config.defaultNamespace\n ? `${namespace}:${request.sessionKey}`\n : request.sessionKey;\n const rawResults = await this.orchestrator.lcmEngine.searchContextFull(\n request.query,\n limit,\n lcmSessionKey,\n );\n\n const results = rawResults.map((r: { session_id: string; content: string; turn_index: number }) => ({\n sessionId: r.session_id,\n content: r.content,\n turnIndex: r.turn_index,\n }));\n\n return {\n query: request.query,\n namespace,\n results,\n count: results.length,\n lcmEnabled: true,\n };\n }\n\n // ── Parity tools (match OpenClaw plugin feature set) ──────────────────\n\n // ── Continuity / Identity ──────────────────────────────────────────────\n\n async continuityAuditGenerate(request: {\n period?: \"weekly\" | \"monthly\";\n key?: string;\n }): Promise<{ enabled: boolean; reason?: string; period?: string; key?: string; reportPath?: string }> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled. Enable `identityContinuityEnabled: true`.\" };\n }\n if (!this.orchestrator.config.continuityAuditEnabled) {\n return { enabled: false, reason: \"Continuity audits are disabled. Enable `continuityAuditEnabled: true`.\" };\n }\n if (!this.orchestrator.compounding) {\n return { enabled: false, reason: \"Compounding engine is disabled. Enable `compoundingEnabled: true`.\" };\n }\n const period = request.period === \"monthly\" ? \"monthly\" : \"weekly\";\n const key = request.key?.trim() || undefined;\n const audit = await this.orchestrator.compounding.synthesizeContinuityAudit({ period, key });\n return { enabled: true, period: audit.period, key: audit.key, reportPath: audit.reportPath };\n }\n\n async continuityIncidentOpen(request: {\n symptom: string;\n namespace?: string;\n principal?: string;\n triggerWindow?: string;\n suspectedCause?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled. Enable `identityContinuityEnabled: true`.\" };\n }\n if (!this.orchestrator.config.continuityIncidentLoggingEnabled) {\n return { enabled: false, reason: \"Continuity incident logging is disabled. Enable `continuityIncidentLoggingEnabled: true`.\" };\n }\n const symptom = request.symptom?.trim();\n if (!symptom) throw new EngramAccessInputError(\"symptom is required\");\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const created = await storage.appendContinuityIncident({\n symptom,\n triggerWindow: request.triggerWindow?.trim() || undefined,\n suspectedCause: request.suspectedCause?.trim() || undefined,\n });\n return { created: true, incident: created };\n }\n\n async continuityIncidentClose(request: {\n id: string;\n namespace?: string;\n principal?: string;\n fixApplied: string;\n verificationResult: string;\n preventiveRule?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n if (!this.orchestrator.config.continuityIncidentLoggingEnabled) {\n return { enabled: false, reason: \"Continuity incident logging is disabled.\" };\n }\n const id = request.id?.trim();\n if (!id) throw new EngramAccessInputError(\"id is required\");\n const fixApplied = request.fixApplied?.trim();\n if (!fixApplied) throw new EngramAccessInputError(\"fixApplied is required\");\n const verificationResult = request.verificationResult?.trim();\n if (!verificationResult) throw new EngramAccessInputError(\"verificationResult is required\");\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const closed = await storage.closeContinuityIncident(id, {\n fixApplied,\n verificationResult,\n preventiveRule: request.preventiveRule?.trim() || undefined,\n });\n if (!closed) return { closed: false, reason: `Incident not found: ${id}` };\n return { closed: true, incident: closed };\n }\n\n async continuityIncidentList(request: {\n state?: \"open\" | \"closed\" | \"all\";\n namespace?: string;\n principal?: string;\n limit?: number;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const state = request.state === \"closed\" || request.state === \"all\" ? request.state : \"open\";\n const limit = Math.max(1, Math.min(200, Math.floor(request.limit ?? 25)));\n const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const incidents = await storage.readContinuityIncidents(limit, state);\n return { state, incidents, count: incidents.length };\n }\n\n async continuityLoopAddOrUpdate(request: {\n id: string;\n cadence: \"daily\" | \"weekly\" | \"monthly\" | \"quarterly\";\n purpose: string;\n status: \"active\" | \"paused\" | \"retired\";\n killCondition: string;\n namespace?: string;\n principal?: string;\n lastReviewed?: string;\n notes?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const loop = await storage.upsertIdentityImprovementLoop({\n id: request.id?.trim() || \"\",\n cadence: request.cadence,\n purpose: request.purpose?.trim() || \"\",\n status: request.status,\n killCondition: request.killCondition?.trim() || \"\",\n lastReviewed: request.lastReviewed?.trim() || undefined,\n notes: request.notes?.trim() || undefined,\n });\n return { saved: true, loop };\n }\n\n async continuityLoopReview(request: {\n id: string;\n namespace?: string;\n principal?: string;\n status?: \"active\" | \"paused\" | \"retired\";\n notes?: string;\n reviewedAt?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const id = request.id?.trim();\n if (!id) throw new EngramAccessInputError(\"id is required\");\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const reviewed = await storage.reviewIdentityImprovementLoop(id, {\n status: request.status,\n notes: request.notes?.trim() || undefined,\n reviewedAt: request.reviewedAt?.trim() || undefined,\n });\n if (!reviewed) return { reviewed: false, reason: `Continuity loop not found: ${id}` };\n return { reviewed: true, loop: reviewed };\n }\n\n async identityAnchorGet(request: {\n namespace?: string;\n principal?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const anchor = await storage.readIdentityAnchor();\n if (!anchor) return { found: false, message: \"No identity anchor found yet. Use identity_anchor_update to create one.\" };\n return { found: true, anchor };\n }\n\n /**\n * @deprecated since issue #679 PR 5/5 — the identity-anchor model is\n * superseded by the peer registry. Use `peerSet({ id: \"self\", ... })` or\n * `remnic peer set self` to update the self peer's identity kernel, and\n * `remnic peer migrate` to seed `peers/self/identity.md` from existing\n * legacy anchor data. This method continues to function for backward\n * compatibility but will be removed in a future major version.\n */\n async identityAnchorUpdate(request: {\n namespace?: string;\n principal?: string;\n identityTraits?: string;\n communicationPreferences?: string;\n operatingPrinciples?: string;\n continuityNotes?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.config.identityContinuityEnabled) {\n return { enabled: false, reason: \"Identity continuity is disabled.\" };\n }\n\n const updates: Record<string, string | undefined> = {\n \"Identity Traits\": request.identityTraits?.trim() || undefined,\n \"Communication Preferences\": request.communicationPreferences?.trim() || undefined,\n \"Operating Principles\": request.operatingPrinciples?.trim() || undefined,\n \"Continuity Notes\": request.continuityNotes?.trim() || undefined,\n };\n const hasUpdate = Object.values(updates).some((v) => typeof v === \"string\" && v.length > 0);\n if (!hasUpdate) throw new EngramAccessInputError(\"At least one section field is required.\");\n\n const resolvedNs = this.resolveWritableNamespace(request.namespace, undefined, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const existing = await storage.readIdentityAnchor();\n\n // Merge sections conservatively (append, don't overwrite)\n const merged = this.mergeIdentityAnchorSections(existing, updates);\n await storage.writeIdentityAnchor(merged);\n\n const updatedSections = Object.entries(updates)\n .filter(([, v]) => typeof v === \"string\" && v.length > 0)\n .map(([name]) => name);\n return { updated: true, sections: updatedSections, anchor: merged };\n }\n\n async memoryIdentity(request: {\n namespace?: string;\n principal?: string;\n }): Promise<unknown> {\n const resolvedNs = this.resolveReadableNamespace(request.namespace, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const identity = await storage.readIdentityReflections();\n if (!identity) return { found: false, message: \"No identity reflections found.\" };\n return { found: true, identity };\n }\n\n // ── Work Layer ──────────────────────────────────────────────────────────\n\n async workTask(request: {\n action: \"create\" | \"get\" | \"list\" | \"update\" | \"transition\" | \"delete\";\n id?: string;\n title?: string;\n description?: string;\n status?: string;\n priority?: string;\n owner?: string;\n assignee?: string;\n projectId?: string;\n tags?: string[];\n dueAt?: string;\n }): Promise<unknown> {\n const STATUSES = new Set([\"todo\", \"in_progress\", \"blocked\", \"done\", \"cancelled\"]);\n const PRIORITIES = new Set([\"low\", \"medium\", \"high\"]);\n const asStatus = (v?: string) => (v && STATUSES.has(v) ? v as \"todo\" | \"in_progress\" | \"blocked\" | \"done\" | \"cancelled\" : undefined);\n const asPriority = (v?: string) => (v && PRIORITIES.has(v) ? v as \"low\" | \"medium\" | \"high\" : undefined);\n\n const storage = new WorkStorage(this.orchestrator.config.memoryDir);\n await storage.ensureDirectories();\n const action = request.action;\n\n if (action === \"create\") {\n if (!request.title?.trim()) throw new EngramAccessInputError(\"title is required for create\");\n const task = await storage.createTask({\n title: request.title,\n description: request.description,\n status: asStatus(request.status),\n priority: asPriority(request.priority),\n owner: request.owner?.trim() || undefined,\n assignee: request.assignee?.trim() || undefined,\n projectId: request.projectId?.trim() || undefined,\n tags: request.tags,\n dueAt: request.dueAt?.trim() || undefined,\n });\n return { action, task };\n }\n if (action === \"get\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for get\");\n return { action, task: await storage.getTask(request.id) };\n }\n if (action === \"list\") {\n const tasks = await storage.listTasks({\n status: asStatus(request.status),\n owner: request.owner?.trim() || undefined,\n assignee: request.assignee?.trim() || undefined,\n projectId: request.projectId?.trim() || undefined,\n });\n return { action, count: tasks.length, tasks };\n }\n if (action === \"update\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for update\");\n const patch: Record<string, unknown> = {};\n if (request.title !== undefined) patch.title = request.title;\n if (request.description !== undefined) patch.description = request.description;\n const st = asStatus(request.status); if (st) patch.status = st;\n const pr = asPriority(request.priority); if (pr) patch.priority = pr;\n if (request.owner !== undefined) patch.owner = request.owner || null;\n if (request.assignee !== undefined) patch.assignee = request.assignee || null;\n if (request.projectId !== undefined) patch.projectId = request.projectId || null;\n if (request.tags) patch.tags = request.tags;\n if (request.dueAt !== undefined) patch.dueAt = request.dueAt || null;\n return { action, task: await storage.updateTask(request.id, patch as any) };\n }\n if (action === \"transition\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for transition\");\n const st = asStatus(request.status);\n if (!st) throw new EngramAccessInputError(\"valid status is required for transition\");\n return { action, task: await storage.transitionTask(request.id, st) };\n }\n if (action === \"delete\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for delete\");\n return { action, deleted: await storage.deleteTask(request.id) };\n }\n throw new EngramAccessInputError(`Unsupported work_task action: ${action}`);\n }\n\n async workProject(request: {\n action: \"create\" | \"get\" | \"list\" | \"update\" | \"delete\" | \"link_task\";\n id?: string;\n name?: string;\n description?: string;\n status?: string;\n owner?: string;\n tags?: string[];\n taskId?: string;\n projectId?: string;\n }): Promise<unknown> {\n const STATUSES = new Set([\"active\", \"on_hold\", \"completed\", \"archived\"]);\n const asStatus = (v?: string) => (v && STATUSES.has(v) ? v as \"active\" | \"on_hold\" | \"completed\" | \"archived\" : undefined);\n\n const storage = new WorkStorage(this.orchestrator.config.memoryDir);\n await storage.ensureDirectories();\n const action = request.action;\n\n if (action === \"create\") {\n if (!request.name?.trim()) throw new EngramAccessInputError(\"name is required for create\");\n const project = await storage.createProject({\n name: request.name,\n description: request.description,\n status: asStatus(request.status),\n owner: request.owner?.trim() || undefined,\n tags: request.tags,\n });\n return { action, project };\n }\n if (action === \"get\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for get\");\n return { action, project: await storage.getProject(request.id) };\n }\n if (action === \"list\") {\n const projects = await storage.listProjects();\n return { action, count: projects.length, projects };\n }\n if (action === \"update\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for update\");\n const patch: Record<string, unknown> = {};\n if (request.name !== undefined) patch.name = request.name;\n if (request.description !== undefined) patch.description = request.description;\n const st = asStatus(request.status); if (st) patch.status = st;\n if (request.owner !== undefined) patch.owner = request.owner || null;\n if (request.tags) patch.tags = request.tags;\n return { action, project: await storage.updateProject(request.id, patch as any) };\n }\n if (action === \"delete\") {\n if (!request.id?.trim()) throw new EngramAccessInputError(\"id is required for delete\");\n return { action, deleted: await storage.deleteProject(request.id) };\n }\n if (action === \"link_task\") {\n if (!request.taskId?.trim() || !request.projectId?.trim()) {\n throw new EngramAccessInputError(\"taskId and projectId are required for link_task\");\n }\n return { action, linked: await storage.linkTaskToProject(request.taskId, request.projectId) };\n }\n throw new EngramAccessInputError(`Unsupported work_project action: ${action}`);\n }\n\n async workBoard(request: {\n action: \"export_markdown\" | \"export_snapshot\" | \"import_snapshot\";\n projectId?: string;\n snapshotJson?: string;\n linkToMemory?: boolean;\n }): Promise<unknown> {\n const memoryDir = this.orchestrator.config.memoryDir;\n await new WorkStorage(memoryDir).ensureDirectories();\n const action = request.action;\n const projectId = request.projectId?.trim() || undefined;\n\n if (action === \"export_markdown\") {\n const markdown = await exportWorkBoardMarkdown({ memoryDir, projectId });\n return { action, markdown: wrapWorkLayerContext(markdown, { linkToMemory: request.linkToMemory === true }) };\n }\n if (action === \"export_snapshot\") {\n const snapshot = await exportWorkBoardSnapshot({ memoryDir, projectId });\n return { action, snapshot };\n }\n if (action === \"import_snapshot\") {\n if (!request.snapshotJson?.trim()) throw new EngramAccessInputError(\"snapshotJson is required for import_snapshot\");\n const snapshot = JSON.parse(request.snapshotJson);\n const result = await importWorkBoardSnapshot({ memoryDir, snapshot, projectId });\n return { action, result };\n }\n throw new EngramAccessInputError(`Unsupported work_board action: ${action}`);\n }\n\n // ── Shared Context / Compounding ────────────────────────────────────────\n\n async sharedContextWriteOutput(request: {\n agentId: string;\n title: string;\n content: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n const fp = await this.orchestrator.sharedContext.writeAgentOutput({\n agentId: request.agentId,\n title: request.title,\n content: request.content,\n });\n return { written: true, path: fp };\n }\n\n async sharedFeedbackRecord(request: {\n agent: string;\n decision: \"approved\" | \"approved_with_feedback\" | \"rejected\";\n reason: string;\n date?: string;\n learning?: string;\n outcome?: string;\n severity?: \"low\" | \"medium\" | \"high\";\n confidence?: number;\n workflow?: string;\n tags?: string[];\n evidenceWindowStart?: string;\n evidenceWindowEnd?: string;\n refs?: string[];\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n await this.orchestrator.sharedContext.appendFeedback({\n agent: request.agent,\n decision: request.decision,\n reason: request.reason,\n date: request.date?.trim() || new Date().toISOString(),\n learning: request.learning,\n outcome: request.outcome,\n severity: request.severity,\n confidence: request.confidence,\n workflow: request.workflow,\n tags: request.tags,\n evidenceWindowStart: request.evidenceWindowStart,\n evidenceWindowEnd: request.evidenceWindowEnd,\n refs: request.refs,\n });\n return { recorded: true };\n }\n\n async sharedPrioritiesAppend(request: {\n agentId: string;\n text: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n await this.orchestrator.sharedContext.appendPrioritiesInbox({\n agentId: request.agentId,\n text: request.text,\n });\n return { appended: true };\n }\n\n async sharedContextCrossSignalsRun(request: {\n date?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n const result = await this.orchestrator.sharedContext.synthesizeCrossSignals({ date: request.date });\n return {\n crossSignalsMarkdownPath: result.crossSignalsMarkdownPath,\n crossSignalsPath: result.crossSignalsPath,\n sourceCount: result.report.sourceCount,\n feedbackCount: result.report.feedbackCount,\n overlapCount: result.overlapCount,\n };\n }\n\n async sharedContextCurateDaily(request: {\n date?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.sharedContext) {\n return { enabled: false, reason: \"Shared context is disabled. Enable `sharedContextEnabled: true`.\" };\n }\n const result = await this.orchestrator.sharedContext.curateDaily({ date: request.date });\n return {\n roundtablePath: result.roundtablePath,\n crossSignalsMarkdownPath: result.crossSignalsMarkdownPath,\n crossSignalsPath: result.crossSignalsPath,\n overlapCount: result.overlapCount,\n };\n }\n\n async compoundingWeeklySynthesize(request: {\n weekId?: string;\n }): Promise<unknown> {\n if (!this.orchestrator.compounding) {\n return { enabled: false, reason: \"Compounding engine is disabled. Enable `compoundingEnabled: true`.\" };\n }\n const res = await this.orchestrator.compounding.synthesizeWeekly({ weekId: request.weekId });\n return {\n weekId: res.weekId,\n reportPath: res.reportPath,\n reportJsonPath: res.reportJsonPath,\n rubricsPath: res.rubricsPath,\n rubricsIndexPath: res.rubricsIndexPath,\n mistakesCount: res.mistakesCount,\n promotionCandidateCount: res.promotionCandidateCount,\n };\n }\n\n async compoundingPromoteCandidate(request: {\n weekId: string;\n candidateId: string;\n dryRun?: boolean;\n }): Promise<unknown> {\n if (!this.orchestrator.compounding) {\n return { enabled: false, reason: \"Compounding engine is disabled. Enable `compoundingEnabled: true`.\" };\n }\n return await this.orchestrator.compounding.promoteCandidate({\n weekId: request.weekId,\n candidateId: request.candidateId,\n dryRun: request.dryRun,\n });\n }\n\n // ── Compression Guidelines ────────────────────────────────────────────\n\n async compressionGuidelinesOptimize(request: {\n dryRun?: boolean;\n eventLimit?: number;\n }): Promise<unknown> {\n if (!this.orchestrator.config.compressionGuidelineLearningEnabled) {\n return { enabled: false, reason: \"Compression guideline learning is disabled. Enable `compressionGuidelineLearningEnabled: true`.\" };\n }\n return await this.orchestrator.optimizeCompressionGuidelines({\n dryRun: request.dryRun,\n eventLimit: request.eventLimit,\n });\n }\n\n async compressionGuidelinesActivate(request: {\n expectedContentHash?: string;\n expectedGuidelineVersion?: number;\n }): Promise<unknown> {\n if (!this.orchestrator.config.compressionGuidelineLearningEnabled) {\n return { enabled: false, reason: \"Compression guideline learning is disabled.\" };\n }\n return await this.orchestrator.activateCompressionGuidelineDraft({\n expectedContentHash: request.expectedContentHash,\n expectedGuidelineVersion: request.expectedGuidelineVersion,\n });\n }\n\n /** Conservative identity anchor section merge (matches tools.ts mergeIdentityAnchor logic). */\n private mergeIdentityAnchorSections(\n existingRaw: string | null,\n updates: Record<string, string | undefined>,\n ): string {\n const TITLE = \"# Identity Continuity Anchor\";\n const SECTION_ORDER = [\"Identity Traits\", \"Communication Preferences\", \"Operating Principles\", \"Continuity Notes\"];\n\n const lines = (existingRaw ?? \"\").replace(/\\r/g, \"\").split(\"\\n\");\n const headerLines: string[] = [];\n const sectionContent = new Map<string, string[]>();\n const order: string[] = [];\n let current: string | null = null;\n for (const line of lines) {\n const m = line.match(/^##\\s+(.+?)\\s*$/);\n if (m) { current = m[1].trim(); if (!sectionContent.has(current)) { sectionContent.set(current, []); order.push(current); } continue; }\n if (!current) { headerLines.push(line); } else { sectionContent.get(current)?.push(line); }\n }\n const sections = new Map<string, string>();\n for (const [name, cLines] of sectionContent) sections.set(name, cLines.join(\"\\n\").trim());\n\n const header = headerLines.join(\"\\n\").trim() || TITLE;\n for (const sectionName of SECTION_ORDER) {\n const prev = sections.get(sectionName)?.trim();\n const next = updates[sectionName]?.trim();\n const existing = prev === \"- (empty)\" ? \"\" : prev;\n if (!next) { if (!sections.has(sectionName)) sections.set(sectionName, \"\"); continue; }\n if (!existing) { sections.set(sectionName, next); continue; }\n if (existing.includes(next)) continue;\n if (next.includes(existing)) { sections.set(sectionName, next); continue; }\n sections.set(sectionName, `${existing}\\n\\n${next}`);\n }\n\n const finalOrder = [...SECTION_ORDER.filter((s) => sections.has(s)), ...order.filter((s) => !SECTION_ORDER.includes(s) && sections.has(s))];\n const out: string[] = [header, \"\"];\n for (const name of finalOrder) {\n out.push(`## ${name}`, \"\");\n const body = sections.get(name)?.trim();\n if (body) out.push(body, \"\");\n else out.push(\"\");\n }\n return out.join(\"\\n\").replace(/\\n{3,}/g, \"\\n\\n\").trimEnd() + \"\\n\";\n }\n\n // ── Memory search & debug ─────────────────────────────────────────────\n\n async memorySearch(request: {\n query: string;\n namespace?: string;\n maxResults?: number;\n collection?: string;\n principal?: string;\n }): Promise<{ query: string; results: Array<{ path: string; score: number; snippet: string }>; count: number }> {\n const { query, namespace, maxResults, collection, principal } = request;\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const namespaceFilter = resolvedNs !== this.orchestrator.config.defaultNamespace ? resolvedNs : undefined;\n\n const results = collection === \"global\"\n ? (await this.orchestrator.qmd.searchGlobal(query, maxResults)).filter((r) =>\n namespaceFilter\n ? r.path.includes(`/namespaces/${namespaceFilter}/`) ||\n (!r.path.includes(\"/namespaces/\") && namespaceFilter === this.orchestrator.config.defaultNamespace)\n : true,\n )\n : await this.orchestrator.searchAcrossNamespaces({\n query,\n namespaces: namespaceFilter ? [namespaceFilter] : undefined,\n maxResults,\n mode: \"search\",\n });\n\n return {\n query,\n results: results.map((r) => ({\n path: r.path,\n score: r.score,\n snippet: (r.snippet ?? \"\").slice(0, 800),\n })),\n count: results.length,\n };\n }\n\n async memoryProfile(namespace?: string, principal?: string): Promise<Record<string, unknown>> {\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const profile = await storage.readProfile();\n return {\n profile: profile || \"No profile built yet. The profile builds automatically through conversations.\",\n };\n }\n\n async memoryEntitiesList(namespace?: string, principal?: string): Promise<{ entities: string[]; count: number }> {\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const entities = await storage.readEntities();\n return { entities, count: entities.length };\n }\n\n async memoryQuestions(namespace?: string, principal?: string): Promise<{ questions: Array<{ id: string; question: string; resolved: boolean }>; count: number }> {\n const resolvedNs = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const questions = await storage.readQuestions();\n return {\n questions: questions.map((q) => ({ id: q.id, question: q.question, resolved: q.resolved })),\n count: questions.length,\n };\n }\n\n async lastRecallSnapshot(sessionKey?: string): Promise<unknown> {\n const snapshot = sessionKey\n ? this.orchestrator.lastRecall.get(sessionKey)\n : this.orchestrator.lastRecall.getMostRecent();\n return snapshot ?? { message: \"No recall snapshot available\" };\n }\n\n async intentDebug(namespace?: string): Promise<unknown> {\n const snapshot = await this.orchestrator.getLastIntentSnapshot(namespace);\n return snapshot ?? { message: \"No intent debug snapshot available\" };\n }\n\n async qmdDebug(namespace?: string): Promise<unknown> {\n const snapshot = await this.orchestrator.getLastQmdRecallSnapshot(namespace);\n return snapshot ?? { message: \"No QMD debug snapshot available\" };\n }\n\n async graphExplainLastRecall(namespace?: string): Promise<unknown> {\n const explanation = await this.orchestrator.explainLastGraphRecall({ namespace });\n return { explanation };\n }\n\n /**\n * Read-only graph snapshot for the admin pane (issue #691 PR 2/5).\n *\n * Reads adjacency from the JSONL edge store written by `GraphIndex` and\n * resolves node metadata via the namespaced storage manager. Namespace\n * resolution mirrors the read-side path used by `recall` /\n * `procedureStats`, so multi-principal deployments can't leak edges from\n * a peer namespace (CLAUDE.md rule 42).\n */\n async graphSnapshot(\n request: GraphSnapshotRequest & { namespace?: string },\n authenticatedPrincipal?: string,\n ): Promise<GraphSnapshotResponse> {\n const namespace = this.resolveReadableNamespace(\n request.namespace,\n authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(namespace);\n const cfg = this.orchestrator.config;\n // Canonicalize the storage root once — through `realpath` so that any\n // symlink in the namespace root path itself is resolved before we\n // compare children against it. This is required because\n // `GraphEdge.from` / `to` are JSONL-parsed strings — a malformed edge\n // with an absolute path, a `..` segment, OR a symlink that resolves\n // to a file outside the namespace would otherwise read a memory file\n // from a peer namespace, leaking metadata across tenants\n // (codex P1 + follow-up on PR #734; CLAUDE.md rule 42).\n let namespaceRootReal: string;\n try {\n namespaceRootReal = await nodeFs.realpath(storage.dir);\n } catch {\n // If the namespace root itself doesn't exist on disk yet (fresh\n // install with no memories), fall back to the lexical resolve so\n // the snapshot can still return an empty result rather than\n // throwing. No symlink can resolve through a missing path, so\n // this fallback is safe — every candidate we see will fail the\n // realpath step below and surface as `null`.\n namespaceRootReal = nodePath.resolve(storage.dir);\n }\n const namespaceRootWithSep = namespaceRootReal.endsWith(nodePath.sep)\n ? namespaceRootReal\n : namespaceRootReal + nodePath.sep;\n const loadNode = async (relPath: string): Promise<GraphSnapshotNodeMetadata | null> => {\n // `GraphEdge.from` / `to` are storage-relative paths; resolve against\n // the namespaced storage root so the metadata read honors namespace\n // boundaries even when the same memory id exists in multiple\n // namespaces.\n //\n // Three-stage guard:\n // 1. Reject absolute paths up front — only relative endpoints are\n // ever produced by the writer, so anything else is malformed.\n // 2. Lexical containment check on the resolved path. This catches\n // `..` traversals before we touch the filesystem.\n // 3. `fs.realpath` containment check — resolves symlinks so an\n // in-namespace path that *points* at an out-of-namespace file\n // is still rejected. Without this step a symlinked endpoint\n // could leak a peer namespace's frontmatter.\n // Bad paths surface a length-only warning (never echo the offending\n // segments — those would themselves cross namespace boundaries\n // through the log surface) and fall through to a `null` metadata\n // result.\n if (nodePath.isAbsolute(relPath)) {\n log.warn(\n `graphSnapshot: rejected absolute edge endpoint (len=${relPath.length}) `\n + `outside namespace root`,\n );\n return null;\n }\n const candidate = nodePath.resolve(namespaceRootReal, relPath);\n if (candidate !== namespaceRootReal && !candidate.startsWith(namespaceRootWithSep)) {\n log.warn(\n `graphSnapshot: rejected traversing edge endpoint (len=${relPath.length}) `\n + `outside namespace root`,\n );\n return null;\n }\n let canonical: string;\n try {\n canonical = await nodeFs.realpath(candidate);\n } catch {\n // Missing file — `readMemoryByPath` will return null too. We\n // intentionally still call it so callers see a consistent\n // \"unknown\" result rather than special-casing missing edges.\n canonical = candidate;\n }\n if (canonical !== namespaceRootReal && !canonical.startsWith(namespaceRootWithSep)) {\n log.warn(\n `graphSnapshot: rejected symlinked edge endpoint (len=${relPath.length}) `\n + `that resolved outside namespace root`,\n );\n return null;\n }\n // Both `canonical` (realpath of candidate) and `namespaceRootReal`\n // (realpath of storage.dir) are fully resolved here, so the\n // containment check above is comparing apples-to-apples even when\n // storage.dir (= storage.baseDir) is itself a symlink to the real\n // directory. Pass `canonical` — not the pre-realpath `candidate` —\n // so the storage read also uses the stable real path.\n const memory = await storage.readMemoryByPath(canonical);\n if (!memory) return null;\n const fm = memory.frontmatter;\n return {\n category: fm.category ?? \"unknown\",\n label: fm.id ?? nodePath.basename(canonical, nodePath.extname(canonical)),\n updated: fm.updated,\n };\n };\n // Use the realpath-resolved namespace root for the edge-file read so\n // the JSONL location is stable whether storage.dir is a direct path\n // or a symlink. namespaceRootReal was computed via `fs.realpath`\n // above; using it here keeps both the graph-file I/O and the loadNode\n // containment check on the same resolved base path.\n return buildGraphSnapshot({\n memoryDir: namespaceRootReal,\n graphConfig: {\n entityGraphEnabled: cfg.entityGraphEnabled === true,\n timeGraphEnabled: cfg.timeGraphEnabled === true,\n causalGraphEnabled: cfg.causalGraphEnabled === true,\n },\n request: {\n limit: request.limit,\n since: request.since,\n focusNodeId: request.focusNodeId,\n categories: request.categories,\n },\n loadNode,\n });\n }\n\n async memoryFeedback(request: {\n memoryId: string;\n vote: \"up\" | \"down\";\n note?: string;\n }): Promise<{ recorded: boolean; enabled?: boolean; reason?: string }> {\n if (!this.orchestrator.config.feedbackEnabled) {\n return {\n recorded: false,\n enabled: false,\n reason: \"Feedback is disabled. Enable `feedbackEnabled: true` in the Engram config to store feedback.\",\n };\n }\n await this.orchestrator.recordMemoryFeedback(\n request.memoryId,\n request.vote,\n request.note,\n );\n return { recorded: true };\n }\n\n /**\n * Record a Memory Worth outcome observation (issue #560 PR 3).\n *\n * This is distinct from `memoryFeedback` — feedback is a human thumbs\n * up/down on whether a recalled memory was relevant; outcome is an\n * automated signal about whether the session that consumed the memory\n * ultimately succeeded or failed. Outcomes feed the Laplace-smoothed\n * worth score (`computeMemoryWorth`, PR 2) that PR 4 will use to\n * downweight memories correlated with bad sessions.\n *\n * The underlying writer only touches fact-category memories. Corrections,\n * procedures, and other kinds return `{ ok: false, reason:\n * \"ineligible_category\" }` so a ledger drainer doesn't need to pre-filter.\n */\n async memoryOutcome(request: {\n memoryId: string;\n outcome: MemoryOutcomeKind;\n namespace?: string;\n principal?: string;\n sessionKey?: string;\n timestamp?: string;\n }): Promise<RecordMemoryOutcomeResult> {\n if (request.memoryId.includes(\"/\") || request.memoryId.includes(\"\\\\\")) {\n throw new EngramAccessInputError(\n \"memoryId must not contain path separators\",\n );\n }\n const resolvedNs = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.principal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNs);\n // We only have the ID at the access surface, but `recordMemoryOutcome`\n // accepts a path for the benefit of ledger-driven callers that already\n // have the path in hand. Build the conventional `<id>.md` shape —\n // `memoryIdFromPath` extracts the basename so the intermediate\n // directory layout doesn't matter.\n return recordMemoryOutcome(storage, {\n memoryPath: `${request.memoryId}.md`,\n outcome: request.outcome,\n timestamp: request.timestamp,\n });\n }\n\n async memoryPromote(request: {\n memoryId: string;\n namespace?: string;\n principal?: string;\n sessionKey?: string;\n }): Promise<unknown> {\n const resolvedNs = this.resolveWritableNamespace(request.namespace, request.sessionKey, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n // Update frontmatter to active status (promote from pending/draft)\n await storage.updateMemoryFrontmatter(request.memoryId, {\n lifecycleState: \"active\",\n updated: new Date().toISOString(),\n });\n return { promoted: true, memoryId: request.memoryId };\n }\n\n async memoryActionApply(request: {\n action: string;\n outcome?: string;\n reason?: string;\n memoryId?: string;\n namespace?: string;\n principal?: string;\n sessionKey?: string;\n content?: string;\n category?: string;\n linkTargetId?: string;\n linkType?: string;\n linkStrength?: number;\n artifactType?: string;\n execute?: boolean;\n sourcePrompt?: string;\n dryRun?: boolean;\n }): Promise<unknown> {\n const actionTypes = new Set<MemoryActionType>([\n \"store_episode\",\n \"store_note\",\n \"update_note\",\n \"create_artifact\",\n \"summarize_node\",\n \"discard\",\n \"link_graph\",\n ]);\n if (!actionTypes.has(request.action as MemoryActionType)) {\n throw new EngramAccessInputError(\n `memory_action_apply: invalid action ${JSON.stringify(request.action)}`,\n );\n }\n\n if (this.orchestrator.config.contextCompressionActionsEnabled !== true) {\n throw new EngramAccessInputError(\n \"memory_action_apply is disabled; enable contextCompressionActionsEnabled to use this tool\",\n );\n }\n\n const outcome = request.outcome ?? \"skipped\";\n if (outcome !== \"applied\" && outcome !== \"skipped\" && outcome !== \"failed\") {\n throw new EngramAccessInputError(\n `memory_action_apply: outcome must be \"applied\", \"skipped\", or \"failed\"; got ${JSON.stringify(outcome)}`,\n );\n }\n\n const resolvedNs = this.resolveWritableNamespace(\n request.namespace,\n request.sessionKey,\n request.principal,\n );\n const inputSummaryParts = [\n request.content,\n request.category ? `category=${request.category}` : undefined,\n request.linkTargetId ? `linkTargetId=${request.linkTargetId}` : undefined,\n request.linkType ? `linkType=${request.linkType}` : undefined,\n typeof request.linkStrength === \"number\"\n ? `linkStrength=${request.linkStrength}`\n : undefined,\n request.artifactType ? `artifactType=${request.artifactType}` : undefined,\n typeof request.execute === \"boolean\" ? `execute=${request.execute}` : undefined,\n ].filter((part): part is string => typeof part === \"string\" && part.length > 0);\n\n const event = {\n action: request.action as MemoryActionType,\n outcome: outcome as MemoryActionOutcome,\n namespace: resolvedNs,\n actor: \"access.memory_action_apply\",\n subsystem: \"access.memory_action_apply\",\n reason: request.reason,\n memoryId: request.memoryId,\n sourceSessionKey: request.sessionKey,\n inputSummary: inputSummaryParts.length > 0\n ? inputSummaryParts.join(\" | \").slice(0, 500)\n : undefined,\n dryRun: request.dryRun === true,\n promptHash:\n typeof request.sourcePrompt === \"string\" && request.sourcePrompt.length > 0\n ? createHash(\"sha256\").update(request.sourcePrompt).digest(\"hex\")\n : undefined,\n };\n const preview = this.orchestrator.previewMemoryActionEvent(event);\n if (request.dryRun === true) {\n return { recorded: false, dryRun: true, event: preview };\n }\n\n const recorded = await this.orchestrator.appendMemoryActionEvent(event);\n return { recorded, event: preview };\n }\n\n async contextCheckpoint(request: {\n sessionKey: string;\n context: string;\n namespace?: string;\n principal?: string;\n }): Promise<{ saved: boolean }> {\n const resolvedNs = this.resolveWritableNamespace(request.namespace, request.sessionKey, request.principal);\n const storage = await this.orchestrator.getStorage(resolvedNs);\n const storageDir = storage.dir;\n const { writeFile, mkdir } = await import(\"node:fs/promises\");\n const { join, resolve } = await import(\"node:path\");\n // Sanitize sessionKey to prevent path traversal\n const safeKey = request.sessionKey.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n if (!safeKey) throw new EngramAccessInputError(\"sessionKey is required\");\n const checkpointDir = join(storageDir, \"checkpoints\", safeKey);\n // Double-check resolved path stays inside storageDir\n const resolved = resolve(checkpointDir);\n if (!resolved.startsWith(resolve(storageDir))) {\n throw new EngramAccessInputError(\"Invalid sessionKey\");\n }\n await mkdir(checkpointDir, { recursive: true });\n const ts = new Date().toISOString().replace(/[:.]/g, \"-\");\n const filePath = join(checkpointDir, `checkpoint-${ts}.md`);\n await writeFile(filePath, request.context, \"utf-8\");\n return { saved: true };\n }\n\n async lcmStatus(): Promise<EngramAccessLcmStatusResponse> {\n if (!this.orchestrator.lcmEngine || !this.orchestrator.lcmEngine.enabled) {\n return {\n enabled: false,\n archiveAvailable: false,\n };\n }\n\n const stats = await this.orchestrator.lcmEngine.getStats();\n return {\n enabled: true,\n archiveAvailable: true,\n stats: {\n totalTurns: stats.totalMessages,\n },\n };\n }\n\n /**\n * Record citation usage from an observed oai-mem-citation block.\n * For each citation entry, extract the memory ID from the path and\n * increment its access tracking via the orchestrator. Returns the\n * count of submitted IDs and the count of IDs that matched real memories.\n */\n async recordCitationUsage(request: {\n sessionId?: string;\n namespace?: string;\n authenticatedPrincipal?: string;\n entries: Array<{ path: string; lineStart: number; lineEnd: number; note: string }>;\n rolloutIds: string[];\n }): Promise<{ submitted: number; matched: number }> {\n if (request.entries.length === 0) return { submitted: 0, matched: 0 };\n\n // Enforce namespace ACLs — citation tracking is a write-like operation.\n // Pass authenticatedPrincipal so the principal resolution matches other\n // write endpoints (gotcha #42: read and write paths must resolve through\n // the same namespace layer).\n const resolvedNamespace = this.resolveWritableNamespace(\n request.namespace,\n request.sessionId,\n request.authenticatedPrincipal,\n );\n\n // Extract memory IDs from citation paths. The path in citations\n // follows the pattern `facts/<id>.md` or just `<id>.md`.\n const memoryIds: string[] = [];\n for (const entry of request.entries) {\n // Strip directory prefix and .md extension to derive the memory ID.\n const basename = entry.path.split(\"/\").pop() ?? entry.path;\n const id = basename.endsWith(\".md\") ? basename.slice(0, -3) : basename;\n if (id.length > 0) {\n memoryIds.push(id);\n }\n }\n\n if (memoryIds.length === 0) return { submitted: 0, matched: 0 };\n\n // Determine which IDs correspond to real memories in storage using a\n // targeted file-existence scan instead of loading all memories (Finding #2).\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const existingIds = await storage.filterExistingMemoryIds(memoryIds);\n const matchedIds = memoryIds.filter((id) => existingIds.has(id));\n\n if (matchedIds.length > 0) {\n try {\n this.orchestrator.trackMemoryAccess(matchedIds);\n } catch {\n // Fail gracefully — citation usage tracking is best-effort.\n log.debug(\"citation usage tracking: failed to record access for cited memories\");\n }\n }\n\n return { submitted: memoryIds.length, matched: matchedIds.length };\n }\n\n // ── Operator Console state (issue #688 PR 2/3) ────────────────────────────\n\n /**\n * Gather a point-in-time `ConsoleStateSnapshot` from the orchestrator.\n *\n * Principal-aware: `resolveReadableNamespace` enforces ACL before the\n * snapshot is gathered, so callers cannot read a namespace they don't\n * have read access to (CLAUDE.md rule 42). The resolved namespace's\n * storage directory is forwarded as `config.memoryDir` so the ledger-\n * tail reader in `gatherConsoleState` scans the correct namespace root\n * rather than the global root. Read-only — never mutates orchestrator state.\n */\n async consoleState(\n namespace?: string,\n principal?: string,\n ): Promise<import(\"./console/state.js\").ConsoleStateSnapshot> {\n // Enforce namespace ACL — throws EngramAccessInputError if unauthorized.\n const resolvedNamespace = this.resolveReadableNamespace(namespace, principal);\n // Resolve the storage dir for the namespace so the ledger-tail reader\n // scans the right directory tree.\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const { gatherConsoleState } = await import(\"./console/state.js\");\n // Pass a thin proxy that overrides config.memoryDir with the namespace-\n // scoped storage dir while delegating everything else to the real\n // orchestrator (buffer, qmd, extraction queue, etc. are process-global\n // and don't require further namespace scoping for a read-only snapshot).\n const orchestratorProxy = Object.create(this.orchestrator, {\n config: {\n value: { ...this.orchestrator.config, memoryDir: storage.dir },\n enumerable: true,\n configurable: true,\n },\n }) as import(\"./console/state.js\").ConsoleStateOrchestratorLike;\n return gatherConsoleState(orchestratorProxy);\n }\n\n // ── Peer Registry surfaces (issue #679 PR 4/5) ────────────────────────────\n\n /**\n * List all registered peers. Returns the array of `Peer` objects in\n * deterministic alphabetical order (mirroring `listPeers` storage semantics).\n */\n async peerList(): Promise<{ peers: import(\"./peers/types.js\").Peer[] }> {\n const { listPeers } = await import(\"./peers/index.js\");\n const peers = await listPeers(this.orchestrator.config.memoryDir);\n return { peers };\n }\n\n /**\n * Get a single peer by id. Returns `{ found: false }` when the peer does\n * not exist rather than throwing, matching the `memoryGet` / `entityGet`\n * pattern used throughout the service.\n */\n async peerGet(\n peerId: string,\n ): Promise<\n | { found: true; peer: import(\"./peers/types.js\").Peer }\n | { found: false }\n > {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n const peer = await peers.readPeer(this.orchestrator.config.memoryDir, peerId);\n if (!peer) return { found: false };\n return { found: true, peer };\n }\n\n /**\n * Upsert a peer. Writes `peers/{id}/identity.md`. On first write the\n * `createdAt` timestamp is set to now; on subsequent writes only\n * `displayName` and `notes` are mutated (kind and createdAt are immutable\n * once set, per the storage contract).\n *\n * Returns `{ created: true }` on first write, `{ created: false }` on update.\n */\n async peerSet(input: {\n id: string;\n kind?: string;\n displayName?: string;\n notes?: string;\n }): Promise<{ ok: true; created: boolean; peer: import(\"./peers/types.js\").Peer }> {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n\n const { id } = input;\n try {\n validateId(id);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n\n const memoryDir = this.orchestrator.config.memoryDir;\n const now = new Date().toISOString();\n const existing = await peers.readPeer(memoryDir, id);\n\n const ALLOWED_KINDS = new Set([\"self\", \"human\", \"agent\", \"integration\"]);\n if (!existing) {\n // First write — require kind.\n const kind = input.kind ?? \"human\";\n if (!ALLOWED_KINDS.has(kind)) {\n throw new EngramAccessInputError(\n `peer kind must be one of ${[...ALLOWED_KINDS].join(\", \")}`,\n );\n }\n const newPeer: import(\"./peers/types.js\").Peer = {\n id,\n kind: kind as import(\"./peers/types.js\").PeerKind,\n displayName: input.displayName ?? id,\n createdAt: now,\n updatedAt: now,\n ...(typeof input.notes === \"string\" ? { notes: input.notes } : {}),\n };\n await peers.writePeer(memoryDir, newPeer);\n return { ok: true, created: true, peer: newPeer };\n }\n\n // Update — kind and createdAt are immutable.\n const updated: import(\"./peers/types.js\").Peer = {\n id: existing.id,\n kind: existing.kind,\n createdAt: existing.createdAt,\n updatedAt: now,\n displayName: input.displayName !== undefined ? input.displayName : existing.displayName,\n ...(input.notes !== undefined\n ? { notes: input.notes }\n : existing.notes !== undefined\n ? { notes: existing.notes }\n : {}),\n };\n await peers.writePeer(memoryDir, updated);\n return { ok: true, created: false, peer: updated };\n }\n\n /**\n * Delete a peer by removing `peers/{id}/identity.md`. If the file does not\n * exist the call is a no-op (idempotent). The peer directory itself\n * (`peers/{id}/`) is intentionally left in place — profile and interaction\n * log data are not destroyed.\n */\n async peerDelete(peerId: string): Promise<{ ok: true; deleted: boolean }> {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n // Cursor M (PR #756 review): route through `peers.deletePeer` so\n // the unlink runs `assertPeerDirNotEscaped`, the peers-root\n // symlink check, and the parent-inode-stable / O_NOFOLLOW guards\n // shared with `readPeer`/`writePeer`. A manual `path.join` +\n // raw `fs.unlink` would let a symlinked `peers/<id>/` redirect\n // the delete to an arbitrary `identity.md` outside `memoryDir`.\n const deleted = await peers.deletePeer(this.orchestrator.config.memoryDir, peerId);\n return { ok: true, deleted };\n }\n\n /**\n * Destructively purge the entire peer directory for a given peerId —\n * `identity.md`, `profile.md`, `interactions.log.md`, and any other\n * files in `peers/{id}/`. Requires `confirm: \"yes\"` to prevent\n * accidental invocation.\n *\n * This is the DESTRUCTIVE counterpart to `peerDelete`, which only\n * removes `identity.md`. All companion files are permanently removed.\n *\n * Returns `{ ok: true, purged: true }` when the directory existed and\n * was removed; `{ ok: true, purged: false }` when the directory did\n * not exist (idempotent no-op).\n */\n async peerForget(\n peerId: string,\n opts: { confirm: string },\n ): Promise<{ ok: true; purged: boolean }> {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n if (opts.confirm !== \"yes\") {\n throw new EngramAccessInputError(\n \"peerForget requires confirm: 'yes' to prevent accidental data loss\",\n );\n }\n const result = await peers.forgetPeer(this.orchestrator.config.memoryDir, peerId, {\n confirm: \"yes\",\n });\n return { ok: true, purged: result.purged };\n }\n\n /**\n * Get the evolving cognitive profile for a peer. Returns `{ found: false }`\n * when no profile file exists yet (profile is written by the async reasoner,\n * PR 2/5). The peer identity itself need not exist for a profile to exist,\n * but in practice the reasoner only writes profiles for registered peers.\n */\n async peerProfileGet(\n peerId: string,\n ): Promise<\n | { found: true; profile: import(\"./peers/types.js\").PeerProfile }\n | { found: false }\n > {\n const peers = await import(\"./peers/index.js\");\n const validateId: (id: unknown) => void = peers.assertValidPeerId;\n try {\n validateId(peerId);\n } catch (err) {\n throw new EngramAccessInputError((err as Error).message);\n }\n const profile = await peers.readPeerProfile(this.orchestrator.config.memoryDir, peerId);\n if (!profile) return { found: false };\n return { found: true, profile };\n }\n\n // ── Contradiction Review (issue #520) ──────────────────────────────────────\n\n get memoryDir(): string {\n return this.orchestrator.config.memoryDir;\n }\n\n /**\n * Resolve the storage directory for a given namespace. Used by the SSE\n * graph-event handler to subscribe to the correct per-namespace bus rather\n * than the global root (CLAUDE.md rule 42 — read/write paths must resolve\n * through the same namespace layer).\n *\n * `principal` must be the transport-bound request principal (from\n * `resolveRequestPrincipal`). When namespaces are enabled, an absent\n * principal causes `resolveReadableNamespace` to throw an auth error,\n * matching the behaviour of every other authenticated read path.\n *\n * Falls back to `this.memoryDir` when namespaces are disabled or the\n * namespace is absent, matching the behaviour of every other read path.\n */\n async getMemoryDirForNamespace(namespace?: string, principal?: string): Promise<string> {\n const resolved = this.resolveReadableNamespace(namespace, principal);\n const storage = await this.orchestrator.getStorage(resolved);\n return storage.dir;\n }\n\n get storageRef(): StorageManager {\n return this.orchestrator.storage;\n }\n\n get configRef(): PluginConfig {\n return this.orchestrator.config;\n }\n\n get localLlmRef(): LocalLlmClient | null {\n return this.orchestrator.localLlm ?? null;\n }\n\n get fallbackLlmRef(): FallbackLlmClient | null {\n return this.orchestrator.fastGatewayLlm ?? null;\n }\n\n get embeddingLookupFactoryRef(): (storage: import(\"./storage.js\").StorageManager) => SemanticDedupLookup | undefined {\n return (storage) => {\n if (!this.orchestrator.config.embeddingFallbackEnabled) return undefined;\n return async (content: string, limit: number) => {\n try {\n return await this.orchestrator.semanticDedupLookup(content, limit, storage);\n } catch {\n return [];\n }\n };\n };\n }\n\n /**\n * Import a capsule archive into the orchestrator's memory directory.\n *\n * Delegates directly to the standalone {@link importCapsuleFn} function.\n * The `root` parameter defaults to the orchestrator's `memoryDir` when\n * omitted, so callers that only have access to the service do not need to\n * thread the config value through.\n *\n * `versioning` defaults to the orchestrator's page-versioning config so\n * `mode: \"overwrite\"` automatically snapshots prior content without the\n * caller having to construct the config object.\n */\n async capsuleImport(\n opts: Omit<ImportCapsuleOptions, \"root\" | \"memoryDir\"> & {\n root?: string;\n memoryDir?: string;\n namespace?: string;\n principal?: string;\n },\n ): Promise<ImportCapsuleResult> {\n const { namespace, principal, root: explicitRoot, memoryDir: explicitMemoryDir, ...importOptions } = opts;\n const resolvedNamespace = this.resolveWritableNamespace(namespace, undefined, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const root = explicitRoot ?? storage.dir;\n const memoryDir = explicitMemoryDir ?? this.orchestrator.config.memoryDir;\n const versioning = importOptions.versioning ?? {\n enabled: this.orchestrator.config.versioningEnabled,\n maxVersionsPerPage: this.orchestrator.config.versioningMaxPerPage,\n sidecarDir: this.orchestrator.config.versioningSidecarDir,\n };\n await this.validateCapsuleImportArchivePath(importOptions.archivePath);\n try {\n return await importCapsuleFn({ ...importOptions, root, memoryDir, versioning });\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n if (this.isCapsuleImportArchiveInputError(err, message)) {\n throw new EngramAccessInputError(`capsule import failed: ${message}`);\n }\n throw err;\n }\n }\n\n private async validateCapsuleImportArchivePath(archivePath: string): Promise<void> {\n let archiveStat;\n try {\n archiveStat = await stat(archivePath);\n } catch (err) {\n if (!this.isCapsuleImportPathInputFsError(err)) throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new EngramAccessInputError(`capsule import failed: archive is not readable: ${message}`);\n }\n if (!archiveStat.isFile()) {\n throw new EngramAccessInputError(\"capsule import failed: archivePath must point to a file\");\n }\n try {\n await nodeFs.access(archivePath, fsConstants.R_OK);\n } catch (err) {\n if (!this.isCapsuleImportPathInputFsError(err)) throw err;\n const message = err instanceof Error ? err.message : String(err);\n throw new EngramAccessInputError(`capsule import failed: archive is not readable: ${message}`);\n }\n }\n\n private isCapsuleImportPathInputFsError(err: unknown): boolean {\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n return (\n code === \"ENOENT\" ||\n code === \"ENOTDIR\" ||\n code === \"EACCES\" ||\n code === \"EPERM\" ||\n code === \"ELOOP\"\n );\n }\n\n private isCapsuleImportArchiveInputError(err: unknown, message: string): boolean {\n if (err instanceof ZodError) return true;\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n if (typeof code === \"string\" && code.startsWith(\"Z_\")) return true;\n return (\n message.startsWith(\"importCapsule: archive\") ||\n message.startsWith(\"importCapsule: bundle\") ||\n message.startsWith(\"importCapsule: manifest\") ||\n message.startsWith(\"importCapsule: record\") ||\n /incorrect header check|invalid stored block lengths|not in gzip format|unexpected end of file/i.test(message)\n );\n }\n\n /**\n * Export a capsule archive from the orchestrator's memory directory.\n *\n * HTTP and future MCP surfaces use this rather than calling the transfer\n * helper directly so namespace ACL checks stay consistent with the archive\n * write side effect. The exporter still owns archive construction and\n * validation.\n */\n async capsuleExport(\n opts: Omit<ExportCapsuleOptions, \"root\" | \"memoryDir\"> & {\n root?: string;\n memoryDir?: string;\n namespace?: string;\n principal?: string;\n },\n ): Promise<ExportCapsuleResult> {\n const { namespace, principal, root: explicitRoot, memoryDir: explicitMemoryDir, ...exportOptions } = opts;\n const resolvedNamespace = this.resolveWritableNamespace(namespace, undefined, principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const root = explicitRoot ?? storage.dir;\n const memoryDir = explicitMemoryDir ?? this.orchestrator.config.memoryDir;\n const pluginVersion = exportOptions.pluginVersion ?? await getPackageVersion();\n return exportCapsuleFn({\n ...exportOptions,\n pluginVersion,\n root,\n memoryDir: exportOptions.encrypt === true ? memoryDir : undefined,\n });\n }\n\n /**\n * List capsule archives in the namespace-scoped capsule store.\n *\n * MCP uses this access-layer method instead of reading arbitrary paths so\n * capsule discovery remains bound to the same namespace ACLs as export and\n * import.\n */\n async capsuleList(options?: {\n namespace?: string;\n principal?: string;\n }): Promise<EngramAccessCapsuleListResponse> {\n const resolvedNamespace = this.resolveReadableNamespace(options?.namespace, options?.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const capsulesDir = defaultCapsulesDir(storage.dir);\n let dirEntries: import(\"node:fs\").Dirent[];\n try {\n const capsulesDirStat = await nodeFs.lstat(capsulesDir);\n if (capsulesDirStat.isSymbolicLink()) {\n throw new EngramAccessInputError(\"capsule list failed: capsule store directory must not be a symlink\");\n }\n if (!capsulesDirStat.isDirectory()) {\n throw new EngramAccessInputError(\"capsule list failed: capsule store path must be a directory\");\n }\n dirEntries = await nodeFs.readdir(capsulesDir, { withFileTypes: true });\n } catch (err) {\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n if (code === \"ENOENT\") {\n return { namespace: resolvedNamespace, capsulesDir, capsules: [] };\n }\n throw err;\n }\n\n const archiveNames = dirEntries\n .filter(\n (entry) =>\n entry.isFile() &&\n (entry.name.endsWith(\".capsule.json.gz\") ||\n entry.name.endsWith(\".capsule.json.gz.enc\")),\n )\n .map((entry) => entry.name)\n .sort();\n\n const capsules: CapsuleListEntry[] = [];\n for (const archiveName of archiveNames) {\n const archivePath = nodePath.join(capsulesDir, archiveName);\n const id = archiveName\n .replace(/\\.capsule\\.json\\.gz\\.enc$/, \"\")\n .replace(/\\.capsule\\.json\\.gz$/, \"\");\n const manifestPath = nodePath.join(capsulesDir, `${id}.manifest.json`);\n\n let createdAt: string | null = null;\n let pluginVersion: string | null = null;\n let fileCount: number | null = null;\n let description: string | null = null;\n let manifestPathOrNull: string | null = manifestPath;\n\n try {\n const manifestStat = await nodeFs.lstat(manifestPath);\n if (manifestStat.isSymbolicLink() || !manifestStat.isFile()) {\n capsules.push({\n id,\n archivePath,\n manifestPath: manifestPathOrNull,\n createdAt,\n pluginVersion,\n fileCount,\n description,\n });\n continue;\n }\n const raw = await nodeFs.readFile(manifestPath, \"utf-8\");\n const sidecar = JSON.parse(raw) as Record<string, unknown>;\n createdAt = typeof sidecar.createdAt === \"string\" ? sidecar.createdAt : null;\n pluginVersion = typeof sidecar.pluginVersion === \"string\" ? sidecar.pluginVersion : null;\n fileCount = Array.isArray(sidecar.files) ? sidecar.files.length : null;\n const capsule = sidecar.capsule as Record<string, unknown> | undefined;\n description = capsule && typeof capsule.description === \"string\"\n ? capsule.description\n : null;\n } catch (err) {\n const code = typeof err === \"object\" && err !== null && \"code\" in err\n ? (err as { code?: unknown }).code\n : undefined;\n if (code === \"ENOENT\") {\n manifestPathOrNull = null;\n }\n }\n\n capsules.push({\n id,\n archivePath,\n manifestPath: manifestPathOrNull,\n createdAt,\n pluginVersion,\n fileCount,\n description,\n });\n }\n\n return { namespace: resolvedNamespace, capsulesDir, capsules };\n }\n\n // ── Dreams pipeline telemetry surfaces (issue #678 PR 3+4) ──────────────\n\n /**\n * Return per-phase Dreams telemetry for the last N hours (default 24).\n */\n async dreamsStatus(options?: {\n windowHours?: number;\n namespace?: string;\n principal?: string;\n }): Promise<import(\"./types.js\").DreamsStatusResult> {\n const { getDreamsStatus, normalizeDreamsStatusWindowHours } = await import(\"./maintenance/dreams-ledger.js\");\n let windowHours: number;\n try {\n windowHours = normalizeDreamsStatusWindowHours(options?.windowHours);\n } catch (error) {\n throw new EngramAccessInputError(error instanceof Error ? error.message : String(error));\n }\n const resolvedNamespace = this.resolveReadableNamespace(options?.namespace, options?.principal);\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n return getDreamsStatus(storage.dir, windowHours);\n }\n\n /**\n * Manually invoke a single Dreams phase pass (PR 4/4).\n *\n * Deep-sleep delegates to memory governance (shadow → dry-run, apply → live).\n * Light-sleep and REM scan the observation ledger and memory corpus\n * respectively, returning the same telemetry shape as a scheduled run.\n */\n async dreamsRun(options: {\n phase: import(\"./types.js\").DreamsPhase;\n dryRun?: boolean;\n namespace?: string;\n authenticatedPrincipal?: string;\n }): Promise<import(\"./types.js\").DreamsRunResult> {\n const { runDreamsPhase } = await import(\"./maintenance/dreams-ledger.js\");\n const validPhases = [\"lightSleep\", \"rem\", \"deepSleep\"];\n if (!validPhases.includes(options.phase)) {\n throw new EngramAccessInputError(\n `Invalid phase: ${String(options.phase)}. Must be one of: ${validPhases.join(\", \")}`,\n );\n }\n const deepSleep = this.orchestrator.config.dreamsPhases.deepSleep;\n if (\n options.phase === \"deepSleep\" &&\n deepSleep.enabled === false &&\n deepSleep.enabledExplicitlySet === true\n ) {\n throw new EngramAccessInputError(\n \"memory governance is disabled by dreams.phases.deepSleep.enabled=false\",\n );\n }\n const dryRun = options.dryRun === true;\n const resolvedNamespace = this.resolveWritableNamespace(\n options.namespace,\n undefined,\n options.authenticatedPrincipal,\n );\n const storage = await this.orchestrator.getStorage(resolvedNamespace);\n const memoryDir = storage.dir;\n const phaseRunner = dryRun || options.phase === \"deepSleep\"\n ? undefined\n : async (_opts: { memoryDir: string; phase: \"lightSleep\" | \"rem\" }) => {\n if (_opts.phase === \"lightSleep\") {\n const result = await this.orchestrator.runLifecyclePolicyNow(storage);\n return {\n itemsProcessed: result.memoriesAssessed,\n notes: `scored ${result.memoriesAssessed} memories`,\n };\n }\n const result = await this.orchestrator.runSemanticConsolidationNow({\n dryRun: false,\n storage,\n });\n const itemsProcessed = result.clusters.reduce(\n (sum, cluster) => sum + cluster.memories.length,\n 0,\n );\n return {\n itemsProcessed,\n notes: `REM consolidation found ${result.clustersFound} clusters`,\n };\n };\n const governanceRunner = options.phase === \"deepSleep\"\n ? async (_opts: { memoryDir: string; dryRun: boolean }) => {\n return this.orchestrator.runDeepSleepGovernanceNow({\n storage,\n dryRun: _opts.dryRun,\n });\n }\n : undefined;\n const result = await runDreamsPhase(\n { memoryDir, phase: options.phase, dryRun },\n governanceRunner,\n phaseRunner,\n );\n return {\n phase: result.phase,\n dryRun: result.dryRun,\n durationMs: result.durationMs,\n itemsProcessed: result.itemsProcessed,\n notes: result.notes,\n };\n }\n}\n","import path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport type {\n CreateWorkProjectInput,\n CreateWorkTaskInput,\n UpdateWorkProjectInput,\n UpdateWorkTaskInput,\n WorkProject,\n WorkProjectStatus,\n WorkTask,\n WorkTaskListFilter,\n WorkTaskStatus,\n} from \"./types.js\";\n\nconst TASK_TRANSITIONS: Record<WorkTaskStatus, Set<WorkTaskStatus>> = {\n todo: new Set([\"in_progress\", \"blocked\", \"cancelled\"]),\n in_progress: new Set([\"todo\", \"blocked\", \"done\", \"cancelled\"]),\n blocked: new Set([\"todo\", \"in_progress\", \"cancelled\"]),\n done: new Set(),\n cancelled: new Set(),\n};\n\nfunction serializeFrontmatter(values: object): string {\n const lines = Object.entries(values).map(([k, v]) => `${k}: ${JSON.stringify(v)}`);\n return `---\\n${lines.join(\"\\n\")}\\n---`;\n}\n\nfunction parseFrontmatter(raw: string): { data: Record<string, unknown>; body: string } | null {\n const match = raw.match(/^---\\n([\\s\\S]*?)\\n---\\n?([\\s\\S]*)$/);\n if (!match) return null;\n const fm = match[1] ?? \"\";\n const body = match[2] ?? \"\";\n const data: Record<string, unknown> = {};\n for (const line of fm.split(\"\\n\")) {\n if (!line.trim()) continue;\n const idx = line.indexOf(\":\");\n if (idx <= 0) continue;\n const key = line.slice(0, idx).trim();\n const rawValue = line.slice(idx + 1).trim();\n try {\n data[key] = JSON.parse(rawValue);\n } catch {\n data[key] = rawValue;\n }\n }\n return { data, body };\n}\n\nfunction toSafeSlug(value: string): string {\n let slug = value.toLowerCase().trim().replace(/[^a-z0-9]+/g, \"-\");\n // Trim leading/trailing dashes without ReDoS-prone anchored quantifiers\n let start = 0;\n while (start < slug.length && slug[start] === \"-\") start++;\n let end = slug.length;\n while (end > start && slug[end - 1] === \"-\") end--;\n return slug.slice(start, end).slice(0, 80);\n}\n\nexport const WORK_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9-]{0,127}$/;\n\nfunction makeId(prefix: string, titleOrName: string, now: Date): string {\n const slug = toSafeSlug(titleOrName) || \"item\";\n const nonce = randomUUID().slice(0, 8);\n return `${prefix}-${now.getTime()}-${slug}-${nonce}`;\n}\n\nfunction assertValidWorkId(id: string, kind: \"task\" | \"project\"): void {\n if (!WORK_ID_PATTERN.test(id)) {\n throw new Error(`invalid ${kind} id: ${id}`);\n }\n}\n\nfunction ensureString(value: unknown, fallback = \"\"): string {\n return typeof value === \"string\" ? value : fallback;\n}\n\nfunction ensureStringArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((entry) => typeof entry === \"string\");\n}\n\nfunction ensureNullableString(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction ensureTaskStatus(value: unknown): WorkTaskStatus {\n if (value === \"todo\" || value === \"in_progress\" || value === \"blocked\" || value === \"done\" || value === \"cancelled\") {\n return value;\n }\n return \"todo\";\n}\n\nfunction ensureTaskPriority(value: unknown): WorkTask[\"priority\"] {\n if (value === \"low\" || value === \"medium\" || value === \"high\") return value;\n return \"medium\";\n}\n\nfunction ensureProjectStatus(value: unknown): WorkProjectStatus {\n if (value === \"active\" || value === \"on_hold\" || value === \"completed\" || value === \"archived\") return value;\n return \"active\";\n}\n\nexport class WorkStorage {\n private readonly tasksDir: string;\n private readonly projectsDir: string;\n\n constructor(private readonly memoryDir: string) {\n this.tasksDir = path.join(memoryDir, \"work\", \"tasks\");\n this.projectsDir = path.join(memoryDir, \"work\", \"projects\");\n }\n\n async ensureDirectories(): Promise<void> {\n await mkdir(this.tasksDir, { recursive: true });\n await mkdir(this.projectsDir, { recursive: true });\n }\n\n private taskPath(id: string): string {\n assertValidWorkId(id, \"task\");\n return path.join(this.tasksDir, `${id}.md`);\n }\n\n private projectPath(id: string): string {\n assertValidWorkId(id, \"project\");\n return path.join(this.projectsDir, `${id}.md`);\n }\n\n private serializeTask(task: WorkTask): string {\n return `${serializeFrontmatter(task)}\\n\\n${task.description}\\n`;\n }\n\n private serializeProject(project: WorkProject): string {\n return `${serializeFrontmatter(project)}\\n\\n${project.description}\\n`;\n }\n\n private parseTask(raw: string): WorkTask | null {\n const parsed = parseFrontmatter(raw);\n if (!parsed) return null;\n const d = parsed.data;\n return {\n id: ensureString(d.id),\n title: ensureString(d.title),\n description: ensureString(d.description, parsed.body.trim()),\n status: ensureTaskStatus(d.status),\n priority: ensureTaskPriority(d.priority),\n owner: ensureNullableString(d.owner),\n assignee: ensureNullableString(d.assignee),\n projectId: ensureNullableString(d.projectId),\n tags: ensureStringArray(d.tags),\n dueAt: ensureNullableString(d.dueAt),\n createdAt: ensureString(d.createdAt),\n updatedAt: ensureString(d.updatedAt),\n };\n }\n\n private parseProject(raw: string): WorkProject | null {\n const parsed = parseFrontmatter(raw);\n if (!parsed) return null;\n const d = parsed.data;\n return {\n id: ensureString(d.id),\n name: ensureString(d.name),\n description: ensureString(d.description, parsed.body.trim()),\n status: ensureProjectStatus(d.status),\n owner: ensureNullableString(d.owner),\n tags: ensureStringArray(d.tags),\n taskIds: ensureStringArray(d.taskIds),\n createdAt: ensureString(d.createdAt),\n updatedAt: ensureString(d.updatedAt),\n };\n }\n\n async createTask(input: CreateWorkTaskInput, now = new Date()): Promise<WorkTask> {\n await this.ensureDirectories();\n const timestamp = now.toISOString();\n const task: WorkTask = {\n id: input.id ?? makeId(\"task\", input.title, now),\n title: input.title,\n description: input.description ?? \"\",\n status: input.status ?? \"todo\",\n priority: input.priority ?? \"medium\",\n owner: input.owner ?? null,\n assignee: input.assignee ?? null,\n projectId: input.projectId ?? null,\n tags: input.tags ?? [],\n dueAt: input.dueAt ?? null,\n createdAt: timestamp,\n updatedAt: timestamp,\n };\n\n if (task.projectId) {\n const project = await this.getProject(task.projectId);\n if (!project) {\n throw new Error(`project not found: ${task.projectId}`);\n }\n }\n\n await writeFile(this.taskPath(task.id), this.serializeTask(task), \"utf-8\");\n\n if (task.projectId) {\n await this.addTaskIdToProject(task.projectId, task.id, now);\n }\n\n return task;\n }\n\n async getTask(id: string): Promise<WorkTask | null> {\n try {\n const raw = await readFile(this.taskPath(id), \"utf-8\");\n return this.parseTask(raw);\n } catch {\n return null;\n }\n }\n\n async listTasks(filter?: WorkTaskListFilter): Promise<WorkTask[]> {\n await this.ensureDirectories();\n const entries = await readdir(this.tasksDir, { withFileTypes: true });\n const out: WorkTask[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const raw = await readFile(path.join(this.tasksDir, entry.name), \"utf-8\");\n const task = this.parseTask(raw);\n if (!task) continue;\n if (filter?.status && task.status !== filter.status) continue;\n if (filter?.owner && task.owner !== filter.owner) continue;\n if (filter?.assignee && task.assignee !== filter.assignee) continue;\n if (filter?.projectId && task.projectId !== filter.projectId) continue;\n out.push(task);\n }\n out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n return out;\n }\n\n async updateTask(\n id: string,\n patch: UpdateWorkTaskInput,\n now = new Date(),\n options?: { skipStatusTransitionValidation?: boolean },\n ): Promise<WorkTask | null> {\n const existing = await this.getTask(id);\n if (!existing) return null;\n\n const projectIdPatched = Object.prototype.hasOwnProperty.call(patch, \"projectId\");\n const statusPatched = Object.prototype.hasOwnProperty.call(patch, \"status\");\n const nextProjectId = projectIdPatched ? patch.projectId ?? null : existing.projectId;\n\n if (\n statusPatched\n && patch.status\n && existing.status !== patch.status\n && options?.skipStatusTransitionValidation !== true\n && !TASK_TRANSITIONS[existing.status].has(patch.status)\n ) {\n throw new Error(`invalid task status transition: ${existing.status} -> ${patch.status}`);\n }\n\n if (projectIdPatched && nextProjectId) {\n const nextProject = await this.getProject(nextProjectId);\n if (!nextProject) {\n throw new Error(`project not found: ${nextProjectId}`);\n }\n }\n\n if (projectIdPatched && existing.projectId !== nextProjectId) {\n if (existing.projectId) {\n await this.removeTaskIdFromProject(existing.projectId, id, now);\n }\n if (nextProjectId) {\n await this.addTaskIdToProject(nextProjectId, id, now);\n }\n }\n\n const next: WorkTask = {\n ...existing,\n ...patch,\n projectId: nextProjectId,\n tags: patch.tags ?? existing.tags,\n updatedAt: now.toISOString(),\n };\n await writeFile(this.taskPath(id), this.serializeTask(next), \"utf-8\");\n return next;\n }\n\n async transitionTask(id: string, nextStatus: WorkTaskStatus, now = new Date()): Promise<WorkTask> {\n const existing = await this.getTask(id);\n if (!existing) throw new Error(`task not found: ${id}`);\n if (existing.status === nextStatus) return existing;\n if (!TASK_TRANSITIONS[existing.status].has(nextStatus)) {\n throw new Error(`invalid task status transition: ${existing.status} -> ${nextStatus}`);\n }\n const updated = await this.updateTask(id, { status: nextStatus }, now);\n if (!updated) throw new Error(`task not found after update: ${id}`);\n return updated;\n }\n\n async deleteTask(id: string): Promise<boolean> {\n try {\n const existing = await this.getTask(id);\n await rm(this.taskPath(id));\n if (existing?.projectId) {\n await this.removeTaskIdFromProject(existing.projectId, id);\n }\n return true;\n } catch {\n return false;\n }\n }\n\n async createProject(input: CreateWorkProjectInput, now = new Date()): Promise<WorkProject> {\n await this.ensureDirectories();\n const timestamp = now.toISOString();\n const project: WorkProject = {\n id: input.id ?? makeId(\"project\", input.name, now),\n name: input.name,\n description: input.description ?? \"\",\n status: input.status ?? \"active\",\n owner: input.owner ?? null,\n tags: input.tags ?? [],\n taskIds: [],\n createdAt: timestamp,\n updatedAt: timestamp,\n };\n await writeFile(this.projectPath(project.id), this.serializeProject(project), \"utf-8\");\n return project;\n }\n\n async getProject(id: string): Promise<WorkProject | null> {\n try {\n const raw = await readFile(this.projectPath(id), \"utf-8\");\n return this.parseProject(raw);\n } catch {\n return null;\n }\n }\n\n async listProjects(): Promise<WorkProject[]> {\n await this.ensureDirectories();\n const entries = await readdir(this.projectsDir, { withFileTypes: true });\n const out: WorkProject[] = [];\n for (const entry of entries) {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) continue;\n const raw = await readFile(path.join(this.projectsDir, entry.name), \"utf-8\");\n const project = this.parseProject(raw);\n if (project) out.push(project);\n }\n out.sort((a, b) => a.createdAt.localeCompare(b.createdAt));\n return out;\n }\n\n async updateProject(id: string, patch: UpdateWorkProjectInput, now = new Date()): Promise<WorkProject | null> {\n const existing = await this.getProject(id);\n if (!existing) return null;\n const next: WorkProject = {\n ...existing,\n ...patch,\n tags: patch.tags ?? existing.tags,\n taskIds: patch.taskIds ? [...patch.taskIds].sort() : existing.taskIds,\n updatedAt: now.toISOString(),\n };\n await writeFile(this.projectPath(id), this.serializeProject(next), \"utf-8\");\n return next;\n }\n\n async deleteProject(id: string): Promise<boolean> {\n try {\n const existing = await this.getProject(id);\n if (existing) {\n for (const taskId of existing.taskIds) {\n await this.updateTask(taskId, { projectId: null });\n }\n }\n await rm(this.projectPath(id));\n return true;\n } catch {\n return false;\n }\n }\n\n async linkTaskToProject(taskId: string, projectId: string, now = new Date()): Promise<{ task: WorkTask; project: WorkProject }> {\n const task = await this.getTask(taskId);\n if (!task) throw new Error(`task not found: ${taskId}`);\n const project = await this.getProject(projectId);\n if (!project) throw new Error(`project not found: ${projectId}`);\n\n const updatedTask = await this.updateTask(taskId, { projectId }, now);\n if (!updatedTask) throw new Error(`task not found after update: ${taskId}`);\n\n const updatedProject = await this.getProject(projectId);\n if (!updatedProject) throw new Error(`project not found after update: ${projectId}`);\n\n return { task: updatedTask, project: updatedProject };\n }\n\n private async removeTaskIdFromProject(projectId: string, taskId: string, now = new Date()): Promise<void> {\n const project = await this.getProject(projectId);\n if (!project) return;\n\n const filtered = project.taskIds.filter((id) => id !== taskId);\n if (filtered.length === project.taskIds.length) return;\n\n await this.updateProject(projectId, { taskIds: filtered }, now);\n }\n\n private async addTaskIdToProject(projectId: string, taskId: string, now = new Date()): Promise<void> {\n const project = await this.getProject(projectId);\n if (!project) return;\n\n const taskIds = new Set(project.taskIds);\n taskIds.add(taskId);\n await this.updateProject(projectId, { taskIds: Array.from(taskIds) }, now);\n }\n}\n","import type { WorkProject, WorkTask, WorkTaskPriority, WorkTaskStatus } from \"./types.js\";\nimport { WORK_ID_PATTERN, WorkStorage } from \"./storage.js\";\n\nconst BOARD_STATUS_ORDER: WorkTaskStatus[] = [\n \"todo\",\n \"in_progress\",\n \"blocked\",\n \"done\",\n \"cancelled\",\n];\n\nconst BOARD_STATUS_LABEL: Record<WorkTaskStatus, string> = {\n todo: \"Todo\",\n in_progress: \"In Progress\",\n blocked: \"Blocked\",\n done: \"Done\",\n cancelled: \"Cancelled\",\n};\n\nconst PRIORITY_WEIGHT: Record<WorkTaskPriority, number> = {\n high: 0,\n medium: 1,\n low: 2,\n};\n\nexport interface WorkBoardItem {\n id: string;\n title: string;\n description: string;\n status: WorkTaskStatus;\n priority: WorkTaskPriority;\n owner: string | null;\n assignee: string | null;\n projectId: string | null;\n tags: string[];\n dueAt: string | null;\n}\n\nexport interface WorkBoardSnapshot {\n version: 1;\n generatedAt: string;\n projectId: string | null;\n projectName: string | null;\n items: WorkBoardItem[];\n}\n\nexport interface ImportWorkBoardResult {\n created: number;\n updated: number;\n}\n\nfunction stableSortTasks(tasks: WorkTask[]): WorkTask[] {\n return [...tasks].sort((a, b) => {\n const priorityCmp = PRIORITY_WEIGHT[a.priority] - PRIORITY_WEIGHT[b.priority];\n if (priorityCmp !== 0) return priorityCmp;\n const createdCmp = a.createdAt.localeCompare(b.createdAt);\n if (createdCmp !== 0) return createdCmp;\n return a.id.localeCompare(b.id);\n });\n}\n\nfunction projectMatches(task: WorkTask, projectId?: string): boolean {\n if (!projectId) return true;\n return task.projectId === projectId;\n}\n\nfunction assertValidImportEnums(item: WorkBoardItem): void {\n if (![\"todo\", \"in_progress\", \"blocked\", \"done\", \"cancelled\"].includes(item.status)) {\n throw new Error(`invalid task status in snapshot for ${item.id}: ${item.status}`);\n }\n if (![\"low\", \"medium\", \"high\"].includes(item.priority)) {\n throw new Error(`invalid task priority in snapshot for ${item.id}: ${item.priority}`);\n }\n}\n\nfunction normalizeImportedProjectId(\n rawValue: unknown,\n taskId: string,\n fallbackForUndefined: string | null,\n): string | null {\n if (rawValue === undefined) return fallbackForUndefined;\n if (rawValue === null) return null;\n if (typeof rawValue === \"string\") {\n const trimmed = rawValue.trim();\n return trimmed.length > 0 ? trimmed : null;\n }\n throw new Error(`invalid task projectId in snapshot for ${taskId}`);\n}\n\nfunction normalizeImportedTags(rawValue: unknown, taskId: string): string[] {\n if (rawValue === undefined || rawValue === null) return [];\n if (!Array.isArray(rawValue)) {\n throw new Error(`invalid task tags in snapshot for ${taskId}`);\n }\n if (!rawValue.every((entry) => typeof entry === \"string\")) {\n throw new Error(`invalid task tags in snapshot for ${taskId}`);\n }\n return [...rawValue];\n}\n\nfunction assertValidImportedTaskId(rawValue: unknown): string {\n if (typeof rawValue !== \"string\") {\n throw new Error(\"invalid task id in snapshot\");\n }\n const trimmed = rawValue.trim();\n if (!WORK_ID_PATTERN.test(trimmed)) {\n throw new Error(`invalid task id in snapshot: ${trimmed}`);\n }\n return trimmed;\n}\n\nfunction normalizeImportedNullableField(\n rawValue: unknown,\n taskId: string,\n fieldName: \"owner\" | \"assignee\" | \"dueAt\",\n fallbackForUndefined: string | null,\n): string | null {\n if (rawValue === undefined) return fallbackForUndefined;\n if (rawValue === null) return null;\n if (typeof rawValue === \"string\") return rawValue;\n throw new Error(`invalid task ${fieldName} in snapshot for ${taskId}`);\n}\n\nfunction normalizeImportedTitle(rawValue: unknown, taskId: string): string {\n if (typeof rawValue !== \"string\") {\n throw new Error(`invalid task title in snapshot for ${taskId}`);\n }\n const trimmed = rawValue.trim();\n if (trimmed.length === 0) {\n throw new Error(`invalid task title in snapshot for ${taskId}`);\n }\n return trimmed;\n}\n\nfunction normalizeImportedDescription(rawValue: unknown, taskId: string): string {\n if (typeof rawValue !== \"string\") {\n throw new Error(`invalid task description in snapshot for ${taskId}`);\n }\n return rawValue;\n}\n\nfunction asBoardItem(task: WorkTask): WorkBoardItem {\n return {\n id: task.id,\n title: task.title,\n description: task.description,\n status: task.status,\n priority: task.priority,\n owner: task.owner,\n assignee: task.assignee,\n projectId: task.projectId,\n tags: [...task.tags],\n dueAt: task.dueAt,\n };\n}\n\nfunction formatTaskLine(task: WorkBoardItem): string {\n const bits: string[] = [`id:${task.id}`, `priority:${task.priority}`];\n if (task.assignee) bits.push(`assignee:${task.assignee}`);\n if (task.owner) bits.push(`owner:${task.owner}`);\n if (task.dueAt) bits.push(`due:${task.dueAt}`);\n if (task.tags.length > 0) bits.push(`tags:${task.tags.join(\",\")}`);\n const checked = task.status === \"done\";\n return `- [${checked ? \"x\" : \" \"}] ${task.title} \\`[${bits.join(\" \")}]\\``;\n}\n\nexport async function exportWorkBoardSnapshot(options: {\n memoryDir: string;\n projectId?: string;\n now?: Date;\n}): Promise<WorkBoardSnapshot> {\n const storage = new WorkStorage(options.memoryDir);\n await storage.ensureDirectories();\n\n const projectId = options.projectId?.trim() || undefined;\n let project: WorkProject | null = null;\n if (projectId) {\n project = await storage.getProject(projectId);\n if (!project) throw new Error(`project not found: ${projectId}`);\n }\n\n const allTasks = await storage.listTasks();\n const filtered = stableSortTasks(allTasks.filter((task) => projectMatches(task, projectId)));\n return {\n version: 1,\n generatedAt: (options.now ?? new Date()).toISOString(),\n projectId: projectId ?? null,\n projectName: project?.name ?? null,\n items: filtered.map(asBoardItem),\n };\n}\n\nfunction renderWorkBoardMarkdown(snapshot: WorkBoardSnapshot): string {\n const lines: string[] = [];\n lines.push(\"# Work Board\");\n lines.push(\"\");\n lines.push(`Generated: ${snapshot.generatedAt}`);\n lines.push(`Project: ${snapshot.projectName ?? \"all\"} (${snapshot.projectId ?? \"all\"})`);\n lines.push(\"\");\n\n for (const status of BOARD_STATUS_ORDER) {\n const bucket = snapshot.items.filter((item) => item.status === status);\n lines.push(`## ${BOARD_STATUS_LABEL[status]} (${bucket.length})`);\n if (bucket.length === 0) {\n lines.push(\"_none_\");\n } else {\n for (const item of bucket) {\n lines.push(formatTaskLine(item));\n }\n }\n lines.push(\"\");\n }\n\n return `${lines.join(\"\\n\").trim()}\\n`;\n}\n\nexport async function exportWorkBoardMarkdown(options: {\n memoryDir: string;\n projectId?: string;\n now?: Date;\n}): Promise<string> {\n const snapshot = await exportWorkBoardSnapshot(options);\n return renderWorkBoardMarkdown(snapshot);\n}\n\nexport async function importWorkBoardSnapshot(options: {\n memoryDir: string;\n snapshot: WorkBoardSnapshot;\n projectId?: string | null;\n now?: Date;\n}): Promise<ImportWorkBoardResult> {\n if (options.snapshot.version !== 1) {\n throw new Error(`unsupported work board snapshot version: ${options.snapshot.version}`);\n }\n\n const storage = new WorkStorage(options.memoryDir);\n await storage.ensureDirectories();\n\n const forcedProjectId = options.projectId === undefined\n ? undefined\n : (options.projectId?.trim() || null);\n const snapshotProjectId = normalizeImportedProjectId(\n (options.snapshot as unknown as { projectId?: unknown }).projectId,\n \"snapshot\",\n null,\n );\n\n type PreparedImportRow = {\n item: WorkBoardItem;\n existing: WorkTask | null;\n id: string;\n title: string;\n description: string;\n projectId: string | null;\n tags: string[];\n owner: string | null;\n assignee: string | null;\n dueAt: string | null;\n };\n\n const preparedRows: PreparedImportRow[] = [];\n const seenItemIds = new Set<string>();\n for (const item of options.snapshot.items) {\n const id = assertValidImportedTaskId((item as unknown as { id?: unknown }).id);\n if (seenItemIds.has(id)) {\n throw new Error(`duplicate task id in snapshot: ${id}`);\n }\n seenItemIds.add(id);\n assertValidImportEnums(item);\n const existing = await storage.getTask(id);\n const title = normalizeImportedTitle((item as unknown as { title?: unknown }).title, id);\n const description = normalizeImportedDescription((item as unknown as { description?: unknown }).description, id);\n const fallbackProjectId = existing ? existing.projectId : snapshotProjectId;\n const projectId = forcedProjectId === undefined\n ? normalizeImportedProjectId(\n (item as unknown as { projectId?: unknown }).projectId,\n item.id,\n fallbackProjectId,\n )\n : forcedProjectId;\n\n const hasTagsField = Object.prototype.hasOwnProperty.call(\n item as unknown as Record<string, unknown>,\n \"tags\",\n );\n const tags = hasTagsField\n ? normalizeImportedTags((item as unknown as { tags?: unknown }).tags, item.id)\n : (existing ? [...existing.tags] : []);\n\n const owner = normalizeImportedNullableField(\n (item as unknown as { owner?: unknown }).owner,\n id,\n \"owner\",\n existing?.owner ?? null,\n );\n const assignee = normalizeImportedNullableField(\n (item as unknown as { assignee?: unknown }).assignee,\n id,\n \"assignee\",\n existing?.assignee ?? null,\n );\n const dueAt = normalizeImportedNullableField(\n (item as unknown as { dueAt?: unknown }).dueAt,\n id,\n \"dueAt\",\n existing?.dueAt ?? null,\n );\n\n preparedRows.push({ item, existing, id, title, description, projectId, tags, owner, assignee, dueAt });\n }\n\n const projectIdsToValidate = new Set(\n preparedRows\n .map((row) => row.projectId)\n .filter((projectId): projectId is string => typeof projectId === \"string\"),\n );\n for (const projectId of projectIdsToValidate) {\n const project = await storage.getProject(projectId);\n if (!project) throw new Error(`project not found: ${projectId}`);\n }\n\n let created = 0;\n let updated = 0;\n for (const row of preparedRows) {\n const { item, existing, id, title, description, projectId, tags, owner, assignee, dueAt } = row;\n\n if (existing) {\n await storage.updateTask(id, {\n title,\n description,\n status: item.status,\n priority: item.priority,\n owner,\n assignee,\n projectId,\n tags,\n dueAt,\n }, options.now, { skipStatusTransitionValidation: true });\n updated += 1;\n continue;\n }\n\n await storage.createTask({\n id,\n title,\n description,\n status: item.status,\n priority: item.priority,\n owner,\n assignee,\n projectId,\n tags,\n dueAt,\n }, options.now);\n created += 1;\n }\n\n return { created, updated };\n}\n","/**\n * Cluster causal trajectories into candidate procedure memories (issue #519).\n */\n\nimport type { PluginConfig } from \"../types.js\";\nimport type { StorageManager } from \"../storage.js\";\nimport type { CausalTrajectoryRecord } from \"../causal-trajectory.js\";\nimport {\n readCausalTrajectoryRecords,\n filterTrajectoriesByLookbackDays,\n} from \"../causal-trajectory.js\";\nimport { buildProcedurePersistBody, normalizeProcedureSteps, type ProcedureStep } from \"./procedure-types.js\";\nimport { clusterByKey } from \"./reinforcement-core.js\";\nimport { log } from \"../logger.js\";\n\n/** Must match truncation on `procedure_cluster` structured attribute (dedupe + storage). */\nconst PROCEDURE_CLUSTER_ATTR_MAX = 500;\n\nexport interface ProcedureMiningResult {\n clustersProcessed: number;\n proceduresWritten: number;\n skippedReason?: string;\n}\n\nfunction clusterKey(record: CausalTrajectoryRecord): string {\n const goal = record.goal.trim().toLowerCase().replace(/\\s+/g, \" \").slice(0, 120);\n const refs = [...(record.entityRefs ?? [])].map((r) => r.trim().toLowerCase()).sort();\n return `${goal}|${refs.join(\",\")}`;\n}\n\nfunction successRate(group: CausalTrajectoryRecord[]): number {\n if (group.length === 0) return 0;\n const ok = group.filter((g) => g.outcomeKind === \"success\" || g.outcomeKind === \"partial\").length;\n return ok / group.length;\n}\n\n/** Derive ordered pseudo-steps from trajectory text (v1 heuristic; no tool-call array on records). */\nfunction pseudoStepsFromCluster(group: CausalTrajectoryRecord[]): ProcedureStep[] {\n const sentences: string[] = [];\n const pushUnique = (raw: string) => {\n const t = raw.trim();\n if (t.length < 8) return;\n if (!sentences.includes(t)) sentences.push(t);\n };\n for (const g of group) {\n const parts = [g.actionSummary, g.observationSummary, g.outcomeSummary]\n .join(\" \")\n .split(/[.!?]\\s+|;|\\n+/)\n .map((s) => s.trim())\n .filter((s) => s.length > 12);\n for (const p of parts) pushUnique(p);\n if (sentences.length >= 5) break;\n }\n if (sentences.length < 2 && group[0]) {\n pushUnique(`${group[0].goal.trim()} — confirm prerequisites and context.`);\n pushUnique(\"Execute the planned actions, then record the outcome.\");\n }\n return sentences.slice(0, 6).map((intent, i) => ({\n order: i + 1,\n intent,\n }));\n}\n\nasync function hasExistingClusterWrite(\n storage: StorageManager,\n cluster: string,\n): Promise<boolean> {\n const clusterKey = cluster.slice(0, PROCEDURE_CLUSTER_ATTR_MAX);\n const memories = await storage.readAllMemories();\n for (const m of memories) {\n if (m.frontmatter.category !== \"procedure\") continue;\n const c = m.frontmatter.structuredAttributes?.procedure_cluster;\n if (c === clusterKey) return true;\n }\n return false;\n}\n\n/**\n * Mine recurring successful trajectories into `procedure` memories (pending_review\n * by default; active when auto-promotion thresholds are met).\n */\nexport async function runProcedureMining(options: {\n memoryDir: string;\n storage: StorageManager;\n config: PluginConfig;\n}): Promise<ProcedureMiningResult> {\n const cfg = options.config.procedural;\n if (!cfg?.enabled) {\n return { clustersProcessed: 0, proceduresWritten: 0, skippedReason: \"procedural_disabled\" };\n }\n if (cfg.minOccurrences <= 0) {\n return { clustersProcessed: 0, proceduresWritten: 0, skippedReason: \"minOccurrences_zero\" };\n }\n\n const trajectoryDir =\n typeof options.config.causalTrajectoryStoreDir === \"string\" &&\n options.config.causalTrajectoryStoreDir.trim().length > 0\n ? options.config.causalTrajectoryStoreDir.trim()\n : undefined;\n const { trajectories } = await readCausalTrajectoryRecords({\n memoryDir: options.memoryDir,\n causalTrajectoryStoreDir: trajectoryDir,\n });\n const recent = filterTrajectoriesByLookbackDays(trajectories, cfg.lookbackDays);\n\n const clusters = clusterByKey(recent, clusterKey);\n\n let clustersProcessed = 0;\n let proceduresWritten = 0;\n\n for (const [key, group] of clusters) {\n if (group.length < cfg.minOccurrences) continue;\n const rate = successRate(group);\n if (rate < cfg.successFloor) continue;\n\n clustersProcessed += 1;\n\n if (await hasExistingClusterWrite(options.storage, key)) {\n log.debug(`procedure-miner: skip duplicate cluster key=${key.slice(0, 40)}…`);\n continue;\n }\n\n const steps = normalizeProcedureSteps(pseudoStepsFromCluster(group));\n if (steps.length < 2) continue;\n\n const title = `When you work on goals like: ${group[0].goal.trim().slice(0, 140)}`;\n const body = buildProcedurePersistBody(title, steps);\n\n const promote =\n cfg.autoPromoteEnabled === true && group.length >= cfg.autoPromoteOccurrences && rate >= cfg.successFloor;\n\n await options.storage.writeMemory(\"procedure\", body, {\n source: \"procedure-miner\",\n status: promote ? \"active\" : \"pending_review\",\n tags: [\"procedure-miner\", \"causal-trajectory\"],\n structuredAttributes: {\n procedure_cluster: key.slice(0, PROCEDURE_CLUSTER_ATTR_MAX),\n trajectory_ids: group\n .map((g) => g.trajectoryId)\n .join(\",\")\n .slice(0, 1900),\n trajectory_count: String(group.length),\n success_rate: rate.toFixed(4),\n },\n });\n proceduresWritten += 1;\n }\n\n return { clustersProcessed, proceduresWritten };\n}\n","/**\n * Procedural memory stats surface (issue #567 PR 5/5).\n *\n * Pure helper that tallies procedure memories by status and summarizes the\n * current `procedural.*` config so operators (and the dashboard) can see,\n * in one call, how procedural memory is behaving in a namespace.\n *\n * Consumed by:\n * - CLI `remnic procedural stats`\n * - HTTP `GET /engram/v1/procedural/stats`\n * - MCP `remnic.procedural_stats` (+ `engram.procedural_stats` alias)\n */\nimport type { MemoryFile, MemoryStatus, PluginConfig } from \"../types.js\";\nimport type { StorageManager } from \"../storage.js\";\n\nexport interface ProcedureStatusCounts {\n total: number;\n active: number;\n pending_review: number;\n rejected: number;\n quarantined: number;\n superseded: number;\n archived: number;\n /** Any status the enum doesn't yet cover. */\n other: number;\n}\n\nexport interface ProcedureStatsConfigSnapshot {\n enabled: boolean;\n minOccurrences: number;\n successFloor: number;\n autoPromoteOccurrences: number;\n autoPromoteEnabled: boolean;\n lookbackDays: number;\n recallMaxProcedures: number;\n}\n\nexport interface ProcedureStatsRecent {\n /** ISO 8601 timestamp of the most recent procedure write, or null. */\n lastWriteAt: string | null;\n /** Count of procedure files with `created` (or `updated`) in the last 7 days. */\n writesLast7Days: number;\n /** Count of procedures whose `source` is the procedure miner. */\n minerSourced: number;\n}\n\nexport interface ProcedureStatsReport {\n schemaVersion: 1;\n generatedAt: string;\n counts: ProcedureStatusCounts;\n recent: ProcedureStatsRecent;\n config: ProcedureStatsConfigSnapshot;\n}\n\nfunction snapshotConfig(config: PluginConfig): ProcedureStatsConfigSnapshot {\n const p = config.procedural;\n return {\n enabled: p?.enabled === true,\n minOccurrences: typeof p?.minOccurrences === \"number\" ? p.minOccurrences : 0,\n successFloor: typeof p?.successFloor === \"number\" ? p.successFloor : 0,\n autoPromoteOccurrences:\n typeof p?.autoPromoteOccurrences === \"number\"\n ? p.autoPromoteOccurrences\n : 0,\n autoPromoteEnabled: p?.autoPromoteEnabled === true,\n lookbackDays: typeof p?.lookbackDays === \"number\" ? p.lookbackDays : 0,\n recallMaxProcedures:\n typeof p?.recallMaxProcedures === \"number\" ? p.recallMaxProcedures : 0,\n };\n}\n\nfunction tsMs(value: unknown): number | null {\n if (typeof value !== \"string\") return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * Read all memories from storage and tally procedures by status + recency.\n * `nowMs` is injectable so tests can pin the \"last 7 days\" window.\n */\nexport async function computeProcedureStats(options: {\n storage: StorageManager;\n config: PluginConfig;\n nowMs?: number;\n}): Promise<ProcedureStatsReport> {\n const { storage, config } = options;\n const nowMs = options.nowMs ?? Date.now();\n const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;\n\n const counts: ProcedureStatusCounts = {\n total: 0,\n active: 0,\n pending_review: 0,\n rejected: 0,\n quarantined: 0,\n superseded: 0,\n archived: 0,\n other: 0,\n };\n\n let lastWriteMs: number | null = null;\n let writesLast7Days = 0;\n let minerSourced = 0;\n\n const known: MemoryStatus[] = [\n \"active\",\n \"pending_review\",\n \"rejected\",\n \"quarantined\",\n \"superseded\",\n \"archived\",\n ];\n\n // Iterate both live and archived memories so the counts surface matches\n // what operators expect when procedures have been archived via\n // `archiveMemory` (Codex P2 on #611). `readAllMemories` alone skips\n // `archive/`, which would otherwise underreport `counts.archived` and\n // `counts.total`.\n const seen = new Set<string>();\n const live = await storage.readAllMemories();\n const archived = await storage.readArchivedMemories();\n const pool: MemoryFile[] = [...live, ...archived];\n for (const m of pool) {\n if (m.frontmatter.category !== \"procedure\") continue;\n // Dedupe by id so a procedure appearing in both live + archive (mid-\n // archive race) isn't counted twice.\n if (seen.has(m.frontmatter.id)) continue;\n seen.add(m.frontmatter.id);\n counts.total += 1;\n const status = m.frontmatter.status ?? \"active\";\n if ((known as string[]).includes(status)) {\n // Safe index: the status enum values are the counts keys.\n (counts as unknown as Record<string, number>)[status] += 1;\n } else {\n counts.other += 1;\n }\n\n // Recency semantics (Codex P2 on #611): use the latest of `updated` and\n // `created`, not a fallback chain, so recently-edited procedures are\n // reflected in `lastWriteAt` and `writesLast7Days`. Missing timestamps\n // skip the row.\n const createdMs = tsMs(m.frontmatter.created);\n const updatedMs = tsMs(m.frontmatter.updated);\n const latestMs =\n createdMs !== null && updatedMs !== null\n ? Math.max(createdMs, updatedMs)\n : (updatedMs ?? createdMs);\n if (latestMs !== null) {\n if (lastWriteMs === null || latestMs > lastWriteMs) {\n lastWriteMs = latestMs;\n }\n // Exclusive upper bound per CLAUDE.md rule 35 — use half-open window.\n if (latestMs >= nowMs - sevenDaysMs && latestMs < nowMs) {\n writesLast7Days += 1;\n }\n }\n\n if (m.frontmatter.source === \"procedure-miner\") {\n minerSourced += 1;\n }\n }\n\n return {\n schemaVersion: 1,\n generatedAt: new Date(nowMs).toISOString(),\n counts,\n recent: {\n lastWriteAt: lastWriteMs !== null ? new Date(lastWriteMs).toISOString() : null,\n writesLast7Days,\n minerSourced,\n },\n config: snapshotConfig(config),\n };\n}\n\n/**\n * Render `ProcedureStatsReport` as a human-friendly plain-text block for CLI\n * operators. Keep it deterministic — no colors, no ANSI. Used by `--format text`.\n */\nexport function formatProcedureStatsText(report: ProcedureStatsReport): string {\n const { counts, recent, config } = report;\n const lines: string[] = [];\n lines.push(`Procedural memory stats (schema v${report.schemaVersion})`);\n lines.push(` generated: ${report.generatedAt}`);\n lines.push(\"\");\n lines.push(` config:`);\n lines.push(` enabled: ${config.enabled}`);\n lines.push(` minOccurrences: ${config.minOccurrences}`);\n lines.push(` successFloor: ${config.successFloor}`);\n lines.push(` autoPromoteOccurrences: ${config.autoPromoteOccurrences}`);\n lines.push(` autoPromoteEnabled: ${config.autoPromoteEnabled}`);\n lines.push(` lookbackDays: ${config.lookbackDays}`);\n lines.push(` recallMaxProcedures: ${config.recallMaxProcedures}`);\n lines.push(\"\");\n lines.push(` counts:`);\n lines.push(` total: ${counts.total}`);\n lines.push(` active: ${counts.active}`);\n lines.push(` pending_review: ${counts.pending_review}`);\n lines.push(` rejected: ${counts.rejected}`);\n lines.push(` quarantined: ${counts.quarantined}`);\n lines.push(` superseded: ${counts.superseded}`);\n lines.push(` archived: ${counts.archived}`);\n if (counts.other > 0) {\n lines.push(` other: ${counts.other}`);\n }\n lines.push(\"\");\n lines.push(` recent:`);\n lines.push(` lastWriteAt: ${recent.lastWriteAt ?? \"(none)\"}`);\n lines.push(` writesLast7Days: ${recent.writesLast7Days}`);\n lines.push(` minerSourced: ${recent.minerSourced}`);\n return lines.join(\"\\n\") + \"\\n\";\n}\n"],"mappings":";;;;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