@remnic/core 1.1.8 → 1.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-cli.js +44 -41
- package/dist/access-cli.js.map +1 -1
- package/dist/access-http.d.ts +8 -7
- package/dist/access-http.js +20 -17
- package/dist/access-mcp.d.ts +8 -7
- package/dist/access-mcp.js +19 -16
- package/dist/{access-service-C0Rkioec.d.ts → access-service-BTTNyo1i.d.ts} +11 -9
- package/dist/access-service.d.ts +8 -7
- package/dist/access-service.js +18 -15
- package/dist/active-memory-bridge.d.ts +2 -1
- package/dist/active-recall.d.ts +3 -2
- package/dist/active-recall.js +2 -2
- package/dist/active-recall.js.map +1 -1
- package/dist/behavior-learner.d.ts +2 -1
- package/dist/behavior-signals.d.ts +2 -1
- package/dist/bootstrap.d.ts +7 -6
- package/dist/briefing.d.ts +3 -2
- package/dist/briefing.js +6 -6
- package/dist/buffer-surprise-report.d.ts +2 -1
- package/dist/buffer.d.ts +3 -2
- package/dist/calibration.d.ts +4 -1
- package/dist/calibration.js +10 -5
- package/dist/calibration.js.map +1 -1
- package/dist/causal-behavior.d.ts +2 -1
- package/dist/causal-consolidation.d.ts +5 -2
- package/dist/causal-consolidation.js +17 -11
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/{chunk-AV2WSYZY.js → chunk-2YMTO4ZJ.js} +2 -2
- package/dist/{chunk-SYWJJTNL.js → chunk-363MWCD3.js} +42 -42
- package/dist/{chunk-65ZPH7QA.js → chunk-36CTNQY7.js} +7 -7
- package/dist/{chunk-GZCUW5IC.js → chunk-3IQ2TR4N.js} +5 -5
- package/dist/chunk-3IQ2TR4N.js.map +1 -0
- package/dist/{chunk-TUFG6VXY.js → chunk-4DWOBS2A.js} +2 -2
- package/dist/chunk-4DWOBS2A.js.map +1 -0
- package/dist/{chunk-SRIDOT64.js → chunk-4DXC6HQQ.js} +6 -4
- package/dist/chunk-4DXC6HQQ.js.map +1 -0
- package/dist/{chunk-L2IO2QPY.js → chunk-4IS4SXIQ.js} +17 -13
- package/dist/chunk-4IS4SXIQ.js.map +1 -0
- package/dist/{chunk-RJSVRPNU.js → chunk-57QNCUEZ.js} +19 -12
- package/dist/chunk-57QNCUEZ.js.map +1 -0
- package/dist/{chunk-GRDDGNYQ.js → chunk-5GCNE7CN.js} +105 -499
- package/dist/chunk-5GCNE7CN.js.map +1 -0
- package/dist/{chunk-LOBRX7VD.js → chunk-5UM2VJ6D.js} +12 -1
- package/dist/chunk-5UM2VJ6D.js.map +1 -0
- package/dist/{chunk-XVOIMCVW.js → chunk-6XA7UN4Z.js} +2 -2
- package/dist/{chunk-QJZ77K7F.js → chunk-6Z6UH6TK.js} +26 -12
- package/dist/chunk-6Z6UH6TK.js.map +1 -0
- package/dist/{chunk-ODWDQNRE.js → chunk-7SI52C65.js} +7 -3
- package/dist/chunk-7SI52C65.js.map +1 -0
- package/dist/{chunk-FIXIX6DE.js → chunk-C5HUWVH2.js} +33 -43
- package/dist/chunk-C5HUWVH2.js.map +1 -0
- package/dist/{chunk-NN3TS5BM.js → chunk-D54LZC5L.js} +4 -4
- package/dist/{chunk-KNQ5YJTO.js → chunk-ERUDW6DU.js} +209 -1
- package/dist/chunk-ERUDW6DU.js.map +1 -0
- package/dist/{chunk-E27HOXMX.js → chunk-EYNQTST2.js} +2 -2
- package/dist/chunk-FVQJYWH7.js +52 -0
- package/dist/chunk-FVQJYWH7.js.map +1 -0
- package/dist/{chunk-3FPTCC3Z.js → chunk-GVPWB7EY.js} +2 -2
- package/dist/chunk-HJYHRE4S.js +647 -0
- package/dist/chunk-HJYHRE4S.js.map +1 -0
- package/dist/{chunk-SWRJFKYW.js → chunk-I6BQZSML.js} +5 -5
- package/dist/chunk-IBX3VFOM.js +446 -0
- package/dist/chunk-IBX3VFOM.js.map +1 -0
- package/dist/{chunk-STB3GUYU.js → chunk-KBYWQWSB.js} +8 -8
- package/dist/chunk-KWBPHZUU.js +83 -0
- package/dist/chunk-KWBPHZUU.js.map +1 -0
- package/dist/{chunk-MYH2IBSP.js → chunk-LIO5X3CM.js} +3 -3
- package/dist/{chunk-XGX4TUF6.js → chunk-MCC6KDQF.js} +5 -5
- package/dist/{chunk-4KAN3GZ3.js → chunk-NN2DKE4T.js} +1 -1
- package/dist/chunk-NN2DKE4T.js.map +1 -0
- package/dist/{chunk-R2XRID2N.js → chunk-NN3LPQ5D.js} +5 -5
- package/dist/chunk-NN3LPQ5D.js.map +1 -0
- package/dist/{chunk-WXPPM426.js → chunk-O4XJUPSF.js} +2 -2
- package/dist/{chunk-WSZIHQBK.js → chunk-P77UEOU2.js} +4 -1
- package/dist/{chunk-WSZIHQBK.js.map → chunk-P77UEOU2.js.map} +1 -1
- package/dist/{chunk-RLV2F337.js → chunk-PB5KW5PL.js} +2 -2
- package/dist/{chunk-S5SQDIF5.js → chunk-PHNGXFQ6.js} +7 -5
- package/dist/chunk-PHNGXFQ6.js.map +1 -0
- package/dist/{chunk-FEMOX5AD.js → chunk-QR3C7BKQ.js} +7 -7
- package/dist/chunk-QR3C7BKQ.js.map +1 -0
- package/dist/{chunk-ETA2JXP5.js → chunk-RXTFCYQF.js} +2 -2
- package/dist/{chunk-Q7FJ5ZHM.js → chunk-S3IP6R6K.js} +8 -2
- package/dist/{chunk-Q7FJ5ZHM.js.map → chunk-S3IP6R6K.js.map} +1 -1
- package/dist/{chunk-3LCWFNVS.js → chunk-SKE7JYKA.js} +2 -2
- package/dist/{chunk-T65SHTJP.js → chunk-VQXK37XA.js} +1 -1
- package/dist/chunk-VQXK37XA.js.map +1 -0
- package/dist/{chunk-DWMXVUGO.js → chunk-VX2IUQFE.js} +98 -10
- package/dist/chunk-VX2IUQFE.js.map +1 -0
- package/dist/{chunk-KHJRMWO4.js → chunk-WGK4VHGP.js} +84 -22
- package/dist/chunk-WGK4VHGP.js.map +1 -0
- package/dist/{chunk-4IT6WL23.js → chunk-WTFWLUSX.js} +2 -2
- package/dist/{chunk-67YLUWLG.js → chunk-XJKFSSDW.js} +3 -3
- package/dist/chunk-XJKFSSDW.js.map +1 -0
- package/dist/{chunk-ASIQZXYO.js → chunk-XMVFHBHT.js} +2 -2
- package/dist/{chunk-Q5TJRAGE.js → chunk-Y5KDIOKF.js} +3 -3
- package/dist/{chunk-FCGWNWG4.js → chunk-Z5S5HNGY.js} +31 -29
- package/dist/chunk-Z5S5HNGY.js.map +1 -0
- package/dist/{chunk-OJMD2LIW.js → chunk-ZL4S7ARC.js} +3 -3
- package/dist/{cli-CIATRu8o.d.ts → cli-BrEwQTnW.d.ts} +4 -4
- package/dist/cli.d.ts +9 -8
- package/dist/cli.js +33 -31
- package/dist/codex-cli-fallback.d.ts +44 -0
- package/dist/codex-cli-fallback.js +12 -0
- package/dist/{codex-materialize-xVqbEmcm.d.ts → codex-materialize-CQlLTzke.d.ts} +1 -1
- package/dist/compression-optimizer.d.ts +2 -1
- package/dist/config.d.ts +2 -1
- package/dist/config.js +1 -1
- package/dist/consolidation-provenance-check.d.ts +3 -2
- package/dist/consolidation-undo.d.ts +3 -2
- package/dist/day-summary.d.ts +2 -1
- package/dist/day-summary.js +1 -1
- package/dist/delinearize.d.ts +2 -1
- package/dist/direct-answer-wiring.d.ts +2 -1
- package/dist/direct-answer.d.ts +2 -1
- package/dist/embedding-fallback.d.ts +2 -1
- package/dist/{engine-MEAYUA7A.js → engine-FOC3IJLA.js} +7 -7
- package/dist/entity-retrieval.d.ts +3 -2
- package/dist/entity-retrieval.js +6 -6
- package/dist/entity-schema.d.ts +2 -1
- package/dist/explicit-capture.d.ts +7 -6
- package/dist/explicit-capture.js +2 -2
- package/dist/explicit-cue-recall.js +1 -1
- package/dist/extraction-judge-telemetry.d.ts +2 -1
- package/dist/extraction-judge-training.d.ts +2 -1
- package/dist/extraction-judge.d.ts +2 -1
- package/dist/extraction.d.ts +2 -1
- package/dist/extraction.js +10 -8
- package/dist/fallback-llm.d.ts +8 -1
- package/dist/fallback-llm.js +5 -3
- package/dist/identity-continuity.d.ts +2 -1
- package/dist/importance.d.ts +2 -1
- package/dist/index-1qIcnbG1.d.ts +34 -0
- package/dist/index.d.ts +15 -13
- package/dist/index.js +175 -168
- package/dist/index.js.map +1 -1
- package/dist/intent.d.ts +2 -1
- package/dist/lifecycle.d.ts +2 -1
- package/dist/live-connectors-runner.d.ts +2 -1
- package/dist/live-connectors-runner.js +2 -2
- package/dist/local-llm.d.ts +2 -1
- package/dist/local-llm.js +1 -1
- package/dist/memory-action-policy.d.ts +2 -1
- package/dist/memory-cache.d.ts +2 -1
- package/dist/{memory-governance-G3XODEXW.js → memory-governance-F3QOJGEY.js} +7 -7
- package/dist/memory-lifecycle-ledger-utils.d.ts +2 -1
- package/dist/{memory-projection-store-lCzmu4JX.d.ts → memory-projection-store-CY8TU40w.d.ts} +1 -1
- package/dist/memory-projection-store.d.ts +3 -2
- package/dist/memory-projection-store.js +1 -1
- package/dist/memory-worth-outcomes.d.ts +3 -2
- package/dist/{migrate-from-identity-anchor-TTEDEJGX.js → migrate-from-identity-anchor-G27MCD6A.js} +2 -2
- package/dist/model-registry.js +1 -1
- package/dist/models-json.d.ts +2 -1
- package/dist/models-json.js +1 -1
- package/dist/native-knowledge.d.ts +2 -1
- package/dist/objective-state-writers.d.ts +23 -1
- package/dist/objective-state-writers.js +10 -306
- package/dist/objective-state-writers.js.map +1 -1
- package/dist/objective-state.d.ts +7 -1
- package/dist/objective-state.js +3 -1
- package/dist/operator-toolkit.d.ts +3 -2
- package/dist/operator-toolkit.js +11 -11
- package/dist/opik-exporter.js +2 -2
- package/dist/opik-exporter.js.map +1 -1
- package/dist/{orchestrator-CvUYwuaL.d.ts → orchestrator-6IvQ-Phj.d.ts} +6 -5
- package/dist/orchestrator.d.ts +7 -6
- package/dist/orchestrator.js +37 -35
- package/dist/patterns-cli.d.ts +2 -1
- package/dist/{peers-6OSQ3NK6.js → peers-HCVGHMAE.js} +3 -3
- package/dist/peers-HCVGHMAE.js.map +1 -0
- package/dist/policy-runtime.d.ts +2 -1
- package/dist/{port-BkWL7hqo.d.ts → port-B6VEDIkC.d.ts} +7 -1
- package/dist/qmd-recall-cache.d.ts +3 -2
- package/dist/qmd.d.ts +4 -2
- package/dist/qmd.js +1 -1
- package/dist/recall-disclosure-escalation.d.ts +2 -1
- package/dist/recall-explain-renderer.d.ts +2 -1
- package/dist/recall-explain-renderer.js +3 -3
- package/dist/recall-state.d.ts +2 -1
- package/dist/recall-tag-filter.d.ts +2 -1
- package/dist/recall-xray-cli.d.ts +2 -1
- package/dist/recall-xray-cli.js +4 -4
- package/dist/recall-xray-renderer.d.ts +2 -1
- package/dist/recall-xray-renderer.js +3 -3
- package/dist/recall-xray.d.ts +2 -1
- package/dist/recall-xray.js +2 -2
- package/dist/resolve-auth-token.d.ts +2 -1
- package/dist/resolve-provider-secret.d.ts +2 -1
- package/dist/resolve-provider-secret.js +3 -1
- package/dist/resume-bundles.js +4 -4
- package/dist/retrieval-agents.d.ts +3 -2
- package/dist/retrieval-tiers.d.ts +2 -1
- package/dist/sanitize.js +1 -1
- package/dist/schemas.d.ts +22 -22
- package/dist/{semantic-consolidation-CGiH52qa.d.ts → semantic-consolidation-ByBXb-sf.d.ts} +2 -2
- package/dist/semantic-consolidation.d.ts +4 -3
- package/dist/semantic-consolidation.js +6 -6
- package/dist/semantic-rule-promotion.js +6 -6
- package/dist/semantic-rule-verifier.d.ts +2 -1
- package/dist/semantic-rule-verifier.js +6 -6
- package/dist/session-observer-bands.d.ts +2 -1
- package/dist/session-observer-state.d.ts +2 -1
- package/dist/signal.d.ts +2 -1
- package/dist/source-attribution.d.ts +1 -1
- package/dist/source-attribution.js +1 -1
- package/dist/storage.d.ts +3 -2
- package/dist/storage.js +5 -5
- package/dist/summarizer.d.ts +2 -1
- package/dist/summarizer.js +8 -6
- package/dist/summary-snapshot.d.ts +2 -1
- package/dist/temporal-supersession.d.ts +3 -2
- package/dist/temporal-validity.d.ts +2 -1
- package/dist/threading.d.ts +2 -1
- package/dist/tier-migration.d.ts +4 -3
- package/dist/tier-routing.d.ts +2 -1
- package/dist/topics.d.ts +2 -1
- package/dist/transcript.d.ts +2 -1
- package/dist/types.d.ts +2693 -1
- package/dist/types.js +1 -1
- package/dist/utility-runtime.d.ts +2 -1
- package/dist/verified-recall.js +6 -6
- package/package.json +1 -1
- package/dist/chunk-4KAN3GZ3.js.map +0 -1
- package/dist/chunk-67YLUWLG.js.map +0 -1
- package/dist/chunk-DWMXVUGO.js.map +0 -1
- package/dist/chunk-FCGWNWG4.js.map +0 -1
- package/dist/chunk-FEMOX5AD.js.map +0 -1
- package/dist/chunk-FIXIX6DE.js.map +0 -1
- package/dist/chunk-GRDDGNYQ.js.map +0 -1
- package/dist/chunk-GZCUW5IC.js.map +0 -1
- package/dist/chunk-KHJRMWO4.js.map +0 -1
- package/dist/chunk-KNQ5YJTO.js.map +0 -1
- package/dist/chunk-L2IO2QPY.js.map +0 -1
- package/dist/chunk-LOBRX7VD.js.map +0 -1
- package/dist/chunk-M62O4P4T.js +0 -41
- package/dist/chunk-M62O4P4T.js.map +0 -1
- package/dist/chunk-ODWDQNRE.js.map +0 -1
- package/dist/chunk-QJZ77K7F.js.map +0 -1
- package/dist/chunk-R2XRID2N.js.map +0 -1
- package/dist/chunk-RJSVRPNU.js.map +0 -1
- package/dist/chunk-S5SQDIF5.js.map +0 -1
- package/dist/chunk-SRIDOT64.js.map +0 -1
- package/dist/chunk-T65SHTJP.js.map +0 -1
- package/dist/chunk-TUFG6VXY.js.map +0 -1
- package/dist/types-H85grL1f.d.ts +0 -2714
- /package/dist/{chunk-AV2WSYZY.js.map → chunk-2YMTO4ZJ.js.map} +0 -0
- /package/dist/{chunk-SYWJJTNL.js.map → chunk-363MWCD3.js.map} +0 -0
- /package/dist/{chunk-65ZPH7QA.js.map → chunk-36CTNQY7.js.map} +0 -0
- /package/dist/{chunk-XVOIMCVW.js.map → chunk-6XA7UN4Z.js.map} +0 -0
- /package/dist/{chunk-NN3TS5BM.js.map → chunk-D54LZC5L.js.map} +0 -0
- /package/dist/{chunk-E27HOXMX.js.map → chunk-EYNQTST2.js.map} +0 -0
- /package/dist/{chunk-3FPTCC3Z.js.map → chunk-GVPWB7EY.js.map} +0 -0
- /package/dist/{chunk-SWRJFKYW.js.map → chunk-I6BQZSML.js.map} +0 -0
- /package/dist/{chunk-STB3GUYU.js.map → chunk-KBYWQWSB.js.map} +0 -0
- /package/dist/{chunk-MYH2IBSP.js.map → chunk-LIO5X3CM.js.map} +0 -0
- /package/dist/{chunk-XGX4TUF6.js.map → chunk-MCC6KDQF.js.map} +0 -0
- /package/dist/{chunk-WXPPM426.js.map → chunk-O4XJUPSF.js.map} +0 -0
- /package/dist/{chunk-RLV2F337.js.map → chunk-PB5KW5PL.js.map} +0 -0
- /package/dist/{chunk-ETA2JXP5.js.map → chunk-RXTFCYQF.js.map} +0 -0
- /package/dist/{chunk-3LCWFNVS.js.map → chunk-SKE7JYKA.js.map} +0 -0
- /package/dist/{chunk-4IT6WL23.js.map → chunk-WTFWLUSX.js.map} +0 -0
- /package/dist/{chunk-ASIQZXYO.js.map → chunk-XMVFHBHT.js.map} +0 -0
- /package/dist/{chunk-Q5TJRAGE.js.map → chunk-Y5KDIOKF.js.map} +0 -0
- /package/dist/{chunk-OJMD2LIW.js.map → chunk-ZL4S7ARC.js.map} +0 -0
- /package/dist/{engine-MEAYUA7A.js.map → codex-cli-fallback.js.map} +0 -0
- /package/dist/{memory-governance-G3XODEXW.js.map → engine-FOC3IJLA.js.map} +0 -0
- /package/dist/{migrate-from-identity-anchor-TTEDEJGX.js.map → memory-governance-F3QOJGEY.js.map} +0 -0
- /package/dist/{peers-6OSQ3NK6.js.map → migrate-from-identity-anchor-G27MCD6A.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/peers/migrate-from-identity-anchor.ts","../src/peers/storage.ts","../src/peers/types.ts"],"sourcesContent":["/**\n * Identity-anchor → peer-registry migration — issue #679 PR 5/5.\n *\n * Reads the legacy `identity/identity-anchor.md` file (written by\n * `StorageManager.writeIdentityAnchor`) and the `IDENTITY.md`\n * reflections file, then seeds the peer registry with a `self` peer\n * whose `peers/self/identity.md` kernel captures the relevant\n * source material.\n *\n * Design principles:\n *\n * 1. **Idempotent** — if `peers/self/identity.md` already exists this\n * function returns `{ skipped: true }` without overwriting it. The\n * second-run guarantee prevents accidental double-migration and\n * makes `remnic peer migrate` safe to run in CI / post-install hooks.\n *\n * 2. **Non-destructive** — the legacy files are never deleted. The\n * operator is responsible for archive / clean-up after verifying the\n * migration result. Legacy `engram.identity_anchor_*` MCP tools\n * continue to work against the on-disk anchor file.\n *\n * 3. **Dry-run** — when `options.dryRun` is `true` the function\n * computes the proposed `Peer` record and returns it alongside a\n * `{ dryRun: true }` marker, without writing anything to disk.\n *\n * 4. **Transparent** — the return value always includes the full\n * proposed `Peer` so callers can print what was (or would be) written.\n *\n * ## Source data\n *\n * The migrator reads two optional legacy sources:\n *\n * - `{memoryDir}/identity/identity-anchor.md` — structured sections\n * (`## Identity Traits`, `## Communication Preferences`, etc.) written\n * by `identityAnchorUpdate`. When present, the full content is\n * embedded in `peer.notes` under a clearly labelled subsection.\n *\n * - `{memoryDir}/IDENTITY.md` — free-form reflection entries appended\n * by the extraction engine. When present it is summarised as\n * a second subsection of `peer.notes`.\n *\n * If neither file exists the `self` peer is still created with sensible\n * defaults so that the peer registry is bootstrapped for fresh installs.\n *\n * ## Path safety\n *\n * All file reads use `path.join` relative to the caller-supplied\n * `memoryDir`. The migration never follows symlinks for the source files\n * (uses `lstat` to detect + skip them). Writes go through the standard\n * `writePeer` helper which enforces all path-traversal and symlink guards.\n */\n\nimport { promises as fs, constants as fsConstants } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { readPeer, writePeer, PEERS_DIR_NAME } from \"./storage.js\";\nimport type { Peer } from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────────────\n// Public types\n// ──────────────────────────────────────────────────────────────────────────────\n\n/** Options for `migrateFromIdentityAnchor`. */\nexport interface MigrateFromIdentityAnchorOptions {\n /**\n * Memory directory (same value as `config.memoryDir`). All source and\n * destination paths are resolved relative to this root.\n */\n memoryDir: string;\n\n /**\n * When `true`, compute and return the proposed peer record without\n * writing anything to disk. The `written` and `skipped` flags in the\n * result will both be `false`; the `peer` field carries the proposed\n * record.\n */\n dryRun?: boolean;\n\n /**\n * Optional override for the `self` peer's display name. Defaults to\n * `\"Self\"`.\n */\n displayName?: string;\n\n /**\n * Optional ISO-8601 timestamp to use as `createdAt`. When omitted the\n * current time is used.\n */\n createdAt?: string;\n}\n\n/** Result returned by `migrateFromIdentityAnchor`. */\nexport interface MigrateFromIdentityAnchorResult {\n /**\n * The peer record that was (or would be) written for `peers/self/`.\n * Always present regardless of `skipped` or `dryRun`.\n */\n peer: Peer;\n\n /**\n * `true` when the migration wrote `peers/self/identity.md` to disk.\n * `false` when `dryRun` is set or the file already existed (`skipped`).\n */\n written: boolean;\n\n /**\n * `true` when an existing `peers/self/identity.md` was detected and\n * the migration was a no-op. When `skipped` is `true`, `written` is\n * always `false`.\n */\n skipped: boolean;\n\n /**\n * `true` when `options.dryRun` was set. No files were written; the\n * `peer` field holds the proposed record.\n */\n dryRun: boolean;\n\n /**\n * The identity-anchor source file path that was read (if found).\n * `null` when the file did not exist or was a symlink (skipped).\n */\n identityAnchorSource: string | null;\n\n /**\n * The `IDENTITY.md` source file path that was read (if found).\n * `null` when the file did not exist or was a symlink (skipped).\n */\n identityMdSource: string | null;\n}\n\n// ──────────────────────────────────────────────────────────────────────────────\n// Internal helpers\n// ──────────────────────────────────────────────────────────────────────────────\n\n/**\n * Read a legacy source file with the same security posture as the peer storage\n * module:\n *\n * 1. **Parent-directory symlink rejection** — lstat the parent directory and\n * return null if it is a symlink. This closes the case where e.g.\n * `memoryDir/identity/` is itself a symlink pointing outside `memoryDir`.\n *\n * 2. **Kernel-level O_NOFOLLOW** — open the file with `O_NOFOLLOW` so the\n * kernel atomically rejects a symlink at the final path component. This\n * eliminates the TOCTOU race between a separate lstat check and the\n * subsequent read that `safeReadLegacyFile` previously had.\n *\n * Returns `{ content, filePath }` on success, or `{ content: null, filePath: null }`\n * when the file is missing, is a symlink, the parent is a symlink, or the\n * path is not a regular file. Re-throws unexpected I/O errors (EACCES, EIO,\n * etc.) so the caller can surface real filesystem problems.\n */\nasync function safeReadLegacyFile(\n filePath: string,\n): Promise<{ content: string; filePath: string } | { content: null; filePath: null }> {\n // 1. Reject a symlinked parent directory.\n const parent = path.dirname(filePath);\n try {\n const parentStat = await fs.lstat(parent);\n if (parentStat.isSymbolicLink()) {\n return { content: null, filePath: null };\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { content: null, filePath: null };\n }\n throw err;\n }\n\n // 2. Open with O_NOFOLLOW so the kernel refuses a symlink at the target\n // path, atomically closing the lstat-then-read TOCTOU window.\n let fh: import(\"node:fs/promises\").FileHandle;\n try {\n fh = await fs.open(filePath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n // ENOENT — file does not exist; ELOOP — O_NOFOLLOW detected a symlink.\n if (code === \"ENOENT\" || code === \"ELOOP\" || code === \"ENOTDIR\") {\n return { content: null, filePath: null };\n }\n throw err;\n }\n\n try {\n // Verify it is a regular file (not a directory, FIFO, device, etc.).\n const stat = await fh.stat();\n if (!stat.isFile()) {\n return { content: null, filePath: null };\n }\n const content = await fh.readFile(\"utf8\");\n return { content, filePath };\n } finally {\n await fh.close();\n }\n}\n\n/**\n * Build the `notes` markdown body for the `self` peer from the two\n * optional legacy sources.\n *\n * The resulting notes are kept intentionally terse — the peer kernel is\n * meant to hold stable identity facts, not a full dump of every reflection\n * entry. We label the sections clearly so operators know exactly what came\n * from where.\n */\nfunction buildSelfNotes(\n anchorContent: string | null,\n identityMdContent: string | null,\n): string | undefined {\n const parts: string[] = [];\n\n if (anchorContent !== null && anchorContent.trim().length > 0) {\n parts.push(\n \"## Migrated from identity-anchor.md\\n\\n\" + anchorContent.trim(),\n );\n }\n\n if (identityMdContent !== null && identityMdContent.trim().length > 0) {\n // IDENTITY.md can be quite long. Embed it as a labelled section so the\n // operator can prune it manually after migration rather than losing data.\n parts.push(\n \"## Migrated from IDENTITY.md\\n\\n\" + identityMdContent.trim(),\n );\n }\n\n if (parts.length === 0) return undefined;\n return parts.join(\"\\n\\n\");\n}\n\n// ──────────────────────────────────────────────────────────────────────────────\n// Public API\n// ──────────────────────────────────────────────────────────────────────────────\n\n/**\n * Migrate legacy identity-anchor data into `peers/self/identity.md`.\n *\n * @see {@link MigrateFromIdentityAnchorOptions} for full option documentation.\n * @see {@link MigrateFromIdentityAnchorResult} for return value semantics.\n */\nexport async function migrateFromIdentityAnchor(\n options: MigrateFromIdentityAnchorOptions,\n): Promise<MigrateFromIdentityAnchorResult> {\n const { memoryDir, dryRun = false } = options;\n const now = new Date().toISOString();\n const createdAt = options.createdAt ?? now;\n const displayName = options.displayName ?? \"Self\";\n\n // 1. Guard: if peers/self/identity.md already exists, skip.\n // We read through the standard `readPeer` helper (which enforces all\n // path-traversal guards) rather than stat-ing the file directly.\n const existing = await readPeer(memoryDir, \"self\");\n if (existing !== null) {\n return {\n peer: existing,\n written: false,\n skipped: true,\n // P2 (codex): preserve the caller-requested dryRun flag even on the\n // skip path. Previously hard-coded `false`, which contradicted the\n // MigrateFromIdentityAnchorResult contract for dry-run callers.\n dryRun,\n identityAnchorSource: null,\n identityMdSource: null,\n };\n }\n\n // 2. Read legacy sources (both optional; symlinks are silently skipped).\n const anchorPath = path.join(memoryDir, \"identity\", \"identity-anchor.md\");\n const identityMdPath = path.join(memoryDir, \"IDENTITY.md\");\n\n const [anchorResult, identityMdResult] = await Promise.all([\n safeReadLegacyFile(anchorPath),\n safeReadLegacyFile(identityMdPath),\n ]);\n\n // 3. Compose the self peer record.\n const notes = buildSelfNotes(\n anchorResult.content,\n identityMdResult.content,\n );\n\n const peer: Peer = {\n id: \"self\",\n kind: \"self\",\n displayName,\n createdAt,\n updatedAt: now,\n ...(notes !== undefined ? { notes } : {}),\n };\n\n // 4. Write (unless dry-run).\n //\n // P2 (codex): the previous readPeer-then-writePeer pattern had a\n // check-then-act TOCTOU race: two concurrent `remnic peer migrate`\n // processes could both observe \"missing\" and the later write would\n // overwrite the file, violating the non-destructive / idempotent\n // guarantee.\n //\n // Mitigation: before calling writePeer we attempt to exclusively create\n // (O_CREAT | O_EXCL | O_NOFOLLOW) the identity file path. If the open\n // succeeds we are the sole creator; close the handle immediately and let\n // writePeer fill in the real content (it mkdirs + rewrites atomically).\n // If O_EXCL fails with EEXIST, another process won the race — re-read the\n // file and return `skipped`. The window between our exclusive open and the\n // writePeer overwrite is deliberate: we've already locked out concurrent\n // migrate calls via EEXIST, and `peer set self` targeting the same file\n // path will succeed (it is a legitimate overwrite, not a migrate race).\n if (!dryRun) {\n const selfPeerDir = path.join(memoryDir, PEERS_DIR_NAME, \"self\");\n await fs.mkdir(selfPeerDir, { recursive: true });\n const identityFilePath = path.join(selfPeerDir, \"identity.md\");\n let exclusiveFh: import(\"node:fs/promises\").FileHandle | null = null;\n try {\n exclusiveFh = await fs.open(\n identityFilePath,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_NOFOLLOW,\n );\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"EEXIST\") {\n // Another process created the file between our readPeer check and\n // now. Re-read and return skipped.\n const raceWinner = await readPeer(memoryDir, \"self\");\n return {\n peer: raceWinner ?? peer,\n written: false,\n skipped: true,\n dryRun,\n identityAnchorSource: null,\n identityMdSource: null,\n };\n }\n throw err;\n } finally {\n if (exclusiveFh !== null) await exclusiveFh.close();\n }\n // We hold the exclusive-create claim. Now writePeer fills in the\n // real content (it calls mkdirPeerDirAtomic + writeFileNoFollow).\n await writePeer(memoryDir, peer);\n }\n\n return {\n peer,\n written: !dryRun,\n skipped: false,\n dryRun,\n identityAnchorSource: anchorResult.filePath,\n identityMdSource: identityMdResult.filePath,\n };\n}\n","/**\n * Peer registry storage primitives — issue #679 PR 1/5.\n *\n * Pure file-I/O helpers for the per-peer kernel files:\n *\n * peers/{peer-id}/identity.md — slow, human-edited identity facts\n * peers/{peer-id}/profile.md — evolving profile (reasoner-owned)\n * peers/{peer-id}/interactions.log.md — append-only signal log\n *\n * No reasoner logic, no recall integration, no migration of existing\n * identity-anchor data — those land in PR 2/5 — 5/5.\n *\n * Path safety: `peerId` is validated against PEER_ID_PATTERN before any\n * filesystem operation. Reading a non-existent peer returns null (does not\n * throw). Reading malformed files throws — callers can catch and recover.\n */\n\nimport { promises as fs, constants as fsConstants } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Atomic, symlink-rejecting open: returns a file handle whose\n * underlying open(2) call carried `O_NOFOLLOW`, so the kernel itself\n * refuses to follow a symlink at the target path. Closes the\n * check-then-use TOCTOU race that a separate `assertPathNotSymlink`\n * + `fs.writeFile` pattern leaves open (codex P1 round 5 on PR #723).\n */\nasync function openNoFollow(file: string, flags: number): Promise<import(\"node:fs/promises\").FileHandle> {\n return fs.open(file, flags | fsConstants.O_NOFOLLOW);\n}\n\n/** Read a file, refusing to follow symlinks at the kernel level\n * AND verifying parent-dir inode stability (codex P1 round 9). */\nasync function readFileNoFollow(file: string): Promise<string> {\n await assertParentDirInodeStable(file);\n const fh = await openNoFollow(file, fsConstants.O_RDONLY);\n try {\n return await fh.readFile(\"utf8\");\n } finally {\n await fh.close();\n }\n}\n\n/**\n * Codex P1 round 9: O_NOFOLLOW only protects the FINAL path\n * component, so a parent-directory swap mid-flight (peers/<id>\n * unlinked + replaced with a symlink between assertPeerDirNotEscaped\n * and the open) could still write outside memoryDir. Without\n * `openat` (Node has no stable JS binding for it), the best\n * pure-Node mitigation is to:\n * 1. Open the parent directory with O_DIRECTORY | O_NOFOLLOW so\n * WE hold the original-inode handle.\n * 2. fstat the parent handle and compare its (dev, inode) against\n * lstat of the parent path. If they diverge, a swap happened\n * between mkdir and now — abort.\n * 3. Then do the symlink-rejecting open of the file.\n * This narrows the race window to the few microseconds between the\n * fstat/lstat compare and the open. Fully closing the race needs\n * `openat`, which is tracked as a follow-up.\n */\nasync function assertParentDirInodeStable(filePath: string): Promise<void> {\n const parent = path.dirname(filePath);\n const dh = await fs.open(\n parent,\n fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,\n );\n try {\n const fstatInfo = await dh.stat();\n const lstatInfo = await fs.lstat(parent);\n if (fstatInfo.ino !== lstatInfo.ino || fstatInfo.dev !== lstatInfo.dev) {\n throw new Error(\n `parent directory \"${parent}\" was swapped between checks (inode mismatch)`,\n );\n }\n if (lstatInfo.isSymbolicLink()) {\n throw new Error(`parent directory \"${parent}\" is a symlink and is rejected`);\n }\n } finally {\n await dh.close();\n }\n}\n\n/** Overwrite a file, refusing to follow symlinks at the kernel level\n * AND verifying the parent directory inode is stable across the open\n * (codex P1 round 9). */\nasync function writeFileNoFollow(file: string, data: string): Promise<void> {\n await assertParentDirInodeStable(file);\n const fh = await openNoFollow(\n file,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC,\n );\n try {\n await fh.writeFile(data, \"utf8\");\n } finally {\n await fh.close();\n }\n}\n\n/** Append to a file, refusing to follow symlinks AND verifying parent\n * inode stability (codex P1 round 9). */\nasync function appendFileNoFollow(file: string, data: string): Promise<void> {\n await assertParentDirInodeStable(file);\n const fh = await openNoFollow(\n file,\n fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_APPEND,\n );\n try {\n await fh.writeFile(data, \"utf8\");\n } finally {\n await fh.close();\n }\n}\n\nimport {\n PEER_ID_MAX_LENGTH,\n PEER_ID_PATTERN,\n type Peer,\n type PeerInteractionLogEntry,\n type PeerKind,\n type PeerProfile,\n type PeerProfileFieldProvenance,\n} from \"./types.js\";\n\n// ──────────────────────────────────────────────────────────────────────\n// Validation\n// ──────────────────────────────────────────────────────────────────────\n\nconst ALLOWED_KINDS: ReadonlySet<PeerKind> = new Set<PeerKind>([\n \"self\",\n \"human\",\n \"agent\",\n \"integration\",\n]);\n\n/**\n * Validate a peer id. Throws `Error` with a descriptive message on failure.\n * Exported so callers can pre-check user input before constructing a Peer.\n */\nexport function assertValidPeerId(peerId: unknown): asserts peerId is string {\n if (typeof peerId !== \"string\") {\n throw new Error(\"peerId must be a string\");\n }\n if (peerId.length === 0) {\n throw new Error(\"peerId must not be empty\");\n }\n if (peerId.length > PEER_ID_MAX_LENGTH) {\n throw new Error(`peerId must be ≤ ${PEER_ID_MAX_LENGTH} characters`);\n }\n if (!PEER_ID_PATTERN.test(peerId)) {\n throw new Error(\n `peerId \"${peerId}\" is invalid — must match ${PEER_ID_PATTERN}`,\n );\n }\n // Defence-in-depth: reject consecutive dots/dashes/underscores. The\n // regex already prevents leading/trailing separators, but explicit\n // adjacency checks document intent and survive future regex refactors.\n if (/[.\\-_]{2,}/.test(peerId)) {\n throw new Error(\n `peerId \"${peerId}\" is invalid — must not contain consecutive separators`,\n );\n }\n}\n\n/**\n * Strict plain-object check. Rejects arrays, null, Maps, Sets, class\n * instances, and anything else with a non-Object/null prototype.\n * Codex P2 round 13: writePeerProfile previously treated any\n * non-null non-array object as plain; inputs like `new Map()` would\n * pass and serialize to `{}` losing all data.\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction assertValidKind(kind: unknown): asserts kind is PeerKind {\n if (typeof kind !== \"string\" || !ALLOWED_KINDS.has(kind as PeerKind)) {\n throw new Error(\n `peer kind must be one of ${Array.from(ALLOWED_KINDS).join(\", \")}`,\n );\n }\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Path helpers\n// ──────────────────────────────────────────────────────────────────────\n\n/** Root directory holding the peer registry, relative to memoryDir. */\nexport const PEERS_DIR_NAME = \"peers\";\n\nfunction peersRoot(memoryDir: string): string {\n return path.join(memoryDir, PEERS_DIR_NAME);\n}\n\nfunction peerDir(memoryDir: string, peerId: string): string {\n // Guard against path traversal on top of regex validation. After\n // assertValidPeerId, peerId cannot contain `/`, `..`, or NUL — but we\n // re-check defensively here.\n assertValidPeerId(peerId);\n const candidate = path.join(peersRoot(memoryDir), peerId);\n const root = peersRoot(memoryDir);\n // Ensure resolved path stays within peersRoot. Note: this is a\n // lexical check only — a symlinked peer directory can still escape.\n // I/O sites must additionally call `assertPeerDirNotEscaped` (below)\n // before reading or writing, which uses lstat to reject symlinks\n // and realpath to confirm physical containment (codex P1 #723).\n const relative = path.relative(root, candidate);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`peerId \"${peerId}\" resolves outside peers root`);\n }\n return candidate;\n}\n\n/**\n * Reject the peers root if it is itself a symlink. Called BEFORE any\n * `fs.mkdir`, so a `peers → /tmp/outside` symlink can't get its\n * target mutated by a recursive mkdir before subsequent checks fire\n * (codex P2 + cursor M on PR #723).\n */\nasync function assertPeersRootNotSymlink(memoryDir: string): Promise<void> {\n const root = peersRoot(memoryDir);\n let rootStat: import(\"node:fs\").Stats | null = null;\n try {\n rootStat = await fs.lstat(root);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n if (rootStat && rootStat.isSymbolicLink()) {\n throw new Error(`peers root \"${root}\" is a symlink and is rejected`);\n }\n}\n\n/**\n * Codex P1 round 13: atomic mkdir of the peer directory under a\n * verified peers root. Opens the peers root with O_DIRECTORY|\n * O_NOFOLLOW first (creating it if missing under the same flags) so\n * a root-symlink swap can't redirect the subsequent mkdir to its\n * target. The dir handle is held across the mkdir, then we lstat\n * the candidate and reject if it's a symlink.\n */\nasync function mkdirPeerDirAtomic(memoryDir: string, peerId: string): Promise<void> {\n const root = peersRoot(memoryDir);\n // Ensure the root exists as a real directory, not a symlink. Use\n // mkdir + lstat: if mkdir succeeds (or EEXIST), lstat must report\n // a directory and not a symlink.\n await fs.mkdir(memoryDir, { recursive: true });\n try {\n await fs.mkdir(root);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"EEXIST\") throw err;\n }\n const rootLstat = await fs.lstat(root);\n if (rootLstat.isSymbolicLink()) {\n throw new Error(`peers root \"${root}\" is a symlink and is rejected`);\n }\n if (!rootLstat.isDirectory()) {\n throw new Error(`peers root \"${root}\" exists but is not a directory`);\n }\n // Open the root with O_DIRECTORY|O_NOFOLLOW to anchor the inode.\n // Hold the handle across the peer-dir mkdir so a root swap\n // mid-operation is detected via fstat-vs-lstat compare afterward.\n const rootHandle = await fs.open(\n root,\n fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,\n );\n try {\n const candidate = peerDir(memoryDir, peerId);\n await fs.mkdir(candidate, { recursive: true });\n // Verify root inode unchanged across the mkdir.\n const fstatRoot = await rootHandle.stat();\n const lstatRoot = await fs.lstat(root);\n if (fstatRoot.ino !== lstatRoot.ino || fstatRoot.dev !== lstatRoot.dev) {\n throw new Error(`peers root \"${root}\" was swapped during mkdir`);\n }\n // Reject symlinked peer dir.\n const peerLstat = await fs.lstat(candidate);\n if (peerLstat.isSymbolicLink()) {\n throw new Error(`peer directory \"${peerId}\" is a symlink and is rejected`);\n }\n } finally {\n await rootHandle.close();\n }\n}\n\n/**\n * Codex P1 on PR #723: `peerDir` only enforces a lexical\n * `path.relative` check, so a symlinked peer directory like\n * `peers/self → /tmp/outside` would slip through. Run this guard\n * AFTER the peer directory has been (or is known to) exist, so we\n * can lstat it and realpath-check containment. For first-time writes,\n * call `mkdirPeerDirAtomic` BEFORE this; for reads, this alone.\n */\nasync function assertPeerDirNotEscaped(memoryDir: string, peerId: string): Promise<void> {\n const candidate = peerDir(memoryDir, peerId);\n const root = peersRoot(memoryDir);\n // 1. The peers root must not be a symlink (defensive — writers\n // already checked this before mkdir, but reads must still verify).\n await assertPeersRootNotSymlink(memoryDir);\n // 2. lstat on the candidate itself. If it's a symlink, refuse.\n let candidateStat: import(\"node:fs\").Stats | null = null;\n try {\n candidateStat = await fs.lstat(candidate);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") throw err;\n }\n if (candidateStat && candidateStat.isSymbolicLink()) {\n throw new Error(`peer directory \"${peerId}\" is a symlink and is rejected`);\n }\n // 3. Real-path containment. Only meaningful if the candidate exists.\n if (candidateStat) {\n const realRoot = await fs.realpath(root);\n const realCandidate = await fs.realpath(candidate);\n const rel = path.relative(realRoot, realCandidate);\n if (rel === \"\" || rel.startsWith(\"..\") || path.isAbsolute(rel)) {\n throw new Error(`peer directory \"${peerId}\" escapes the peers root`);\n }\n }\n}\n\nfunction identityPath(memoryDir: string, peerId: string): string {\n return path.join(peerDir(memoryDir, peerId), \"identity.md\");\n}\n\nfunction profilePath(memoryDir: string, peerId: string): string {\n return path.join(peerDir(memoryDir, peerId), \"profile.md\");\n}\n\nfunction interactionsPath(memoryDir: string, peerId: string): string {\n return path.join(peerDir(memoryDir, peerId), \"interactions.log.md\");\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Minimal YAML helpers (peer files only)\n// ──────────────────────────────────────────────────────────────────────\n//\n// We deliberately do not depend on the codebase's primary YAML parser\n// (`storage.ts`) because the peer schema is small and structured. We emit\n// a strict, predictable subset:\n//\n// ---\n// id: my-peer\n// kind: agent\n// displayName: \"Codex\"\n// createdAt: 2026-04-25T00:00:00.000Z\n// updatedAt: 2026-04-25T00:00:00.000Z\n// ---\n// {free-form markdown notes}\n//\n// String values are always double-quoted with `\\\\` and `\\\"` escapes. ISO\n// timestamps and the kind enum are emitted bare. This keeps round-trip\n// behaviour deterministic and easy to validate.\n\nfunction escapeYamlString(value: string): string {\n // Cursor Medium: must escape newlines / carriage returns / tabs so a\n // value like `displayName: \"first\\nsecond\"` doesn't blow up the\n // line-oriented parsePeerFrontmatter. Backslash → `\\\\`, double-quote\n // → `\\\"`, newline → `\\n`, carriage return → `\\r`, tab → `\\t`.\n return `\"${value\n .replace(/\\\\/g, \"\\\\\\\\\")\n .replace(/\"/g, '\\\\\"')\n .replace(/\\n/g, \"\\\\n\")\n .replace(/\\r/g, \"\\\\r\")\n .replace(/\\t/g, \"\\\\t\")}\"`;\n}\n\nfunction unescapeYamlString(quoted: string): string {\n // Caller has already verified `quoted` starts and ends with a double quote.\n const body = quoted.slice(1, -1);\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n const ch = body[i];\n if (ch === \"\\\\\" && i + 1 < body.length) {\n const next = body[i + 1];\n if (next === \"\\\\\" || next === '\"') {\n out += next;\n i++;\n continue;\n }\n if (next === \"n\") {\n out += \"\\n\";\n i++;\n continue;\n }\n if (next === \"r\") {\n out += \"\\r\";\n i++;\n continue;\n }\n if (next === \"t\") {\n out += \"\\t\";\n i++;\n continue;\n }\n }\n out += ch;\n }\n return out;\n}\n\ninterface ParsedFrontmatter {\n fields: Record<string, string>;\n body: string;\n}\n\nfunction parsePeerFrontmatter(raw: string): ParsedFrontmatter {\n // Frontmatter must begin with a `---` line. We tolerate a leading BOM\n // and trailing newlines but otherwise require a strict, line-oriented\n // YAML subset of `key: value` pairs.\n const text = raw.replace(/^\\uFEFF/, \"\");\n if (!text.startsWith(\"---\")) {\n throw new Error(\"peer file is missing YAML frontmatter delimiter\");\n }\n // Split on the first occurrence of `\\n---` after the leading `---`.\n const after = text.slice(3);\n const close = after.indexOf(\"\\n---\");\n if (close === -1) {\n throw new Error(\"peer file frontmatter is not terminated\");\n }\n const fmBlock = after.slice(0, close).replace(/^\\n/, \"\");\n const body = after.slice(close + 4).replace(/^\\n/, \"\");\n const fields: Record<string, string> = {};\n for (const lineRaw of fmBlock.split(\"\\n\")) {\n const line = lineRaw.trim();\n if (line === \"\" || line.startsWith(\"#\")) continue;\n const colon = line.indexOf(\":\");\n if (colon === -1) {\n throw new Error(`peer frontmatter line is malformed: ${line}`);\n }\n const key = line.slice(0, colon).trim();\n const valueRaw = line.slice(colon + 1).trim();\n if (key === \"\") {\n throw new Error(`peer frontmatter has empty key: ${line}`);\n }\n let value: string;\n if (valueRaw.startsWith('\"') && valueRaw.endsWith('\"') && valueRaw.length >= 2) {\n value = unescapeYamlString(valueRaw);\n } else {\n value = valueRaw;\n }\n fields[key] = value;\n }\n return { fields, body };\n}\n\nfunction emitPeerIdentity(peer: Peer): string {\n const lines: string[] = [\"---\"];\n lines.push(`id: ${escapeYamlString(peer.id)}`);\n lines.push(`kind: ${peer.kind}`);\n lines.push(`displayName: ${escapeYamlString(peer.displayName)}`);\n // Cursor M: emit timestamps as quoted YAML strings — bare emission\n // would let a `createdAt` value containing a newline inject extra\n // frontmatter fields when round-tripped through `parsePeerFrontmatter`.\n // (`writePeer` validates these are non-empty strings, but the type\n // doesn't constrain content.)\n lines.push(`createdAt: ${escapeYamlString(peer.createdAt)}`);\n lines.push(`updatedAt: ${escapeYamlString(peer.updatedAt)}`);\n lines.push(\"---\");\n lines.push(\"\");\n lines.push(peer.notes ?? \"\");\n // Trailing newline for POSIX friendliness.\n // CodeQL: the previous `replace(/\\n+$/, \"\\n\")` flagged as\n // polynomial-regex risk because `\\n+` can backtrack on long\n // trailing-newline runs. Strip trailing newlines with a bounded\n // loop instead — O(N) over the trailing-newline count, no regex.\n let out = lines.join(\"\\n\");\n while (out.endsWith(\"\\n\")) out = out.slice(0, -1);\n return out + \"\\n\";\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Public storage API\n// ──────────────────────────────────────────────────────────────────────\n\n/**\n * Read a peer's identity kernel.\n *\n * Returns `null` (does not throw) when the peer directory or identity\n * file does not exist. Throws on filesystem errors other than ENOENT and\n * on malformed files.\n */\nexport async function readPeer(\n memoryDir: string,\n peerId: string,\n): Promise<Peer | null> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = identityPath(memoryDir, peerId);\n // Codex P1 #2: even with the directory validated, a symlinked\n // identity.md inside a real peer dir would let us read arbitrary\n // out-of-scope files. Reject symlinks at the file level too.\n let raw: string;\n try {\n raw = await readFileNoFollow(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n const { fields, body } = parsePeerFrontmatter(raw);\n const id = fields.id ?? peerId;\n if (id !== peerId) {\n throw new Error(\n `peer identity file mismatch — expected id \"${peerId}\", file claims \"${id}\"`,\n );\n }\n const kind = fields.kind;\n assertValidKind(kind);\n const displayName = fields.displayName ?? \"\";\n const createdAt = fields.createdAt ?? \"\";\n if (createdAt === \"\") {\n throw new Error(`peer \"${peerId}\" is missing createdAt`);\n }\n // Codex P2: nullish-coalescing alone treated `updatedAt: \"\"` as a\n // valid empty timestamp, contradicting writePeer's non-empty\n // validation and the module's \"malformed files throw\" contract.\n // Treat empty string as missing and fall back to createdAt; throw\n // only when the field is malformed in some other way (caught by\n // the typeof check).\n const rawUpdatedAt = fields.updatedAt;\n const updatedAt =\n typeof rawUpdatedAt === \"string\" && rawUpdatedAt.length > 0\n ? rawUpdatedAt\n : createdAt;\n // Codex P2 + CodeQL: previously used `body.replace(/^\\s+/, \"\")`\n // which stripped ALL leading whitespace — including indentation in\n // notes. The `\\s+` patterns also flagged as polynomial-regex risk\n // (CodeQL alert #74) because they can backtrack on adversarial\n // inputs. Strip exactly one leading separator newline and one\n // trailing newline — internal AND user-authored leading\n // indentation are preserved verbatim, and the regex is bounded.\n let trimmedBody = body;\n if (trimmedBody.startsWith(\"\\r\\n\")) trimmedBody = trimmedBody.slice(2);\n else if (trimmedBody.startsWith(\"\\n\")) trimmedBody = trimmedBody.slice(1);\n if (trimmedBody.endsWith(\"\\r\\n\")) trimmedBody = trimmedBody.slice(0, -2);\n else if (trimmedBody.endsWith(\"\\n\")) trimmedBody = trimmedBody.slice(0, -1);\n return {\n id: peerId,\n kind,\n displayName,\n createdAt,\n updatedAt,\n notes: trimmedBody === \"\" ? undefined : trimmedBody,\n };\n}\n\n/**\n * Write (create or overwrite) a peer's identity kernel.\n *\n * Creates `peers/{id}/` if it does not exist. Does not touch the peer's\n * profile or interaction log. Atomic-write semantics are deferred to\n * later PRs — for the schema slice we simply write the file.\n */\nexport async function writePeer(memoryDir: string, peer: Peer): Promise<void> {\n assertValidPeerId(peer.id);\n assertValidKind(peer.kind);\n if (typeof peer.displayName !== \"string\") {\n throw new Error(\"peer.displayName must be a string\");\n }\n if (typeof peer.createdAt !== \"string\" || peer.createdAt === \"\") {\n throw new Error(\"peer.createdAt must be a non-empty ISO-8601 string\");\n }\n if (typeof peer.updatedAt !== \"string\" || peer.updatedAt === \"\") {\n throw new Error(\"peer.updatedAt must be a non-empty ISO-8601 string\");\n }\n // Codex P2 round 8: reject non-string `peer.notes`. Without this,\n // an untyped JS caller passing an object/number would silently\n // coerce to \"[object Object]\"/\"42\" via lines.push(notes ?? \"\")\n // and corrupt user-authored identity content. Notes are optional;\n // omit by passing undefined (NOT null).\n if (peer.notes !== undefined && typeof peer.notes !== \"string\") {\n throw new Error(\"peer.notes must be a string when provided\");\n }\n // Codex P1 round 13: atomic root validation. Open the peers root\n // (or its parent if peers doesn't exist yet) with O_DIRECTORY|\n // O_NOFOLLOW BEFORE the mkdir. This holds a kernel handle on the\n // original-inode root, so a swap between the symlink check and\n // the mkdir can't redirect mkdir to a symlink-target. We then\n // mkdir, lstat the result against the held handle, and only\n // proceed if they match.\n await mkdirPeerDirAtomic(memoryDir, peer.id);\n await assertPeerDirNotEscaped(memoryDir, peer.id);\n const file = identityPath(memoryDir, peer.id);\n // Codex P1 #2: reject if identity.md exists as a symlink so we\n // don't follow it on overwrite.\n await writeFileNoFollow(file, emitPeerIdentity(peer));\n}\n\n/**\n * Delete a peer's `identity.md` if present, applying the same symlink\n * and path-escape protections as the read/write paths.\n *\n * Returns `true` if a regular file was unlinked, `false` if no\n * `identity.md` existed at the time of the call. The peer directory\n * itself is left in place so any companion files (`profile.md`,\n * `interactions/`, etc.) are untouched. Idempotent: missing target\n * returns `false` rather than throwing.\n *\n * Cursor M (PR #756 review): a manual `path.join` + raw `fs.unlink`\n * bypasses `assertPeerDirNotEscaped`, the peers-root symlink check,\n * and the parent-inode-stable / lstat guards used by every other\n * peer I/O entrypoint. A symlinked `peers/<id>/` could redirect the\n * unlink to an arbitrary `identity.md` outside `memoryDir`. This\n * function consolidates the safe-delete contract so callers cannot\n * skip the guards.\n */\nexport async function deletePeer(memoryDir: string, peerId: string): Promise<boolean> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = identityPath(memoryDir, peerId);\n // Refuse to follow a symlink at `identity.md` itself: lstat first\n // and reject if the target is a symlink. Then verify the parent\n // directory inode is stable across the unlink (mirrors the\n // assertParentDirInodeStable + O_NOFOLLOW pattern used by\n // writeFileNoFollow). This narrows the TOCTOU window between the\n // lstat and the unlink to the same few microseconds the write path\n // accepts.\n let lstatBefore: import(\"node:fs\").Stats;\n try {\n lstatBefore = await fs.lstat(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n if (lstatBefore.isSymbolicLink()) {\n throw new Error(`refusing to unlink \"${file}\": target is a symlink`);\n }\n if (!lstatBefore.isFile()) {\n throw new Error(`refusing to unlink \"${file}\": target is not a regular file`);\n }\n await assertParentDirInodeStable(file);\n try {\n await fs.unlink(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return false;\n }\n throw err;\n }\n return true;\n}\n\n/**\n * Destructively purge the entire peer directory for a given peerId —\n * `identity.md`, `profile.md`, `interactions.log.md`, and any other\n * files written by future extensions.\n *\n * This is the DESTRUCTIVE counterpart to `deletePeer` (which only\n * removes `identity.md`). Callers must pass `confirm: \"yes\"` to prevent\n * accidental data loss — the function throws `Error(\"forgetPeer requires\n * confirm: 'yes'\")` when the flag is absent or wrong.\n *\n * Idempotent: if the peer directory does not exist the function returns\n * `{ purged: false }` rather than throwing. Safe to run twice.\n *\n * Security contract (mirrors `deletePeer`):\n * - `peerId` is validated against `PEER_ID_PATTERN`.\n * - The peers root is checked for symlink swap (assertPeersRootNotSymlink).\n * - `assertPeerDirNotEscaped` performs realpath containment: symlinked\n * peer directories are rejected and the resolved path is confirmed to\n * stay inside peersRoot (same guard used by every other I/O entry-point).\n * - A secondary `lstat` + `isSymbolicLink()` check is kept as defence-in-\n * depth before the `fs.rm` call itself.\n * - `fs.rm` with `{ recursive: true, force: true }` is used for the\n * actual removal so partially-populated directories are handled\n * atomically by the OS rather than file-by-file in userland.\n *\n * Returns:\n * `{ purged: true }` — directory existed and was removed.\n * `{ purged: false }` — directory did not exist (no-op).\n */\nexport async function forgetPeer(\n memoryDir: string,\n peerId: string,\n opts: { confirm: string },\n): Promise<{ purged: boolean }> {\n if (opts.confirm !== \"yes\") {\n throw new Error(\"forgetPeer requires confirm: 'yes'\");\n }\n assertValidPeerId(peerId);\n await assertPeersRootNotSymlink(memoryDir);\n // assertPeerDirNotEscaped performs the realpath-containment check that\n // the lexical `peerDir()` guard alone cannot provide: it lstat-checks\n // the candidate, rejects symlinks, and confirms the resolved path stays\n // inside peersRoot. Mirrors the contract of every other I/O entry-point\n // in this module (`readPeer`, `writePeer`, `deletePeer`,\n // `appendInteractionLog`, `readPeerProfile`, `writePeerProfile`).\n // The function handles ENOENT gracefully (returns without throwing), so\n // calling it here is safe for the idempotent no-op path as well.\n await assertPeerDirNotEscaped(memoryDir, peerId);\n\n const dir = peerDir(memoryDir, peerId);\n\n // lstat the candidate directory. Return early (idempotent) if it\n // doesn't exist. Reject if it resolves to a symlink.\n let dirStat: import(\"node:fs\").Stats;\n try {\n dirStat = await fs.lstat(dir);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return { purged: false };\n }\n throw err;\n }\n if (dirStat.isSymbolicLink()) {\n throw new Error(\n `refusing to purge peer directory \"${peerId}\": target is a symlink`,\n );\n }\n if (!dirStat.isDirectory()) {\n throw new Error(\n `refusing to purge peer directory \"${peerId}\": target is not a directory`,\n );\n }\n\n // Perform the recursive removal. `fs.rm` with `{ recursive: true }`\n // is the correct API (replaces the deprecated `fs.rmdir`). The\n // `force: true` flag makes it a no-op if the directory was already\n // removed between our lstat and this call (race-safe idempotency).\n await fs.rm(dir, { recursive: true, force: true });\n return { purged: true };\n}\n\n/**\n * Enumerate all peers under `memoryDir/peers/`.\n *\n * Returns an empty array if the peers root does not exist. Subdirectories\n * whose name fails `PEER_ID_PATTERN` are skipped (defensive: the user\n * may have hand-edited the directory). Directories that exist but lack\n * `identity.md` are also skipped.\n */\nexport async function listPeers(memoryDir: string): Promise<Peer[]> {\n // Codex P2 round 13: atomic readdir against the root. Open the\n // peers directory with O_DIRECTORY|O_NOFOLLOW first so we hold the\n // original-inode handle, then readdir from that handle. A\n // root-symlink swap between assertPeersRootNotSymlink and a path-\n // based readdir is no longer possible — the kernel rejects the\n // open if the path resolves to a symlink, and the dirHandle.read()\n // operates on the original inode regardless of subsequent path-\n // based mutations.\n const root = peersRoot(memoryDir);\n // Cursor M round 14: Node's FileHandle has no `readdir` method\n // (only `fs.readdir(path)` is exposed), so we can't read directly\n // from the handle. Instead anchor the original-inode by opening\n // the dir with O_NOFOLLOW, fstat it, then do path-based readdir\n // and confirm the path's lstat AFTER matches the held inode. If\n // it diverges, a swap happened — abort. This is a fence around\n // the readdir, not the kernel-level guarantee a true `fdreaddir`\n // would give, but it closes the path-traversal race without\n // requiring native bindings.\n let entries: string[];\n let dh: import(\"node:fs/promises\").FileHandle | null = null;\n try {\n dh = await fs.open(\n root,\n fsConstants.O_RDONLY | fsConstants.O_DIRECTORY | fsConstants.O_NOFOLLOW,\n );\n const fstatBefore = await dh.stat();\n entries = await fs.readdir(root);\n const lstatAfter = await fs.lstat(root);\n if (\n fstatBefore.ino !== lstatAfter.ino ||\n fstatBefore.dev !== lstatAfter.dev ||\n lstatAfter.isSymbolicLink()\n ) {\n throw new Error(`peers root \"${root}\" was swapped during readdir`);\n }\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return [];\n }\n throw err;\n } finally {\n if (dh) await dh.close();\n }\n const peers: Peer[] = [];\n // Sort for deterministic ordering — callers that need a different\n // sort order can re-sort the result.\n entries.sort();\n for (const name of entries) {\n if (!PEER_ID_PATTERN.test(name) || name.length > PEER_ID_MAX_LENGTH) {\n continue;\n }\n let stat;\n try {\n // Codex P1: use `lstat` so we don't follow symlinks. A\n // `peers/<valid-id>` symlink pointing at an arbitrary directory\n // would otherwise let listPeers (and the readPeer that\n // follows) traverse outside the peers root.\n stat = await fs.lstat(path.join(root, name));\n } catch (err) {\n // Codex P2 round 13: don't swallow non-ENOENT errors.\n // Permission-denied / EACCES / EIO need to surface so the\n // operator sees a real I/O problem rather than a silently\n // truncated peer list.\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") continue;\n throw err;\n }\n // Skip symlinks entirely — only real directories are peers.\n if (!stat.isDirectory() || stat.isSymbolicLink()) continue;\n let peer: Peer | null = null;\n try {\n peer = await readPeer(memoryDir, name);\n } catch (err) {\n // Cursor M round 14: classifying by `.code` alone treated\n // security-check failures (assertPeerDirNotEscaped /\n // assertParentDirInodeStable / \"is a symlink and is rejected\"\n // / \"inode mismatch\") as parse failures and silently skipped\n // them. Those messages are critical signals — an attacker\n // attempted to redirect a read outside the peers root. Match\n // by message prefix to detect them and propagate.\n const code = (err as NodeJS.ErrnoException).code;\n const message = err instanceof Error ? err.message : String(err);\n const isSecurityFailure =\n message.startsWith(\"peers root\") ||\n message.startsWith(\"peer directory\") ||\n message.startsWith(\"parent directory\") ||\n message.startsWith(\"path \") /* \"path \\\"...\\\" is a symlink\" */ ||\n message.includes(\"escapes the peers root\") ||\n message.includes(\"inode mismatch\") ||\n message.includes(\"is a symlink and is rejected\") ||\n message.includes(\"was swapped\");\n if (isSecurityFailure) throw err;\n // Real I/O errors (EACCES, EIO, EBUSY, etc.) propagate too.\n if (code && code !== \"ENOENT\") throw err;\n // Schema/parse failures fall through and skip the entry.\n continue;\n }\n if (peer !== null) {\n peers.push(peer);\n }\n }\n return peers;\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Interaction log (append-only)\n// ──────────────────────────────────────────────────────────────────────\n\nfunction sanitizeLogField(value: string): string {\n // Cursor Medium: every interaction-log field — not just summary —\n // must collapse newlines so a malicious or buggy `timestamp` /\n // `kind` / `sessionId` value can't break the one-line-per-entry\n // invariant the append-only log relies on. Replace CR/LF/Tab with\n // a single space; trim leading/trailing whitespace.\n return value.replace(/[\\r\\n\\t]+/g, \" \").trim();\n}\n\nfunction formatLogEntry(entry: PeerInteractionLogEntry): string {\n // One line per entry. We use a leading bullet so the file remains\n // readable as ordinary markdown. Order: timestamp, kind, optional\n // session id, summary. ALL fields are passed through `sanitizeLogField`\n // so a stray newline anywhere can't shatter the append-only invariant\n // (cursor Medium on PR #723).\n //\n // Cursor Low on PR #736: the previous bare `session=<id>` token was\n // ambiguous with summaries that literally start with `session=`\n // (e.g. summary `\"session=foo bar\"` round-tripped to\n // `{sessionId: \"foo\", summary: \"bar\"}`). New entries wrap the\n // session marker in square brackets — `[session=<id>]` — which a\n // sanitized summary can never start with (sanitizeLogField never\n // emits `[` as the first character of a summary that originally\n // started with `session=`, and bracketed metadata is unambiguously\n // distinct from `session=` text). Old entries written by previous\n // code remain parseable through the legacy fallback in\n // `parseLogLine`.\n const ts = sanitizeLogField(entry.timestamp);\n const kind = sanitizeLogField(entry.kind);\n const summary = sanitizeLogField(entry.summary);\n const session = entry.sessionId\n ? ` [session=${sanitizeLogField(entry.sessionId)}]`\n : \"\";\n return `- [${ts}] (${kind})${session} ${summary}`;\n}\n\n/**\n * Append one entry to a peer's interaction log.\n *\n * Creates `peers/{id}/` and `interactions.log.md` if needed. The file is\n * append-only by contract — this helper never rewrites prior entries.\n * Returns the absolute path of the log file (useful for tests).\n */\nexport async function appendInteractionLog(\n memoryDir: string,\n peerId: string,\n entry: PeerInteractionLogEntry,\n): Promise<string> {\n assertValidPeerId(peerId);\n // Codex P2 round 10: trim() before the empty check matches what\n // sanitizeLogField does at format time. A whitespace-only\n // `timestamp` or `kind` would previously pass validation and then\n // be normalized to \"\" later, producing an entry like `- [] ()`\n // that breaks downstream parsers.\n if (typeof entry.timestamp !== \"string\" || entry.timestamp.trim() === \"\") {\n throw new Error(\"interaction entry must have a non-whitespace timestamp\");\n }\n if (typeof entry.kind !== \"string\" || entry.kind.trim() === \"\") {\n throw new Error(\"interaction entry must have a non-whitespace kind\");\n }\n if (typeof entry.summary !== \"string\") {\n throw new Error(\"interaction entry must have a string summary\");\n }\n // Codex P2 round 6/8/9: optional sessionId must be a non-empty\n // string OR strictly `undefined` (omitted). null and empty string\n // are both rejected explicitly: the previous behavior silently\n // dropped them during formatting, which reinterprets invalid input\n // instead of failing fast like other validators in this module.\n // Codex P2 round 12: trim() before the empty check matches what\n // sanitizeLogField does at format time. Whitespace-only sessionId\n // would otherwise pass validation and produce a `session=` token\n // with an empty value that breaks downstream log parsers.\n if (entry.sessionId !== undefined) {\n if (typeof entry.sessionId !== \"string\" || entry.sessionId.trim() === \"\") {\n throw new Error(\"interaction entry sessionId must be a non-whitespace string when provided\");\n }\n }\n await mkdirPeerDirAtomic(memoryDir, peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = interactionsPath(memoryDir, peerId);\n const line = formatLogEntry(entry) + \"\\n\";\n // `appendFile` creates the file if it does not exist. POSIX guarantees\n // writes < PIPE_BUF are atomic; entries on this path are well under\n // that bound. Ordering across concurrent writers is the caller's\n // responsibility for now — the reasoner runs serially in PR 2/5.\n await appendFileNoFollow(file, line);\n return file;\n}\n\n// ──────────────────────────────────────────────────────────────────────\n// Profile read/write (schema scaffold; reasoner ships in PR 2/5)\n// ──────────────────────────────────────────────────────────────────────\n\ninterface ProfileFile {\n updatedAt: string;\n fields: Record<string, string>;\n provenance: Record<string, PeerProfileFieldProvenance[]>;\n}\n\nfunction emitPeerProfile(profile: PeerProfile): string {\n // Profiles use a JSON-in-fenced-code-block payload inside a markdown\n // file so they remain human-readable. The frontmatter holds the\n // updatedAt stamp; the body holds the full structured payload.\n const payload: ProfileFile = {\n updatedAt: profile.updatedAt,\n fields: { ...profile.fields },\n provenance: Object.fromEntries(\n Object.entries(profile.provenance).map(([k, v]) => [k, [...v]]),\n ),\n };\n const json = JSON.stringify(payload, null, 2);\n return [\n \"---\",\n `peerId: ${escapeYamlString(profile.peerId)}`,\n `updatedAt: ${escapeYamlString(profile.updatedAt)}`,\n \"---\",\n \"\",\n \"<!-- peer profile — managed by the async reasoner. Manual edits will be overwritten. -->\",\n \"\",\n \"```json\",\n json,\n \"```\",\n \"\",\n ].join(\"\\n\");\n}\n\nfunction parsePeerProfile(raw: string, peerId: string): PeerProfile {\n const { fields: fm, body } = parsePeerFrontmatter(raw);\n if (fm.peerId !== undefined && fm.peerId !== peerId) {\n throw new Error(\n `peer profile mismatch — expected \"${peerId}\", file claims \"${fm.peerId}\"`,\n );\n }\n const fenceMatch = body.match(/```json\\s*\\n([\\s\\S]*?)\\n```/);\n if (!fenceMatch) {\n throw new Error(`peer profile for \"${peerId}\" is missing JSON payload`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(fenceMatch[1]);\n } catch (err) {\n throw new Error(\n `peer profile for \"${peerId}\" has invalid JSON: ${(err as Error).message}`,\n );\n }\n if (typeof parsed !== \"object\" || parsed === null) {\n throw new Error(`peer profile for \"${peerId}\" is not an object`);\n }\n const payload = parsed as Partial<ProfileFile>;\n // Codex P2: only accept string updatedAt values. A malformed payload\n // like `{ \"updatedAt\": 123 }` would previously short-circuit through\n // `payload.updatedAt ?? fm.updatedAt ?? \"\"` and produce a `PeerProfile`\n // whose updatedAt is a number — corrupting any downstream code that\n // assumes the contract.\n const payloadUpdatedAt = typeof payload.updatedAt === \"string\" ? payload.updatedAt : undefined;\n const updatedAt = payloadUpdatedAt ?? fm.updatedAt ?? \"\";\n if (typeof updatedAt !== \"string\" || updatedAt === \"\") {\n throw new Error(`peer profile for \"${peerId}\" is missing updatedAt`);\n }\n // Codex P2 round 10: a malformed `fields: \"wat\"` or\n // `provenance: 42` previously coerced to {} and silently dropped\n // the section. That contradicts the \"malformed files throw\"\n // contract — the file IS malformed, not just empty. Reject loudly.\n // `undefined` is still tolerated (an older profile file might omit\n // the section entirely).\n let fieldsObj: object;\n if (payload.fields === undefined) {\n fieldsObj = {};\n } else if (\n typeof payload.fields === \"object\" &&\n payload.fields !== null &&\n !Array.isArray(payload.fields)\n ) {\n fieldsObj = payload.fields;\n } else {\n throw new Error(`peer profile for \"${peerId}\" has malformed fields section`);\n }\n let provenanceObj: object;\n if (payload.provenance === undefined) {\n provenanceObj = {};\n } else if (\n typeof payload.provenance === \"object\" &&\n payload.provenance !== null &&\n !Array.isArray(payload.provenance)\n ) {\n provenanceObj = payload.provenance;\n } else {\n throw new Error(`peer profile for \"${peerId}\" has malformed provenance section`);\n }\n // Coerce values defensively. We never trust the on-disk shape.\n // Codex P1: skip prototype-pollution keys explicitly. We don't use\n // null-prototype objects in the returned shape because callers\n // (tests, downstream consumers) expect plain objects with normal\n // semantics — the assertion `assert.deepEqual` differentiates by\n // prototype. The skip-list is the load-bearing defense; iteration\n // via Object.entries() of attacker-controlled JSON objects is safe\n // as long as we never assign through dangerous keys.\n const DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n const fields: Record<string, string> = {};\n for (const [k, v] of Object.entries(fieldsObj)) {\n if (DANGEROUS_KEYS.has(k)) continue;\n if (typeof v === \"string\") fields[k] = v;\n }\n const provenance: Record<string, PeerProfileFieldProvenance[]> = {};\n for (const [k, v] of Object.entries(provenanceObj)) {\n if (DANGEROUS_KEYS.has(k)) continue;\n if (!Array.isArray(v)) continue;\n const list: PeerProfileFieldProvenance[] = [];\n for (const item of v) {\n if (\n typeof item !== \"object\" ||\n item === null ||\n Array.isArray(item)\n ) {\n continue;\n }\n const r = item as unknown as Record<string, unknown>;\n // Codex P2 round 9: empty observedAt/signal strings should be\n // treated as malformed, not valid. Drop the entry.\n if (typeof r.observedAt !== \"string\" || r.observedAt === \"\") continue;\n if (typeof r.signal !== \"string\" || r.signal === \"\") continue;\n // Codex P2 round 6: previously the optional fields were never\n // type-checked, so a hand-edited `{sourceSessionId: 123}`\n // survived and corrupted the PeerProfileFieldProvenance contract.\n // Build a clean record with only string-typed optional fields.\n const clean: PeerProfileFieldProvenance = {\n observedAt: r.observedAt,\n signal: r.signal,\n ...(typeof r.sourceSessionId === \"string\" && r.sourceSessionId.length > 0\n ? { sourceSessionId: r.sourceSessionId }\n : {}),\n ...(typeof r.note === \"string\" && r.note.length > 0\n ? { note: r.note }\n : {}),\n };\n list.push(clean);\n }\n provenance[k] = list;\n }\n return { peerId, updatedAt, fields, provenance };\n}\n\n/**\n * Read a peer's profile. Returns null if the profile file does not exist.\n *\n * The PR-1 surface only ships the structured read/write so the reasoner\n * (PR 2/5) and recall integration (PR 3/5) have a stable target. We do\n * not yet expose any field-update helpers.\n */\nexport async function readPeerProfile(\n memoryDir: string,\n peerId: string,\n): Promise<PeerProfile | null> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = profilePath(memoryDir, peerId);\n let raw: string;\n try {\n raw = await readFileNoFollow(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return null;\n }\n throw err;\n }\n return parsePeerProfile(raw, peerId);\n}\n\n/**\n * Write (create or overwrite) a peer's profile.\n */\nexport async function writePeerProfile(\n memoryDir: string,\n profile: PeerProfile,\n): Promise<void> {\n assertValidPeerId(profile.peerId);\n if (typeof profile.updatedAt !== \"string\" || profile.updatedAt === \"\") {\n throw new Error(\"profile.updatedAt must be a non-empty ISO-8601 string\");\n }\n // Codex P2 round 6: validate the nested payload shape on write so\n // round-trip semantics are preserved. Without this, untyped JS\n // callers can persist non-string field values or malformed\n // provenance entries — readPeerProfile silently scrubs them on\n // the way back, so data is lost without an error. Fail fast at\n // the boundary instead.\n if (!isPlainObject(profile.fields)) {\n throw new Error(\"profile.fields must be a plain object\");\n }\n // Codex P2 round 11: parsePeerProfile drops \"__proto__\" /\n // \"constructor\" / \"prototype\" keys on read. Without symmetric\n // rejection on write, those keys silently disappear during\n // round-trip — failing the contract that what writes succeeds\n // also reads back. Reject at the boundary so JS callers learn\n // immediately that those keys aren't allowed.\n const RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n for (const [key, value] of Object.entries(profile.fields)) {\n if (RESERVED_KEYS.has(key)) {\n throw new Error(`profile.fields key \"${key}\" is reserved and cannot be persisted`);\n }\n if (typeof value !== \"string\") {\n throw new Error(`profile.fields[\"${key}\"] must be a string`);\n }\n }\n if (!isPlainObject(profile.provenance)) {\n throw new Error(\"profile.provenance must be a plain object\");\n }\n for (const [key, list] of Object.entries(profile.provenance)) {\n if (RESERVED_KEYS.has(key)) {\n throw new Error(`profile.provenance key \"${key}\" is reserved and cannot be persisted`);\n }\n if (!Array.isArray(list)) {\n throw new Error(`profile.provenance[\"${key}\"] must be an array`);\n }\n for (let i = 0; i < list.length; i++) {\n const item = list[i] as unknown;\n if (typeof item !== \"object\" || item === null || Array.isArray(item)) {\n throw new Error(`profile.provenance[\"${key}\"][${i}] must be an object`);\n }\n const r = item as Record<string, unknown>;\n if (typeof r.observedAt !== \"string\" || r.observedAt === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].observedAt must be a non-empty string`);\n }\n if (typeof r.signal !== \"string\" || r.signal === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].signal must be a non-empty string`);\n }\n // Cursor M round 9: empty optional strings would round-trip lose\n // (parsePeerProfile drops them on read). Reject at the boundary\n // for consistency with other validators in this module.\n if (r.sourceSessionId !== undefined) {\n if (typeof r.sourceSessionId !== \"string\" || r.sourceSessionId === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].sourceSessionId must be a non-empty string when provided`);\n }\n }\n if (r.note !== undefined) {\n if (typeof r.note !== \"string\" || r.note === \"\") {\n throw new Error(`profile.provenance[\"${key}\"][${i}].note must be a non-empty string when provided`);\n }\n }\n }\n }\n await mkdirPeerDirAtomic(memoryDir, profile.peerId);\n await assertPeerDirNotEscaped(memoryDir, profile.peerId);\n const file = profilePath(memoryDir, profile.peerId);\n await writeFileNoFollow(file, emitPeerProfile(profile));\n}\n\n/**\n * Read the raw interaction log for a peer.\n *\n * Returns the empty string if the log does not yet exist. Callers parse\n * the log themselves — this PR does not ship structured log parsing.\n * Exposed primarily so tests can verify monotonic append semantics.\n */\nexport async function readInteractionLogRaw(\n memoryDir: string,\n peerId: string,\n): Promise<string> {\n assertValidPeerId(peerId);\n await assertPeerDirNotEscaped(memoryDir, peerId);\n const file = interactionsPath(memoryDir, peerId);\n try {\n return await readFileNoFollow(file);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") {\n return \"\";\n }\n throw err;\n }\n}\n\n/**\n * Inverse of `formatLogEntry`. Used by `readPeerInteractionLog` to\n * convert the on-disk one-line bullet form back into a structured\n * `PeerInteractionLogEntry`. Returns `null` for malformed lines so\n * callers can keep the rest of the log even when a single entry was\n * hand-edited or partially written.\n *\n * Formats accepted (must match `formatLogEntry`):\n *\n * - [TS] (KIND) [session=SID] SUMMARY // canonical (PR #736)\n * - [TS] (KIND) SUMMARY // session optional\n *\n * The unbracketed `session=SID` form (which would have been written\n * by an earlier draft of #679 PR 2/5) is intentionally NOT parsed —\n * the cursor #736 finding showed it was indistinguishable from a\n * summary that legitimately starts with `session=`. Since #679 PR\n * 2/5 is the first shipped writer for `sessionId` AND ships the\n * bracketed canonical form simultaneously, there is no real legacy\n * data on disk to support. A summary like `session=foo bar` thus\n * round-trips verbatim into `summary` rather than being mis-claimed\n * as a session id.\n *\n * Whitespace inside SUMMARY is preserved verbatim. The parser is\n * deliberately strict — anything that doesn't start with `- [` is\n * rejected and dropped (the file is also markdown-friendly, so blank\n * lines and stray prose are simply ignored).\n */\nfunction parseLogLine(line: string): PeerInteractionLogEntry | null {\n if (!line.startsWith(\"- [\")) return null;\n const tsClose = line.indexOf(\"]\", 3);\n if (tsClose === -1) return null;\n const timestamp = line.slice(3, tsClose).trim();\n if (timestamp === \"\") return null;\n // Skip optional whitespace between `]` and `(`.\n let cursor = tsClose + 1;\n while (cursor < line.length && line[cursor] === \" \") cursor += 1;\n if (line[cursor] !== \"(\") return null;\n const kindOpen = cursor;\n const kindClose = line.indexOf(\")\", kindOpen + 1);\n if (kindClose === -1) return null;\n const kind = line.slice(kindOpen + 1, kindClose).trim();\n if (kind === \"\") return null;\n cursor = kindClose + 1;\n let sessionId: string | undefined;\n // Optional session id token. We tolerate any leading whitespace\n // count; `formatLogEntry` always emits exactly one space, but\n // operator-edited logs may diverge.\n while (cursor < line.length && line[cursor] === \" \") cursor += 1;\n // Canonical form (PR #736): `[session=<id>]`. Unambiguous because\n // a sanitized summary cannot start with `[session=` followed by a\n // closing bracket and a space — sanitization preserves user content\n // verbatim except for newlines/CR/tab, so a summary that literally\n // begins `[session=foo]` would imply the OPERATOR wrote a real\n // session marker, which is acceptable as session attribution.\n if (line.startsWith(\"[session=\", cursor)) {\n const close = line.indexOf(\"]\", cursor + \"[session=\".length);\n // A `[session=...]` with no closing bracket on the same line is\n // malformed metadata; treat the whole tail as summary instead of\n // misclaiming a session id.\n if (close > -1) {\n const sid = line.slice(cursor + \"[session=\".length, close).trim();\n if (sid.length > 0) sessionId = sid;\n cursor = close + 1;\n }\n }\n // NOTE: the legacy unbracketed `session=<id>` form is intentionally\n // NOT parsed. The cursor #736 finding is fundamentally a format\n // ambiguity: `- [TS] (KIND) session=foo bar` is indistinguishable\n // from a real session token vs. a summary that begins with the\n // literal text `session=foo bar`. Since #679 PR 2/5 is the first\n // PR that writes `sessionId` to the log AND ships the bracketed\n // canonical form simultaneously, there is no production legacy\n // data to support. Old `session=`-style summaries — both real\n // operator notes and hypothetical legacy entries — round-trip\n // verbatim into `summary` rather than being silently mis-claimed\n // as a session id.\n // Remaining tail is the summary (possibly empty if the log was\n // hand-edited; we still accept \"\" because `formatLogEntry` itself\n // accepts an empty summary string).\n while (cursor < line.length && line[cursor] === \" \") cursor += 1;\n const summary = line.slice(cursor);\n return sessionId === undefined\n ? { timestamp, kind, summary }\n : { timestamp, kind, sessionId, summary };\n}\n\n/**\n * Read the structured interaction log for a peer.\n *\n * Returns an empty array when the log file does not exist. Each line\n * is parsed via `parseLogLine`; malformed lines are silently skipped\n * so the reasoner can still derive profile fields from a partially\n * corrupt log rather than aborting the whole pass.\n *\n * `options.limit` (when > 0) restricts the result to the most recent\n * N entries. `options.afterTimestamp` (ISO-8601) filters out entries\n * with `timestamp < afterTimestamp` (string compare is safe for\n * canonical ISO-8601 form). Both filters are applied in order:\n * timestamp first, then limit.\n *\n * Order: oldest → newest, matching the append-only on-disk order so\n * downstream consumers can reason about temporal evolution without\n * re-sorting.\n */\nexport async function readPeerInteractionLog(\n memoryDir: string,\n peerId: string,\n options: { limit?: number; afterTimestamp?: string } = {},\n): Promise<PeerInteractionLogEntry[]> {\n const raw = await readInteractionLogRaw(memoryDir, peerId);\n if (raw === \"\") return [];\n const entries: PeerInteractionLogEntry[] = [];\n // Split on bare newlines; logs are written with a trailing `\\n` per\n // entry by `appendInteractionLog`, so the final element after split\n // is typically the empty string. Both `\\r\\n` and `\\n` are tolerated.\n for (const lineRaw of raw.split(/\\r?\\n/)) {\n const line = lineRaw.trimEnd();\n if (line === \"\") continue;\n const parsed = parseLogLine(line);\n if (parsed === null) continue;\n entries.push(parsed);\n }\n let filtered = entries;\n if (typeof options.afterTimestamp === \"string\" && options.afterTimestamp.length > 0) {\n const cutoff = options.afterTimestamp;\n filtered = filtered.filter((e) => e.timestamp > cutoff);\n }\n // Gotcha #27: guard slice(-n) against n === 0 — `slice(-0)` returns\n // the entire array. Treat 0 and negatives as \"no limit applied\".\n if (typeof options.limit === \"number\" && options.limit > 0) {\n if (filtered.length > options.limit) {\n filtered = filtered.slice(filtered.length - options.limit);\n }\n }\n return filtered;\n}\n","/**\n * Peer registry types — issue #679 PR 1/5.\n *\n * Generalizes the singular identity-anchor model to a multi-peer registry.\n * Every party Remnic interacts with — humans, agents, integrations, and\n * \"self\" — is represented as a `Peer` with an evolving cognitive profile.\n *\n * This module defines pure types only. Storage primitives live in\n * `./storage.ts`. Reasoner integration, recall injection, CLI/HTTP/MCP\n * surfaces, and migration of existing identity-anchor data ship in later\n * PRs (2/5 — 5/5).\n */\n\n/**\n * Kind of peer.\n *\n * - `self` — the current Remnic operator (replaces singular identity-anchor).\n * - `human` — another human collaborator distinct from self.\n * - `agent` — another AI agent (Claude Code, Codex, Hermes, etc.).\n * - `integration` — non-conversational integration (cron, webhook, importer).\n */\nexport type PeerKind = \"self\" | \"human\" | \"agent\" | \"integration\";\n\n/**\n * Stable, slow-changing facts about a peer.\n *\n * `id` matches `^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$`, 1-64 chars,\n * with no leading/trailing/consecutive dots or dashes. Stored on disk under\n * `peers/{id}/identity.md` as YAML frontmatter + markdown body.\n */\nexport interface Peer {\n /** Stable, opaque identifier. See PEER_ID_PATTERN. */\n readonly id: string;\n /** Kind of peer. Drives default profile schema and recall posture. */\n readonly kind: PeerKind;\n /** Human-readable display name. Distinct from `id`; mutable. */\n readonly displayName: string;\n /** ISO-8601 timestamp of first registration. */\n readonly createdAt: string;\n /** ISO-8601 timestamp of most recent update to identity. */\n readonly updatedAt: string;\n /** Optional free-form markdown body for the identity kernel. */\n readonly notes?: string;\n}\n\n/**\n * Evolving cognitive profile for a peer.\n *\n * Updated by the async profile reasoner (PR 2/5) from observable session\n * signals. Every field carries provenance back to its originating session\n * and signal. This PR only defines the shape — population is deferred.\n */\nexport interface PeerProfile {\n /** Peer this profile belongs to. */\n readonly peerId: string;\n /** ISO-8601 timestamp of most recent profile mutation. */\n readonly updatedAt: string;\n /**\n * Arbitrary key/value profile fields. Values are markdown strings.\n * Keys are stable section identifiers (e.g. `communication_style`,\n * `recurring_concerns`). The reasoner is responsible for choosing\n * keys; this PR does not constrain them beyond requiring strings.\n */\n readonly fields: Record<string, string>;\n /**\n * Per-field provenance. Maps field key → list of provenance entries.\n * A field may have multiple sources (the reasoner accumulates evidence\n * across sessions before promoting a field).\n */\n readonly provenance: Record<string, ReadonlyArray<PeerProfileFieldProvenance>>;\n}\n\n/**\n * Provenance for a single profile-field mutation.\n *\n * Reasoner output (PR 2/5) attaches one of these every time it touches a\n * field, so the user can audit exactly why a profile claim exists.\n */\nexport interface PeerProfileFieldProvenance {\n /** ISO-8601 timestamp the field was set/updated by this signal. */\n readonly observedAt: string;\n /** Originating session id (or other source identifier). */\n readonly sourceSessionId?: string;\n /** Short label for the signal type (e.g. \"explicit_preference\"). */\n readonly signal: string;\n /** Optional free-form note explaining the inference. */\n readonly note?: string;\n}\n\n/**\n * One row of the append-only interaction log for a peer.\n *\n * Stored on disk under `peers/{id}/interactions.log.md` as a sequence of\n * markdown bullet entries with a leading ISO-8601 timestamp. Append-only\n * by contract — the reasoner reads this log to derive profile updates.\n */\nexport interface PeerInteractionLogEntry {\n /** ISO-8601 timestamp the interaction occurred. */\n readonly timestamp: string;\n /** Originating session id, if any. */\n readonly sessionId?: string;\n /** Short kind label (e.g. \"message\", \"tool_call\", \"preference_set\"). */\n readonly kind: string;\n /** Free-form markdown summary of the interaction. */\n readonly summary: string;\n}\n\n/**\n * Regex enforced on `Peer.id`. Exported so callers can mirror validation\n * before constructing a `Peer`.\n *\n * Rules:\n * - 1-64 characters total\n * - First and last character must be `[A-Za-z0-9]`\n * - Interior may contain `.`, `_`, `-` in addition to alphanumerics\n * - No leading or trailing dot/dash/underscore\n * - No consecutive separators (`..`, `--`, `__`, `.-`, etc.)\n *\n * Cursor Medium: previously the regex allowed `a..b` even though the\n * docs claimed otherwise — a separate JS-side check enforced the rule\n * but the standalone PATTERN was wrong for any external consumer\n * relying on it. Tighten the regex itself so PEER_ID_PATTERN is the\n * single source of truth: an alphanumeric, optionally followed by\n * groups of (one separator + one-or-more alphanumerics), with the\n * final group ending on an alphanumeric. Negative lookahead-free so\n * it works in any JS engine.\n */\n// CodeQL alert #75: the previous form `^[A-Za-z0-9](?:[._-]?[A-Za-z0-9]+)*$`\n// was ambiguous on alphanumeric runs because `[._-]?` could match\n// empty, letting each iteration consume 1+ alphanumerics in many\n// overlapping ways — exponential backtracking on adversarial inputs.\n// Tighten so the optional group REQUIRES a separator before each\n// subsequent alphanumeric run; no overlapping match paths, linear\n// time on any input.\nexport const PEER_ID_PATTERN = /^[A-Za-z0-9]+(?:[._-][A-Za-z0-9]+)*$/;\n\n/** Maximum length for `Peer.id`. */\nexport const PEER_ID_MAX_LENGTH = 64;\n"],"mappings":";AAoDA,SAAS,YAAYA,KAAI,aAAaC,oBAAmB;AACzD,OAAOC,WAAU;;;ACpCjB,SAAS,YAAY,IAAI,aAAa,mBAAmB;AACzD,OAAO,UAAU;;;ACoHV,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;;;AD9GlC,eAAe,aAAa,MAAc,OAA+D;AACvG,SAAO,GAAG,KAAK,MAAM,QAAQ,YAAY,UAAU;AACrD;AAIA,eAAe,iBAAiB,MAA+B;AAC7D,QAAM,2BAA2B,IAAI;AACrC,QAAM,KAAK,MAAM,aAAa,MAAM,YAAY,QAAQ;AACxD,MAAI;AACF,WAAO,MAAM,GAAG,SAAS,MAAM;AAAA,EACjC,UAAE;AACA,UAAM,GAAG,MAAM;AAAA,EACjB;AACF;AAmBA,eAAe,2BAA2B,UAAiC;AACzE,QAAM,SAAS,KAAK,QAAQ,QAAQ;AACpC,QAAM,KAAK,MAAM,GAAG;AAAA,IAClB;AAAA,IACA,YAAY,WAAW,YAAY,cAAc,YAAY;AAAA,EAC/D;AACA,MAAI;AACF,UAAM,YAAY,MAAM,GAAG,KAAK;AAChC,UAAM,YAAY,MAAM,GAAG,MAAM,MAAM;AACvC,QAAI,UAAU,QAAQ,UAAU,OAAO,UAAU,QAAQ,UAAU,KAAK;AACtE,YAAM,IAAI;AAAA,QACR,qBAAqB,MAAM;AAAA,MAC7B;AAAA,IACF;AACA,QAAI,UAAU,eAAe,GAAG;AAC9B,YAAM,IAAI,MAAM,qBAAqB,MAAM,gCAAgC;AAAA,IAC7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rB;AAAA,QACAC,aAAY,WAAWA,aAAY,UAAUA,aAAY,SAASA,aAAY;AAAA,MAChF;AAAA,IACF,SAAS,KAAK;AACZ,YAAM,OAAQ,IAA8B;AAC5C,UAAI,SAAS,UAAU;AAGrB,cAAM,aAAa,MAAM,SAAS,WAAW,MAAM;AACnD,eAAO;AAAA,UACL,MAAM,cAAc;AAAA,UACpB,SAAS;AAAA,UACT,SAAS;AAAA,UACT;AAAA,UACA,sBAAsB;AAAA,UACtB,kBAAkB;AAAA,QACpB;AAAA,MACF;AACA,YAAM;AAAA,IACR,UAAE;AACA,UAAI,gBAAgB,KAAM,OAAM,YAAY,MAAM;AAAA,IACpD;AAGA,UAAM,UAAU,WAAW,IAAI;AAAA,EACjC;AAEA,SAAO;AAAA,IACL;AAAA,IACA,SAAS,CAAC;AAAA,IACV,SAAS;AAAA,IACT;AAAA,IACA,sBAAsB,aAAa;AAAA,IACnC,kBAAkB,iBAAiB;AAAA,EACrC;AACF;","names":["fs","fsConstants","path","path","fs","fsConstants"]}
|
|
@@ -3,13 +3,13 @@ import {
|
|
|
3
3
|
} from "./chunk-IXEJRKCZ.js";
|
|
4
4
|
import {
|
|
5
5
|
StorageManager
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-MCC6KDQF.js";
|
|
7
7
|
import {
|
|
8
8
|
parseContinuityImprovementLoops
|
|
9
9
|
} from "./chunk-QSVPYQPG.js";
|
|
10
10
|
import {
|
|
11
11
|
sanitizeMemoryContent
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-FVQJYWH7.js";
|
|
13
13
|
import {
|
|
14
14
|
log
|
|
15
15
|
} from "./chunk-2ODBA7MQ.js";
|
|
@@ -839,6 +839,7 @@ var CompoundingEngine = class {
|
|
|
839
839
|
causalTrajectoryStoreDir: this.config.causalTrajectoryStoreDir,
|
|
840
840
|
gatewayConfig: this.config.gatewayConfig,
|
|
841
841
|
gatewayAgentId: this.config.modelSource === "gateway" ? this.config.gatewayAgentId || void 0 : void 0,
|
|
842
|
+
workspaceDir: this.config.workspaceDir,
|
|
842
843
|
pluginConfig: this.config,
|
|
843
844
|
config: {
|
|
844
845
|
minRecurrence: this.config.cmcConsolidationMinRecurrence,
|
|
@@ -869,7 +870,8 @@ var CompoundingEngine = class {
|
|
|
869
870
|
const calRules = await runCalibrationConsolidation({
|
|
870
871
|
memoryDir: this.config.memoryDir,
|
|
871
872
|
gatewayConfig: this.config.gatewayConfig,
|
|
872
|
-
gatewayAgentId: this.config.modelSource === "gateway" ? this.config.gatewayAgentId || void 0 : void 0
|
|
873
|
+
gatewayAgentId: this.config.modelSource === "gateway" ? this.config.gatewayAgentId || void 0 : void 0,
|
|
874
|
+
workspaceDir: this.config.workspaceDir
|
|
873
875
|
});
|
|
874
876
|
log.debug(`[calibration] weekly synthesis produced ${calRules.length} calibration rule(s)`);
|
|
875
877
|
} catch (error) {
|
|
@@ -1832,4 +1834,4 @@ export {
|
|
|
1832
1834
|
defaultTierMigrationCycleBudget,
|
|
1833
1835
|
CompoundingEngine
|
|
1834
1836
|
};
|
|
1835
|
-
//# sourceMappingURL=chunk-
|
|
1837
|
+
//# sourceMappingURL=chunk-4DXC6HQQ.js.map
|