@remnic/core 9.66.10 → 9.66.11

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.
Files changed (61) hide show
  1. package/dist/access-admin-ops-surface.js +2 -1
  2. package/dist/access-authorization-probe.js +2 -1
  3. package/dist/access-boundary.js +2 -1
  4. package/dist/access-cli.js +8 -7
  5. package/dist/access-cli.js.map +1 -1
  6. package/dist/access-extraction-force-flush.js +2 -1
  7. package/dist/access-http-query.js +2 -1
  8. package/dist/access-http.js +2 -1
  9. package/dist/access-identity-continuity-surface.js +2 -1
  10. package/dist/access-lcm-surface.js +2 -1
  11. package/dist/access-mcp.js +2 -1
  12. package/dist/access-namespace-preflight.js +2 -1
  13. package/dist/access-observe-write-surface.js +2 -1
  14. package/dist/access-operations-batch.js +2 -1
  15. package/dist/access-operations.js +2 -1
  16. package/dist/access-recall-concurrency.js +2 -1
  17. package/dist/access-recall-response.js +2 -1
  18. package/dist/access-recall-surface.js +2 -1
  19. package/dist/access-service.js +2 -1
  20. package/dist/access-surface-catalog.js +2 -1
  21. package/dist/access-surface-catalog.js.map +1 -1
  22. package/dist/causal-consolidation.js +3 -2
  23. package/dist/causal-consolidation.js.map +1 -1
  24. package/dist/chunk-3UXOZBHV.js +20 -0
  25. package/dist/chunk-3UXOZBHV.js.map +1 -0
  26. package/dist/{chunk-YYDOUOYM.js → chunk-6H7JWYTC.js} +16 -11
  27. package/dist/chunk-6H7JWYTC.js.map +1 -0
  28. package/dist/{chunk-KWVXCRFZ.js → chunk-BCM6ZAJ3.js} +4 -4
  29. package/dist/{chunk-TXCLDIXJ.js → chunk-K6PWPC7O.js} +2 -2
  30. package/dist/{chunk-M2BY5IZL.js → chunk-PVV42HM4.js} +5 -2
  31. package/dist/chunk-PVV42HM4.js.map +1 -0
  32. package/dist/{chunk-VSQG4AXL.js → chunk-PWVRMD37.js} +1 -1
  33. package/dist/{chunk-NR36NW24.js → chunk-UWOA5L6N.js} +40 -43
  34. package/dist/{chunk-NR36NW24.js.map → chunk-UWOA5L6N.js.map} +1 -1
  35. package/dist/{chunk-ZPZLGN4Y.js → chunk-XZ7QLOTJ.js} +4 -20
  36. package/dist/chunk-XZ7QLOTJ.js.map +1 -0
  37. package/dist/cli.js +5 -4
  38. package/dist/coding/export-okf-codegraph.js +1 -1
  39. package/dist/compounding/engine.js +1 -1
  40. package/dist/connectors/codex-materialize-runner.js +2 -1
  41. package/dist/connectors/index.js +2 -1
  42. package/dist/external-wiki-access.js +2 -1
  43. package/dist/extraction.js +2 -1
  44. package/dist/index.js +8 -7
  45. package/dist/orchestrator.js +8 -7
  46. package/dist/semantic-consolidation.js +3 -2
  47. package/dist/source-agent-qualifier.js +2 -1
  48. package/dist/support-passport/index.js +2 -1
  49. package/dist/transfer/export-okf.d.ts +8 -0
  50. package/dist/transfer/export-okf.js +3 -2
  51. package/package.json +2 -2
  52. package/src/cli/okf-commands.ts +2 -5
  53. package/src/okf/render.ts +11 -2
  54. package/src/transfer/export-okf.test.ts +77 -1
  55. package/src/transfer/export-okf.ts +25 -9
  56. package/dist/chunk-M2BY5IZL.js.map +0 -1
  57. package/dist/chunk-YYDOUOYM.js.map +0 -1
  58. package/dist/chunk-ZPZLGN4Y.js.map +0 -1
  59. /package/dist/{chunk-KWVXCRFZ.js.map → chunk-BCM6ZAJ3.js.map} +0 -0
  60. /package/dist/{chunk-TXCLDIXJ.js.map → chunk-K6PWPC7O.js.map} +0 -0
  61. /package/dist/{chunk-VSQG4AXL.js.map → chunk-PWVRMD37.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/access-surface-catalog.ts"],"sourcesContent":["/**\n * Static inventory of every handler on the MCP and HTTP access surfaces, with\n * its migration status against the access boundary (issue #1525).\n *\n * The fitness test (`access-surface-catalog.test.ts`) walks this catalog,\n * checks each entry against the live registry, and counts unmigrated handlers.\n * The ratchet (`scripts/check-ratchets.mjs`) reads this file and counts\n * `operation: null` entries so the unmigrated count can only decrease.\n *\n * WHEN MIGRATING A HANDLER (follow-up PRs):\n * 1. Add the operation to `access-operations.ts` via `defineOperation`.\n * 2. Flip its entry here from `operation: null` to `operation: \"<name>\"`.\n * 3. Delete the surface-local validation the handler used to do.\n * 4. Run `node scripts/check-ratchets.mjs --update` to ratchet the count\n * down — the improvement is recorded in `scripts/ratchet-baseline.json`.\n *\n * WHEN ADDING A NEW HANDLER:\n * 1. Add the entry here with `operation: null` (the fitness test will fail\n * until you either migrate it or acknowledge it as unmigrated).\n * 2. Migrate it in the same PR if it carries user input — the boundary's\n * whole point is that no new handler bypasses it.\n */\n\nimport type { OperationName } from \"./access-boundary.js\";\nimport { SUPPORT_PASSPORT_OWNER_HTTP_ROUTES } from \"./support-passport/access-http.js\";\nimport { SUPPORT_PASSPORT_PUBLIC_HTTP_ROUTES } from \"./support-passport/public-http.js\";\n\n/**\n * One row per MCP tool, keyed by the canonical SHORT name (no `engram.`/\n * `remnic.` prefix — both aliases dispatch to the same operation). The name\n * MUST match the tool's short suffix as advertised by `tools/list`.\n */\nexport interface McpToolEntry {\n readonly tool: string;\n readonly operation: OperationName | null;\n}\n\n/**\n * One row per HTTP route that invokes an access-service method. Routes that\n * only serve static assets, SSE streams, or admin console HTML are excluded —\n * they don't carry user-validated request envelopes into the facade.\n */\nexport interface HttpRouteEntry {\n readonly method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n readonly pathname: string;\n readonly operation: OperationName | null;\n}\n\n// Each tool below corresponds 1:1 to an `engram.*` definition in\n// `EngramMcpServer.tools` (access-mcp.ts). The fitness test asserts the live\n// `tools/list` response matches this list by short name, so a new tool cannot\n// land without either migrating it or acknowledging the unmigrated count.\nexport const MCP_TOOLS: readonly McpToolEntry[] = [\n { tool: \"recall\", operation: \"recall\" },\n { tool: \"recall_explain\", operation: \"recall_explain\" },\n { tool: \"set_coding_context\", operation: \"set_coding_context\" },\n { tool: \"recall_tier_explain\", operation: \"recall_tier_explain\" },\n { tool: \"recall_xray\", operation: \"recall_xray\" },\n { tool: \"who_knows\", operation: \"who_knows\" },\n { tool: \"promotion_candidates\", operation: \"promotion_candidates\" },\n { tool: \"wearables_status\", operation: \"wearables_status\" },\n { tool: \"wearables_sync\", operation: \"wearables_sync\" },\n { tool: \"transcript_day\", operation: \"transcript_day\" },\n { tool: \"transcript_search\", operation: \"transcript_search\" },\n { tool: \"transcript_memories\", operation: \"transcript_memories\" },\n { tool: \"location_status\", operation: \"location_status\" },\n { tool: \"location_check\", operation: \"location_check\" },\n { tool: \"location_sync\", operation: \"location_sync\" },\n { tool: \"location_backfill\", operation: \"location_backfill\" },\n { tool: \"location_day\", operation: \"location_day\" },\n { tool: \"meetings_list\", operation: \"meetings_list\" },\n { tool: \"meetings_get\", operation: \"meetings_get\" },\n { tool: \"meetings_build\", operation: \"meetings_build\" },\n { tool: \"standup\", operation: \"standup\" },\n { tool: \"action_confidence\", operation: \"action_confidence\" },\n { tool: \"chatgpt_memory_inspector\", operation: \"chatgpt_memory_inspector\" },\n { tool: \"day_summary\", operation: \"day_summary\" },\n { tool: \"capsule_export\", operation: \"capsule_export\" },\n { tool: \"capsule_import\", operation: \"capsule_import\" },\n { tool: \"capsule_list\", operation: \"capsule_list\" },\n { tool: \"memory_governance_run\", operation: \"memory_governance_run\" },\n { tool: \"entity_synthesis_run\", operation: \"entity_synthesis_run\" },\n { tool: \"procedure_mining_run\", operation: \"procedure_mining_run\" },\n { tool: \"pattern_reinforcement_run\", operation: \"pattern_reinforcement_run\" },\n { tool: \"procedural_stats\", operation: \"procedural_stats\" },\n { tool: \"procedure_library_maintenance\", operation: \"procedure_library_maintenance\" },\n { tool: \"memory_get\", operation: \"memory_get\" },\n { tool: \"memory_timeline\", operation: \"memory_timeline\" },\n { tool: \"memory_store\", operation: \"memory_store\" },\n // Correction Contract (issue #1580) — one plan/apply pipeline.\n { tool: \"memory_correct_plan\", operation: \"memory_correct_plan\" },\n { tool: \"memory_correct_apply\", operation: \"memory_correct_apply\" },\n // Conversational memory inspection + correction (issue #1583) — unmigrated\n // handler dispatched to processChatMessage (not a boundary operation).\n { tool: \"memory_chat\", operation: \"chat_message\" },\n { tool: \"coding_decision\", operation: \"coding_decision\" },\n { tool: \"coding_architecture\", operation: \"coding_architecture\" },\n // codegraph parity tools (issue #1554)\n { tool: \"codegraph_index\", operation: \"codegraph_index\" },\n { tool: \"codegraph_list_projects\", operation: \"codegraph_list_projects\" },\n { tool: \"codegraph_delete_project\", operation: \"codegraph_delete_project\" },\n { tool: \"codegraph_index_status\", operation: \"codegraph_index_status\" },\n { tool: \"codegraph_search_graph\", operation: \"codegraph_search_graph\" },\n { tool: \"codegraph_trace_path\", operation: \"codegraph_trace_path\" },\n { tool: \"codegraph_detect_changes\", operation: \"codegraph_detect_changes\" },\n { tool: \"codegraph_query_graph\", operation: \"codegraph_query_graph\" },\n { tool: \"codegraph_get_schema\", operation: \"codegraph_get_schema\" },\n { tool: \"codegraph_get_snippet\", operation: \"codegraph_get_snippet\" },\n { tool: \"codegraph_get_architecture\", operation: \"codegraph_get_architecture\" },\n { tool: \"codegraph_search_code\", operation: \"codegraph_search_code\" },\n { tool: \"codegraph_manage_adr\", operation: \"codegraph_manage_adr\" },\n { tool: \"codegraph_ingest_traces\", operation: \"codegraph_ingest_traces\" },\n { tool: \"coding_delta\", operation: \"coding_delta\" },\n { tool: \"suggestion_submit\", operation: \"suggestion_submit\" },\n { tool: \"entity_get\", operation: \"entity_get\" },\n { tool: \"review_queue_list\", operation: \"review_queue_list\" },\n { tool: \"observe\", operation: \"observe\" },\n { tool: \"lcm_search\", operation: \"lcm_search\" },\n { tool: \"lcm_compaction_flush\", operation: \"lcm_compaction_flush\" },\n { tool: \"extraction_force_flush\", operation: \"extraction_force_flush\" },\n { tool: \"lcm_compaction_record\", operation: \"lcm_compaction_record\" },\n { tool: \"continuity_audit_generate\", operation: \"continuity_audit_generate\" },\n { tool: \"continuity_incident_open\", operation: \"continuity_incident_open\" },\n { tool: \"continuity_incident_close\", operation: \"continuity_incident_close\" },\n { tool: \"continuity_incident_list\", operation: \"continuity_incident_list\" },\n { tool: \"continuity_loop_add_or_update\", operation: \"continuity_loop_add_or_update\" },\n { tool: \"continuity_loop_review\", operation: \"continuity_loop_review\" },\n { tool: \"identity_anchor_get\", operation: \"identity_anchor_get\" },\n { tool: \"identity_anchor_update\", operation: \"identity_anchor_update\" },\n { tool: \"memory_identity\", operation: \"memory_identity\" },\n { tool: \"work_task\", operation: \"work_task\" },\n { tool: \"work_project\", operation: \"work_project\" },\n { tool: \"work_board\", operation: \"work_board\" },\n { tool: \"shared_context_write_output\", operation: \"shared_context_write_output\" },\n { tool: \"shared_feedback_record\", operation: \"shared_feedback_record\" },\n { tool: \"shared_priorities_append\", operation: \"shared_priorities_append\" },\n { tool: \"shared_context_cross_signals_run\", operation: \"shared_context_cross_signals_run\" },\n { tool: \"shared_context_curate_daily\", operation: \"shared_context_curate_daily\" },\n { tool: \"compounding_weekly_synthesize\", operation: \"compounding_weekly_synthesize\" },\n { tool: \"compounding_promote_candidate\", operation: \"compounding_promote_candidate\" },\n { tool: \"compression_guidelines_optimize\", operation: \"compression_guidelines_optimize\" },\n { tool: \"compression_guidelines_activate\", operation: \"compression_guidelines_activate\" },\n { tool: \"memory_search\", operation: \"memory_search\" },\n { tool: \"external_wiki_search\", operation: \"external_wiki_search\" },\n { tool: \"memory_profile\", operation: \"memory_profile\" },\n { tool: \"memory_entities_list\", operation: \"memory_entities_list\" },\n { tool: \"memory_questions\", operation: \"memory_questions\" },\n { tool: \"memory_last_recall\", operation: \"memory_last_recall\" },\n { tool: \"memory_intent_debug\", operation: \"memory_intent_debug\" },\n { tool: \"memory_qmd_debug\", operation: \"memory_qmd_debug\" },\n { tool: \"memory_graph_explain\", operation: \"memory_graph_explain\" },\n { tool: \"graph_snapshot\", operation: \"graph_snapshot\" },\n { tool: \"memory_feedback\", operation: \"memory_feedback\" },\n { tool: \"memory_promote\", operation: \"memory_promote\" },\n { tool: \"memory_outcome\", operation: \"memory_outcome\" },\n { tool: \"memory_action_apply\", operation: \"memory_action_apply\" },\n { tool: \"context_checkpoint\", operation: \"context_checkpoint\" },\n { tool: \"briefing\", operation: \"briefing\" },\n { tool: \"review_list\", operation: \"review_list\" },\n { tool: \"review_resolve\", operation: \"review_resolve\" },\n { tool: \"contradiction_scan_run\", operation: \"contradiction_scan_run\" },\n { tool: \"preference_drift_scan\", operation: \"preference_drift_scan\" },\n { tool: \"memory_summarize_hourly\", operation: \"memory_summarize_hourly\" },\n { tool: \"conversation_index_update\", operation: \"conversation_index_update\" },\n { tool: \"profiling_report\", operation: \"profiling_report\" },\n { tool: \"graph_edge_decay_run\", operation: \"graph_edge_decay_run\" },\n { tool: \"live_connectors_run\", operation: \"live_connectors_run\" },\n { tool: \"peer_list\", operation: \"peer_list\" },\n { tool: \"peer_get\", operation: \"peer_get\" },\n { tool: \"peer_set\", operation: \"peer_set\" },\n { tool: \"peer_delete\", operation: \"peer_delete\" },\n { tool: \"peer_profile_get\", operation: \"peer_profile_get\" },\n { tool: \"peer_forget\", operation: \"peer_forget\" },\n { tool: \"console_state\", operation: \"console_state\" },\n { tool: \"dreams_status\", operation: \"dreams_status\" },\n { tool: \"dreams_run\", operation: \"dreams_run\" },\n { tool: \"support_passport_memory_preview\", operation: \"support_passport_memory_preview\" },\n { tool: \"support_passport_cards_list\", operation: \"support_passport_cards_list\" },\n { tool: \"support_passport_draft_create\", operation: \"support_passport_draft_create\" },\n { tool: \"support_passport_drafts_generate\", operation: \"support_passport_drafts_generate\" },\n { tool: \"support_passport_card_replace\", operation: \"support_passport_card_replace\" },\n { tool: \"support_passport_card_approve\", operation: \"support_passport_card_approve\" },\n { tool: \"support_passport_card_reject\", operation: \"support_passport_card_reject\" },\n { tool: \"support_passport_card_withdraw\", operation: \"support_passport_card_withdraw\" },\n { tool: \"support_passport_grant_create\", operation: \"support_passport_grant_create\" },\n { tool: \"support_passport_grants_list\", operation: \"support_passport_grants_list\" },\n { tool: \"support_passport_grant_revoke\", operation: \"support_passport_grant_revoke\" },\n];\n\n// Each route below corresponds 1:1 to a service-invoking route branch in\n// `EngramAccessHttpServer.handle` (access-http.ts). Pathname patterns use\n// `:param` for path segments. The fitness test asserts each entry resolves\n// against the catalog so a new service route cannot land without either\n// Infrastructure routes (health, the /mcp delegate, admin console, UI assets)\n// carry no user request envelope and are intentionally excluded. The adapters\n// route was migrated through the boundary in issue #1850 round 5 (finding 1):\n// it is now op-gated by `enforceTokenOp(\"adapters_status\")` so a scoped token\n// cannot reach adapter metadata, and is tracked here so the gate is enforced.\nexport const HTTP_ROUTES: readonly HttpRouteEntry[] = [\n { method: \"GET\", pathname: \"/engram/v1/adapters\", operation: \"adapters_status\" },\n { method: \"POST\", pathname: \"/engram/v1/recall\", operation: \"recall\" },\n { method: \"POST\", pathname: \"/engram/v1/external-wikis/search\", operation: \"external_wiki_search\" },\n { method: \"POST\", pathname: \"/engram/v1/memories/search\", operation: \"memory_search\" },\n { method: \"POST\", pathname: \"/engram/v1/coding-context\", operation: \"set_coding_context\" },\n { method: \"POST\", pathname: \"/engram/v1/capsules/export\", operation: \"capsule_export\" },\n { method: \"POST\", pathname: \"/engram/v1/capsules/import\", operation: \"capsule_import\" },\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/snapshot\", operation: \"offline_sync_snapshot\" },\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/capabilities\", operation: \"offline_sync_snapshot\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/snapshot\", operation: \"offline_sync_snapshot\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/files\", operation: \"offline_sync_files\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/file-content\", operation: \"offline_sync_file_content\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/apply-file-content\", operation: \"offline_sync_apply_file_content\" },\n {\n method: \"POST\",\n pathname: \"/engram/v1/offline-sync/convergence-complete\",\n operation: \"offline_sync_apply_file_content\",\n },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/apply\", operation: \"offline_sync_apply\" },\n { method: \"POST\", pathname: \"/engram/v1/recall/explain\", operation: \"recall_explain\" },\n { method: \"POST\", pathname: \"/engram/v1/action-confidence\", operation: \"action_confidence\" },\n { method: \"GET\", pathname: \"/engram/v1/recall/tier-explain\", operation: \"recall_tier_explain\" },\n { method: \"GET\", pathname: \"/engram/v1/recall/xray\", operation: \"recall_xray\" },\n { method: \"GET\", pathname: \"/engram/v1/who-knows\", operation: \"who_knows\" },\n { method: \"GET\", pathname: \"/engram/v1/namespace/writable\", operation: \"namespace_writable\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/status\", operation: \"wearables_status\" },\n { method: \"POST\", pathname: \"/engram/v1/wearables/sync\", operation: \"wearables_sync\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/transcript\", operation: \"transcript_day\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/transcripts/search\", operation: \"transcript_search\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/memories\", operation: \"transcript_memories\" },\n { method: \"GET\", pathname: \"/engram/v1/location/status\", operation: \"location_status\" },\n { method: \"GET\", pathname: \"/engram/v1/location/check\", operation: \"location_check\" },\n { method: \"POST\", pathname: \"/engram/v1/location/sync\", operation: \"location_sync\" },\n { method: \"POST\", pathname: \"/engram/v1/location/backfill\", operation: \"location_backfill\" },\n { method: \"GET\", pathname: \"/engram/v1/location/day\", operation: \"location_day\" },\n { method: \"GET\", pathname: \"/engram/v1/meetings\", operation: \"meetings_list\" },\n { method: \"POST\", pathname: \"/engram/v1/meetings/build\", operation: \"meetings_build\" },\n { method: \"GET\", pathname: \"/engram/v1/meetings/:id\", operation: \"meetings_get\" },\n { method: \"GET\", pathname: \"/engram/v1/standup\", operation: \"standup\" },\n { method: \"POST\", pathname: \"/engram/v1/observe\", operation: \"observe\" },\n { method: \"POST\", pathname: \"/engram/v1/lcm/search\", operation: \"lcm_search\" },\n { method: \"POST\", pathname: \"/engram/v1/lcm/compaction/flush\", operation: \"lcm_compaction_flush\" },\n { method: \"POST\", pathname: \"/engram/v1/extraction/flush\", operation: \"extraction_force_flush\" },\n { method: \"POST\", pathname: \"/engram/v1/lcm/compaction/record\", operation: \"lcm_compaction_record\" },\n { method: \"GET\", pathname: \"/engram/v1/lcm/status\", operation: \"lcm_status\" },\n { method: \"GET\", pathname: \"/engram/v1/relay/missions/:id\", operation: \"relay_mission_read\" },\n { method: \"POST\", pathname: \"/engram/v1/relay/missions/:id/events\", operation: \"relay_mission_append\" },\n // Correction Contract (issue #1580) — plan/apply/pending.\n { method: \"POST\", pathname: \"/engram/v1/correction/plan\", operation: \"memory_correct_plan\" },\n { method: \"POST\", pathname: \"/engram/v1/correction/apply\", operation: \"memory_correct_apply\" },\n { method: \"GET\", pathname: \"/engram/v1/correction/pending\", operation: \"correction_pending\" },\n { method: \"POST\", pathname: \"/engram/v1/memories\", operation: \"memory_store\" },\n { method: \"POST\", pathname: \"/engram/v1/coding/decisions\", operation: \"coding_decision\" },\n { method: \"POST\", pathname: \"/engram/v1/coding/architecture\", operation: \"coding_architecture\" },\n { method: \"POST\", pathname: \"/engram/v1/coding/delta\", operation: \"coding_delta\" },\n { method: \"POST\", pathname: \"/engram/v1/suggestions\", operation: \"suggestion_submit\" },\n { method: \"GET\", pathname: \"/engram/v1/memories\", operation: \"memory_list\" },\n { method: \"GET\", pathname: \"/engram/v1/recall/timings\", operation: \"recall_timings\" },\n { method: \"GET\", pathname: \"/engram/v1/memories/:id\", operation: \"memory_get\" },\n { method: \"GET\", pathname: \"/engram/v1/memories/:id/timeline\", operation: \"memory_timeline\" },\n { method: \"GET\", pathname: \"/engram/v1/entities\", operation: \"entity_list\" },\n { method: \"GET\", pathname: \"/engram/v1/entities/:id\", operation: \"entity_get\" },\n { method: \"GET\", pathname: \"/engram/v1/review-queue\", operation: \"review_queue_list\" },\n { method: \"GET\", pathname: \"/engram/v1/maintenance\", operation: \"maintenance_status\" },\n { method: \"GET\", pathname: \"/engram/v1/quality\", operation: \"quality_status\" },\n { method: \"GET\", pathname: \"/engram/v1/trust-zones/status\", operation: \"trust_zones_status\" },\n { method: \"GET\", pathname: \"/engram/v1/procedural/stats\", operation: \"procedural_stats\" },\n { method: \"GET\", pathname: \"/engram/v1/trust-zones/records\", operation: \"trust_zones_records\" },\n { method: \"POST\", pathname: \"/engram/v1/review-disposition\", operation: \"review_disposition\" },\n { method: \"GET\", pathname: \"/engram/v1/review/deck\", operation: \"review_deck_list\" },\n { method: \"POST\", pathname: \"/engram/v1/review/deck/action\", operation: \"review_deck_action\" },\n { method: \"POST\", pathname: \"/engram/v1/review/deck/undo\", operation: \"review_deck_undo\" },\n { method: \"POST\", pathname: \"/engram/v1/trust-zones/promote\", operation: \"trust_zones_promote\" },\n { method: \"POST\", pathname: \"/engram/v1/trust-zones/demo-seed\", operation: \"trust_zones_demo_seed\" },\n { method: \"POST\", pathname: \"/v1/citations/observed\", operation: \"citations_observed\" },\n { method: \"GET\", pathname: \"/engram/v1/review/contradictions\", operation: \"review_list\" },\n { method: \"GET\", pathname: \"/engram/v1/review/contradictions/:id\", operation: \"contradiction_detail\" },\n { method: \"POST\", pathname: \"/engram/v1/review/resolve\", operation: \"review_resolve\" },\n { method: \"GET\", pathname: \"/engram/v1/graph/snapshot\", operation: \"graph_snapshot\" },\n { method: \"POST\", pathname: \"/engram/v1/contradiction-scan\", operation: \"contradiction_scan_run\" },\n { method: \"GET\", pathname: \"/engram/v1/console/state\", operation: \"console_state\" },\n { method: \"GET\", pathname: \"/engram/v1/peers\", operation: \"peer_list\" },\n { method: \"GET\", pathname: \"/engram/v1/peers/:id/profile\", operation: \"peer_profile_get\" },\n { method: \"GET\", pathname: \"/engram/v1/peers/:id\", operation: \"peer_get\" },\n { method: \"PUT\", pathname: \"/engram/v1/peers/:id\", operation: \"peer_set\" },\n { method: \"DELETE\", pathname: \"/engram/v1/peers/:id\", operation: \"peer_delete\" },\n { method: \"GET\", pathname: \"/engram/v1/dreams/status\", operation: \"dreams_status\" },\n { method: \"POST\", pathname: \"/engram/v1/dreams/run\", operation: \"dreams_run\" },\n // SSE-only endpoints: carried in the catalog for completeness tracking.\n // The operation registration makes them visible to the boundary; the\n // streaming lifecycle is owned by the HTTP transport (handleGraphEventsSSE).\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/snapshot-stream\", operation: \"offline_sync_snapshot_stream\" },\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/manifest-stream\", operation: \"offline_sync_snapshot_stream\" },\n { method: \"GET\", pathname: \"/engram/v1/graph/events\", operation: \"graph_events\" },\n { method: \"POST\", pathname: \"/engram/v1/chat/message\", operation: \"chat_message\" },\n { method: \"GET\", pathname: \"/engram/v1/chat/events/:id\", operation: \"chat_events\" },\n ...SUPPORT_PASSPORT_OWNER_HTTP_ROUTES,\n ...SUPPORT_PASSPORT_PUBLIC_HTTP_ROUTES,\n];\n\n/**\n * Total unmigrated-handler count across both surfaces. The ratchet baseline\n * tracks this number; it may only decrease. `access-surface-catalog.test.ts`\n * recomputes it from the live catalog and asserts equality, so a catalog edit\n * without a baseline bump (or, ideally, a migration) fails the gate.\n */\nexport function countUnmigratedHandlers(): number {\n let count = 0;\n for (const entry of MCP_TOOLS) {\n if (entry.operation === null) count += 1;\n }\n for (const entry of HTTP_ROUTES) {\n if (entry.operation === null) count += 1;\n }\n return count;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,IAAM,YAAqC;AAAA,EAChD,EAAE,MAAM,UAAU,WAAW,SAAS;AAAA,EACtC,EAAE,MAAM,kBAAkB,WAAW,iBAAiB;AAAA,EACtD,EAAE,MAAM,sBAAsB,WAAW,qBAA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AA,EAChH,EAAE,QAAQ,OAAO,UAAU,2CAA2C,WAAW,+BAA+B;AAAA,EAChH,EAAE,QAAQ,OAAO,UAAU,2BAA2B,WAAW,eAAe;AAAA,EAChF,EAAE,QAAQ,QAAQ,UAAU,2BAA2B,WAAW,eAAe;AAAA,EACjF,EAAE,QAAQ,OAAO,UAAU,8BAA8B,WAAW,cAAc;AAAA,EAClF,GAAG;AAAA,EACH,GAAG;AACL;AAQO,SAAS,0BAAkC;AAChD,MAAI,QAAQ;AACZ,aAAW,SAAS,WAAW;AAC7B,QAAI,MAAM,cAAc,KAAM,UAAS;AAAA,EACzC;AACA,aAAW,SAAS,aAAa;AAC/B,QAAI,MAAM,cAAc,KAAM,UAAS;AAAA,EACzC;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/access-surface-catalog.ts"],"sourcesContent":["/**\n * Static inventory of every handler on the MCP and HTTP access surfaces, with\n * its migration status against the access boundary (issue #1525).\n *\n * The fitness test (`access-surface-catalog.test.ts`) walks this catalog,\n * checks each entry against the live registry, and counts unmigrated handlers.\n * The ratchet (`scripts/check-ratchets.mjs`) reads this file and counts\n * `operation: null` entries so the unmigrated count can only decrease.\n *\n * WHEN MIGRATING A HANDLER (follow-up PRs):\n * 1. Add the operation to `access-operations.ts` via `defineOperation`.\n * 2. Flip its entry here from `operation: null` to `operation: \"<name>\"`.\n * 3. Delete the surface-local validation the handler used to do.\n * 4. Run `node scripts/check-ratchets.mjs --update` to ratchet the count\n * down — the improvement is recorded in `scripts/ratchet-baseline.json`.\n *\n * WHEN ADDING A NEW HANDLER:\n * 1. Add the entry here with `operation: null` (the fitness test will fail\n * until you either migrate it or acknowledge it as unmigrated).\n * 2. Migrate it in the same PR if it carries user input — the boundary's\n * whole point is that no new handler bypasses it.\n */\n\nimport type { OperationName } from \"./access-boundary.js\";\nimport { SUPPORT_PASSPORT_OWNER_HTTP_ROUTES } from \"./support-passport/access-http.js\";\nimport { SUPPORT_PASSPORT_PUBLIC_HTTP_ROUTES } from \"./support-passport/public-http.js\";\n\n/**\n * One row per MCP tool, keyed by the canonical SHORT name (no `engram.`/\n * `remnic.` prefix — both aliases dispatch to the same operation). The name\n * MUST match the tool's short suffix as advertised by `tools/list`.\n */\nexport interface McpToolEntry {\n readonly tool: string;\n readonly operation: OperationName | null;\n}\n\n/**\n * One row per HTTP route that invokes an access-service method. Routes that\n * only serve static assets, SSE streams, or admin console HTML are excluded —\n * they don't carry user-validated request envelopes into the facade.\n */\nexport interface HttpRouteEntry {\n readonly method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n readonly pathname: string;\n readonly operation: OperationName | null;\n}\n\n// Each tool below corresponds 1:1 to an `engram.*` definition in\n// `EngramMcpServer.tools` (access-mcp.ts). The fitness test asserts the live\n// `tools/list` response matches this list by short name, so a new tool cannot\n// land without either migrating it or acknowledging the unmigrated count.\nexport const MCP_TOOLS: readonly McpToolEntry[] = [\n { tool: \"recall\", operation: \"recall\" },\n { tool: \"recall_explain\", operation: \"recall_explain\" },\n { tool: \"set_coding_context\", operation: \"set_coding_context\" },\n { tool: \"recall_tier_explain\", operation: \"recall_tier_explain\" },\n { tool: \"recall_xray\", operation: \"recall_xray\" },\n { tool: \"who_knows\", operation: \"who_knows\" },\n { tool: \"promotion_candidates\", operation: \"promotion_candidates\" },\n { tool: \"wearables_status\", operation: \"wearables_status\" },\n { tool: \"wearables_sync\", operation: \"wearables_sync\" },\n { tool: \"transcript_day\", operation: \"transcript_day\" },\n { tool: \"transcript_search\", operation: \"transcript_search\" },\n { tool: \"transcript_memories\", operation: \"transcript_memories\" },\n { tool: \"location_status\", operation: \"location_status\" },\n { tool: \"location_check\", operation: \"location_check\" },\n { tool: \"location_sync\", operation: \"location_sync\" },\n { tool: \"location_backfill\", operation: \"location_backfill\" },\n { tool: \"location_day\", operation: \"location_day\" },\n { tool: \"meetings_list\", operation: \"meetings_list\" },\n { tool: \"meetings_get\", operation: \"meetings_get\" },\n { tool: \"meetings_build\", operation: \"meetings_build\" },\n { tool: \"standup\", operation: \"standup\" },\n { tool: \"action_confidence\", operation: \"action_confidence\" },\n { tool: \"chatgpt_memory_inspector\", operation: \"chatgpt_memory_inspector\" },\n { tool: \"day_summary\", operation: \"day_summary\" },\n { tool: \"capsule_export\", operation: \"capsule_export\" },\n { tool: \"capsule_import\", operation: \"capsule_import\" },\n { tool: \"capsule_list\", operation: \"capsule_list\" },\n { tool: \"memory_governance_run\", operation: \"memory_governance_run\" },\n { tool: \"entity_synthesis_run\", operation: \"entity_synthesis_run\" },\n { tool: \"procedure_mining_run\", operation: \"procedure_mining_run\" },\n { tool: \"pattern_reinforcement_run\", operation: \"pattern_reinforcement_run\" },\n { tool: \"procedural_stats\", operation: \"procedural_stats\" },\n { tool: \"procedure_library_maintenance\", operation: \"procedure_library_maintenance\" },\n { tool: \"memory_get\", operation: \"memory_get\" },\n { tool: \"memory_timeline\", operation: \"memory_timeline\" },\n { tool: \"memory_store\", operation: \"memory_store\" },\n // Correction Contract (issue #1580) — one plan/apply pipeline.\n { tool: \"memory_correct_plan\", operation: \"memory_correct_plan\" },\n { tool: \"memory_correct_apply\", operation: \"memory_correct_apply\" },\n // Conversational memory inspection + correction (issue #1583) — unmigrated\n // handler dispatched to processChatMessage (not a boundary operation).\n { tool: \"memory_chat\", operation: \"chat_message\" },\n { tool: \"coding_decision\", operation: \"coding_decision\" },\n { tool: \"coding_architecture\", operation: \"coding_architecture\" },\n // codegraph parity tools (issue #1554)\n { tool: \"codegraph_index\", operation: \"codegraph_index\" },\n { tool: \"codegraph_list_projects\", operation: \"codegraph_list_projects\" },\n { tool: \"codegraph_delete_project\", operation: \"codegraph_delete_project\" },\n { tool: \"codegraph_index_status\", operation: \"codegraph_index_status\" },\n { tool: \"codegraph_search_graph\", operation: \"codegraph_search_graph\" },\n { tool: \"codegraph_trace_path\", operation: \"codegraph_trace_path\" },\n { tool: \"codegraph_detect_changes\", operation: \"codegraph_detect_changes\" },\n { tool: \"codegraph_query_graph\", operation: \"codegraph_query_graph\" },\n { tool: \"codegraph_get_schema\", operation: \"codegraph_get_schema\" },\n { tool: \"codegraph_get_snippet\", operation: \"codegraph_get_snippet\" },\n { tool: \"codegraph_get_architecture\", operation: \"codegraph_get_architecture\" },\n { tool: \"codegraph_search_code\", operation: \"codegraph_search_code\" },\n { tool: \"codegraph_manage_adr\", operation: \"codegraph_manage_adr\" },\n { tool: \"codegraph_ingest_traces\", operation: \"codegraph_ingest_traces\" },\n { tool: \"coding_delta\", operation: \"coding_delta\" },\n { tool: \"suggestion_submit\", operation: \"suggestion_submit\" },\n { tool: \"entity_get\", operation: \"entity_get\" },\n { tool: \"review_queue_list\", operation: \"review_queue_list\" },\n { tool: \"observe\", operation: \"observe\" },\n { tool: \"lcm_search\", operation: \"lcm_search\" },\n { tool: \"lcm_compaction_flush\", operation: \"lcm_compaction_flush\" },\n { tool: \"extraction_force_flush\", operation: \"extraction_force_flush\" },\n { tool: \"lcm_compaction_record\", operation: \"lcm_compaction_record\" },\n { tool: \"continuity_audit_generate\", operation: \"continuity_audit_generate\" },\n { tool: \"continuity_incident_open\", operation: \"continuity_incident_open\" },\n { tool: \"continuity_incident_close\", operation: \"continuity_incident_close\" },\n { tool: \"continuity_incident_list\", operation: \"continuity_incident_list\" },\n { tool: \"continuity_loop_add_or_update\", operation: \"continuity_loop_add_or_update\" },\n { tool: \"continuity_loop_review\", operation: \"continuity_loop_review\" },\n { tool: \"identity_anchor_get\", operation: \"identity_anchor_get\" },\n { tool: \"identity_anchor_update\", operation: \"identity_anchor_update\" },\n { tool: \"memory_identity\", operation: \"memory_identity\" },\n { tool: \"work_task\", operation: \"work_task\" },\n { tool: \"work_project\", operation: \"work_project\" },\n { tool: \"work_board\", operation: \"work_board\" },\n { tool: \"shared_context_write_output\", operation: \"shared_context_write_output\" },\n { tool: \"shared_feedback_record\", operation: \"shared_feedback_record\" },\n { tool: \"shared_priorities_append\", operation: \"shared_priorities_append\" },\n { tool: \"shared_context_cross_signals_run\", operation: \"shared_context_cross_signals_run\" },\n { tool: \"shared_context_curate_daily\", operation: \"shared_context_curate_daily\" },\n { tool: \"compounding_weekly_synthesize\", operation: \"compounding_weekly_synthesize\" },\n { tool: \"compounding_promote_candidate\", operation: \"compounding_promote_candidate\" },\n { tool: \"compression_guidelines_optimize\", operation: \"compression_guidelines_optimize\" },\n { tool: \"compression_guidelines_activate\", operation: \"compression_guidelines_activate\" },\n { tool: \"memory_search\", operation: \"memory_search\" },\n { tool: \"external_wiki_search\", operation: \"external_wiki_search\" },\n { tool: \"memory_profile\", operation: \"memory_profile\" },\n { tool: \"memory_entities_list\", operation: \"memory_entities_list\" },\n { tool: \"memory_questions\", operation: \"memory_questions\" },\n { tool: \"memory_last_recall\", operation: \"memory_last_recall\" },\n { tool: \"memory_intent_debug\", operation: \"memory_intent_debug\" },\n { tool: \"memory_qmd_debug\", operation: \"memory_qmd_debug\" },\n { tool: \"memory_graph_explain\", operation: \"memory_graph_explain\" },\n { tool: \"graph_snapshot\", operation: \"graph_snapshot\" },\n { tool: \"memory_feedback\", operation: \"memory_feedback\" },\n { tool: \"memory_promote\", operation: \"memory_promote\" },\n { tool: \"memory_outcome\", operation: \"memory_outcome\" },\n { tool: \"memory_action_apply\", operation: \"memory_action_apply\" },\n { tool: \"context_checkpoint\", operation: \"context_checkpoint\" },\n { tool: \"briefing\", operation: \"briefing\" },\n { tool: \"review_list\", operation: \"review_list\" },\n { tool: \"review_resolve\", operation: \"review_resolve\" },\n { tool: \"contradiction_scan_run\", operation: \"contradiction_scan_run\" },\n { tool: \"preference_drift_scan\", operation: \"preference_drift_scan\" },\n { tool: \"memory_summarize_hourly\", operation: \"memory_summarize_hourly\" },\n { tool: \"conversation_index_update\", operation: \"conversation_index_update\" },\n { tool: \"profiling_report\", operation: \"profiling_report\" },\n { tool: \"graph_edge_decay_run\", operation: \"graph_edge_decay_run\" },\n { tool: \"live_connectors_run\", operation: \"live_connectors_run\" },\n { tool: \"peer_list\", operation: \"peer_list\" },\n { tool: \"peer_get\", operation: \"peer_get\" },\n { tool: \"peer_set\", operation: \"peer_set\" },\n { tool: \"peer_delete\", operation: \"peer_delete\" },\n { tool: \"peer_profile_get\", operation: \"peer_profile_get\" },\n { tool: \"peer_forget\", operation: \"peer_forget\" },\n { tool: \"console_state\", operation: \"console_state\" },\n { tool: \"dreams_status\", operation: \"dreams_status\" },\n { tool: \"dreams_run\", operation: \"dreams_run\" },\n { tool: \"support_passport_memory_preview\", operation: \"support_passport_memory_preview\" },\n { tool: \"support_passport_cards_list\", operation: \"support_passport_cards_list\" },\n { tool: \"support_passport_draft_create\", operation: \"support_passport_draft_create\" },\n { tool: \"support_passport_drafts_generate\", operation: \"support_passport_drafts_generate\" },\n { tool: \"support_passport_card_replace\", operation: \"support_passport_card_replace\" },\n { tool: \"support_passport_card_approve\", operation: \"support_passport_card_approve\" },\n { tool: \"support_passport_card_reject\", operation: \"support_passport_card_reject\" },\n { tool: \"support_passport_card_withdraw\", operation: \"support_passport_card_withdraw\" },\n { tool: \"support_passport_grant_create\", operation: \"support_passport_grant_create\" },\n { tool: \"support_passport_grants_list\", operation: \"support_passport_grants_list\" },\n { tool: \"support_passport_grant_revoke\", operation: \"support_passport_grant_revoke\" },\n];\n\n// Each route below corresponds 1:1 to a service-invoking route branch in\n// `EngramAccessHttpServer.handle` (access-http.ts). Pathname patterns use\n// `:param` for path segments. The fitness test asserts each entry resolves\n// against the catalog so a new service route cannot land without either\n// Infrastructure routes (health, the /mcp delegate, admin console, UI assets)\n// carry no user request envelope and are intentionally excluded. The adapters\n// route was migrated through the boundary in issue #1850 round 5 (finding 1):\n// it is now op-gated by `enforceTokenOp(\"adapters_status\")` so a scoped token\n// cannot reach adapter metadata, and is tracked here so the gate is enforced.\nexport const HTTP_ROUTES: readonly HttpRouteEntry[] = [\n { method: \"GET\", pathname: \"/engram/v1/adapters\", operation: \"adapters_status\" },\n { method: \"POST\", pathname: \"/engram/v1/recall\", operation: \"recall\" },\n { method: \"POST\", pathname: \"/engram/v1/external-wikis/search\", operation: \"external_wiki_search\" },\n { method: \"POST\", pathname: \"/engram/v1/memories/search\", operation: \"memory_search\" },\n { method: \"POST\", pathname: \"/engram/v1/coding-context\", operation: \"set_coding_context\" },\n { method: \"POST\", pathname: \"/engram/v1/capsules/export\", operation: \"capsule_export\" },\n { method: \"POST\", pathname: \"/engram/v1/capsules/import\", operation: \"capsule_import\" },\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/snapshot\", operation: \"offline_sync_snapshot\" },\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/capabilities\", operation: \"offline_sync_snapshot\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/snapshot\", operation: \"offline_sync_snapshot\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/files\", operation: \"offline_sync_files\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/file-content\", operation: \"offline_sync_file_content\" },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/apply-file-content\", operation: \"offline_sync_apply_file_content\" },\n {\n method: \"POST\",\n pathname: \"/engram/v1/offline-sync/convergence-complete\",\n operation: \"offline_sync_apply_file_content\",\n },\n { method: \"POST\", pathname: \"/engram/v1/offline-sync/apply\", operation: \"offline_sync_apply\" },\n { method: \"POST\", pathname: \"/engram/v1/recall/explain\", operation: \"recall_explain\" },\n { method: \"POST\", pathname: \"/engram/v1/action-confidence\", operation: \"action_confidence\" },\n { method: \"GET\", pathname: \"/engram/v1/recall/tier-explain\", operation: \"recall_tier_explain\" },\n { method: \"GET\", pathname: \"/engram/v1/recall/xray\", operation: \"recall_xray\" },\n { method: \"GET\", pathname: \"/engram/v1/who-knows\", operation: \"who_knows\" },\n { method: \"GET\", pathname: \"/engram/v1/namespace/writable\", operation: \"namespace_writable\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/status\", operation: \"wearables_status\" },\n { method: \"POST\", pathname: \"/engram/v1/wearables/sync\", operation: \"wearables_sync\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/transcript\", operation: \"transcript_day\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/transcripts/search\", operation: \"transcript_search\" },\n { method: \"GET\", pathname: \"/engram/v1/wearables/memories\", operation: \"transcript_memories\" },\n { method: \"GET\", pathname: \"/engram/v1/location/status\", operation: \"location_status\" },\n { method: \"GET\", pathname: \"/engram/v1/location/check\", operation: \"location_check\" },\n { method: \"POST\", pathname: \"/engram/v1/location/sync\", operation: \"location_sync\" },\n { method: \"POST\", pathname: \"/engram/v1/location/backfill\", operation: \"location_backfill\" },\n { method: \"GET\", pathname: \"/engram/v1/location/day\", operation: \"location_day\" },\n { method: \"GET\", pathname: \"/engram/v1/meetings\", operation: \"meetings_list\" },\n { method: \"POST\", pathname: \"/engram/v1/meetings/build\", operation: \"meetings_build\" },\n { method: \"GET\", pathname: \"/engram/v1/meetings/:id\", operation: \"meetings_get\" },\n { method: \"GET\", pathname: \"/engram/v1/standup\", operation: \"standup\" },\n { method: \"POST\", pathname: \"/engram/v1/observe\", operation: \"observe\" },\n { method: \"POST\", pathname: \"/engram/v1/lcm/search\", operation: \"lcm_search\" },\n { method: \"POST\", pathname: \"/engram/v1/lcm/compaction/flush\", operation: \"lcm_compaction_flush\" },\n { method: \"POST\", pathname: \"/engram/v1/extraction/flush\", operation: \"extraction_force_flush\" },\n { method: \"POST\", pathname: \"/engram/v1/lcm/compaction/record\", operation: \"lcm_compaction_record\" },\n { method: \"GET\", pathname: \"/engram/v1/lcm/status\", operation: \"lcm_status\" },\n { method: \"GET\", pathname: \"/engram/v1/relay/missions/:id\", operation: \"relay_mission_read\" },\n { method: \"POST\", pathname: \"/engram/v1/relay/missions/:id/events\", operation: \"relay_mission_append\" },\n // Correction Contract (issue #1580) — plan/apply/pending.\n { method: \"POST\", pathname: \"/engram/v1/correction/plan\", operation: \"memory_correct_plan\" },\n { method: \"POST\", pathname: \"/engram/v1/correction/apply\", operation: \"memory_correct_apply\" },\n { method: \"GET\", pathname: \"/engram/v1/correction/pending\", operation: \"correction_pending\" },\n { method: \"POST\", pathname: \"/engram/v1/memories\", operation: \"memory_store\" },\n { method: \"POST\", pathname: \"/engram/v1/coding/decisions\", operation: \"coding_decision\" },\n { method: \"POST\", pathname: \"/engram/v1/coding/architecture\", operation: \"coding_architecture\" },\n { method: \"POST\", pathname: \"/engram/v1/coding/delta\", operation: \"coding_delta\" },\n { method: \"POST\", pathname: \"/engram/v1/suggestions\", operation: \"suggestion_submit\" },\n { method: \"GET\", pathname: \"/engram/v1/memories\", operation: \"memory_list\" },\n { method: \"GET\", pathname: \"/engram/v1/recall/timings\", operation: \"recall_timings\" },\n { method: \"GET\", pathname: \"/engram/v1/memories/:id\", operation: \"memory_get\" },\n { method: \"GET\", pathname: \"/engram/v1/memories/:id/timeline\", operation: \"memory_timeline\" },\n { method: \"GET\", pathname: \"/engram/v1/entities\", operation: \"entity_list\" },\n { method: \"GET\", pathname: \"/engram/v1/entities/:id\", operation: \"entity_get\" },\n { method: \"GET\", pathname: \"/engram/v1/review-queue\", operation: \"review_queue_list\" },\n { method: \"GET\", pathname: \"/engram/v1/maintenance\", operation: \"maintenance_status\" },\n { method: \"GET\", pathname: \"/engram/v1/quality\", operation: \"quality_status\" },\n { method: \"GET\", pathname: \"/engram/v1/trust-zones/status\", operation: \"trust_zones_status\" },\n { method: \"GET\", pathname: \"/engram/v1/procedural/stats\", operation: \"procedural_stats\" },\n { method: \"GET\", pathname: \"/engram/v1/trust-zones/records\", operation: \"trust_zones_records\" },\n { method: \"POST\", pathname: \"/engram/v1/review-disposition\", operation: \"review_disposition\" },\n { method: \"GET\", pathname: \"/engram/v1/review/deck\", operation: \"review_deck_list\" },\n { method: \"POST\", pathname: \"/engram/v1/review/deck/action\", operation: \"review_deck_action\" },\n { method: \"POST\", pathname: \"/engram/v1/review/deck/undo\", operation: \"review_deck_undo\" },\n { method: \"POST\", pathname: \"/engram/v1/trust-zones/promote\", operation: \"trust_zones_promote\" },\n { method: \"POST\", pathname: \"/engram/v1/trust-zones/demo-seed\", operation: \"trust_zones_demo_seed\" },\n { method: \"POST\", pathname: \"/v1/citations/observed\", operation: \"citations_observed\" },\n { method: \"GET\", pathname: \"/engram/v1/review/contradictions\", operation: \"review_list\" },\n { method: \"GET\", pathname: \"/engram/v1/review/contradictions/:id\", operation: \"contradiction_detail\" },\n { method: \"POST\", pathname: \"/engram/v1/review/resolve\", operation: \"review_resolve\" },\n { method: \"GET\", pathname: \"/engram/v1/graph/snapshot\", operation: \"graph_snapshot\" },\n { method: \"POST\", pathname: \"/engram/v1/contradiction-scan\", operation: \"contradiction_scan_run\" },\n { method: \"GET\", pathname: \"/engram/v1/console/state\", operation: \"console_state\" },\n { method: \"GET\", pathname: \"/engram/v1/peers\", operation: \"peer_list\" },\n { method: \"GET\", pathname: \"/engram/v1/peers/:id/profile\", operation: \"peer_profile_get\" },\n { method: \"GET\", pathname: \"/engram/v1/peers/:id\", operation: \"peer_get\" },\n { method: \"PUT\", pathname: \"/engram/v1/peers/:id\", operation: \"peer_set\" },\n { method: \"DELETE\", pathname: \"/engram/v1/peers/:id\", operation: \"peer_delete\" },\n { method: \"GET\", pathname: \"/engram/v1/dreams/status\", operation: \"dreams_status\" },\n { method: \"POST\", pathname: \"/engram/v1/dreams/run\", operation: \"dreams_run\" },\n // SSE-only endpoints: carried in the catalog for completeness tracking.\n // The operation registration makes them visible to the boundary; the\n // streaming lifecycle is owned by the HTTP transport (handleGraphEventsSSE).\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/snapshot-stream\", operation: \"offline_sync_snapshot_stream\" },\n { method: \"GET\", pathname: \"/engram/v1/offline-sync/manifest-stream\", operation: \"offline_sync_snapshot_stream\" },\n { method: \"GET\", pathname: \"/engram/v1/graph/events\", operation: \"graph_events\" },\n { method: \"POST\", pathname: \"/engram/v1/chat/message\", operation: \"chat_message\" },\n { method: \"GET\", pathname: \"/engram/v1/chat/events/:id\", operation: \"chat_events\" },\n ...SUPPORT_PASSPORT_OWNER_HTTP_ROUTES,\n ...SUPPORT_PASSPORT_PUBLIC_HTTP_ROUTES,\n];\n\n/**\n * Total unmigrated-handler count across both surfaces. The ratchet baseline\n * tracks this number; it may only decrease. `access-surface-catalog.test.ts`\n * recomputes it from the live catalog and asserts equality, so a catalog edit\n * without a baseline bump (or, ideally, a migration) fails the gate.\n */\nexport function countUnmigratedHandlers(): number {\n let count = 0;\n for (const entry of MCP_TOOLS) {\n if (entry.operation === null) count += 1;\n }\n for (const entry of HTTP_ROUTES) {\n if (entry.operation === null) count += 1;\n }\n return count;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDO,IAAM,YAAqC;AAAA,EAChD,EAAE,MAAM,UAAU,WAAW,SAAS;AAAA,EACtC,EAAE,MAAM,kBAAkB,WAAW,iBAAiB;AAAA,EACtD,EAAE,MAAM,sBAAsB,WAAW,qBAAqB;AAAA,EAC9D,EAAE,MAAM,uBAAuB,WAAW,sBAAsB;AAAA,EAChE,EAAE,MAAM,eAAe,WAAW,cAAc;AAAA,EAChD,EAAE,MAAM,aAAa,WAAW,YAAY;AAAA,EAC5C,EAAE,MAAM,wBAAwB,WAAW,uBAAuB;AAAA,EAClE,EAAE,MAAM,oBAAoB,WAAW,mBAAmB;AAAA,EAC1D,EAAE,MAAM,kBAAkB,WAAW,iBAAiB;AAAA,EACtD,EAAE,MAAM,kBAAkB,WAAW,iBAAiB;AAAA,EACtD,EAAE,MAAM,qBAAqB,WAAW,oBAAoB;AAAA,EAC5D,EAAE,MAAM,uBAAuB,WAAW,sBAAsB;AAAA,EAChE,EAAE,MAAM,mBAAmB,WAAW,kBAAkB;AAAA,EACxD,EAAE,MA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12 +4,13 @@ import {
4
4
  } from "./chunk-AWGXR2PV.js";
5
5
  import {
6
6
  buildExtensionsBlockForConsolidation
7
- } from "./chunk-TXCLDIXJ.js";
7
+ } from "./chunk-K6PWPC7O.js";
8
8
  import "./chunk-5JMAGU26.js";
9
9
  import "./chunk-B7RWBZXW.js";
10
10
  import {
11
11
  runPostConsolidationMaterialize
12
- } from "./chunk-ZPZLGN4Y.js";
12
+ } from "./chunk-XZ7QLOTJ.js";
13
+ import "./chunk-3UXOZBHV.js";
13
14
  import "./chunk-ZXBTTMGZ.js";
14
15
  import "./chunk-4PHT7KE2.js";
15
16
  import "./chunk-UHVXE24Y.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/causal-consolidation.ts"],"sourcesContent":["/**\n * causal-consolidation.ts — CMC Phase 2: LLM-Assisted Causal Consolidation\n *\n * Uses an LLM to analyze causal trajectory patterns across sessions.\n * The LLM receives the causal chain graph as context — connected trajectories\n * from different sessions — and identifies recurring behavioral patterns,\n * preference signals, and actionable rules.\n *\n * This is the core CMC innovation: the LLM gets cross-session causal context\n * that no other memory system provides. It can see that a user investigated\n * a bug in session 1, attempted a fix in session 2, and succeeded in session 3 —\n * and synthesize a rule or preference from that chain.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { resolveCausalTrajectoryStoreDir, type CausalTrajectoryRecord } from \"./causal-trajectory.js\";\nimport { readChainIndex, resolveChainsDir, type CausalChainIndex, type CausalEdge } from \"./causal-chain.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig } from \"./fallback-llm.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, MemoryFile, PluginConfig } from \"./types.js\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport { runPostConsolidationMaterialize } from \"./connectors/codex-materialize-runner.js\";\nimport type { MaterializeResult, RolloutSummaryInput } from \"./connectors/codex-materialize.js\";\nimport { buildExtensionsBlockForConsolidation } from \"./semantic-consolidation.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CausalPatternCandidate {\n id: string;\n sourceType: \"causal-pattern\";\n subject: string;\n category: \"principle\" | \"rule\" | \"preference\";\n content: string;\n score: number;\n rationale: string;\n outcome: null;\n provenance: string[];\n agent: string | null;\n workflow: string | null;\n}\n\nexport interface ConsolidationConfig {\n minRecurrence: number;\n minSessions: number;\n successThreshold: number;\n}\n\nexport interface LlmConsolidationResult {\n rules: Array<{\n content: string;\n category: \"rule\" | \"principle\" | \"preference\";\n confidence: number;\n evidence: string[];\n }>;\n preferences: Array<{\n statement: string;\n confidence: number;\n evidence: string[];\n }>;\n}\n\nconst CAUSAL_RULE_CATEGORIES = new Set([\"rule\", \"principle\", \"preference\"]);\n\ninterface ConsolidationLlmClient {\n isAvailable(options?: { agentId?: string; modelChain?: AgentPersonaModelConfig }): boolean;\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: { temperature?: number; maxTokens?: number; agentId?: string; modelChain?: AgentPersonaModelConfig },\n ): Promise<{ content: string } | null>;\n}\n\n// ─── Trajectory Reading ──────────────────────────────────────────────────────\n\nasync function readAllTrajectories(\n memoryDir: string,\n causalTrajectoryStoreDir?: string,\n): Promise<CausalTrajectoryRecord[]> {\n const root = resolveCausalTrajectoryStoreDir(memoryDir, causalTrajectoryStoreDir);\n const trajectoriesDir = path.join(root, \"trajectories\");\n\n const files = await listJsonFiles(trajectoriesDir).catch(() => [] as string[]);\n const results: CausalTrajectoryRecord[] = [];\n\n for (const filePath of files) {\n try {\n const raw = await readJsonFile(filePath);\n if (isRecord(raw) && typeof raw.trajectoryId === \"string\") {\n results.push(raw as unknown as CausalTrajectoryRecord);\n }\n } catch {\n // skip invalid\n }\n }\n\n return results;\n}\n\n// ─── Context Formatting ──────────────────────────────────────────────────────\n\n/**\n * Format trajectories and their causal connections as a readable context\n * for the LLM. Groups by session and shows chain connections.\n */\nfunction formatCausalContext(\n trajectories: CausalTrajectoryRecord[],\n chainIndex: CausalChainIndex,\n maxChars: number = 8000,\n): string {\n // Group trajectories by session\n const bySession = new Map<string, CausalTrajectoryRecord[]>();\n for (const t of trajectories) {\n const list = bySession.get(t.sessionKey) ?? [];\n list.push(t);\n bySession.set(t.sessionKey, list);\n }\n\n const lines: string[] = [];\n lines.push(`## Causal Trajectories (${trajectories.length} across ${bySession.size} sessions)`);\n lines.push(\"\");\n\n // Format each session's trajectories\n for (const [sessionKey, sessionTrajs] of bySession) {\n lines.push(`### Session: ${sessionKey}`);\n for (const t of sessionTrajs.slice(0, 5)) {\n const outcome = t.outcomeKind === \"success\" ? \"+\" : t.outcomeKind === \"failure\" ? \"-\" : \"~\";\n lines.push(`[${outcome}] Goal: ${t.goal}`);\n lines.push(` Action: ${t.actionSummary}`);\n lines.push(` Outcome: ${t.outcomeSummary}`);\n if (t.followUpSummary) lines.push(` Follow-up: ${t.followUpSummary}`);\n if (t.entityRefs?.length) lines.push(` Entities: ${t.entityRefs.join(\", \")}`);\n }\n lines.push(\"\");\n }\n\n // Format causal chain connections\n const edgeCount = Object.keys(chainIndex.edges).length;\n if (edgeCount > 0) {\n lines.push(`## Cross-Session Causal Chains (${edgeCount} connections)`);\n lines.push(\"\");\n\n const trajectoryMap = new Map(trajectories.map((t) => [t.trajectoryId, t]));\n const shown = new Set<string>();\n\n for (const [edgeId, edge] of Object.entries(chainIndex.edges)) {\n if (shown.size >= 10) break; // limit output size\n const from = trajectoryMap.get(edge.fromTrajectoryId);\n const to = trajectoryMap.get(edge.toTrajectoryId);\n if (!from || !to) continue;\n\n lines.push(`${edge.edgeType}: \"${from.goal}\" (${from.sessionKey}) → \"${to.goal}\" (${to.sessionKey})`);\n shown.add(edgeId);\n }\n lines.push(\"\");\n }\n\n const result = lines.join(\"\\n\");\n return result.length > maxChars ? result.slice(0, maxChars) + \"\\n[truncated]\" : result;\n}\n\n// ─── LLM Consolidation ──────────────────────────────────────────────────────\n\nconst CONSOLIDATION_PROMPT = `You are analyzing a user's causal trajectory history across multiple sessions. Trajectories record what the user tried to do (goal), what they did (action), and what happened (outcome).\n\nYour job is to identify:\n1. BEHAVIORAL RULES: Recurring patterns where the same approach consistently succeeds or fails. These should be actionable guidance for future sessions.\n2. PREFERENCES: What the user cares about, prefers, or consistently chooses — even if never explicitly stated. Infer preferences from what they repeatedly do, retry until successful, or always include in their workflow.\n\nIMPORTANT:\n- Look for CROSS-SESSION patterns — things that repeat across different sessions are more significant than within-session patterns.\n- A user who retries the same goal across sessions has a strong implicit preference for that outcome.\n- Consistent action choices reveal preferences even when the user never says \"I prefer X.\"\n- Frame preferences as \"The user would prefer responses that...\" when applicable.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\"content\": \"actionable rule text\", \"category\": \"rule|principle\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ],\n \"preferences\": [\n {\"statement\": \"The user would prefer...\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ]\n}\n\nIf no clear patterns exist, return {\"rules\": [], \"preferences\": []}.`;\n\nasync function consolidateWithLlm(\n context: string,\n llm: ConsolidationLlmClient,\n options: { agentId?: string; modelChain?: AgentPersonaModelConfig } = {},\n): Promise<LlmConsolidationResult> {\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CONSOLIDATION_PROMPT },\n { role: \"user\", content: context },\n ],\n { temperature: 0.2, maxTokens: 2000, agentId: options.agentId, modelChain: options.modelChain },\n );\n\n if (!response?.content) {\n return { rules: [], preferences: [] };\n }\n\n try {\n // Extract JSON from response (may have markdown code fences)\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n const rawPreferences: unknown[] = Array.isArray(parsed.preferences) ? parsed.preferences : [];\n return {\n rules: rawRules\n .map(parseLlmRule)\n .filter((rule): rule is LlmConsolidationResult[\"rules\"][number] => !!rule),\n preferences: rawPreferences\n .map(parseLlmPreference)\n .filter((pref): pref is LlmConsolidationResult[\"preferences\"][number] => !!pref),\n };\n } catch {\n log.warn(\"[cmc] failed to parse LLM consolidation response\");\n return { rules: [], preferences: [] };\n }\n}\n\n// ─── Candidate Generation ────────────────────────────────────────────────────\n\nfunction stablePatternId(content: string): string {\n const digest = createHash(\"sha256\")\n .update(`causal-pattern\\0${content}`)\n .digest(\"hex\")\n .slice(0, 16);\n return `causal-pattern:${digest}`;\n}\n\nfunction parseConfidence(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return Math.max(0, Math.min(1, value));\n}\n\nfunction parseEvidence(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction parseLlmRule(raw: unknown): LlmConsolidationResult[\"rules\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const r = raw as Record<string, unknown>;\n const content = typeof r.content === \"string\" ? r.content.trim() : \"\";\n const category = typeof r.category === \"string\" ? r.category : \"\";\n const confidence = parseConfidence(r.confidence);\n if (content.length <= 5 || !CAUSAL_RULE_CATEGORIES.has(category) || confidence === undefined) {\n return undefined;\n }\n return {\n content,\n category: category as \"rule\" | \"principle\" | \"preference\",\n confidence,\n evidence: parseEvidence(r.evidence),\n };\n}\n\nfunction parseLlmPreference(raw: unknown): LlmConsolidationResult[\"preferences\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const p = raw as Record<string, unknown>;\n const statement = typeof p.statement === \"string\" ? p.statement.trim() : \"\";\n const confidence = parseConfidence(p.confidence);\n if (statement.length <= 5 || confidence === undefined) return undefined;\n return {\n statement,\n confidence,\n evidence: parseEvidence(p.evidence),\n };\n}\n\nfunction llmResultToCandidates(result: LlmConsolidationResult): CausalPatternCandidate[] {\n const candidates: CausalPatternCandidate[] = [];\n\n for (const rule of result.rules) {\n const category =\n rule.category === \"principle\" || rule.category === \"preference\"\n ? rule.category\n : \"rule\";\n candidates.push({\n id: stablePatternId(rule.content),\n sourceType: \"causal-pattern\",\n subject: rule.content.slice(0, 80),\n category,\n content: rule.content,\n score: Math.min(1, rule.confidence ?? 0.7),\n rationale: \"LLM-identified causal pattern from cross-session trajectory analysis\",\n outcome: null,\n provenance: (rule.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n for (const preference of result.preferences) {\n candidates.push({\n id: stablePatternId(preference.statement),\n sourceType: \"causal-pattern\",\n subject: preference.statement.slice(0, 80),\n category: \"preference\",\n content: preference.statement,\n score: Math.min(1, preference.confidence ?? 0.7),\n rationale: \"LLM-identified preference from cross-session trajectory analysis\",\n outcome: null,\n provenance: (preference.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n return candidates;\n}\n\nfunction normalizePositiveInteger(value: number, fallback: number): number {\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\nfunction normalizeSuccessThreshold(value: number): number {\n if (!Number.isFinite(value) || value <= 0) return 0;\n return Math.min(1, value);\n}\n\nfunction trajectorySuccessScore(trajectory: CausalTrajectoryRecord): number {\n if (trajectory.outcomeKind === \"success\") return 1;\n if (trajectory.outcomeKind === \"partial\") return 0.5;\n return 0;\n}\n\nfunction averageSuccessScore(trajectories: CausalTrajectoryRecord[]): number {\n if (trajectories.length === 0) return 0;\n const total = trajectories.reduce((sum, trajectory) => sum + trajectorySuccessScore(trajectory), 0);\n return total / trajectories.length;\n}\n\nfunction passesConsolidationGates(\n trajectories: CausalTrajectoryRecord[],\n config: ConsolidationConfig,\n): boolean {\n const minRecurrence = normalizePositiveInteger(config.minRecurrence, 1);\n if (trajectories.length < minRecurrence) return false;\n\n const minSessions = normalizePositiveInteger(config.minSessions, 1);\n const sessionCount = new Set(trajectories.map((trajectory) => trajectory.sessionKey)).size;\n if (sessionCount < minSessions) return false;\n\n const successThreshold = normalizeSuccessThreshold(config.successThreshold);\n if (successThreshold > 0 && averageSuccessScore(trajectories) < successThreshold) {\n return false;\n }\n\n return true;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run LLM-assisted consolidation: read trajectories, format causal context,\n * ask LLM to identify patterns and preferences.\n */\nexport async function deriveCausalPromotionCandidates(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n config: ConsolidationConfig;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n llmClient?: ConsolidationLlmClient;\n}): Promise<CausalPatternCandidate[]> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (!passesConsolidationGates(trajectories, options.config)) return [];\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n\n // Format the causal context for the LLM\n let context = formatCausalContext(trajectories, chainIndex);\n\n // Append memory extensions block if available (#382)\n if (options.pluginConfig) {\n const extBlock = await buildExtensionsBlockForConsolidation(options.pluginConfig);\n if (extBlock.length > 0) {\n context += \"\\n\\n\" + extBlock;\n }\n }\n\n // If no LLM available, fall back to empty (no deterministic fallback)\n const llm = options.llmClient ?? new FallbackLlmClient(\n options.gatewayConfig,\n options.pluginConfig\n ? fallbackLlmRuntimeContextFromConfig(options.pluginConfig, {\n workspaceDir: options.workspaceDir ?? options.pluginConfig.workspaceDir,\n })\n : { workspaceDir: options.workspaceDir },\n );\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) {\n log.debug(\"[cmc] no LLM available for consolidation — skipping\");\n return [];\n }\n\n // Call LLM for pattern analysis\n const result = await consolidateWithLlm(context, llm, llmOptions);\n const candidates = llmResultToCandidates(result);\n\n log.debug(`[cmc] LLM consolidation produced ${candidates.length} rule(s) and ${result.preferences.length} preference(s)`);\n return candidates;\n } catch (error) {\n log.warn(`[cmc] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Get LLM-synthesized preferences from causal trajectory analysis.\n * Returns formatted preference statements for recall injection.\n */\nexport async function synthesizeCausalPreferencesViaLlm(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n minTrajectories?: number;\n}): Promise<string | null> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (trajectories.length < (options.minTrajectories ?? 2)) return null;\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n const context = formatCausalContext(trajectories, chainIndex);\n\n const llm = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) return null;\n\n const result = await consolidateWithLlm(context, llm, llmOptions);\n if (result.preferences.length === 0 && result.rules.length === 0) return null;\n\n const lines: string[] = [\"## Behavioral Insights (from Causal Chain Analysis)\", \"\"];\n\n for (const pref of result.preferences) {\n lines.push(`- ${pref.statement}`);\n }\n\n for (const rule of result.rules) {\n lines.push(`- ${rule.content}`);\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n } catch (error) {\n log.warn(`[cmc] preference synthesis failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n}\n\n/**\n * Optional post-consolidation hook — materializes Codex-native memory artifacts\n * after a causal consolidation run. Guarded by `codexMaterializeMemories` and\n * `codexMaterializeOnConsolidation`. Returns `null` when disabled or when the\n * sentinel is missing (honors user hand-edits).\n *\n * Split from the orchestrator-owned flow so #378 avoids touching\n * orchestrator.ts while Wave 1 edits are in flight.\n */\nexport async function materializeAfterCausalConsolidation(options: {\n config: PluginConfig;\n namespace?: string;\n memories?: MemoryFile[];\n memoryDir?: string;\n codexHome?: string;\n rolloutSummaries?: RolloutSummaryInput[];\n now?: Date;\n}): Promise<MaterializeResult | null> {\n // Delegates to the shared post-consolidation helper — see\n // runPostConsolidationMaterialize in codex-materialize-runner.ts.\n return runPostConsolidationMaterialize(\"[cmc]\", options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAO3B,OAAO,UAAU;AA0CjB,IAAM,yBAAyB,oBAAI,IAAI,CAAC,QAAQ,aAAa,YAAY,CAAC;AAY1E,eAAe,oBACb,WACA,0BACmC;AACnC,QAAM,OAAO,gCAAgC,WAAW,wBAAwB;AAChF,QAAM,kBAAkB,KAAK,KAAK,MAAM,cAAc;AAEtD,QAAM,QAAQ,MAAM,cAAc,eAAe,EAAE,MAAM,MAAM,CAAC,CAAa;AAC7E,QAAM,UAAoC,CAAC;AAE3C,aAAW,YAAY,OAAO;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,aAAa,QAAQ;AACvC,UAAI,SAAS,GAAG,KAAK,OAAO,IAAI,iBAAiB,UAAU;AACzD,gBAAQ,KAAK,GAAwC;AAAA,MACvD;AAAA,IACF,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,SAAO;AACT;AAQA,SAAS,oBACP,cACA,YACA,WAAmB,KACX;AAER,QAAM,YAAY,oBAAI,IAAsC;AAC5D,aAAW,KAAK,cAAc;AAC5B,UAAM,OAAO,UAAU,IAAI,EAAE,UAAU,KAAK,CAAC;AAC7C,SAAK,KAAK,CAAC;AACX,cAAU,IAAI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,WAAW;AACrF,QAAI,CAAC,IAAI,YAAY,UAAU,EAAG,QAAO;AAEzC,UAAM,SAAS,MAAM,mBAAmB,SAAS,KAAK,UAAU;AAChE,QAAI,OAAO,YAAY,WAAW,KAAK,OAAO,MAAM,WAAW,EAAG,QAAO;AAEzE,UAAM,QAAkB,CAAC,uDAAuD,EAAE;AAElF,eAAW,QAAQ,OAAO,aAAa;AACrC,YAAM,KAAK,KAAK,KAAK,SAAS,EAAE;AAAA,IAClC;AAEA,eAAW,QAAQ,OAAO,OAAO;AAC/B,YAAM,KAAK,KAAK,KAAK,OAAO,EAAE;AAAA,IAChC;AAEA,UAAM,KAAK,EAAE;AACb,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,SAAS,OAAO;AACd,QAAI,KAAK,kDAAkD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACnH,WAAO;AAAA,EACT;AACF;AAWA,eAAsB,oCAAoC,SAQpB;AAGpC,SAAO,gCAAgC,SAAS,OAAO;AACzD;","names":[]}
1
+ {"version":3,"sources":["../src/causal-consolidation.ts"],"sourcesContent":["/**\n * causal-consolidation.ts — CMC Phase 2: LLM-Assisted Causal Consolidation\n *\n * Uses an LLM to analyze causal trajectory patterns across sessions.\n * The LLM receives the causal chain graph as context — connected trajectories\n * from different sessions — and identifies recurring behavioral patterns,\n * preference signals, and actionable rules.\n *\n * This is the core CMC innovation: the LLM gets cross-session causal context\n * that no other memory system provides. It can see that a user investigated\n * a bug in session 1, attempted a fix in session 2, and succeeded in session 3 —\n * and synthesize a rule or preference from that chain.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { resolveCausalTrajectoryStoreDir, type CausalTrajectoryRecord } from \"./causal-trajectory.js\";\nimport { readChainIndex, resolveChainsDir, type CausalChainIndex, type CausalEdge } from \"./causal-chain.js\";\nimport { listJsonFiles, readJsonFile } from \"./json-store.js\";\nimport { isRecord } from \"./store-contract.js\";\nimport { FallbackLlmClient, fallbackLlmRuntimeContextFromConfig } from \"./fallback-llm.js\";\nimport type { AgentPersonaModelConfig, GatewayConfig, MemoryFile, PluginConfig } from \"./types.js\";\nimport path from \"node:path\";\nimport { log } from \"./logger.js\";\nimport { runPostConsolidationMaterialize } from \"./connectors/codex-materialize-runner.js\";\nimport type { MaterializeResult, RolloutSummaryInput } from \"./connectors/codex-materialize.js\";\nimport { buildExtensionsBlockForConsolidation } from \"./semantic-consolidation.js\";\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\nexport interface CausalPatternCandidate {\n id: string;\n sourceType: \"causal-pattern\";\n subject: string;\n category: \"principle\" | \"rule\" | \"preference\";\n content: string;\n score: number;\n rationale: string;\n outcome: null;\n provenance: string[];\n agent: string | null;\n workflow: string | null;\n}\n\nexport interface ConsolidationConfig {\n minRecurrence: number;\n minSessions: number;\n successThreshold: number;\n}\n\nexport interface LlmConsolidationResult {\n rules: Array<{\n content: string;\n category: \"rule\" | \"principle\" | \"preference\";\n confidence: number;\n evidence: string[];\n }>;\n preferences: Array<{\n statement: string;\n confidence: number;\n evidence: string[];\n }>;\n}\n\nconst CAUSAL_RULE_CATEGORIES = new Set([\"rule\", \"principle\", \"preference\"]);\n\ninterface ConsolidationLlmClient {\n isAvailable(options?: { agentId?: string; modelChain?: AgentPersonaModelConfig }): boolean;\n chatCompletion(\n messages: Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string }>,\n options?: { temperature?: number; maxTokens?: number; agentId?: string; modelChain?: AgentPersonaModelConfig },\n ): Promise<{ content: string } | null>;\n}\n\n// ─── Trajectory Reading ──────────────────────────────────────────────────────\n\nasync function readAllTrajectories(\n memoryDir: string,\n causalTrajectoryStoreDir?: string,\n): Promise<CausalTrajectoryRecord[]> {\n const root = resolveCausalTrajectoryStoreDir(memoryDir, causalTrajectoryStoreDir);\n const trajectoriesDir = path.join(root, \"trajectories\");\n\n const files = await listJsonFiles(trajectoriesDir).catch(() => [] as string[]);\n const results: CausalTrajectoryRecord[] = [];\n\n for (const filePath of files) {\n try {\n const raw = await readJsonFile(filePath);\n if (isRecord(raw) && typeof raw.trajectoryId === \"string\") {\n results.push(raw as unknown as CausalTrajectoryRecord);\n }\n } catch {\n // skip invalid\n }\n }\n\n return results;\n}\n\n// ─── Context Formatting ──────────────────────────────────────────────────────\n\n/**\n * Format trajectories and their causal connections as a readable context\n * for the LLM. Groups by session and shows chain connections.\n */\nfunction formatCausalContext(\n trajectories: CausalTrajectoryRecord[],\n chainIndex: CausalChainIndex,\n maxChars: number = 8000,\n): string {\n // Group trajectories by session\n const bySession = new Map<string, CausalTrajectoryRecord[]>();\n for (const t of trajectories) {\n const list = bySession.get(t.sessionKey) ?? [];\n list.push(t);\n bySession.set(t.sessionKey, list);\n }\n\n const lines: string[] = [];\n lines.push(`## Causal Trajectories (${trajectories.length} across ${bySession.size} sessions)`);\n lines.push(\"\");\n\n // Format each session's trajectories\n for (const [sessionKey, sessionTrajs] of bySession) {\n lines.push(`### Session: ${sessionKey}`);\n for (const t of sessionTrajs.slice(0, 5)) {\n const outcome = t.outcomeKind === \"success\" ? \"+\" : t.outcomeKind === \"failure\" ? \"-\" : \"~\";\n lines.push(`[${outcome}] Goal: ${t.goal}`);\n lines.push(` Action: ${t.actionSummary}`);\n lines.push(` Outcome: ${t.outcomeSummary}`);\n if (t.followUpSummary) lines.push(` Follow-up: ${t.followUpSummary}`);\n if (t.entityRefs?.length) lines.push(` Entities: ${t.entityRefs.join(\", \")}`);\n }\n lines.push(\"\");\n }\n\n // Format causal chain connections\n const edgeCount = Object.keys(chainIndex.edges).length;\n if (edgeCount > 0) {\n lines.push(`## Cross-Session Causal Chains (${edgeCount} connections)`);\n lines.push(\"\");\n\n const trajectoryMap = new Map(trajectories.map((t) => [t.trajectoryId, t]));\n const shown = new Set<string>();\n\n for (const [edgeId, edge] of Object.entries(chainIndex.edges)) {\n if (shown.size >= 10) break; // limit output size\n const from = trajectoryMap.get(edge.fromTrajectoryId);\n const to = trajectoryMap.get(edge.toTrajectoryId);\n if (!from || !to) continue;\n\n lines.push(`${edge.edgeType}: \"${from.goal}\" (${from.sessionKey}) → \"${to.goal}\" (${to.sessionKey})`);\n shown.add(edgeId);\n }\n lines.push(\"\");\n }\n\n const result = lines.join(\"\\n\");\n return result.length > maxChars ? result.slice(0, maxChars) + \"\\n[truncated]\" : result;\n}\n\n// ─── LLM Consolidation ──────────────────────────────────────────────────────\n\nconst CONSOLIDATION_PROMPT = `You are analyzing a user's causal trajectory history across multiple sessions. Trajectories record what the user tried to do (goal), what they did (action), and what happened (outcome).\n\nYour job is to identify:\n1. BEHAVIORAL RULES: Recurring patterns where the same approach consistently succeeds or fails. These should be actionable guidance for future sessions.\n2. PREFERENCES: What the user cares about, prefers, or consistently chooses — even if never explicitly stated. Infer preferences from what they repeatedly do, retry until successful, or always include in their workflow.\n\nIMPORTANT:\n- Look for CROSS-SESSION patterns — things that repeat across different sessions are more significant than within-session patterns.\n- A user who retries the same goal across sessions has a strong implicit preference for that outcome.\n- Consistent action choices reveal preferences even when the user never says \"I prefer X.\"\n- Frame preferences as \"The user would prefer responses that...\" when applicable.\n\nOutput valid JSON only:\n{\n \"rules\": [\n {\"content\": \"actionable rule text\", \"category\": \"rule|principle\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ],\n \"preferences\": [\n {\"statement\": \"The user would prefer...\", \"confidence\": 0.0-1.0, \"evidence\": [\"trajectory IDs\"]}\n ]\n}\n\nIf no clear patterns exist, return {\"rules\": [], \"preferences\": []}.`;\n\nasync function consolidateWithLlm(\n context: string,\n llm: ConsolidationLlmClient,\n options: { agentId?: string; modelChain?: AgentPersonaModelConfig } = {},\n): Promise<LlmConsolidationResult> {\n const response = await llm.chatCompletion(\n [\n { role: \"system\", content: CONSOLIDATION_PROMPT },\n { role: \"user\", content: context },\n ],\n { temperature: 0.2, maxTokens: 2000, agentId: options.agentId, modelChain: options.modelChain },\n );\n\n if (!response?.content) {\n return { rules: [], preferences: [] };\n }\n\n try {\n // Extract JSON from response (may have markdown code fences)\n let jsonStr = response.content.trim();\n const fenceMatch = jsonStr.match(/```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?\\s*```/);\n if (fenceMatch) jsonStr = fenceMatch[1];\n\n const parsed = JSON.parse(jsonStr);\n const rawRules: unknown[] = Array.isArray(parsed.rules) ? parsed.rules : [];\n const rawPreferences: unknown[] = Array.isArray(parsed.preferences) ? parsed.preferences : [];\n return {\n rules: rawRules\n .map(parseLlmRule)\n .filter((rule): rule is LlmConsolidationResult[\"rules\"][number] => !!rule),\n preferences: rawPreferences\n .map(parseLlmPreference)\n .filter((pref): pref is LlmConsolidationResult[\"preferences\"][number] => !!pref),\n };\n } catch {\n log.warn(\"[cmc] failed to parse LLM consolidation response\");\n return { rules: [], preferences: [] };\n }\n}\n\n// ─── Candidate Generation ────────────────────────────────────────────────────\n\nfunction stablePatternId(content: string): string {\n const digest = createHash(\"sha256\")\n .update(`causal-pattern\\0${content}`)\n .digest(\"hex\")\n .slice(0, 16);\n return `causal-pattern:${digest}`;\n}\n\nfunction parseConfidence(value: unknown): number | undefined {\n if (typeof value !== \"number\" || !Number.isFinite(value)) return undefined;\n return Math.max(0, Math.min(1, value));\n}\n\nfunction parseEvidence(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.filter((item): item is string => typeof item === \"string\" && item.trim().length > 0);\n}\n\nfunction parseLlmRule(raw: unknown): LlmConsolidationResult[\"rules\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const r = raw as Record<string, unknown>;\n const content = typeof r.content === \"string\" ? r.content.trim() : \"\";\n const category = typeof r.category === \"string\" ? r.category : \"\";\n const confidence = parseConfidence(r.confidence);\n if (content.length <= 5 || !CAUSAL_RULE_CATEGORIES.has(category) || confidence === undefined) {\n return undefined;\n }\n return {\n content,\n category: category as \"rule\" | \"principle\" | \"preference\",\n confidence,\n evidence: parseEvidence(r.evidence),\n };\n}\n\nfunction parseLlmPreference(raw: unknown): LlmConsolidationResult[\"preferences\"][number] | undefined {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) return undefined;\n const p = raw as Record<string, unknown>;\n const statement = typeof p.statement === \"string\" ? p.statement.trim() : \"\";\n const confidence = parseConfidence(p.confidence);\n if (statement.length <= 5 || confidence === undefined) return undefined;\n return {\n statement,\n confidence,\n evidence: parseEvidence(p.evidence),\n };\n}\n\nfunction llmResultToCandidates(result: LlmConsolidationResult): CausalPatternCandidate[] {\n const candidates: CausalPatternCandidate[] = [];\n\n for (const rule of result.rules) {\n const category =\n rule.category === \"principle\" || rule.category === \"preference\"\n ? rule.category\n : \"rule\";\n candidates.push({\n id: stablePatternId(rule.content),\n sourceType: \"causal-pattern\",\n subject: rule.content.slice(0, 80),\n category,\n content: rule.content,\n score: Math.min(1, rule.confidence ?? 0.7),\n rationale: \"LLM-identified causal pattern from cross-session trajectory analysis\",\n outcome: null,\n provenance: (rule.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n for (const preference of result.preferences) {\n candidates.push({\n id: stablePatternId(preference.statement),\n sourceType: \"causal-pattern\",\n subject: preference.statement.slice(0, 80),\n category: \"preference\",\n content: preference.statement,\n score: Math.min(1, preference.confidence ?? 0.7),\n rationale: \"LLM-identified preference from cross-session trajectory analysis\",\n outcome: null,\n provenance: (preference.evidence ?? []).slice(0, 5),\n agent: null,\n workflow: null,\n });\n }\n\n return candidates;\n}\n\nfunction normalizePositiveInteger(value: number, fallback: number): number {\n return Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;\n}\n\nfunction normalizeSuccessThreshold(value: number): number {\n if (!Number.isFinite(value) || value <= 0) return 0;\n return Math.min(1, value);\n}\n\nfunction trajectorySuccessScore(trajectory: CausalTrajectoryRecord): number {\n if (trajectory.outcomeKind === \"success\") return 1;\n if (trajectory.outcomeKind === \"partial\") return 0.5;\n return 0;\n}\n\nfunction averageSuccessScore(trajectories: CausalTrajectoryRecord[]): number {\n if (trajectories.length === 0) return 0;\n const total = trajectories.reduce((sum, trajectory) => sum + trajectorySuccessScore(trajectory), 0);\n return total / trajectories.length;\n}\n\nfunction passesConsolidationGates(\n trajectories: CausalTrajectoryRecord[],\n config: ConsolidationConfig,\n): boolean {\n const minRecurrence = normalizePositiveInteger(config.minRecurrence, 1);\n if (trajectories.length < minRecurrence) return false;\n\n const minSessions = normalizePositiveInteger(config.minSessions, 1);\n const sessionCount = new Set(trajectories.map((trajectory) => trajectory.sessionKey)).size;\n if (sessionCount < minSessions) return false;\n\n const successThreshold = normalizeSuccessThreshold(config.successThreshold);\n if (successThreshold > 0 && averageSuccessScore(trajectories) < successThreshold) {\n return false;\n }\n\n return true;\n}\n\n// ─── Public API ──────────────────────────────────────────────────────────────\n\n/**\n * Run LLM-assisted consolidation: read trajectories, format causal context,\n * ask LLM to identify patterns and preferences.\n */\nexport async function deriveCausalPromotionCandidates(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n config: ConsolidationConfig;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n pluginConfig?: PluginConfig;\n llmClient?: ConsolidationLlmClient;\n}): Promise<CausalPatternCandidate[]> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (!passesConsolidationGates(trajectories, options.config)) return [];\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n\n // Format the causal context for the LLM\n let context = formatCausalContext(trajectories, chainIndex);\n\n // Append memory extensions block if available (#382)\n if (options.pluginConfig) {\n const extBlock = await buildExtensionsBlockForConsolidation(options.pluginConfig);\n if (extBlock.length > 0) {\n context += \"\\n\\n\" + extBlock;\n }\n }\n\n // If no LLM available, fall back to empty (no deterministic fallback)\n const llm = options.llmClient ?? new FallbackLlmClient(\n options.gatewayConfig,\n options.pluginConfig\n ? fallbackLlmRuntimeContextFromConfig(options.pluginConfig, {\n workspaceDir: options.workspaceDir ?? options.pluginConfig.workspaceDir,\n })\n : { workspaceDir: options.workspaceDir },\n );\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) {\n log.debug(\"[cmc] no LLM available for consolidation — skipping\");\n return [];\n }\n\n // Call LLM for pattern analysis\n const result = await consolidateWithLlm(context, llm, llmOptions);\n const candidates = llmResultToCandidates(result);\n\n log.debug(`[cmc] LLM consolidation produced ${candidates.length} rule(s) and ${result.preferences.length} preference(s)`);\n return candidates;\n } catch (error) {\n log.warn(`[cmc] consolidation failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return [];\n }\n}\n\n/**\n * Get LLM-synthesized preferences from causal trajectory analysis.\n * Returns formatted preference statements for recall injection.\n */\nexport async function synthesizeCausalPreferencesViaLlm(options: {\n memoryDir: string;\n causalTrajectoryStoreDir?: string;\n gatewayConfig?: GatewayConfig;\n gatewayAgentId?: string;\n modelChain?: AgentPersonaModelConfig;\n workspaceDir?: string;\n minTrajectories?: number;\n}): Promise<string | null> {\n try {\n const trajectories = await readAllTrajectories(options.memoryDir, options.causalTrajectoryStoreDir);\n if (trajectories.length < (options.minTrajectories ?? 2)) return null;\n\n const chainsDir = resolveChainsDir(options.memoryDir, options.causalTrajectoryStoreDir);\n const chainIndex = await readChainIndex(chainsDir);\n const context = formatCausalContext(trajectories, chainIndex);\n\n const llm = new FallbackLlmClient(options.gatewayConfig, {\n workspaceDir: options.workspaceDir,\n });\n const llmOptions = { agentId: options.gatewayAgentId, modelChain: options.modelChain };\n if (!llm.isAvailable(llmOptions)) return null;\n\n const result = await consolidateWithLlm(context, llm, llmOptions);\n if (result.preferences.length === 0 && result.rules.length === 0) return null;\n\n const lines: string[] = [\"## Behavioral Insights (from Causal Chain Analysis)\", \"\"];\n\n for (const pref of result.preferences) {\n lines.push(`- ${pref.statement}`);\n }\n\n for (const rule of result.rules) {\n lines.push(`- ${rule.content}`);\n }\n\n lines.push(\"\");\n return lines.join(\"\\n\");\n } catch (error) {\n log.warn(`[cmc] preference synthesis failed (non-fatal): ${error instanceof Error ? error.message : String(error)}`);\n return null;\n }\n}\n\n/**\n * Optional post-consolidation hook — materializes Codex-native memory artifacts\n * after a causal consolidation run. Guarded by `codexMaterializeMemories` and\n * `codexMaterializeOnConsolidation`. Returns `null` when disabled or when the\n * sentinel is missing (honors user hand-edits).\n *\n * Split from the orchestrator-owned flow so #378 avoids touching\n * orchestrator.ts while Wave 1 edits are in flight.\n */\nexport async function materializeAfterCausalConsolidation(options: {\n config: PluginConfig;\n namespace?: string;\n memories?: MemoryFile[];\n memoryDir?: string;\n codexHome?: string;\n rolloutSummaries?: RolloutSummaryInput[];\n now?: Date;\n}): Promise<MaterializeResult | null> {\n // Delegates to the shared post-consolidation helper — see\n // runPostConsolidationMaterialize in codex-materialize-runner.ts.\n return runPostConsolidationMaterialize(\"[cmc]\", options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,kBAAkB;AAO3B,OAAO,UAAU;AA0CjB,IAAM,yBAAyB,oBAAI,IAAI,CAAC,QAAQ,aAAa,YAAY,CAAC;AAY1E,eAAe,oBACb,WACA,0BACmC;AACnC,QAAM,OAAO,gCAAgC,WAAW,wBAAwB;AAChF,QAAM,kBAAkB,KAAK,KAAK,MAAM,cAAc;AAEtD,QAAM,QAAQ,MAAM,cAAc,eAAe,EAAE,MAAM,MAAM,CAAC,CAAa;AAC7E,QAAM,UAAoC,CAAC;AAE3C,aAAW,YAAY,OAAO;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,aAAa,QAAQ;AACvC,UAAI,SAAS,GAAG,KAAK,OAAO,IAAI,iBAAiB,UAAU;AACzD,gBAAQ,KAAK,GAAwC;AAAA,MACvD;AAAA,IACF,QAAQ;AAAA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AwB;AACtF,UAAM,aAAa,MAAM,eAAe,SAAS;AACjD,UAAM,UAAU,oBAAoB,cAAc,UAAU;AAE5D,UAAM,MAAM,IAAI,kBAAkB,QAAQ,eAAe;AAAA,MACvD,cAAc,QAAQ;AAAA,IACxB,CAAC;AACD,UAAM,aAAa,EAAE,SAAS,QAAQ,gBAAgB,YAAY,QAAQ,WAAW;AACrF,QAAI,CAAC,IAAI,YAAY,UAAU,EAAG,QAAO;AAEzC,UAAM,SAAS,MAAM,mBAAmB,SAAS,KAAK,UAAU;AAChE,QAAI,OAAO,YAAY,WAAW,KAAK,OAAO,MAAM,WAAW,EAAG,QAAO;AAEzE,UAAM,QAAkB,CAAC,uDAAuD,EAAE;AAElF,eAAW,QAAQ,OAAO,aAAa;AACrC,YAAM,KAAK,KAAK,KAAK,SAAS,EAAE;AAAA,IAClC;AAEA,eAAW,QAAQ,OAAO,OAAO;AAC/B,YAAM,KAAK,KAAK,KAAK,OAAO,EAAE;AAAA,IAChC;AAEA,UAAM,KAAK,EAAE;AACb,WAAO,MAAM,KAAK,IAAI;AAAA,EACxB,SAAS,OAAO;AACd,QAAI,KAAK,kDAAkD,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AACnH,WAAO;AAAA,EACT;AACF;AAWA,eAAsB,oCAAoC,SAQpB;AAGpC,SAAO,gCAAgC,SAAS,OAAO;AACzD;","names":[]}
@@ -0,0 +1,20 @@
1
+ // src/namespaces/path.ts
2
+ import path from "path";
3
+ function assertNamespacePathInsideRoot(root, candidate, namespace, label = "namespace path") {
4
+ const relative = path.relative(root, candidate);
5
+ if (relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative)) {
6
+ return;
7
+ }
8
+ throw new Error(`invalid ${label}: ${namespace}`);
9
+ }
10
+ function resolveNamespaceChildRoot(memoryDir, namespace, label = "namespace path") {
11
+ const namespaceRoot = path.resolve(memoryDir, "namespaces");
12
+ const candidate = path.resolve(namespaceRoot, namespace);
13
+ assertNamespacePathInsideRoot(namespaceRoot, candidate, namespace, label);
14
+ return candidate;
15
+ }
16
+
17
+ export {
18
+ resolveNamespaceChildRoot
19
+ };
20
+ //# sourceMappingURL=chunk-3UXOZBHV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/namespaces/path.ts"],"sourcesContent":["import path from \"node:path\";\n\nexport function assertNamespacePathInsideRoot(\n root: string,\n candidate: string,\n namespace: string,\n label = \"namespace path\",\n): void {\n const relative = path.relative(root, candidate);\n if (relative === \"\" || (!relative.startsWith(\"..\") && !path.isAbsolute(relative))) {\n return;\n }\n throw new Error(`invalid ${label}: ${namespace}`);\n}\n\nexport function resolveNamespaceChildRoot(\n memoryDir: string,\n namespace: string,\n label = \"namespace path\",\n): string {\n const namespaceRoot = path.resolve(memoryDir, \"namespaces\");\n const candidate = path.resolve(namespaceRoot, namespace);\n assertNamespacePathInsideRoot(namespaceRoot, candidate, namespace, label);\n return candidate;\n}\n"],"mappings":";AAAA,OAAO,UAAU;AAEV,SAAS,8BACd,MACA,WACA,WACA,QAAQ,kBACF;AACN,QAAM,WAAW,KAAK,SAAS,MAAM,SAAS;AAC9C,MAAI,aAAa,MAAO,CAAC,SAAS,WAAW,IAAI,KAAK,CAAC,KAAK,WAAW,QAAQ,GAAI;AACjF;AAAA,EACF;AACA,QAAM,IAAI,MAAM,WAAW,KAAK,KAAK,SAAS,EAAE;AAClD;AAEO,SAAS,0BACd,WACA,WACA,QAAQ,kBACA;AACR,QAAM,gBAAgB,KAAK,QAAQ,WAAW,YAAY;AAC1D,QAAM,YAAY,KAAK,QAAQ,eAAe,SAAS;AACvD,gCAA8B,eAAe,WAAW,WAAW,KAAK;AACxE,SAAO;AACT;","names":[]}
@@ -5,10 +5,13 @@ import {
5
5
  rejectSymlinkPath,
6
6
  renderFrontmatter,
7
7
  writeBundleFile
8
- } from "./chunk-M2BY5IZL.js";
8
+ } from "./chunk-PVV42HM4.js";
9
9
  import {
10
10
  parseOaiMemCitation
11
11
  } from "./chunk-D24OXEPB.js";
12
+ import {
13
+ resolveNamespaceChildRoot
14
+ } from "./chunk-3UXOZBHV.js";
12
15
  import {
13
16
  OKF_PROFILE_TYPE,
14
17
  StorageManager,
@@ -22,9 +25,8 @@ import {
22
25
  } from "./chunk-7RJUVTVF.js";
23
26
 
24
27
  // src/transfer/export-okf.ts
25
- import { rmSync } from "fs";
28
+ import { mkdirSync, rmSync } from "fs";
26
29
  import { mkdtemp } from "fs/promises";
27
- import os from "os";
28
30
  import path from "path";
29
31
  var OKF_LOG_TRUNCATION_MARKER = "<!-- okf-log-truncated -->";
30
32
  var DEFAULT_OKF_LOG_MAX_ENTRIES = 500;
@@ -51,15 +53,17 @@ function parseIncludeStatus(raw) {
51
53
  async function exportOkfBundle(opts) {
52
54
  const outDir = path.resolve(opts.outDir);
53
55
  rejectSymlinkPath(outDir);
56
+ const namespace = (opts.namespace ?? "").trim();
57
+ const memoryDir = namespace ? resolveNamespaceChildRoot(opts.memoryDir, namespace, "--namespace") : opts.memoryDir;
54
58
  const includeStatus = new Set(parseIncludeStatus(opts.includeStatus));
55
59
  const includeCategories = opts.includeCategories?.length ? new Set(opts.includeCategories) : null;
56
60
  const excludeTags = new Set(opts.excludeTags ?? []);
57
- const storage = new StorageManager(opts.memoryDir);
61
+ const storage = new StorageManager(memoryDir);
58
62
  const memories = await storage.readAllMemories();
59
63
  const included = [];
60
64
  let excluded = 0;
61
65
  for (const memory of memories) {
62
- const rel = toRel(memory.path, opts.memoryDir);
66
+ const rel = toRel(memory.path, memoryDir);
63
67
  if (!opts.includeWearables && rel.startsWith("wearables/")) {
64
68
  excluded += 1;
65
69
  continue;
@@ -79,16 +83,17 @@ async function exportOkfBundle(opts) {
79
83
  }
80
84
  included.push(memory);
81
85
  }
82
- included.sort((a, b) => toRel(a.path, opts.memoryDir).localeCompare(toRel(b.path, opts.memoryDir)));
83
- const staging = await mkdtemp(path.join(os.tmpdir(), "remnic-okf-export-"));
86
+ included.sort((a, b) => toRel(a.path, memoryDir).localeCompare(toRel(b.path, memoryDir)));
87
+ mkdirSync(path.dirname(outDir), { recursive: true });
88
+ const staging = await mkdtemp(path.join(path.dirname(outDir), ".remnic-okf-export-"));
84
89
  const byCategory = {};
85
90
  const idToRel = /* @__PURE__ */ new Map();
86
91
  for (const memory of included) {
87
- const rel = toRel(memory.path, opts.memoryDir);
92
+ const rel = toRel(memory.path, memoryDir);
88
93
  idToRel.set(memory.frontmatter.id, rel);
89
94
  }
90
95
  for (const memory of included) {
91
- const rel = toRel(memory.path, opts.memoryDir);
96
+ const rel = toRel(memory.path, memoryDir);
92
97
  const rendered = renderMemory(memory, rel, idToRel);
93
98
  writeBundleFile(staging, rel, rendered);
94
99
  const category = memory.frontmatter.category;
@@ -115,7 +120,7 @@ async function exportOkfBundle(opts) {
115
120
  const events = await storage.readAllMemoryLifecycleEvents();
116
121
  writeBundleFile(staging, "log.md", renderLog(events, idToRel, opts.logMaxEntries ?? DEFAULT_OKF_LOG_MAX_ENTRIES));
117
122
  }
118
- writeIndexes(staging, included, opts.memoryDir);
123
+ writeIndexes(staging, included, memoryDir);
119
124
  const lint = lintOkfDir(staging);
120
125
  const blocking = lint.findings.filter((f) => f.code !== "skipped_encrypted" && f.code !== "reserved_basename");
121
126
  if (blocking.length > 0) {
@@ -264,4 +269,4 @@ export {
264
269
  parseIncludeStatus,
265
270
  exportOkfBundle
266
271
  };
267
- //# sourceMappingURL=chunk-YYDOUOYM.js.map
272
+ //# sourceMappingURL=chunk-6H7JWYTC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transfer/export-okf.ts"],"sourcesContent":["import { mkdirSync, rmSync } from \"node:fs\";\nimport { mkdtemp } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { parseOaiMemCitation } from \"../citations.js\";\nimport { inferMemoryStatus } from \"../memory-lifecycle-ledger-utils.js\";\nimport { normalizeProjectionPreview } from \"../memory-projection-format.js\";\nimport { lintOkfDir } from \"../okf/lint.js\";\nimport { okfTypeForMemory, OKF_PROFILE_TYPE } from \"../okf/type-mapping.js\";\nimport { resolveNamespaceChildRoot } from \"../namespaces/path.js\";\nimport {\n OKF_EXPORT_VERSION,\n publishBundle,\n renderFrontmatter,\n rejectSymlinkPath,\n writeBundleFile,\n} from \"../okf/render.js\";\n// Re-exported for the existing `@remnic/core/export-okf` consumers and tests\n// (one public surface; the value itself now lives in okf/render.ts).\nexport { OKF_EXPORT_VERSION };\nimport { StorageManager } from \"../storage.js\";\nimport type { MemoryFile, MemoryLink, MemoryStatus } from \"../types.js\";\n\n// Shared bundle mechanics (frontmatter, publish, symlink guard, file write)\n// live in ../okf/render.ts — one source of truth for every OKF exporter.\nexport const OKF_LOG_TRUNCATION_MARKER = \"<!-- okf-log-truncated -->\";\nexport const DEFAULT_OKF_LOG_MAX_ENTRIES = 500;\n\nconst MEMORY_STATUSES: readonly MemoryStatus[] = [\n \"active\",\n \"pending_review\",\n \"rejected\",\n \"quarantined\",\n \"superseded\",\n \"archived\",\n \"forgotten\",\n];\n\nexport interface ExportOkfOptions {\n memoryDir: string;\n /**\n * Optional namespace segment. Resolved here, once, through the shared\n * containment guard: both CLI entry points used to join the raw operator\n * value onto `memoryDir/namespaces`, so `--namespace ../../..` escaped the\n * namespace root and exported an arbitrary tree (rule 9 — one resolver, not\n * a per-caller guard).\n */\n namespace?: string;\n outDir: string;\n includeStatus?: readonly string[];\n includeCategories?: readonly string[];\n excludeTags?: readonly string[];\n includeProfile?: boolean;\n includeWearables?: boolean;\n includeLog?: boolean;\n logMaxEntries?: number;\n force?: boolean;\n}\n\nexport interface ExportOkfResult {\n exported: number;\n excluded: number;\n byCategory: Record<string, number>;\n plaintextWarning: boolean;\n}\n\nexport function parseIncludeStatus(raw: unknown): MemoryStatus[] {\n const values = splitCsv(raw);\n if (values.length === 0) return [\"active\"];\n const allowed = new Set<string>(MEMORY_STATUSES);\n for (const value of values) {\n if (!allowed.has(value)) {\n throw new Error(`invalid --include-status ${value}; allowed: ${MEMORY_STATUSES.join(\", \")}`);\n }\n }\n return values as MemoryStatus[];\n}\n\nexport async function exportOkfBundle(opts: ExportOkfOptions): Promise<ExportOkfResult> {\n const outDir = path.resolve(opts.outDir);\n rejectSymlinkPath(outDir);\n const namespace = (opts.namespace ?? \"\").trim();\n const memoryDir = namespace\n ? resolveNamespaceChildRoot(opts.memoryDir, namespace, \"--namespace\")\n : opts.memoryDir;\n const includeStatus = new Set(parseIncludeStatus(opts.includeStatus));\n const includeCategories = opts.includeCategories?.length ? new Set(opts.includeCategories) : null;\n const excludeTags = new Set(opts.excludeTags ?? []);\n const storage = new StorageManager(memoryDir);\n const memories = await storage.readAllMemories();\n const included: MemoryFile[] = [];\n let excluded = 0;\n for (const memory of memories) {\n const rel = toRel(memory.path, memoryDir);\n if (!opts.includeWearables && rel.startsWith(\"wearables/\")) {\n excluded += 1;\n continue;\n }\n const status = inferMemoryStatus(memory.frontmatter, memory.path);\n if (!includeStatus.has(status)) {\n excluded += 1;\n continue;\n }\n if (includeCategories && !includeCategories.has(memory.frontmatter.category)) {\n excluded += 1;\n continue;\n }\n if ((memory.frontmatter.tags ?? []).some((tag) => excludeTags.has(tag))) {\n excluded += 1;\n continue;\n }\n included.push(memory);\n }\n included.sort((a, b) => toRel(a.path, memoryDir).localeCompare(toRel(b.path, memoryDir)));\n\n // Stage inside the destination's parent, not the OS temp dir: publishBundle\n // finishes with a rename, and a rename across filesystems fails with EXDEV\n // whenever --out lives on a different mount than /tmp.\n mkdirSync(path.dirname(outDir), { recursive: true });\n const staging = await mkdtemp(path.join(path.dirname(outDir), \".remnic-okf-export-\"));\n const byCategory: Record<string, number> = {};\n const idToRel = new Map<string, string>();\n for (const memory of included) {\n const rel = toRel(memory.path, memoryDir);\n idToRel.set(memory.frontmatter.id, rel);\n }\n for (const memory of included) {\n const rel = toRel(memory.path, memoryDir);\n const rendered = renderMemory(memory, rel, idToRel);\n writeBundleFile(staging, rel, rendered);\n const category = memory.frontmatter.category;\n byCategory[category] = (byCategory[category] ?? 0) + 1;\n }\n\n if (opts.includeProfile) {\n try {\n const profile = await storage.readProfile();\n if (profile) {\n writeBundleFile(\n staging,\n \"profile.md\",\n renderFrontmatter({\n type: OKF_PROFILE_TYPE,\n title: \"User Profile\",\n timestamp: new Date(0).toISOString(),\n }) + profile.replace(/^\\uFEFF/, \"\"),\n );\n }\n } catch {\n // Profile is optional even when requested.\n }\n }\n\n if (opts.includeLog) {\n const events = await storage.readAllMemoryLifecycleEvents();\n writeBundleFile(staging, \"log.md\", renderLog(events, idToRel, opts.logMaxEntries ?? DEFAULT_OKF_LOG_MAX_ENTRIES));\n }\n\n writeIndexes(staging, included, memoryDir);\n const lint = lintOkfDir(staging);\n const blocking = lint.findings.filter((f) => f.code !== \"skipped_encrypted\" && f.code !== \"reserved_basename\");\n if (blocking.length > 0) {\n rmSync(staging, { recursive: true, force: true });\n throw new Error(`OKF export failed lint: ${blocking.map((f) => `${f.file}: ${f.message}`).join(\"; \")}`);\n }\n\n publishBundle(staging, outDir, opts.force === true);\n return {\n exported: included.length,\n excluded,\n byCategory,\n plaintextWarning: true,\n };\n}\n\n\nfunction renderMemory(memory: MemoryFile, rel: string, idToRel: Map<string, string>): string {\n const fm = memory.frontmatter;\n const title = firstHeading(memory.content) ?? `${humanize(fm.category)} ${fm.created.slice(0, 10)}`;\n const type = fm.type ?? okfTypeForMemory(fm);\n const fields: Record<string, unknown> = {\n ...fm,\n type,\n title,\n description: normalizeProjectionPreview(memory.content),\n tags: fm.tags ?? [],\n timestamp: fm.updated,\n };\n if (fm.artifactType) fields.resource = rel;\n let body = memory.content.trim();\n const citation = parseOaiMemCitation(body);\n if (citation) {\n const start = body.indexOf(\"<oai-mem-citation>\");\n const end = body.indexOf(\"</oai-mem-citation>\");\n if (start >= 0 && end > start) {\n body = `${body.slice(0, start).trimEnd()}\\n\\n${body.slice(end + \"</oai-mem-citation>\".length).trimStart()}`.trim();\n }\n const lines = citation.entries.map((entry, index) => `${index + 1}. [${entry.path}](${entry.path})`);\n body = `${body}\\n\\n# Citations\\n\\n${lines.join(\"\\n\")}\\n`;\n }\n const links = fm.links ?? [];\n if (links.length > 0) {\n body += `\\n# Related\\n\\n${links.map((link) => renderRelated(link, idToRel)).join(\"\\n\")}\\n`;\n }\n return renderFrontmatter(fields) + body + (body.endsWith(\"\\n\") ? \"\" : \"\\n\");\n}\n\nfunction renderRelated(link: MemoryLink, idToRel: Map<string, string>): string {\n const target = idToRel.get(link.targetId) ?? link.targetId;\n const href = target.startsWith(\"/\") ? target : `/${target}`;\n return `- ${link.linkType}: [${link.targetId}](${href})`;\n}\n\nfunction writeIndexes(root: string, memories: MemoryFile[], memoryDir: string): void {\n const groups = new Map<string, MemoryFile[]>();\n for (const memory of memories) {\n const rel = toRel(memory.path, memoryDir);\n const dir = path.posix.dirname(rel);\n const key = dir === \".\" ? \"\" : dir.split(\"/\")[0] ?? \"\";\n const list = groups.get(key) ?? [];\n list.push(memory);\n groups.set(key, list);\n }\n const sections = [...groups.keys()].sort().map((key) => {\n const heading = key === \"\" ? \"Root\" : humanize(key);\n const lines = (groups.get(key) ?? [])\n .sort((a, b) => toRel(a.path, memoryDir).localeCompare(toRel(b.path, memoryDir)))\n .map((memory) => {\n const rel = toRel(memory.path, memoryDir);\n const title = firstHeading(memory.content) ?? memory.frontmatter.id;\n const description = normalizeProjectionPreview(memory.content);\n return `* [${title}](/${rel}) - ${description}`;\n });\n return `## ${heading}\\n\\n${lines.join(\"\\n\")}`;\n });\n writeBundleFile(root, \"index.md\", `---\\nokf_version: \"${OKF_EXPORT_VERSION}\"\\n---\\n\\n${sections.join(\"\\n\\n\")}\\n`);\n}\n\nfunction renderLog(\n events: Array<{ timestamp?: string; type?: string; action?: string; memoryId?: string }>,\n idToRel: Map<string, string>,\n maxEntries: number,\n): string {\n const sorted = [...events].sort((a, b) => String(b.timestamp ?? \"\").localeCompare(String(a.timestamp ?? \"\")));\n const truncated = sorted.length > maxEntries;\n const kept = sorted.slice(0, maxEntries);\n const byDay = new Map<string, typeof kept>();\n for (const event of kept) {\n const day = String(event.timestamp ?? \"\").slice(0, 10) || \"unknown\";\n const list = byDay.get(day) ?? [];\n list.push(event);\n byDay.set(day, list);\n }\n const days = [...byDay.keys()].sort((a, b) => b.localeCompare(a));\n const parts = [\"# Log\", \"\"];\n for (const day of days) {\n parts.push(`## ${day}`, \"\");\n for (const event of byDay.get(day) ?? []) {\n const action = boldAction(event.type ?? event.action ?? \"Update\");\n const id = event.memoryId;\n const rel = id ? idToRel.get(id) : undefined;\n const target = rel ? `[${id}](/${rel})` : id ?? \"\";\n parts.push(`- **${action}** ${target}`.trimEnd());\n }\n parts.push(\"\");\n }\n if (truncated) parts.push(OKF_LOG_TRUNCATION_MARKER, \"\");\n return `${parts.join(\"\\n\")}\\n`;\n}\n\nfunction boldAction(raw: string): string {\n const lower = raw.toLowerCase();\n if (lower.includes(\"create\") || lower.includes(\"add\")) return \"Creation\";\n if (lower.includes(\"deprecat\") || lower.includes(\"delete\") || lower.includes(\"archiv\")) return \"Deprecation\";\n return \"Update\";\n}\n\n\nfunction firstHeading(content: string): string | undefined {\n for (const line of content.split(\"\\n\")) {\n const match = /^#\\s+(.+)$/.exec(line.trim());\n if (match) return match[1]!.trim();\n }\n return undefined;\n}\n\nfunction humanize(value: string): string {\n return value.replace(/[_-]/g, \" \").replace(/\\b\\w/g, (ch) => ch.toUpperCase());\n}\n\n\n\nfunction splitCsv(raw: unknown): string[] {\n if (raw === undefined || raw === null || raw === \"\") return [];\n const parts = Array.isArray(raw) ? raw.map(String) : String(raw).split(\",\");\n return parts.map((part) => part.trim()).filter((part) => part.length > 0);\n}\n\nfunction toRel(abs: string, root: string): string {\n return path.relative(path.resolve(root), path.resolve(abs)).split(path.sep).join(\"/\");\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,cAAc;AAClC,SAAS,eAAe;AACxB,OAAO,UAAU;AAuBV,IAAM,4BAA4B;AAClC,IAAM,8BAA8B;AAE3C,IAAM,kBAA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G,YAAY,CAAC;AAC9E;AAIA,SAAS,SAAS,KAAwB;AACxC,MAAI,QAAQ,UAAa,QAAQ,QAAQ,QAAQ,GAAI,QAAO,CAAC;AAC7D,QAAM,QAAQ,MAAM,QAAQ,GAAG,IAAI,IAAI,IAAI,MAAM,IAAI,OAAO,GAAG,EAAE,MAAM,GAAG;AAC1E,SAAO,MAAM,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EAAE,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC;AAC1E;AAEA,SAAS,MAAM,KAAa,MAAsB;AAChD,SAAO,KAAK,SAAS,KAAK,QAAQ,IAAI,GAAG,KAAK,QAAQ,GAAG,CAAC,EAAE,MAAM,KAAK,GAAG,EAAE,KAAK,GAAG;AACtF;","names":[]}
@@ -32,7 +32,7 @@ import {
32
32
  import {
33
33
  CompoundingEngine,
34
34
  defaultTierMigrationCycleBudget
35
- } from "./chunk-VSQG4AXL.js";
35
+ } from "./chunk-PWVRMD37.js";
36
36
  import {
37
37
  SharedContextManager
38
38
  } from "./chunk-VI637ILW.js";
@@ -216,7 +216,7 @@ import {
216
216
  getWearableConnector,
217
217
  listWearableConnectors,
218
218
  screenCandidateFact
219
- } from "./chunk-NR36NW24.js";
219
+ } from "./chunk-UWOA5L6N.js";
220
220
  import {
221
221
  normalizeReplaySessionKey
222
222
  } from "./chunk-AJVLDJU6.js";
@@ -284,7 +284,7 @@ import {
284
284
  materializeAfterSemanticConsolidation,
285
285
  parseConsolidationResponse,
286
286
  parseOperatorAwareConsolidationResponse
287
- } from "./chunk-TXCLDIXJ.js";
287
+ } from "./chunk-K6PWPC7O.js";
288
288
  import {
289
289
  semanticChunkContent
290
290
  } from "./chunk-2GBFKHBZ.js";
@@ -29309,4 +29309,4 @@ export {
29309
29309
  blendGraphExpandedRecallScore,
29310
29310
  Orchestrator
29311
29311
  };
29312
- //# sourceMappingURL=chunk-KWVXCRFZ.js.map
29312
+ //# sourceMappingURL=chunk-BCM6ZAJ3.js.map
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-5JMAGU26.js";
6
6
  import {
7
7
  runPostConsolidationMaterialize
8
- } from "./chunk-ZPZLGN4Y.js";
8
+ } from "./chunk-XZ7QLOTJ.js";
9
9
  import {
10
10
  isSemanticConsolidationLlmOperator
11
11
  } from "./chunk-G7D6GZ5J.js";
@@ -220,4 +220,4 @@ export {
220
220
  buildExtensionsBlockForConsolidation,
221
221
  materializeAfterSemanticConsolidation
222
222
  };
223
- //# sourceMappingURL=chunk-TXCLDIXJ.js.map
223
+ //# sourceMappingURL=chunk-K6PWPC7O.js.map
@@ -96,6 +96,7 @@ function lintOkfDir(memoryDir) {
96
96
  }
97
97
 
98
98
  // src/okf/render.ts
99
+ import { randomUUID } from "crypto";
99
100
  import { lstatSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from "fs";
100
101
  import path2 from "path";
101
102
  var OKF_EXPORT_VERSION = "0.1";
@@ -143,6 +144,7 @@ function publishBundle(staging, outDir, force) {
143
144
  try {
144
145
  const stat = lstatSync(outDir);
145
146
  if (stat.isSymbolicLink()) throw new Error(`--out must not be a symlink: ${outDir}`);
147
+ if (!stat.isDirectory()) throw new Error(`--out exists and is not a directory: ${outDir}`);
146
148
  exists = true;
147
149
  const entries = readdirSync(outDir).filter((name) => name !== "." && name !== "..");
148
150
  if (entries.length > 0 && !force) {
@@ -154,7 +156,7 @@ function publishBundle(staging, outDir, force) {
154
156
  }
155
157
  mkdirSync(path2.dirname(outDir), { recursive: true });
156
158
  if (exists && force) {
157
- const backup = `${outDir}.okf-prev`;
159
+ const backup = `${outDir}.okf-prev-${randomUUID().slice(0, 8)}`;
158
160
  try {
159
161
  renameSync(outDir, backup);
160
162
  } catch {
@@ -167,6 +169,7 @@ function publishBundle(staging, outDir, force) {
167
169
  } catch (err) {
168
170
  try {
169
171
  renameSync(backup, outDir);
172
+ rmSync(staging, { recursive: true, force: true });
170
173
  } catch {
171
174
  }
172
175
  throw err;
@@ -199,4 +202,4 @@ export {
199
202
  publishBundle,
200
203
  rejectSymlinkPath
201
204
  };
202
- //# sourceMappingURL=chunk-M2BY5IZL.js.map
205
+ //# sourceMappingURL=chunk-PVV42HM4.js.map