@theokit/sdk 5.4.0 → 5.6.0

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 (132) hide show
  1. package/CHANGELOG.md +642 -0
  2. package/dist/{agent-AUVD4TI4.cjs → agent-47NS6ZVL.cjs} +13 -13
  3. package/dist/{agent-AUVD4TI4.cjs.map → agent-47NS6ZVL.cjs.map} +1 -1
  4. package/dist/{agent-C1Efo7PI.d.cts → agent-82d_DrCL.d.cts} +33 -2
  5. package/dist/{agent-Bmy2G_ml.d.ts → agent-G6g-uwcB.d.ts} +33 -2
  6. package/dist/{agent-MNINE73R.js → agent-JJZM2VIK.js} +12 -12
  7. package/dist/{agent-MNINE73R.js.map → agent-JJZM2VIK.js.map} +1 -1
  8. package/dist/{chunk-IKBLU7ZS.js → chunk-2UXQASTX.js} +232 -32
  9. package/dist/chunk-2UXQASTX.js.map +1 -0
  10. package/dist/{chunk-VPK6PHIE.cjs → chunk-52FDUJSV.cjs} +8 -8
  11. package/dist/{chunk-VPK6PHIE.cjs.map → chunk-52FDUJSV.cjs.map} +1 -1
  12. package/dist/{chunk-2XRAWOZZ.js → chunk-5NELQ6LB.js} +65 -3
  13. package/dist/chunk-5NELQ6LB.js.map +1 -0
  14. package/dist/{chunk-3FDU5JFE.cjs → chunk-7IZKTQ5G.cjs} +35 -7
  15. package/dist/chunk-7IZKTQ5G.cjs.map +1 -0
  16. package/dist/{chunk-7SZAV6QG.js → chunk-7MMTZBTT.js} +3 -3
  17. package/dist/{chunk-7SZAV6QG.js.map → chunk-7MMTZBTT.js.map} +1 -1
  18. package/dist/{chunk-SADXXGWU.js → chunk-BZ3YMAMP.js} +3 -3
  19. package/dist/{chunk-NQTNSHSB.cjs.map → chunk-BZ3YMAMP.js.map} +1 -1
  20. package/dist/{chunk-LX7SEXOQ.js → chunk-CA5VUAP3.js} +25 -7
  21. package/dist/chunk-CA5VUAP3.js.map +1 -0
  22. package/dist/{chunk-IU5N5224.cjs → chunk-EIOMN5VA.cjs} +8 -8
  23. package/dist/chunk-EIOMN5VA.cjs.map +1 -0
  24. package/dist/{chunk-KWGSBZ2Q.js → chunk-FPIY5CLV.js} +3 -3
  25. package/dist/{chunk-KWGSBZ2Q.js.map → chunk-FPIY5CLV.js.map} +1 -1
  26. package/dist/{chunk-UALC6Q3J.cjs → chunk-GCHZMH42.cjs} +290 -88
  27. package/dist/chunk-GCHZMH42.cjs.map +1 -0
  28. package/dist/{chunk-NQTNSHSB.cjs → chunk-GFFBXSQT.cjs} +5 -5
  29. package/dist/chunk-GFFBXSQT.cjs.map +1 -0
  30. package/dist/{chunk-J6KZE2ZQ.cjs → chunk-HG4UN4MN.cjs} +4 -4
  31. package/dist/{chunk-J6KZE2ZQ.cjs.map → chunk-HG4UN4MN.cjs.map} +1 -1
  32. package/dist/{chunk-N6OOOYFZ.js → chunk-HUDNLFY4.js} +4 -4
  33. package/dist/chunk-HUDNLFY4.js.map +1 -0
  34. package/dist/{chunk-LOHMT36V.cjs → chunk-LD6HASA5.cjs} +65 -2
  35. package/dist/chunk-LD6HASA5.cjs.map +1 -0
  36. package/dist/{chunk-QATRS7JD.cjs → chunk-MYJGWS2J.cjs} +26 -8
  37. package/dist/chunk-MYJGWS2J.cjs.map +1 -0
  38. package/dist/{chunk-XD3FS5OI.js → chunk-N2KAIZ5D.js} +34 -7
  39. package/dist/chunk-N2KAIZ5D.js.map +1 -0
  40. package/dist/{chunk-HW7SEELD.cjs → chunk-QRVS2PRE.cjs} +31 -8
  41. package/dist/chunk-QRVS2PRE.cjs.map +1 -0
  42. package/dist/{chunk-AYA65JA5.cjs → chunk-RWPLWMCZ.cjs} +25 -9
  43. package/dist/chunk-RWPLWMCZ.cjs.map +1 -0
  44. package/dist/{chunk-WS5ULCL4.js → chunk-STGSMJMJ.js} +3 -3
  45. package/dist/{chunk-WS5ULCL4.js.map → chunk-STGSMJMJ.js.map} +1 -1
  46. package/dist/{chunk-O7L7M42F.js → chunk-T3ZDEYTJ.js} +21 -5
  47. package/dist/chunk-T3ZDEYTJ.js.map +1 -0
  48. package/dist/{chunk-43YXGD3P.cjs → chunk-TY56BKSK.cjs} +8 -4
  49. package/dist/chunk-TY56BKSK.cjs.map +1 -0
  50. package/dist/chunk-UOLBAPDM.js +66 -0
  51. package/dist/chunk-UOLBAPDM.js.map +1 -0
  52. package/dist/{chunk-Z2JFX372.cjs → chunk-VUHXC74Q.cjs} +15 -15
  53. package/dist/{chunk-Z2JFX372.cjs.map → chunk-VUHXC74Q.cjs.map} +1 -1
  54. package/dist/{chunk-NSLHPAC7.js → chunk-X7EUUHXU.js} +6 -5
  55. package/dist/chunk-X7EUUHXU.js.map +1 -0
  56. package/dist/context/index.cjs +7 -7
  57. package/dist/context/index.js +3 -3
  58. package/dist/{context-4AIK26QB.cjs → context-HR4KMXMA.cjs} +7 -7
  59. package/dist/{context-4AIK26QB.cjs.map → context-HR4KMXMA.cjs.map} +1 -1
  60. package/dist/context-J5BJ3LBS.js +6 -0
  61. package/dist/{context-EGM6CHXD.js.map → context-J5BJ3LBS.js.map} +1 -1
  62. package/dist/{cron-DSMdlhyF.d.cts → cron-DWv69ZSD.d.cts} +1 -1
  63. package/dist/{cron-Dcdrdv_T.d.ts → cron-GynWtAax.d.ts} +1 -1
  64. package/dist/cron.cjs +12 -12
  65. package/dist/cron.d.cts +2 -2
  66. package/dist/cron.d.ts +2 -2
  67. package/dist/cron.js +11 -11
  68. package/dist/eval.cjs +11 -11
  69. package/dist/eval.js +10 -10
  70. package/dist/{index-manager-W7FDMGEG.js → index-manager-27WLNQEE.js} +5 -5
  71. package/dist/{index-manager-W7FDMGEG.js.map → index-manager-27WLNQEE.js.map} +1 -1
  72. package/dist/{index-manager-3UNPYH34.cjs → index-manager-BBHDKMQS.cjs} +6 -6
  73. package/dist/{index-manager-3UNPYH34.cjs.map → index-manager-BBHDKMQS.cjs.map} +1 -1
  74. package/dist/index.cjs +274 -40
  75. package/dist/index.cjs.map +1 -1
  76. package/dist/index.d.cts +168 -5
  77. package/dist/index.d.ts +168 -5
  78. package/dist/index.js +246 -23
  79. package/dist/index.js.map +1 -1
  80. package/dist/internal/memory/storage/index.cjs +32 -32
  81. package/dist/internal/memory/storage/index.js +3 -3
  82. package/dist/internal/memory/storage/memory-root.d.cts +27 -0
  83. package/dist/internal/memory/storage/memory-root.d.ts +27 -0
  84. package/dist/internal/persistence/index.cjs +4 -4
  85. package/dist/internal/persistence/index.js +1 -1
  86. package/dist/internal/runtime/compat/foreign-config-sources.d.ts +17 -4
  87. package/dist/internal/runtime/compat/managed-settings.d.ts +80 -0
  88. package/dist/internal/runtime/context/context-discovery-runner.d.ts +14 -0
  89. package/dist/internal/runtime/context/context-discovery.d.ts +37 -0
  90. package/dist/internal/runtime/context/context-manager.d.ts +21 -1
  91. package/dist/internal/runtime/context/yaml-frontmatter.d.ts +6 -3
  92. package/dist/internal/runtime/hooks/hooks-executor.d.ts +23 -1
  93. package/dist/internal/runtime/hooks/hooks-source.d.ts +46 -1
  94. package/dist/internal/runtime/skills/discover-skills.d.ts +4 -0
  95. package/dist/project.cjs +3 -3
  96. package/dist/project.js +1 -1
  97. package/dist/skills.cjs +5 -5
  98. package/dist/skills.js +2 -2
  99. package/dist/subagents-loader-CJFYQQU2.js +7 -0
  100. package/dist/{subagents-loader-AIVDQ2D5.js.map → subagents-loader-CJFYQQU2.js.map} +1 -1
  101. package/dist/subagents-loader-MOO7DC4E.cjs +16 -0
  102. package/dist/{subagents-loader-DN4LETGL.cjs.map → subagents-loader-MOO7DC4E.cjs.map} +1 -1
  103. package/dist/subagents-loader.cjs +4 -4
  104. package/dist/subagents-loader.d.cts +1 -1
  105. package/dist/subagents-loader.d.ts +1 -1
  106. package/dist/subagents-loader.js +3 -3
  107. package/dist/types/agent.d.ts +6 -1
  108. package/dist/types/hooks.d.ts +22 -0
  109. package/docs/error-codes.md +20 -18
  110. package/docs/harness-capability-map.md +9 -1
  111. package/package.json +1 -1
  112. package/dist/chunk-2XRAWOZZ.js.map +0 -1
  113. package/dist/chunk-3FDU5JFE.cjs.map +0 -1
  114. package/dist/chunk-43YXGD3P.cjs.map +0 -1
  115. package/dist/chunk-AYA65JA5.cjs.map +0 -1
  116. package/dist/chunk-HW7SEELD.cjs.map +0 -1
  117. package/dist/chunk-IKBLU7ZS.js.map +0 -1
  118. package/dist/chunk-IU5N5224.cjs.map +0 -1
  119. package/dist/chunk-JNAA4G4H.js +0 -43
  120. package/dist/chunk-JNAA4G4H.js.map +0 -1
  121. package/dist/chunk-LOHMT36V.cjs.map +0 -1
  122. package/dist/chunk-LX7SEXOQ.js.map +0 -1
  123. package/dist/chunk-N6OOOYFZ.js.map +0 -1
  124. package/dist/chunk-NSLHPAC7.js.map +0 -1
  125. package/dist/chunk-O7L7M42F.js.map +0 -1
  126. package/dist/chunk-QATRS7JD.cjs.map +0 -1
  127. package/dist/chunk-SADXXGWU.js.map +0 -1
  128. package/dist/chunk-UALC6Q3J.cjs.map +0 -1
  129. package/dist/chunk-XD3FS5OI.js.map +0 -1
  130. package/dist/context-EGM6CHXD.js +0 -6
  131. package/dist/subagents-loader-AIVDQ2D5.js +0 -7
  132. package/dist/subagents-loader-DN4LETGL.cjs +0 -16
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkNQTNSHSB_cjs = require('./chunk-NQTNSHSB.cjs');
3
+ var chunkGFFBXSQT_cjs = require('./chunk-GFFBXSQT.cjs');
4
4
  var chunkJLRLCBJ4_cjs = require('./chunk-JLRLCBJ4.cjs');
5
5
  var chunkJ7J7J2GN_cjs = require('./chunk-J7J7J2GN.cjs');
6
6
  var chunk6LHQPOMI_cjs = require('./chunk-6LHQPOMI.cjs');
@@ -51,9 +51,9 @@ function entryHash(entry) {
51
51
  ).digest("hex");
52
52
  }
53
53
  async function readAllSqliteFacts(root) {
54
- const dbPath = chunkNQTNSHSB_cjs.defaultIndexPath(root);
54
+ const dbPath = chunkGFFBXSQT_cjs.defaultIndexPath(root);
55
55
  if (!fs.existsSync(dbPath)) return [];
56
- const db = await chunkNQTNSHSB_cjs.openMemoryDb({ filePath: dbPath });
56
+ const db = await chunkGFFBXSQT_cjs.openMemoryDb({ filePath: dbPath });
57
57
  try {
58
58
  const stmt = db.prepare("SELECT id, path, source, start_line, end_line, text FROM chunks");
59
59
  const rows = stmt.all();
@@ -82,8 +82,8 @@ function assertUsableBatchSize(batchSize) {
82
82
  async function migrateSqliteToLance(opts) {
83
83
  assertUsableBatchSize(opts.batchSize);
84
84
  const cwd = opts.cwd;
85
- const memoryRoot = chunkNQTNSHSB_cjs.resolveMemoryRoot(cwd, { directory: opts.directory });
86
- const finalPath = chunkNQTNSHSB_cjs.lanceStoragePath(memoryRoot);
85
+ const memoryRoot = chunkGFFBXSQT_cjs.resolveMemoryRoot(cwd, { directory: opts.directory });
86
+ const finalPath = chunkGFFBXSQT_cjs.lanceStoragePath(memoryRoot);
87
87
  const newPath = path.join(memoryRoot, "lance-new");
88
88
  const rawLog = opts.logger ?? ((m) => console.log(m));
89
89
  const log = (m) => rawLog(chunk6LHQPOMI_cjs.redactSecrets(m));
@@ -127,7 +127,7 @@ async function migrateSqliteToLance(opts) {
127
127
  };
128
128
  fs.mkdirSync(newPath, { recursive: true });
129
129
  log(`Writing Lance index to ${newPath} ...`);
130
- const lance = await chunkNQTNSHSB_cjs.LanceIndex.open({
130
+ const lance = await chunkGFFBXSQT_cjs.LanceIndex.open({
131
131
  cwd,
132
132
  embedding: placeholderEmbedding,
133
133
  storagePath: newPath
@@ -207,5 +207,5 @@ exports.entryHash = entryHash;
207
207
  exports.migrateSqliteToLance = migrateSqliteToLance;
208
208
  exports.readAllSqliteFacts = readAllSqliteFacts;
209
209
  exports.renderDiaryEntry = renderDiaryEntry;
210
- //# sourceMappingURL=chunk-VPK6PHIE.cjs.map
211
- //# sourceMappingURL=chunk-VPK6PHIE.cjs.map
210
+ //# sourceMappingURL=chunk-52FDUJSV.cjs.map
211
+ //# sourceMappingURL=chunk-52FDUJSV.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/internal/memory/dreaming/diary.ts","../src/internal/memory/migrate-sqlite-to-lance.ts"],"names":["join","readFile","replaceFileAtomic","createHash","defaultIndexPath","existsSync","openMemoryDb","ConfigurationError","resolveMemoryRoot","lanceStoragePath","redactSecrets","rmSync","mkdirSync","LanceIndex","renameSync"],"mappings":";;;;;;;;;;;AA6BO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAOA,SAAA,CAAK,MAAM,gBAAgB,CAAA;AACpC;AAOO,SAAS,iBAAiB,KAAA,EAA2B;AAC1D,EAAA,MAAM,QAAQ,IAAI,IAAA,CAAK,KAAA,CAAM,WAAW,EAAE,WAAA,EAAY;AACtD,EAAA,MAAM,OAAO,SAAA,CAAU,KAAK,CAAA,CAAE,KAAA,CAAM,GAAG,CAAC,CAAA;AACxC,EAAA,OAAO;AAAA,IACL,MAAM,KAAK,CAAA,CAAA;AAAA,IACX,EAAA;AAAA,IACA,iBAAiB,IAAI,CAAA,CAAA;AAAA,IACrB,CAAA,gBAAA,EAAmB,MAAM,WAAW,CAAA,CAAA;AAAA,IACpC,CAAA,eAAA,EAAkB,MAAM,UAAU,CAAA,CAAA;AAAA,IAClC,CAAA,sBAAA,EAAyB,MAAM,iBAAiB,CAAA,CAAA;AAAA,IAChD,CAAA,oBAAA,EAAuB,MAAM,eAAe,CAAA,CAAA;AAAA,IAC5C,CAAA,iBAAA,EAAoB,MAAM,YAAY,CAAA,CAAA;AAAA,IACtC;AAAA,GACF,CAAE,KAAK,IAAI,CAAA;AACb;AAQA,eAAsB,gBAAA,CAAiB,MAAkB,KAAA,EAAkC;AACzF,EAAA,MAAM,IAAA,GAAO,UAAU,IAAI,CAAA;AAC3B,EAAA,IAAI,GAAA,GAAM,EAAA;AACV,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAMC,iBAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AAAA,EACnC,CAAA,CAAA,MAAQ;AACN,IAAA,GAAA,GAA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B,IAAA,GAAA,CAAI,mDAA8C,CAAA;AAClD,IAAAF,SAAA,CAAO,SAAS,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAChD,IAAA,OAAO;AAAA,MACL,aAAa,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA,EAAY,UAAA;AAAA,MACZ,SAAA;AAAA,MACA,iBAAA;AAAA,MACA,SAAA,EAAW,SAAA;AAAA,MACX,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAEA,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,GAAA,CAAI,6EAAwE,CAAA;AAC5E,IAAAA,SAAA,CAAO,SAAS,EAAE,SAAA,EAAW,IAAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAChD,IAAA,OAAO;AAAA,MACL,aAAa,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA,EAAY,UAAA;AAAA,MACZ,SAAA,EAAW,KAAA;AAAA,MACX,iBAAA;AAAA,MACA,SAAA,EAAW,SAAA;AAAA,MACX,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAGA,EAAAG,aAAA,CAAW,SAAS,SAAS,CAAA;AAC7B,EAAA,GAAA,CAAI,CAAA,uBAAA,EAA0B,SAAS,CAAA,CAAA,CAAG,CAAA;AAC1C,EAAA,OAAO;AAAA,IACL,aAAa,WAAA,CAAY,MAAA;AAAA,IACzB,UAAA,EAAY,UAAA;AAAA,IACZ,SAAA,EAAW,IAAA;AAAA,IACX,iBAAA;AAAA,IACA,SAAA,EAAW,SAAA;AAAA,IACX,SAAA,EAAW;AAAA,GACb;AACF","file":"chunk-VPK6PHIE.cjs","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport type { MemoryRoot } from \"../storage/memory-root.js\";\n\n/**\n * Dream-diary append (ADR D7).\n *\n * Diary lives at `.theokit/memory/dream-diary.md` and grows with one entry\n * per sweep. Each entry is content-hashed so the same input produces the\n * same entry — idempotency contract.\n *\n * Writes go through `replaceFileAtomic` (EC-3 of edge-case review) so a\n * crash mid-write can never leave a half-written diary.\n *\n * Shared with `@theokit/sdk-memory`; see the memory-store barrel.\n */\n\nexport interface DiaryEntry {\n timestampMs: number;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/** `<memory root>/dream-diary.md`. Takes the RESOLVED ROOT — see `storage/memory-root.ts` (#463). */\nexport function diaryPath(root: MemoryRoot): string {\n return join(root, \"dream-diary.md\");\n}\n\n/**\n * One diary entry as the markdown that gets appended: a timestamp heading, the short entry hash,\n * and the counts the sweep produced. The hash is what makes a re-run recognisable as the same\n * sweep rather than a new one.\n */\nexport function renderDiaryEntry(entry: DiaryEntry): string {\n const stamp = new Date(entry.timestampMs).toISOString();\n const hash = entryHash(entry).slice(0, 8);\n return [\n `## ${stamp}`,\n \"\",\n `- entry-hash: ${hash}`,\n `- facts before: ${entry.factsBefore}`,\n `- facts after: ${entry.factsAfter}`,\n `- duplicates removed: ${entry.duplicatesRemoved}`,\n `- clusters created: ${entry.clustersCreated}`,\n `- notes written: ${entry.notesWritten}`,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Append one sweep's entry to `<memory root>/dream-diary.md`, creating the file with its header\n * when this is the first sweep. The diary is a human-readable record of what dreaming changed —\n * consolidations are otherwise invisible, because they alter the notes rather than announce\n * themselves.\n */\nexport async function appendDiaryEntry(root: MemoryRoot, entry: DiaryEntry): Promise<void> {\n const path = diaryPath(root);\n let raw = \"\";\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n raw = \"# Dream Diary\\n\\n\";\n }\n const next = `${raw.endsWith(\"\\n\") ? raw : `${raw}\\n`}${renderDiaryEntry(entry)}`;\n await replaceFileAtomic(path, next);\n}\n\n/**\n * A stable hash of one entry's counts, so two sweeps that did the same work read as the same work.\n * Rendered truncated in the entry; the full value is what callers compare.\n */\nexport function entryHash(entry: DiaryEntry): string {\n return createHash(\"sha256\")\n .update(\n [\n entry.factsBefore,\n entry.factsAfter,\n entry.duplicatesRemoved,\n entry.clustersCreated,\n entry.notesWritten,\n ].join(\"|\"),\n )\n .digest(\"hex\");\n}\n","import { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { defaultIndexPath, openMemoryDb } from \"./index-db.js\";\nimport { LanceIndex, lanceStoragePath } from \"./lance-index.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n/**\n * Migrate Memory.index from SQLite to LanceDB (ADR D44).\n *\n * EC-3 MUST FIX: validation uses NFC unicode normalization on both sides.\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel (#463).\n */\n\nexport interface MigrateOptions {\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to migrate, when the agent that wrote it\n * set `memory.directory`. Defaults to `<cwd>/.theokit/memory` (#463).\n */\n directory?: string;\n dryRun?: boolean;\n batchSize?: number;\n /** Inject for tests; defaults to console.log. */\n logger?: (msg: string) => void;\n}\n\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n /** Set when validation succeeded (or dryRun); false on validation failure. */\n validated: boolean;\n /** Per-fact compare results (size = sample count, up to 10). */\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n /** Lance storage location (final, after migration). */\n lancePath: string;\n /** Was the migration committed (false for dry-run). */\n committed: boolean;\n}\n\n/**\n * One row of the SQLite memory index, as the Lance migration reads it: the chunk plus the tenant\n * columns the target table needs. Shared with `@theokit/sdk-memory`, which migrates the same table.\n */\nexport interface SqliteFactRow {\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n namespace?: string | null;\n scope?: string | null;\n user_id?: string | null;\n}\n\n/**\n * Read all facts from the SQLite memory index. Returns empty array if the\n * SQLite db file does not exist (workspace never used Memory).\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel, so it carries no visibility\n * tag — naming that tag in this block would delete the function below it (#463).\n */\nexport async function readAllSqliteFacts(root: MemoryRoot): Promise<SqliteFactRow[]> {\n const dbPath = defaultIndexPath(root);\n if (!existsSync(dbPath)) return [];\n const db = await openMemoryDb({ filePath: dbPath });\n try {\n // SQLite schema: chunks table holds the facts. Schema may vary; we\n // probe column existence and fall back to safe defaults.\n const stmt = db.prepare(\"SELECT id, path, source, start_line, end_line, text FROM chunks\");\n const rows = stmt.all() as Array<{\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n }>;\n return rows.map((r) => ({\n ...r,\n namespace: \"default\",\n scope: \"agent\",\n user_id: \"default\",\n }));\n } finally {\n db.close();\n }\n}\n\n/**\n * Compare two strings via NFC normalization (EC-3 MUST FIX). Required\n * because SQLite/Lance native bindings can normalize unicode differently\n * (NFC vs NFD), producing false negatives on facts with accents/emojis.\n *\n * @internal\n */\nfunction nfcEqual(a: string, b: string): boolean {\n return a.normalize(\"NFC\") === b.normalize(\"NFC\");\n}\n\n/**\n * Refuse a `batchSize` the loop below cannot make progress with, before anything is migrated.\n *\n * The loop is `for (let i = 0; i < facts.length; i += batchSize)`, so the three ways this goes wrong\n * are all silent and all different:\n *\n * - 0 or negative: `i` never advances past the guard. The migration SPINS FOREVER, calling\n * `addFacts([])` and writing a \"Migrated x/y\" line every iteration — a hang with unbounded output,\n * which is the worst shape a failure can take because it looks like work.\n * - NaN (`Number(\"abc\")`): `i += NaN` makes the guard false on the first check, zero facts move, and\n * the caller is told \"Validation FAILED. SQLite preserved.\" A typo in an argument is reported as a\n * migration failure.\n * - a fraction: `slice` truncates and the loop still terminates, but the batch boundaries stop\n * matching the number the caller asked for.\n *\n * Validated HERE rather than only in the CLI that motivated the finding, because the CLI is a wrapper\n * over this function and a programmatic caller reaches it with no wrapper at all.\n *\n * @internal\n */\nfunction assertUsableBatchSize(batchSize: number | undefined): void {\n if (batchSize === undefined) return;\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new ConfigurationError(\n `migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,\n { code: \"invalid_batch_size\" },\n );\n }\n}\n\n/**\n * Run the migration. Writes Lance to `<cwd>/.theokit/memory/lance-new/`\n * first, validates round-trip, then renames to `lance/` on success.\n * SQLite db is preserved (CLI prompts user to delete).\n *\n * @internal\n */\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: migration is a single transaction (read → write → validate → commit-or-rollback); splitting harms atomicity reasoning.\nexport async function migrateSqliteToLance(opts: MigrateOptions): Promise<MigrateResult> {\n assertUsableBatchSize(opts.batchSize);\n const cwd = opts.cwd;\n // One resolution, reused by every path this migration touches (#463).\n const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });\n const finalPath = lanceStoragePath(memoryRoot);\n const newPath = join(memoryRoot, \"lance-new\");\n // T1.4 (ADR D68): wrap logger so any fact text containing secrets is\n // masked before reaching the destination (console or user-supplied sink).\n // Caller-supplied loggers cannot bypass — by design (D70).\n const rawLog = opts.logger ?? ((m: string) => console.log(m));\n const log = (m: string) => rawLog(redactSecrets(m));\n\n // EC: destination exists → typed error.\n if (existsSync(finalPath)) {\n throw new ConfigurationError(\n `Destination already exists: ${finalPath}. Remove it manually (\\`rm -rf ${finalPath}\\`) and re-run.`,\n { code: \"migration_destination_exists\" },\n );\n }\n if (existsSync(newPath)) {\n // Leftover from a previous failed/interrupted migration. Safe to delete.\n log(`Removing stale ${newPath} from a previous run...`);\n rmSync(newPath, { recursive: true, force: true });\n }\n\n log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);\n const sqliteFacts = await readAllSqliteFacts(memoryRoot);\n log(`SQLite has ${sqliteFacts.length} facts.`);\n if (sqliteFacts.length === 0) {\n return {\n countSqlite: 0,\n countLance: 0,\n validated: true,\n sampleComparisons: [],\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Reuse the embedding runtime configured in the workspace? For v1.2 we\n // require the caller to pass embedding explicitly via env. The migration\n // path is documented as: \"set OPENAI_API_KEY (or similar) before running.\"\n // Here we ship a placeholder embedder that uses a deterministic\n // content-hash — sufficient for migration validation; consumers should\n // re-embed on first real query after migration if needed.\n const placeholderEmbedding = {\n id: \"migration-placeholder\",\n model: \"deterministic-hash\",\n dimension: 8,\n embed: async (texts: ReadonlyArray<string>) => {\n // Simple deterministic hash → 8-dim vector (migration validation only).\n return texts.map((t) => {\n const arr = new Array(8).fill(0);\n for (let i = 0; i < t.length; i += 1) {\n arr[i % 8] += t.charCodeAt(i);\n }\n return arr.map((x) => x / 1000);\n });\n },\n stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 }),\n };\n\n mkdirSync(newPath, { recursive: true });\n log(`Writing Lance index to ${newPath} ...`);\n\n const lance = await LanceIndex.open({\n cwd,\n embedding: placeholderEmbedding,\n storagePath: newPath,\n });\n\n const batchSize = opts.batchSize ?? 100;\n for (let i = 0; i < sqliteFacts.length; i += batchSize) {\n const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({\n id: f.id,\n text: f.text,\n source: f.source,\n namespace: f.namespace ?? \"default\",\n scope: f.scope ?? \"agent\",\n user_id: f.user_id ?? \"default\",\n timestamp: 0,\n }));\n await lance.addFacts(batch);\n log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);\n }\n\n // Validation: count + sample compare (10 random) with NFC normalization.\n const lanceCount = await lance.countFacts(\"default\");\n log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);\n\n const sampleSize = Math.min(10, sqliteFacts.length);\n const sampleComparisons: { id: string; match: boolean }[] = [];\n for (let i = 0; i < sampleSize; i += 1) {\n const sqliteFact = sqliteFacts[Math.floor((i * sqliteFacts.length) / sampleSize)];\n if (sqliteFact === undefined) continue;\n // Search Lance for this fact's text — best-effort round-trip.\n const hits = await lance.search(sqliteFact.text, {\n namespace: sqliteFact.namespace ?? \"default\",\n limit: 1,\n });\n // EC-3: compare with NFC normalization.\n const hit = hits[0];\n const match = hit !== undefined && nfcEqual(hit.text, sqliteFact.text);\n sampleComparisons.push({ id: sqliteFact.id, match });\n }\n\n const allMatch = sampleComparisons.every((c) => c.match);\n const countMatch = lanceCount === sqliteFacts.length;\n const validated = allMatch && countMatch;\n\n await lance.close();\n\n if (opts.dryRun === true) {\n log(\"Dry-run mode — discarding Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n if (!validated) {\n log(\"Validation FAILED — leaving SQLite intact, removing Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: false,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Atomic commit via rename.\n renameSync(newPath, finalPath);\n log(`Migration committed to ${finalPath}.`);\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: true,\n sampleComparisons,\n lancePath: finalPath,\n committed: true,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/internal/memory/dreaming/diary.ts","../src/internal/memory/migrate-sqlite-to-lance.ts"],"names":["join","readFile","replaceFileAtomic","createHash","defaultIndexPath","existsSync","openMemoryDb","ConfigurationError","resolveMemoryRoot","lanceStoragePath","redactSecrets","rmSync","mkdirSync","LanceIndex","renameSync"],"mappings":";;;;;;;;;;;AA6BO,SAAS,UAAU,IAAA,EAA0B;AAClD,EAAA,OAAOA,SAAA,CAAK,MAAM,gBAAgB,CAAA;AACpC;AAOO,SAAS,iBAAiB,KAAA,EAA2B;AAC1D,EAAA,MAAM,QAAQ,IAAI,IAAA,CAAK,KAAA,CAAM,WAAW,EAAE,WAAA,EAAY;AACt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AAA,EAAM,KAAA,EAAO,MAAM,CAAA;AAChD,IAAA,OAAO;AAAA,MACL,aAAa,WAAA,CAAY,MAAA;AAAA,MACzB,UAAA,EAAY,UAAA;AAAA,MACZ,SAAA,EAAW,KAAA;AAAA,MACX,iBAAA;AAAA,MACA,SAAA,EAAW,SAAA;AAAA,MACX,SAAA,EAAW;AAAA,KACb;AAAA,EACF;AAGA,EAAAG,aAAA,CAAW,SAAS,SAAS,CAAA;AAC7B,EAAA,GAAA,CAAI,CAAA,uBAAA,EAA0B,SAAS,CAAA,CAAA,CAAG,CAAA;AAC1C,EAAA,OAAO;AAAA,IACL,aAAa,WAAA,CAAY,MAAA;AAAA,IACzB,UAAA,EAAY,UAAA;AAAA,IACZ,SAAA,EAAW,IAAA;AAAA,IACX,iBAAA;AAAA,IACA,SAAA,EAAW,SAAA;AAAA,IACX,SAAA,EAAW;AAAA,GACb;AACF","file":"chunk-52FDUJSV.cjs","sourcesContent":["import { createHash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport type { MemoryRoot } from \"../storage/memory-root.js\";\n\n/**\n * Dream-diary append (ADR D7).\n *\n * Diary lives at `.theokit/memory/dream-diary.md` and grows with one entry\n * per sweep. Each entry is content-hashed so the same input produces the\n * same entry — idempotency contract.\n *\n * Writes go through `replaceFileAtomic` (EC-3 of edge-case review) so a\n * crash mid-write can never leave a half-written diary.\n *\n * Shared with `@theokit/sdk-memory`; see the memory-store barrel.\n */\n\nexport interface DiaryEntry {\n timestampMs: number;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/** `<memory root>/dream-diary.md`. Takes the RESOLVED ROOT — see `storage/memory-root.ts` (#463). */\nexport function diaryPath(root: MemoryRoot): string {\n return join(root, \"dream-diary.md\");\n}\n\n/**\n * One diary entry as the markdown that gets appended: a timestamp heading, the short entry hash,\n * and the counts the sweep produced. The hash is what makes a re-run recognisable as the same\n * sweep rather than a new one.\n */\nexport function renderDiaryEntry(entry: DiaryEntry): string {\n const stamp = new Date(entry.timestampMs).toISOString();\n const hash = entryHash(entry).slice(0, 8);\n return [\n `## ${stamp}`,\n \"\",\n `- entry-hash: ${hash}`,\n `- facts before: ${entry.factsBefore}`,\n `- facts after: ${entry.factsAfter}`,\n `- duplicates removed: ${entry.duplicatesRemoved}`,\n `- clusters created: ${entry.clustersCreated}`,\n `- notes written: ${entry.notesWritten}`,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Append one sweep's entry to `<memory root>/dream-diary.md`, creating the file with its header\n * when this is the first sweep. The diary is a human-readable record of what dreaming changed —\n * consolidations are otherwise invisible, because they alter the notes rather than announce\n * themselves.\n */\nexport async function appendDiaryEntry(root: MemoryRoot, entry: DiaryEntry): Promise<void> {\n const path = diaryPath(root);\n let raw = \"\";\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n raw = \"# Dream Diary\\n\\n\";\n }\n const next = `${raw.endsWith(\"\\n\") ? raw : `${raw}\\n`}${renderDiaryEntry(entry)}`;\n await replaceFileAtomic(path, next);\n}\n\n/**\n * A stable hash of one entry's counts, so two sweeps that did the same work read as the same work.\n * Rendered truncated in the entry; the full value is what callers compare.\n */\nexport function entryHash(entry: DiaryEntry): string {\n return createHash(\"sha256\")\n .update(\n [\n entry.factsBefore,\n entry.factsAfter,\n entry.duplicatesRemoved,\n entry.clustersCreated,\n entry.notesWritten,\n ].join(\"|\"),\n )\n .digest(\"hex\");\n}\n","import { existsSync, mkdirSync, renameSync, rmSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { defaultIndexPath, openMemoryDb } from \"./index-db.js\";\nimport { LanceIndex, lanceStoragePath } from \"./lance-index.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./storage/memory-root.js\";\n\n/**\n * Migrate Memory.index from SQLite to LanceDB (ADR D44).\n *\n * EC-3 MUST FIX: validation uses NFC unicode normalization on both sides.\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel (#463).\n */\n\nexport interface MigrateOptions {\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to migrate, when the agent that wrote it\n * set `memory.directory`. Defaults to `<cwd>/.theokit/memory` (#463).\n */\n directory?: string;\n dryRun?: boolean;\n batchSize?: number;\n /** Inject for tests; defaults to console.log. */\n logger?: (msg: string) => void;\n}\n\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n /** Set when validation succeeded (or dryRun); false on validation failure. */\n validated: boolean;\n /** Per-fact compare results (size = sample count, up to 10). */\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n /** Lance storage location (final, after migration). */\n lancePath: string;\n /** Was the migration committed (false for dry-run). */\n committed: boolean;\n}\n\n/**\n * One row of the SQLite memory index, as the Lance migration reads it: the chunk plus the tenant\n * columns the target table needs. Shared with `@theokit/sdk-memory`, which migrates the same table.\n */\nexport interface SqliteFactRow {\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n namespace?: string | null;\n scope?: string | null;\n user_id?: string | null;\n}\n\n/**\n * Read all facts from the SQLite memory index. Returns empty array if the\n * SQLite db file does not exist (workspace never used Memory).\n *\n * Shared with `@theokit/sdk-memory` through the memory-store barrel, so it carries no visibility\n * tag — naming that tag in this block would delete the function below it (#463).\n */\nexport async function readAllSqliteFacts(root: MemoryRoot): Promise<SqliteFactRow[]> {\n const dbPath = defaultIndexPath(root);\n if (!existsSync(dbPath)) return [];\n const db = await openMemoryDb({ filePath: dbPath });\n try {\n // SQLite schema: chunks table holds the facts. Schema may vary; we\n // probe column existence and fall back to safe defaults.\n const stmt = db.prepare(\"SELECT id, path, source, start_line, end_line, text FROM chunks\");\n const rows = stmt.all() as Array<{\n id: string;\n path: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n start_line: number;\n end_line: number;\n text: string;\n }>;\n return rows.map((r) => ({\n ...r,\n namespace: \"default\",\n scope: \"agent\",\n user_id: \"default\",\n }));\n } finally {\n db.close();\n }\n}\n\n/**\n * Compare two strings via NFC normalization (EC-3 MUST FIX). Required\n * because SQLite/Lance native bindings can normalize unicode differently\n * (NFC vs NFD), producing false negatives on facts with accents/emojis.\n *\n * @internal\n */\nfunction nfcEqual(a: string, b: string): boolean {\n return a.normalize(\"NFC\") === b.normalize(\"NFC\");\n}\n\n/**\n * Refuse a `batchSize` the loop below cannot make progress with, before anything is migrated.\n *\n * The loop is `for (let i = 0; i < facts.length; i += batchSize)`, so the three ways this goes wrong\n * are all silent and all different:\n *\n * - 0 or negative: `i` never advances past the guard. The migration SPINS FOREVER, calling\n * `addFacts([])` and writing a \"Migrated x/y\" line every iteration — a hang with unbounded output,\n * which is the worst shape a failure can take because it looks like work.\n * - NaN (`Number(\"abc\")`): `i += NaN` makes the guard false on the first check, zero facts move, and\n * the caller is told \"Validation FAILED. SQLite preserved.\" A typo in an argument is reported as a\n * migration failure.\n * - a fraction: `slice` truncates and the loop still terminates, but the batch boundaries stop\n * matching the number the caller asked for.\n *\n * Validated HERE rather than only in the CLI that motivated the finding, because the CLI is a wrapper\n * over this function and a programmatic caller reaches it with no wrapper at all.\n *\n * @internal\n */\nfunction assertUsableBatchSize(batchSize: number | undefined): void {\n if (batchSize === undefined) return;\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new ConfigurationError(\n `migrateSqliteToLance: batchSize must be a whole number of at least 1; received ${String(batchSize)}.`,\n { code: \"invalid_batch_size\" },\n );\n }\n}\n\n/**\n * Run the migration. Writes Lance to `<cwd>/.theokit/memory/lance-new/`\n * first, validates round-trip, then renames to `lance/` on success.\n * SQLite db is preserved (CLI prompts user to delete).\n *\n * @internal\n */\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: migration is a single transaction (read → write → validate → commit-or-rollback); splitting harms atomicity reasoning.\nexport async function migrateSqliteToLance(opts: MigrateOptions): Promise<MigrateResult> {\n assertUsableBatchSize(opts.batchSize);\n const cwd = opts.cwd;\n // One resolution, reused by every path this migration touches (#463).\n const memoryRoot = resolveMemoryRoot(cwd, { directory: opts.directory });\n const finalPath = lanceStoragePath(memoryRoot);\n const newPath = join(memoryRoot, \"lance-new\");\n // T1.4 (ADR D68): wrap logger so any fact text containing secrets is\n // masked before reaching the destination (console or user-supplied sink).\n // Caller-supplied loggers cannot bypass — by design (D70).\n const rawLog = opts.logger ?? ((m: string) => console.log(m));\n const log = (m: string) => rawLog(redactSecrets(m));\n\n // EC: destination exists → typed error.\n if (existsSync(finalPath)) {\n throw new ConfigurationError(\n `Destination already exists: ${finalPath}. Remove it manually (\\`rm -rf ${finalPath}\\`) and re-run.`,\n { code: \"migration_destination_exists\" },\n );\n }\n if (existsSync(newPath)) {\n // Leftover from a previous failed/interrupted migration. Safe to delete.\n log(`Removing stale ${newPath} from a previous run...`);\n rmSync(newPath, { recursive: true, force: true });\n }\n\n log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);\n const sqliteFacts = await readAllSqliteFacts(memoryRoot);\n log(`SQLite has ${sqliteFacts.length} facts.`);\n if (sqliteFacts.length === 0) {\n return {\n countSqlite: 0,\n countLance: 0,\n validated: true,\n sampleComparisons: [],\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Reuse the embedding runtime configured in the workspace? For v1.2 we\n // require the caller to pass embedding explicitly via env. The migration\n // path is documented as: \"set OPENAI_API_KEY (or similar) before running.\"\n // Here we ship a placeholder embedder that uses a deterministic\n // content-hash — sufficient for migration validation; consumers should\n // re-embed on first real query after migration if needed.\n const placeholderEmbedding = {\n id: \"migration-placeholder\",\n model: \"deterministic-hash\",\n dimension: 8,\n embed: async (texts: ReadonlyArray<string>) => {\n // Simple deterministic hash → 8-dim vector (migration validation only).\n return texts.map((t) => {\n const arr = new Array(8).fill(0);\n for (let i = 0; i < t.length; i += 1) {\n arr[i % 8] += t.charCodeAt(i);\n }\n return arr.map((x) => x / 1000);\n });\n },\n stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 }),\n };\n\n mkdirSync(newPath, { recursive: true });\n log(`Writing Lance index to ${newPath} ...`);\n\n const lance = await LanceIndex.open({\n cwd,\n embedding: placeholderEmbedding,\n storagePath: newPath,\n });\n\n const batchSize = opts.batchSize ?? 100;\n for (let i = 0; i < sqliteFacts.length; i += batchSize) {\n const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({\n id: f.id,\n text: f.text,\n source: f.source,\n namespace: f.namespace ?? \"default\",\n scope: f.scope ?? \"agent\",\n user_id: f.user_id ?? \"default\",\n timestamp: 0,\n }));\n await lance.addFacts(batch);\n log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);\n }\n\n // Validation: count + sample compare (10 random) with NFC normalization.\n const lanceCount = await lance.countFacts(\"default\");\n log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);\n\n const sampleSize = Math.min(10, sqliteFacts.length);\n const sampleComparisons: { id: string; match: boolean }[] = [];\n for (let i = 0; i < sampleSize; i += 1) {\n const sqliteFact = sqliteFacts[Math.floor((i * sqliteFacts.length) / sampleSize)];\n if (sqliteFact === undefined) continue;\n // Search Lance for this fact's text — best-effort round-trip.\n const hits = await lance.search(sqliteFact.text, {\n namespace: sqliteFact.namespace ?? \"default\",\n limit: 1,\n });\n // EC-3: compare with NFC normalization.\n const hit = hits[0];\n const match = hit !== undefined && nfcEqual(hit.text, sqliteFact.text);\n sampleComparisons.push({ id: sqliteFact.id, match });\n }\n\n const allMatch = sampleComparisons.every((c) => c.match);\n const countMatch = lanceCount === sqliteFacts.length;\n const validated = allMatch && countMatch;\n\n await lance.close();\n\n if (opts.dryRun === true) {\n log(\"Dry-run mode — discarding Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n if (!validated) {\n log(\"Validation FAILED — leaving SQLite intact, removing Lance staging dir.\");\n rmSync(newPath, { recursive: true, force: true });\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: false,\n sampleComparisons,\n lancePath: finalPath,\n committed: false,\n };\n }\n\n // Atomic commit via rename.\n renameSync(newPath, finalPath);\n log(`Migration committed to ${finalPath}.`);\n return {\n countSqlite: sqliteFacts.length,\n countLance: lanceCount,\n validated: true,\n sampleComparisons,\n lancePath: finalPath,\n committed: true,\n };\n}\n"]}
@@ -3,6 +3,11 @@ import { glob } from 'fs/promises';
3
3
  import { isAbsolute, resolve, join, dirname } from 'path';
4
4
 
5
5
  // src/internal/runtime/context/context-discovery.ts
6
+ function admittedSpecs(specs, declaredKinds) {
7
+ if (declaredKinds === void 0) return specs;
8
+ const granted = new Set(declaredKinds);
9
+ return specs.filter((spec) => spec.dialect === void 0 || granted.has(spec.dialect));
10
+ }
6
11
  var DEFAULT_DISCOVERY_SPECS = [
7
12
  {
8
13
  id: "AGENTS.md",
@@ -59,6 +64,7 @@ var DEFAULT_DISCOVERY_SPECS = [
59
64
  // 46, 48 or 49 is unaffected. A consumer that had chosen 47 now collides — that is the cost of
60
65
  // an eighth default, paid once and recorded here rather than discovered later.
61
66
  id: "claude-rules",
67
+ dialect: "claude-code",
62
68
  pattern: ".claude/rules/*.md",
63
69
  scope: "globbed",
64
70
  parser: "rules-frontmatter",
@@ -103,6 +109,62 @@ var DEFAULT_DISCOVERY_SPECS = [
103
109
  parser: "plain-markdown",
104
110
  followImports: false,
105
111
  priority: 60
112
+ },
113
+ // ── The private chain (B-023) ───────────────────────────────────────────────────────────────
114
+ //
115
+ // `*.local.md` is the gitignored companion where an operator keeps the standing corrections too
116
+ // personal or too situational to commit. Nothing read it: measured 2026-09-12, a grep for the four
117
+ // `.local` spellings returned 0 files across this package's source, against a control of 23 for
118
+ // `CLAUDE.md`. The file exists, it is named the documented way, and the agent behaves exactly as
119
+ // it would if the operator had written nothing.
120
+ //
121
+ // ORDER. They sit ABOVE every public spec because a correction has to be composed after the rule
122
+ // it corrects, and they keep the public chain's relative order among themselves (AGENTS, CLAUDE,
123
+ // THEO) so the two halves read the same way.
124
+ //
125
+ // THE COST OF THAT, stated rather than discovered later: `applyAggregateCap` fills the budget in
126
+ // ascending priority, so the HIGHEST numbers are the first dropped when the total cap is reached.
127
+ // Placing the private chain last therefore makes it the first to go under pressure. The
128
+ // alternative — a low number, to protect it — would compose the operator's refinement BEFORE the
129
+ // general rule, which inverts its meaning and is the defect this item is about. The existing table
130
+ // already accepts that trade: `.theokit/THEO.md`, the project's most specific instructions, is at
131
+ // 60 and is equally droppable. This follows the convention rather than inventing an exception.
132
+ //
133
+ // WHY THESE THREE AND NOT SIX. A private companion pairs with a public file THIS seam reads, and
134
+ // the documented convention is THEO / AGENTS / CLAUDE. `GEMINI.local.md` and a private
135
+ // `.cursor/rules` are not part of it, and inventing them would publish a convention nobody writes.
136
+ // Note the rule lands differently in `@theokit/agents`' `DEFAULT_FILE_NAMES`, which has no
137
+ // `CLAUDE.md` and therefore gets no `CLAUDE.local.md` — same rule, two seams, stated at both ends.
138
+ //
139
+ // UNGATED, like the public repo-root files beside them. `CLAUDE.local.md` is a repo-root file, not
140
+ // a `.claude/` one, so it follows `CLAUDE.md` rather than `claude-rules` — see `dialect`'s
141
+ // docblock for why the grant gates the foreign ROOT and not the files beside it.
142
+ {
143
+ id: "AGENTS.local.md",
144
+ pattern: "AGENTS.local.md",
145
+ scope: "git-root-walk",
146
+ parser: "plain-markdown",
147
+ followImports: false,
148
+ priority: 70
149
+ },
150
+ {
151
+ id: "CLAUDE.local.md",
152
+ pattern: "CLAUDE.local.md",
153
+ scope: "git-root-walk",
154
+ parser: "plain-markdown",
155
+ // Mirrors `CLAUDE.md`, which follows imports. A private file that could not `@import` while its
156
+ // public sibling can would be a difference nobody declared.
157
+ followImports: true,
158
+ priority: 75
159
+ },
160
+ {
161
+ id: "THEO.local.md",
162
+ pattern: "THEO.local.md",
163
+ scope: "git-root-walk",
164
+ parser: "plain-markdown",
165
+ // Mirrors `THEO.md.root`, which follows imports.
166
+ followImports: true,
167
+ priority: 80
106
168
  }
107
169
  ];
108
170
  var SAFE_FILENAME = /^[a-zA-Z0-9_.\-/*]+$/;
@@ -167,6 +229,6 @@ async function walkUpForGlob(cwd, pattern) {
167
229
  return found.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
168
230
  }
169
231
 
170
- export { DEFAULT_DISCOVERY_SPECS, findGitRoot, isSafePattern, walkUpForFile, walkUpForGlob };
171
- //# sourceMappingURL=chunk-2XRAWOZZ.js.map
172
- //# sourceMappingURL=chunk-2XRAWOZZ.js.map
232
+ export { DEFAULT_DISCOVERY_SPECS, admittedSpecs, findGitRoot, isSafePattern, walkUpForFile, walkUpForGlob };
233
+ //# sourceMappingURL=chunk-5NELQ6LB.js.map
234
+ //# sourceMappingURL=chunk-5NELQ6LB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/context/context-discovery.ts"],"names":[],"mappings":";;;;;AAsIO,SAAS,aAAA,CACd,OACA,aAAA,EAC8B;AAC9B,EAAA,IAAI,aAAA,KAAkB,QAAW,OAAO,KAAA;AACxC,EAAA,MAAM,OAAA,GAAU,IAAI,GAAA,CAAI,aAAa,CAAA;AACrC,EAAA,OAAO,KAAA,CAAM,MAAA,CAAO,CAAC,IAAA,KAAS,IAAA,CAAK,OAAA,KAAY,MAAA,IAAa,OAAA,CAAQ,GAAA,CAAI,IAAA,CAAK,OAAO,CAAC,CAAA;AACvF;AAmBO,IAAM,uBAAA,GAAwD;AAAA,EACnE;AAAA,IACE,EAAA,EAAI,WAAA;AAAA,IACJ,OAAA,EAAS,WAAA;AAAA,IACT,KAAA,EAAO,eAAA;AAAA,IACP,MAAA,EAAQ,gBAAA;AAAA,IACR,aAAA,EAAe,KAAA;AAAA,IACf,QAAA,EAAU;AAAA,GACZ;AAAA,EACA;A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;AAGN,IAAA,OAAO,EAAC;AAAA,EACV;AAQA,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,CAAC,CAAA,EAAG,CAAA,KAAO,CAAA,GAAI,CAAA,GAAI,EAAA,GAAK,CAAA,GAAI,CAAA,GAAI,CAAA,GAAI,CAAE,CAAA;AAC1D","file":"chunk-5NELQ6LB.js","sourcesContent":["/**\n * Context file discovery (T1.1, ADRs D150 / D151).\n *\n * Discovers context files via three scopes:\n * - `cwd-only` — single dir, single path lookup\n * - `git-root-walk` — walk cwd → git-root, collect every directory's match\n * (nearest-first ordering)\n * - `globbed` — glob pattern relative to cwd (e.g. `.cursor/rules/*.mdc`)\n *\n * Pure `existsSync` checks — **no `.gitignore` parsing** (EC-A, KISS) and\n * **no invented `.theokitignore`** (EC-B). Paths normalized via\n * `realpath` to dedup symlink chains pointing to the same physical file\n * (EC-F). Git worktrees work transparently because `.git` exists as a\n * file in that case (EC-N).\n *\n * @internal\n */\n\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { glob } from \"node:fs/promises\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\n\n/** Single filename (\"AGENTS.md\") or relative glob (\".cursor/rules/*.mdc\"). */\nexport type DiscoveryScope = \"cwd-only\" | \"git-root-walk\" | \"globbed\";\n\n/** Parser to apply once file is read. */\nexport type DiscoveryParser = \"plain-markdown\" | \"mdc\" | \"frontmatter-zod\" | \"rules-frontmatter\";\n\n/**\n * One kind of context file the runner knows how to find and read. The shipped registry is\n * `DEFAULT_DISCOVERY_SPECS`; a caller supplies its own array to change the set.\n *\n * `scope` decides how `pattern` is used and how many files a single spec can yield:\n * `cwd-only` looks for one path and stops, `git-root-walk` collects a match in every directory\n * from `cwd` up to the git root (nearest first), and `globbed` expands `pattern` as a glob\n * relative to `cwd`. So `pattern` is a filename for the first two and a glob for the third —\n * putting a glob on a walk scope silently finds nothing.\n *\n * `priority` orders the merged prompt, ascending, and is a plain number rather than an index, so\n * a new spec can be slotted between two existing ones. Lower means earlier and therefore more\n * general; later content wins on conflict.\n *\n * `parser` must match the file format — `plain-markdown` reads the whole file, `mdc` and\n * `rules-frontmatter` parse frontmatter and can DECLINE the file when its activation conditions\n * do not hold, and `frontmatter-zod` is the legacy path the runner currently skips entirely.\n *\n * `followImports` is honored only by `plain-markdown`, and turns `@path` directives in the body\n * into inlined content bounded by the import root. Setting it on a frontmatter parser does\n * nothing.\n *\n * `id` names the source in `<source name=\"\">` and in telemetry. When one spec matches files in\n * several directories, the runner suffixes it with the path relative to the git root to keep them\n * apart.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport interface DiscoverySpec {\n /** Stable identifier — used as `<source name=\"\">` and telemetry key. */\n readonly id: string;\n /** Priority for merge (lower = earlier in prompt). */\n readonly priority: number;\n /** Filename (cwd-only/git-root-walk) or glob (globbed). */\n readonly pattern: string;\n readonly scope: DiscoveryScope;\n readonly parser: DiscoveryParser;\n /** Whether to follow `@path` import directives (CLAUDE.md / GEMINI.md). */\n readonly followImports: boolean;\n /**\n * The `CompatSource` kind whose grant gates this file — the name a consumer writes in\n * `local.compatSources` to receive it.\n *\n * Absent means UNGATED, and that covers two different situations which the field deliberately does\n * not distinguish, because the gate treats them identically:\n *\n * 1. **Native.** theokit's own roots. Declaring theokit is what running theokit means, so there is\n * no separate grant to ask for.\n * 2. **A repo-root instruction file.** `AGENTS.md`, `GEMINI.md`, `CLAUDE.md` and\n * `.cursor/rules/*.mdc` are every bit as foreign as `.claude/` is, and every one of them puts\n * a cloned repository's prose into the system prompt. They are ungated anyway, for a reason\n * that is a limit rather than a judgement: `adaptersFor` registers ONE foreign adapter,\n * `claude-code`, so `compatSources` has no spelling that admits `agents`, `gemini` or\n * `cursor`. Labelling them would gate them on a grant nobody can write, making three formats\n * permanently unreachable — a silent loss of capability with no way to restore it, which is a\n * worse defect than the one being fixed and the exact shape this codebase already paid for in\n * usetheokit/theokit-sdk#524.\n *\n * `CLAUDE.md` is ungated for the adjacent reason, and this one IS a judgement: the grant gates\n * the foreign ROOT — the `.claude/` directory whose hooks, skills, subagents and plugins\n * already require it — and `CLAUDE.md` does not live there. It sits at the repository root\n * beside the other three, is widely used as a generic agent-instructions file by projects that\n * have no `.claude/` at all, and gating it would take it from them.\n *\n * So this field closes the door the grant vocabulary already has a key for, and leaves three\n * named. Whether a repo-root instruction file should require an opt-in at all is a product\n * decision affecting every consumer, not a bug fix, and it is tracked separately — writing it\n * down is the point, because an undocumented gap reads as an oversight.\n *\n * Optional because this interface is `@public` and under semver: a caller passing its own array\n * keeps working, and its specs read as ungated — the behaviour they had before this field existed.\n *\n * On the SPEC rather than as a condition at the call site, because the table MIXES dialects.\n * Adding one is adding a row, not editing a branch somebody else has to find.\n */\n readonly dialect?: string;\n}\n\n/**\n * The specs a consumer's declared compat sources admit.\n *\n * The half that turns {@link DiscoverySpec.dialect} from a label into a gate. A field nobody consults\n * is a control that is declared, exported, documented and wired to nothing — which is the failure\n * this whole change exists to close, and it would be a poor joke to reproduce it here.\n *\n * Three rules, and each is a decision rather than a convenience:\n *\n * - **A spec with no `dialect` is always admitted.** Absent means native, and a caller's own array\n * predates this field: filtering it by a question it never answered would remove content nobody\n * asked to remove.\n * - **`undefined` sources admit everything.** That is every consumer before this field existed. This\n * is the back-compatibility floor and the reason the change is a minor rather than a breaking one.\n * - **A declared list admits only the dialects it names.** This is the fix: a consumer who grants\n * `theokit` for its own roots and never declares `claude-code` stops receiving that repository's\n * `.claude/rules/*.md` in its prompt.\n *\n * `@internal`, deliberately. The docblock claimed `@public — re-exported from\n * '@theokit/sdk/context'` and the barrel exported no such name: a reach asserted and not given,\n * which is the defect this whole change is about, committed in the fix for it. A consumer building\n * its own `specs` array does not need this function — it passes `declaredCompatKinds` to\n * `runDiscovery` and gets the same filtering, through a public option on a public interface. So the\n * honest correction is to narrow the claim rather than widen the surface.\n *\n * @internal — exported from the module so the gate is testable at its boundary rather than only\n * through a whole agent, and not re-exported from any public entry point.\n */\nexport function admittedSpecs(\n specs: ReadonlyArray<DiscoverySpec>,\n declaredKinds: ReadonlyArray<string> | undefined,\n): ReadonlyArray<DiscoverySpec> {\n if (declaredKinds === undefined) return specs;\n const granted = new Set(declaredKinds);\n return specs.filter((spec) => spec.dialect === undefined || granted.has(spec.dialect));\n}\n\n/**\n * The context files theokit looks for out of the box, in the order they are concatenated.\n *\n * Two things follow from the ordering. `AGENTS.md` comes first at priority 10 and `THEO.md` last,\n * so theokit-specific instruction wins over the vendor-neutral file on conflict. And the array is\n * consumed in the order written — the runner does not re-sort it — so a caller passing its own\n * array is responsible for keeping `priority` and array position consistent.\n *\n * `CLAUDE.md` and `GEMINI.md` are the only two entries with `followImports: true`, which means\n * they are the only files whose `@path` directives pull other files into the prompt. Those\n * imports cannot escape the import root.\n *\n * Frozen only by type: `ReadonlyArray` is a compile-time constraint, and the array and its\n * elements are not deep-frozen at runtime. Build a new array rather than mutating this one.\n *\n * @public — re-exported from `@theokit/sdk/context`, and therefore under semver.\n */\nexport const DEFAULT_DISCOVERY_SPECS: ReadonlyArray<DiscoverySpec> = [\n {\n id: \"AGENTS.md\",\n pattern: \"AGENTS.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 10,\n },\n {\n id: \"GEMINI.md\",\n pattern: \"GEMINI.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 20,\n },\n {\n id: \"CLAUDE.md\",\n pattern: \"CLAUDE.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 30,\n },\n {\n id: \"cursor-rules\",\n pattern: \".cursor/rules/*.mdc\",\n scope: \"globbed\",\n parser: \"mdc\",\n followImports: false,\n priority: 40,\n },\n {\n id: \"theokit-rules\",\n pattern: \".theokit/rules/*.md\",\n scope: \"globbed\",\n parser: \"rules-frontmatter\",\n followImports: false,\n priority: 45,\n },\n {\n // Rules written for the Claude Code CLI. Measured 2026-08-26 over this repository's 32 rule\n // files: none carries frontmatter, and `rules-frontmatter` already reads a file without it as\n // `alwaysApply: true` — the format needed nothing, only a spec pointing at the directory.\n //\n // 47, not 46. Specs sort ascending and a context budget drops the tail first, so it must land\n // AFTER `.theokit/rules` (45) — the explicit namespace should survive a squeeze the borrowed one\n // does not. It must also leave a slot on BOTH sides: B-127 makes these numbers a public contract\n // precisely so a consumer can place its own source between two defaults, and 46 would have left\n // no room between 45 and itself. 47 keeps 46 free below and 48–49 free above.\n //\n // The reckoning B-127's docblock asks for: no published priority MOVES, so a consumer that chose\n // 46, 48 or 49 is unaffected. A consumer that had chosen 47 now collides — that is the cost of\n // an eighth default, paid once and recorded here rather than discovered later.\n id: \"claude-rules\",\n dialect: \"claude-code\",\n pattern: \".claude/rules/*.md\",\n scope: \"globbed\",\n parser: \"rules-frontmatter\",\n followImports: false,\n priority: 47,\n },\n {\n id: \"theokit-context\",\n pattern: \".theokit/context/*.md\",\n scope: \"globbed\",\n parser: \"frontmatter-zod\",\n followImports: false,\n priority: 50,\n },\n {\n // usetheokit/theokit-sdk#531 — THEO.md was the only context file that could not live at the\n // project root: every sibling here is `git-root-walk`, and this one was `cwd-only` pointed\n // at `.theokit/THEO.md` specifically, with no warning that a root THEO.md was inert.\n //\n // ADDED rather than moving the existing entry below: a project already using\n // `.theokit/THEO.md` keeps working unchanged. 55 sits between `theokit-context` (50) and the\n // existing `THEO.md` (60), leaving room on both sides — the numbering discipline\n // `claude-rules` (47) already established for this array.\n //\n // `followImports: true`, unlike the existing entry (`false`) and unlike `AGENTS.md`. This is\n // a DELIBERATE divergence between the two THEO.md specs, not an inconsistency: a root-level\n // file is edited by the same people, in the same place, as CLAUDE.md/GEMINI.md — the two\n // other root-level, human-facing files that both carry `followImports: true` — so it belongs\n // in their category rather than AGENTS.md's vendor-neutral, import-free one. Because this is a\n // NEW spec, choosing `true` here changes nothing for `.theokit/THEO.md`, which keeps `false`.\n id: \"THEO.md.root\",\n pattern: \"THEO.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: true,\n priority: 55,\n },\n {\n id: \"THEO.md\",\n pattern: \".theokit/THEO.md\",\n scope: \"cwd-only\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 60,\n },\n\n // ── The private chain (B-023) ───────────────────────────────────────────────────────────────\n //\n // `*.local.md` is the gitignored companion where an operator keeps the standing corrections too\n // personal or too situational to commit. Nothing read it: measured 2026-09-12, a grep for the four\n // `.local` spellings returned 0 files across this package's source, against a control of 23 for\n // `CLAUDE.md`. The file exists, it is named the documented way, and the agent behaves exactly as\n // it would if the operator had written nothing.\n //\n // ORDER. They sit ABOVE every public spec because a correction has to be composed after the rule\n // it corrects, and they keep the public chain's relative order among themselves (AGENTS, CLAUDE,\n // THEO) so the two halves read the same way.\n //\n // THE COST OF THAT, stated rather than discovered later: `applyAggregateCap` fills the budget in\n // ascending priority, so the HIGHEST numbers are the first dropped when the total cap is reached.\n // Placing the private chain last therefore makes it the first to go under pressure. The\n // alternative — a low number, to protect it — would compose the operator's refinement BEFORE the\n // general rule, which inverts its meaning and is the defect this item is about. The existing table\n // already accepts that trade: `.theokit/THEO.md`, the project's most specific instructions, is at\n // 60 and is equally droppable. This follows the convention rather than inventing an exception.\n //\n // WHY THESE THREE AND NOT SIX. A private companion pairs with a public file THIS seam reads, and\n // the documented convention is THEO / AGENTS / CLAUDE. `GEMINI.local.md` and a private\n // `.cursor/rules` are not part of it, and inventing them would publish a convention nobody writes.\n // Note the rule lands differently in `@theokit/agents`' `DEFAULT_FILE_NAMES`, which has no\n // `CLAUDE.md` and therefore gets no `CLAUDE.local.md` — same rule, two seams, stated at both ends.\n //\n // UNGATED, like the public repo-root files beside them. `CLAUDE.local.md` is a repo-root file, not\n // a `.claude/` one, so it follows `CLAUDE.md` rather than `claude-rules` — see `dialect`'s\n // docblock for why the grant gates the foreign ROOT and not the files beside it.\n {\n id: \"AGENTS.local.md\",\n pattern: \"AGENTS.local.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n followImports: false,\n priority: 70,\n },\n {\n id: \"CLAUDE.local.md\",\n pattern: \"CLAUDE.local.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n // Mirrors `CLAUDE.md`, which follows imports. A private file that could not `@import` while its\n // public sibling can would be a difference nobody declared.\n followImports: true,\n priority: 75,\n },\n {\n id: \"THEO.local.md\",\n pattern: \"THEO.local.md\",\n scope: \"git-root-walk\",\n parser: \"plain-markdown\",\n // Mirrors `THEO.md.root`, which follows imports.\n followImports: true,\n priority: 80,\n },\n];\n\nconst SAFE_FILENAME = /^[a-zA-Z0-9_.\\-/*]+$/;\nconst TRAVERSAL_RE = /(^|\\/)\\.\\.(\\/|$)/;\n\n/**\n * Reject patterns that contain path traversal (`..`) or non-allowed\n * characters (D81 parity, EC-4).\n *\n * @internal\n */\nexport function isSafePattern(pattern: string): boolean {\n if (typeof pattern !== \"string\" || pattern.length === 0) return false;\n if (TRAVERSAL_RE.test(pattern)) return false;\n if (isAbsolute(pattern)) return false;\n return SAFE_FILENAME.test(pattern);\n}\n\n/**\n * Walk upward from `cwd` looking for the closest directory containing\n * a `.git` entry (file OR directory — worktrees use a `.git` FILE,\n * EC-N). Returns the absolute path of that directory, or `undefined`\n * when no git root exists at or above `cwd`.\n *\n * @internal\n */\nexport function findGitRoot(cwd: string): string | undefined {\n if (typeof cwd !== \"string\" || cwd.length === 0) return undefined;\n let current = resolve(cwd);\n // Guard against infinite loops on weird filesystems.\n for (let i = 0; i < 64; i += 1) {\n if (existsSync(join(current, \".git\"))) return current;\n const parent = dirname(current);\n if (parent === current) return undefined;\n current = parent;\n }\n return undefined;\n}\n\n/**\n * Walk `cwd` upward to `stopDir` (inclusive) collecting every existing\n * occurrence of `filename`. Returns absolute, realpath-deduped paths in\n * nearest-first order (innermost dir first).\n *\n * No `.gitignore` parsing (EC-A). Realpath collapses symlink chains\n * pointing to the same physical file (EC-F). Filesystem races (file\n * deleted mid-walk) are skipped silently (EC-5).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: walk-up loop combines validation + realpath dedup + FS-race handling + stopDir guard in a single bounded loop; splitting fragments the dedup invariant.\nexport function walkUpForFile(\n cwd: string,\n filename: string,\n stopDir: string | undefined,\n): string[] {\n if (!isSafePattern(filename)) {\n return [];\n }\n const start = resolve(cwd);\n const stop = stopDir !== undefined ? resolve(stopDir) : undefined;\n const found: string[] = [];\n const seenReal = new Set<string>();\n let current = start;\n // 64-level depth cap.\n for (let i = 0; i < 64; i += 1) {\n const candidate = join(current, filename);\n if (existsSync(candidate)) {\n let real: string;\n try {\n real = realpathSync(candidate);\n } catch {\n // FS race (deleted mid-walk) — skip.\n real = candidate;\n }\n if (!seenReal.has(real)) {\n seenReal.add(real);\n found.push(real);\n }\n }\n if (stop !== undefined && current === stop) break;\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n return found;\n}\n\n/**\n * Glob-style discovery under `cwd` (e.g. `.cursor/rules/*.mdc`, `.theokit/rules/**\\/*.md`).\n * Returns absolute, lex-sorted paths.\n *\n * `*` matches within one path segment and `**` spans any depth, including zero — so\n * `.theokit/rules/**\\/*.md` finds `rules/top.md` as well as `rules/deep/nested/inner.md`, while\n * `.theokit/rules/*.md` keeps its flat meaning and finds only the first. That distinction is the\n * compatibility contract: every existing spec uses a single `*`, and widening it would silently\n * start absorbing nested files nobody chose to expose.\n *\n * ## Why this used to be flat, and what changed (B-119)\n *\n * The previous implementation split the pattern at its LAST `/`, treated the prefix as a literal\n * directory and did one `readdir` — documented as \"nested directories deferred to v2\" (EC-R). The\n * deferral was deliberate; what made it a defect was measured from a consumer. TheoCode's own rule\n * loader descends recursively, so migrating it onto the `theokit-rules` spec would have silently\n * dropped every nested rule — on the path that decides whether a repository's hooks execute. And a\n * pattern written to say so, `.theokit/rules/**\\/*.md`, resolved its directory part to a literal\n * `**` and matched NOTHING, not even the top-level file it matched before the globstar was added.\n *\n * ## Why the stdlib rather than a walker\n *\n * `fs.promises.glob` (Node ≥ 22, and this package requires ≥ 22.12) implements exactly these\n * semantics, verified against a fixture before adoption: `**\\/*.md` returns all three depths,\n * `*.md` returns one, and it emits no experimental warning. Writing a recursive walker here would\n * have been a third implementation of matching inside one package — the same duplication that let\n * the enumerator and the compiler in `context-glob.ts` disagree in the first place. `globToRegex`\n * stays where it belongs: deciding whether a rule APPLIES to a set of paths, which is a different\n * question from which files exist.\n *\n * `isSafePattern` still runs first and is unchanged, so `..` is refused before any I/O.\n *\n * @internal\n */\nexport async function walkUpForGlob(cwd: string, pattern: string): Promise<string[]> {\n if (!isSafePattern(pattern)) return [];\n const found: string[] = [];\n try {\n for await (const entry of glob(pattern, { cwd })) {\n found.push(resolve(cwd, entry));\n }\n } catch {\n // A pattern whose directory does not exist is the ordinary case — most projects have no\n // `.cursor/rules/`. Same outcome as matching nothing.\n return [];\n }\n // Sorted, because discovery order becomes prompt order and must not vary with the filesystem.\n //\n // The comparator is explicit and deliberately NOT `localeCompare`, which is the usual suggestion\n // for a bare `.sort()`. `localeCompare` orders by the machine's locale, so the same tree would\n // assemble a different prompt on a differently-configured machine — trading one source of\n // non-determinism for a subtler one. Code-unit ordering is what a bare `.sort()` already does for\n // strings; writing it out states the intent and keeps the result machine-independent.\n return found.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunk43YXGD3P_cjs = require('./chunk-43YXGD3P.cjs');
3
+ var chunkTY56BKSK_cjs = require('./chunk-TY56BKSK.cjs');
4
4
  var chunkJ7J7J2GN_cjs = require('./chunk-J7J7J2GN.cjs');
5
5
  var chunk6LHQPOMI_cjs = require('./chunk-6LHQPOMI.cjs');
6
6
  var async_hooks = require('async_hooks');
@@ -21,6 +21,12 @@ function warnOnce(key, message) {
21
21
  chunk6LHQPOMI_cjs.diag(`${message}
22
22
  `);
23
23
  }
24
+ function warnFailureOnce(key, message) {
25
+ if (warned.has(key)) return;
26
+ warned.add(key);
27
+ chunk6LHQPOMI_cjs.diagFailure(`${message}
28
+ `);
29
+ }
24
30
  async function loadHookConfig(cwd, compatSources = []) {
25
31
  const merged = {};
26
32
  let sawAny = false;
@@ -29,7 +35,7 @@ async function loadHookConfig(cwd, compatSources = []) {
29
35
  sawAny = true;
30
36
  mergeInto(merged, stampSource(await readHookFile(path), path));
31
37
  }
32
- if (!sawAny && fs.existsSync(path.join(chunk43YXGD3P_cjs.theokitConfigRoot(cwd), "hooks"))) {
38
+ if (!sawAny && fs.existsSync(path.join(chunkTY56BKSK_cjs.theokitConfigRoot(cwd), "hooks"))) {
33
39
  warnOnce(
34
40
  "hooks-md-unsupported",
35
41
  "[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) \u2014 migrate to a Claude-Code-shaped .theokit/hooks.json"
@@ -38,7 +44,7 @@ async function loadHookConfig(cwd, compatSources = []) {
38
44
  return merged;
39
45
  }
40
46
  function hookConfigCandidates(cwd, compatSources) {
41
- const roots = chunk43YXGD3P_cjs.projectConfigRoots(cwd, compatSources, "hooks");
47
+ const roots = chunkTY56BKSK_cjs.projectConfigRoots(cwd, compatSources, "hooks");
42
48
  return [
43
49
  ...roots.map((root) => path.join(root, "hooks.json")),
44
50
  ...roots.map((root) => path.join(root, "settings.json")),
@@ -108,7 +114,7 @@ function parseClaudeCodeConfig(raw, path) {
108
114
  for (const [ccEvent, groups] of Object.entries(hooksRec)) {
109
115
  const event = CLAUDE_CODE_EVENT_MAP[ccEvent];
110
116
  if (event === void 0) {
111
- warnOnce(
117
+ warnFailureOnce(
112
118
  `hooks-event-${ccEvent}`,
113
119
  `[theokit-sdk] hooks: event "${ccEvent}" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(", ")}) \u2014 skipping`
114
120
  );
@@ -129,6 +135,26 @@ function flattenEventGroups(groups, path, ccEvent) {
129
135
  }
130
136
  return commands;
131
137
  }
138
+ var UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS = /* @__PURE__ */ new Set([
139
+ "if",
140
+ "args",
141
+ "statusMessage",
142
+ "once",
143
+ "async",
144
+ "asyncRewake",
145
+ "shell"
146
+ ]);
147
+ var ACCEPTED_HOOK_FIELDS = /* @__PURE__ */ new Set(["type", "command", "timeout"]);
148
+ function rejectUnreadHookFields(cmd, path, ccEvent) {
149
+ for (const key of Object.keys(cmd)) {
150
+ if (ACCEPTED_HOOK_FIELDS.has(key)) continue;
151
+ const origin = UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS.has(key) ? ` \u2014 "${key}" is a Claude Code hook field that this runtime does not implement. The same applies to: ${[...UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS].filter((f) => f !== key).join(", ")}` : "";
152
+ throw new chunkJ7J7J2GN_cjs.ConfigurationError(
153
+ `hooks.${ccEvent}: unsupported field "${key}" (accepted: ${[...ACCEPTED_HOOK_FIELDS].join(", ")}) in ${path}${origin}`,
154
+ { code: "hooks_unsupported_field" }
155
+ );
156
+ }
157
+ }
132
158
  function parseClaudeCodeCommand(raw, matcher, path, ccEvent) {
133
159
  const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);
134
160
  if (cmd.type !== "command") {
@@ -142,7 +168,8 @@ function parseClaudeCodeCommand(raw, matcher, path, ccEvent) {
142
168
  code: "hooks_invalid_command"
143
169
  });
144
170
  }
145
- const hc = { command: cmd.command };
171
+ rejectUnreadHookFields(cmd, path, ccEvent);
172
+ const hc = { command: cmd.command, sourceEvent: ccEvent };
146
173
  if (matcher !== void 0) hc.matcher = matcher;
147
174
  if (typeof cmd.timeout === "number" && cmd.timeout > 0) {
148
175
  hc.timeoutMs = Math.round(cmd.timeout * 1e3);
@@ -167,8 +194,9 @@ function warnPersonalitySwitchInsideFork(agentId) {
167
194
 
168
195
  exports.currentPersonalityContext = currentPersonalityContext;
169
196
  exports.loadHookConfig = loadHookConfig;
197
+ exports.warnFailureOnce = warnFailureOnce;
170
198
  exports.warnOnce = warnOnce;
171
199
  exports.warnPersonalitySwitchInsideFork = warnPersonalitySwitchInsideFork;
172
200
  exports.withPersonalityContext = withPersonalityContext;
173
- //# sourceMappingURL=chunk-3FDU5JFE.cjs.map
174
- //# sourceMappingURL=chunk-3FDU5JFE.cjs.map
201
+ //# sourceMappingURL=chunk-7IZKTQ5G.cjs.map
202
+ //# sourceMappingURL=chunk-7IZKTQ5G.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/internal/runtime/hooks/hooks-source.ts","../src/internal/personality/context.ts"],"names":["diag","diagFailure","existsSync","join","theokitConfigRoot","projectConfigRoots","readFile","ConfigurationError","AsyncLocalStorage"],"mappings":";;;;;;;;;;AA8DO,IAAM,qBAAA,GAA6D;AAAA,EACxE,UAAA,EAAY,YAAA;AAAA,EACZ,WAAA,EAAa,aAAA;AAAA,EACb,gBAAA,EAAkB,QAAA;AAAA,EAClB,IAAA,EAAM;AACR,CAAA;AA+BA,IAAM,MAAA,uBAAa,GAAA,EAAY;AAYxB,SAAS,QAAA,CAAS,KAAa,OAAA,EAAuB;AAC3D,EAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG;AACrB,EAAA,MAAA,CAAO,IAAI,GAAG,CAAA;AACd,EAAAA,sBAAA,CAAK,GAAG,OAAO;AAAA,CAAI,CAAA;AACrB;AAoBO,SAAS,eAAA,CAAgB,KAAa,OAAA,EAAuB;AAClE,EAAA,IAAI,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA,EAAG;AACrB,EAAA,MAAA,CAAO,IAAI,GAAG,CAAA;AACd,EAAAC,6BAAA,CAAY,GAAG,OAAO;AAAA,CAAI,CAAA;AAC5B;AAcA,eAAsB,cAAA,CACpB,GAAA,EACA,aAAA,GAAoD,EAAC,EAChC;AACrB,EAAA,MAAM,SAAqB,EAAC;AAC5B,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,oBAAA,CAAqB,GAAA,EAAK,aAAa,CAAA,EAAG;AAC3D,IAAA,IAAI,CA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GAAA,CAAI,OAAA,KAAY,YAAY,GAAA,CAAI,OAAA,CAAQ,WAAW,CAAA,EAAG;AAC/D,IAAA,MAAM,IAAIA,oCAAA,CAAmB,CAAA,+CAAA,EAAkD,IAAI,CAAA,CAAA,EAAI;AAAA,MACrF,IAAA,EAAM;AAAA,KACP,CAAA;AAAA,EACH;AAGA,EAAA,sBAAA,CAAuB,GAAA,EAAK,MAAM,OAAO,CAAA;AACzC,EAAA,MAAM,KAAkB,EAAE,OAAA,EAAS,GAAA,CAAI,OAAA,EAAS,aAAa,OAAA,EAAQ;AACrE,EAAA,IAAI,OAAA,KAAY,MAAA,EAAW,EAAA,CAAG,OAAA,GAAU,OAAA;AACxC,EAAA,IAAI,OAAO,GAAA,CAAI,OAAA,KAAY,QAAA,IAAY,GAAA,CAAI,UAAU,CAAA,EAAG;AACtD,IAAA,EAAA,CAAG,SAAA,GAAY,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,UAAU,GAAI,CAAA;AAAA,EAC9C;AACA,EAAA,OAAO,EAAA;AACT;;;ACjYA,IAAM,OAAA,GAAU,IAAIC,6BAAA,EAA0C;AAQvD,SAAS,sBAAA,CACd,KACA,EAAA,EACY;AACZ,EAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,EAAE,CAAA;AAC5B;AAQO,SAAS,yBAAA,GAAgE;AAC9E,EAAA,OAAO,QAAQ,QAAA,EAAS;AAC1B;AASO,SAAS,gCAAgC,OAAA,EAAuB;AACrE,EAAA,QAAA;AAAA,IACE,8BAA8B,OAAO,CAAA,CAAA;AAAA,IACrC,CAAA,0IAAA;AAAA,GACF;AACF","file":"chunk-7IZKTQ5G.cjs","sourcesContent":["/**\n * Single source of truth for loading the hooks config (ADR 0016 — reverses\n * D74/D77 for hooks: JSON is canonical again, in the Claude Code shape).\n *\n * `.theokit/hooks.json` (Claude-Code-shaped JSON) is the only supported form.\n * A stray legacy `.theokit/hooks/*.md` dir (no hooks.json) is NOT loaded — it\n * warns to migrate and yields no hooks. Absent both → empty config.\n *\n * Consumed by `hooks-executor.ts` (runtime dispatch).\n *\n * Config SHAPE is Claude Code's `settings.json` hooks:\n * { \"hooks\": { \"PreToolUse\": [ { \"matcher\": \"shell\",\n * \"hooks\": [ { \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 } ] } ] } }\n *\n * The shape, not the event COVERAGE. Four of the thirty-three documented events are fired by this\n * runtime — see {@link CLAUDE_CODE_EVENT_MAP} for which, why the rest are refused rather than\n * mapped, and the order in which they should be added. An event outside the set is reported to the\n * operator rather than skipped in silence.\n *\n * @internal\n */\n\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { diag, diagFailure } from \"../../diagnostics.js\";\nimport { projectConfigRoots, theokitConfigRoot } from \"../../persistence/paths.js\";\nimport type { CompatSourceDeclaration } from \"../compat/foreign-config-sources.js\";\n\n/** The five lifecycle events the SDK runtime actually fires. */\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\n/**\n * The Claude Code event names this runtime actually FIRES, and the internal event each becomes.\n *\n * Exported so the supported set is stated rather than implied. It used to be private, and the\n * docblock above claimed a shape \"identical to Claude Code's `settings.json` hooks\" while accepting\n * four of the thirty-three documented events — a claim nothing could contradict.\n *\n * A Claude Code event with no firing point here — `SessionStart`, `SubagentStop`, `PreCompact`,\n * `Notification`, `SessionEnd` among them — is skipped with a report rather than silently accepted,\n * because it would never run.\n *\n * ## Why this map is not simply grown\n *\n * Mapping a name the runtime does not fire is strictly WORSE than refusing it. An operator declaring\n * `PreCompact` today gets a report saying it will not fire; with the name mapped they would get\n * silence and a guard that never runs — a declared veto that does not exist. The map grows when the\n * seam exists, one event at a time.\n *\n * ## Priority, when it does grow\n *\n * The blocking events first. An unwired veto loses a CAPABILITY; an unwired observer loses a\n * SIGNAL. Thirteen of the sixteen the spec marks \"Can block? Yes\" are unwired, and\n * `tests/internal/runtime/hooks/the-supported-event-set-is-stated.test.ts` lists them in the order\n * they should be taken, so the next person does not re-derive which is which.\n *\n * `postRun` is reachable through this SDK's own config and has no entry here on purpose: it fires\n * per RUN, and no documented Claude Code event means that. `SessionEnd` is the near miss, and a\n * session is not a run.\n */\nexport const CLAUDE_CODE_EVENT_MAP: Readonly<Record<string, HookEvent>> = {\n PreToolUse: \"preToolUse\",\n PostToolUse: \"postToolUse\",\n UserPromptSubmit: \"preRun\",\n Stop: \"stop\",\n};\n\nexport interface HookCommand {\n command: string;\n matcher?: string;\n timeoutMs?: number;\n /**\n * #637 — the event key as written in the config file (`PreToolUse`), carried so the approval\n * gate can report the vocabulary the consumer's stored fingerprint was taken against.\n *\n * REQUIRED, not optional: `parseClaudeCodeCommand` is the only producer of a `HookCommand` in\n * this package, so every command has one. An optional field would hand every reader a fallback\n * branch for a case that cannot occur — and if an in-memory producer is added later, required is\n * what forces it to supply a value instead of inheriting a silent `undefined`.\n */\n sourceEvent: string;\n /**\n * The config file this command was declared in.\n *\n * Carried so the executor can supply the runtime contract the declaring DIALECT presumes — a\n * command from `.claude/settings.json` is written against Claude Code's runtime and expects\n * `$CLAUDE_PROJECT_DIR` to exist (#522). Absent for a command built in memory, which is native by\n * construction.\n */\n sourcePath?: string;\n}\n\nexport interface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit a stderr warn once per process per unique key. Helps surface the\n * deprecation path without spamming when the loader is called many times\n * during a session (cron + send + skills all hit this).\n *\n * Note: spawned workers (cron, subagent) start fresh processes — warn\n * re-emits there, by design (1 per process boot, not per call).\n *\n * @internal\n */\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diag(`${message}\\n`);\n}\n\n/**\n * A warn-once that is NOT dropped when the host installed no diagnostics sink.\n *\n * `diag` is silent by default and that is right for chatter — a library must not assume the host's\n * stderr is a free-form log, because in a TUI it is the render surface. A configuration the operator\n * WROTE and this runtime will not honour is not chatter. `diagFailure`'s own docblock records the\n * precedent, `theokit-sdk#189`: an MCP server failed to start, the only report went to `diag()`, the\n * embedding UI never read it, and \"the user saw an agent with missing tools and no reason given\".\n *\n * A dropped hook is that shape with a sharper edge, because the missing thing is a guard: the\n * operator declared a refusal, it silently does not exist, and nothing distinguishes that from a\n * refusal that ran and approved.\n *\n * The asymmetry that decides it is quoted from the same place: a corrupted frame is visible and\n * recoverable, while a silently dropped failure is neither.\n *\n * @internal\n */\nexport function warnFailureOnce(key: string, message: string): void {\n if (warned.has(key)) return;\n warned.add(key);\n diagFailure(`${message}\\n`);\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetWarnOnceForTests(): void {\n warned.clear();\n}\n\n/**\n * Load hooks from `.theokit/hooks.json` (Claude-Code-shaped — the only supported\n * form). A stray legacy `.theokit/hooks/*.md` markdown dir (no `hooks.json`) is\n * NOT loaded — it emits a one-time migration warn and yields no hooks.\n *\n * @internal\n */\nexport async function loadHookConfig(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[] = [],\n): Promise<HookConfig> {\n const merged: HookConfig = {};\n let sawAny = false;\n for (const path of hookConfigCandidates(cwd, compatSources)) {\n if (!existsSync(path)) continue;\n sawAny = true;\n // Stamped at merge, where the file is still known. One line later the commands are pooled per\n // event and every trace of which dialect declared them is gone — which is how a Claude Code\n // command came to be run without Claude Code's runtime (#522).\n mergeInto(merged, stampSource(await readHookFile(path), path));\n }\n if (!sawAny && existsSync(join(theokitConfigRoot(cwd), \"hooks\"))) {\n warnOnce(\n \"hooks-md-unsupported\",\n \"[theokit-sdk] .theokit/hooks/*.md hooks are no longer supported (ADR 0016) — migrate to a Claude-Code-shaped .theokit/hooks.json\",\n );\n }\n return merged;\n}\n\n/**\n * Every file that may declare hooks, in precedence order.\n *\n * `hooks.json` under each project config root, then the Claude Code CLI's own settings files — which\n * is where the CLI actually keeps hooks, so a repository set up for it presents its hooks here\n * without being converted. `settings.local.json` is the CLI's personal-override file and sits beside\n * the shared one rather than replacing it.\n *\n * The shape never needed translating: `parseClaudeCodeConfig` reads the `hooks` key off whatever\n * object it is given, and a settings file is that same object with other keys alongside.\n */\nfunction hookConfigCandidates(\n cwd: string,\n compatSources: readonly CompatSourceDeclaration[],\n): string[] {\n const roots = projectConfigRoots(cwd, compatSources, \"hooks\");\n return [\n ...roots.map((root) => join(root, \"hooks.json\")),\n ...roots.map((root) => join(root, \"settings.json\")),\n ...roots.map((root) => join(root, \"settings.local.json\")),\n ];\n}\n\n/**\n * Record which file each command came from.\n *\n * A command already carrying a `sourcePath` keeps it: nothing produces that today, and a nested\n * config that declared its own origin would be describing something this function cannot see.\n */\nfunction stampSource(config: HookConfig, sourcePath: string): HookConfig {\n if (config.hooks === undefined) return config;\n const hooks: NonNullable<HookConfig[\"hooks\"]> = {};\n for (const [event, commands] of Object.entries(config.hooks) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined) continue;\n hooks[event] = commands.map((c) => ({ sourcePath, ...c }));\n }\n return { hooks };\n}\n\n/**\n * Append one source's commands onto the accumulator, per event.\n *\n * MERGED, not first-wins, and the distinction is deliberate. An agent or a skill is a NAMED\n * declaration: two files claiming one name collide, and the explicit namespace should win. Hooks are\n * unnamed lists — two files declaring `PreToolUse` are two sets of commands an operator wrote, and\n * keeping only one drops the other in silence, which is the failure class this package guards\n * against everywhere else.\n */\nfunction mergeInto(target: HookConfig, source: HookConfig): void {\n for (const [event, commands] of Object.entries(source.hooks ?? {}) as [\n HookEvent,\n HookCommand[] | undefined,\n ][]) {\n if (commands === undefined || commands.length === 0) continue;\n target.hooks ??= {};\n target.hooks[event] = [...(target.hooks[event] ?? []), ...commands];\n }\n}\n\nasync function readHookFile(jsonPath: string): Promise<HookConfig> {\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read hooks config: ${jsonPath}`, {\n code: \"hooks_read_error\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in hooks config: ${jsonPath}`, {\n code: \"hooks_json_invalid\",\n cause,\n });\n }\n return parseClaudeCodeConfig(parsed, jsonPath);\n}\n\n/**\n * Narrow an unknown to a record, or throw a typed config error.\n *\n * `hint` names the shape that WOULD be accepted, and exists because the message without it names\n * only the validator's expectation. Measured on a consumer in 2026-09: a flat `hooks` array in a\n * `.theokit/settings.json` made this throw on every turn, and `expected an object at \"hooks\"` gave\n * the operator nothing to act on — the file parses fine for the product that wrote it, and it is\n * this independent read of the same path that fails. An error on a refusal path should carry the\n * fix, not the diagnosis.\n */\nfunction asRecord(\n value: unknown,\n path: string,\n where: string,\n hint?: string,\n): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new ConfigurationError(\n `hooks: expected an object at ${where} in ${path}${hint === undefined ? \"\" : ` — ${hint}`}`,\n { code: \"hooks_json_invalid\" },\n );\n }\n return value as Record<string, unknown>;\n}\n\n/**\n * The shape this loader accepts, quoted back on the one refusal an operator is most likely to hit:\n * `hooks` keyed by event, each event an array of matcher groups.\n */\nconst HOOKS_SHAPE_HINT =\n 'hooks are keyed by event, e.g. { \"hooks\": { \"PreToolUse\": [ { \"hooks\": ' +\n '[ { \"type\": \"command\", \"command\": \"…\" } ] } ] } }';\n\n/** Narrow an unknown to an array, or throw a typed config error. */\nfunction asArray(value: unknown, path: string, where: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new ConfigurationError(`hooks: expected an array at ${where} in ${path}`, {\n code: \"hooks_json_invalid\",\n });\n }\n return value;\n}\n\n/**\n * Parse Claude Code's nested hooks config into the SDK's flat internal shape:\n * `{ hooks: { PreToolUse: [{ matcher?, hooks: [{ type:\"command\", command, timeout? }] }] } }`\n * → `{ hooks: { preToolUse: [{ command, matcher?, timeoutMs? }] } }`. Each group's\n * `matcher` applies to every command it wraps; `timeout` (seconds) → `timeoutMs`.\n */\nfunction parseClaudeCodeConfig(raw: unknown, path: string): HookConfig {\n const root = asRecord(raw, path, \"the root\");\n if (root.hooks === undefined) return {};\n const hooksRec = asRecord(root.hooks, path, `\"hooks\"`, HOOKS_SHAPE_HINT);\n const grouped: Partial<Record<HookEvent, HookCommand[]>> = {};\n\n for (const [ccEvent, groups] of Object.entries(hooksRec)) {\n const event = CLAUDE_CODE_EVENT_MAP[ccEvent];\n if (event === undefined) {\n // The operator wrote this event and it will not fire. Reported through the channel that\n // survives an absent sink — see `warnFailureOnce`.\n warnFailureOnce(\n `hooks-event-${ccEvent}`,\n `[theokit-sdk] hooks: event \"${ccEvent}\" is not fired by the SDK runtime (supported: ${Object.keys(CLAUDE_CODE_EVENT_MAP).join(\", \")}) — skipping`,\n );\n continue;\n }\n grouped[event] = [...(grouped[event] ?? []), ...flattenEventGroups(groups, path, ccEvent)];\n }\n return { hooks: grouped };\n}\n\n/** Flatten one Claude Code event's matcher-groups into internal HookCommands. */\nfunction flattenEventGroups(groups: unknown, path: string, ccEvent: string): HookCommand[] {\n const commands: HookCommand[] = [];\n for (const rawGroup of asArray(groups, path, `hooks.${ccEvent}`)) {\n const group = asRecord(rawGroup, path, `hooks.${ccEvent}[]`);\n const matcher = group.matcher === undefined ? undefined : String(group.matcher);\n for (const rawCmd of asArray(group.hooks, path, `hooks.${ccEvent}[].hooks`)) {\n commands.push(parseClaudeCodeCommand(rawCmd, matcher, path, ccEvent));\n }\n }\n return commands;\n}\n\n/**\n * Fields a Claude Code hook entry may declare that this runtime does not implement.\n *\n * Listed rather than lumped into \"unknown\" because the two are different facts to the operator\n * reading the error: a typo is theirs to fix, and a field written for another runtime is a tree\n * that was never going to work here. The same split is made for subagent frontmatter, for the same\n * reason — an operator migrating a `.claude/` tree learned one key per round trip otherwise.\n *\n * `if` is the one that made refusal the right answer rather than a warning. Dropped, it fails OPEN:\n * a deny hook narrowed to one dangerous command shape silently becomes a deny hook over every call\n * of that tool. Every other field in this set loses a convenience; this one inverts the intent.\n */\nconst UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS = new Set([\n \"if\",\n \"args\",\n \"statusMessage\",\n \"once\",\n \"async\",\n \"asyncRewake\",\n \"shell\",\n]);\n\n/** What `parseClaudeCodeCommand` reads. Anything else is refused. */\nconst ACCEPTED_HOOK_FIELDS = new Set([\"type\", \"command\", \"timeout\"]);\n\n/**\n * Refuse a hook entry that declares a field this parser does not read.\n *\n * The parser used to take `type`, `command` and `timeout` and discard the rest in silence, while\n * `packages/agents` — reading the same file one layer up — already refused an unknown key loudly\n * through a `.strict()` schema. Two layers disagreeing about whether a field is an error is bad on\n * its own; the permissive one being the layer that actually runs the hook is the defect.\n */\nfunction rejectUnreadHookFields(cmd: Record<string, unknown>, path: string, ccEvent: string): void {\n for (const key of Object.keys(cmd)) {\n if (ACCEPTED_HOOK_FIELDS.has(key)) continue;\n const origin = UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS.has(key)\n ? ` — \"${key}\" is a Claude Code hook field that this runtime does not implement. The same ` +\n `applies to: ${[...UNIMPLEMENTED_CLAUDE_CODE_HOOK_FIELDS].filter((f) => f !== key).join(\", \")}`\n : \"\";\n throw new ConfigurationError(\n `hooks.${ccEvent}: unsupported field \"${key}\" (accepted: ${[...ACCEPTED_HOOK_FIELDS].join(\", \")}) in ${path}${origin}`,\n { code: \"hooks_unsupported_field\" },\n );\n }\n}\n\n/** One `{ type:\"command\", command, timeout? }` entry → an internal HookCommand. */\nfunction parseClaudeCodeCommand(\n raw: unknown,\n matcher: string | undefined,\n path: string,\n ccEvent: string,\n): HookCommand {\n const cmd = asRecord(raw, path, `hooks.${ccEvent}[].hooks[]`);\n if (cmd.type !== \"command\") {\n throw new ConfigurationError(\n `hooks: only { \"type\": \"command\" } is supported (got ${JSON.stringify(cmd.type)}) in ${path}`,\n { code: \"hooks_unsupported_type\" },\n );\n }\n if (typeof cmd.command !== \"string\" || cmd.command.length === 0) {\n throw new ConfigurationError(`hooks: \"command\" must be a non-empty string in ${path}`, {\n code: \"hooks_invalid_command\",\n });\n }\n // After the type/command checks, so a `{ type: \"http\", url }` entry still fails for its own\n // reason rather than for its `url`.\n rejectUnreadHookFields(cmd, path, ccEvent);\n const hc: HookCommand = { command: cmd.command, sourceEvent: ccEvent };\n if (matcher !== undefined) hc.matcher = matcher;\n if (typeof cmd.timeout === \"number\" && cmd.timeout > 0) {\n hc.timeoutMs = Math.round(cmd.timeout * 1000);\n }\n return hc;\n}\n","/**\n * Personality fork-context (ADR D168 + EC-A snapshot semantic).\n *\n * Uses Node's `AsyncLocalStorage` so a fork's execution chain can know\n * that it is running inside a fork AND can see the slug that was active\n * on the parent **at fork-construction time**.\n *\n * **EC-A:** The slug stored here is captured ONCE at the wrap site\n * (`localAgentFork`) — passing `parentStore.active(parentAgentId)`\n * returns a primitive `string | undefined`, which is then frozen\n * inside the ALS context object. Subsequent `usePersonality` calls on\n * the parent do NOT mutate the fork's view, because the fork reads from\n * its own ALS frame, not from the parent's store.\n *\n * @internal\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\n/**\n * Snapshot data carried into a fork's async context.\n *\n * @internal\n */\nexport interface PersonalityForkContext {\n /** Parent's active personality slug at fork-construction time. */\n readonly slug: string | undefined;\n /** Always `true` inside this scope (used by guards). */\n readonly isFork: true;\n}\n\nconst storage = new AsyncLocalStorage<PersonalityForkContext>();\n\n/**\n * Run `fn` with `ctx` bound as the active fork context. Nested calls\n * shadow the outer context (EC-22).\n *\n * @internal\n */\nexport function withPersonalityContext<T>(\n ctx: PersonalityForkContext,\n fn: () => Promise<T>,\n): Promise<T> {\n return storage.run(ctx, fn);\n}\n\n/**\n * Return the active fork context, or `undefined` when called outside a\n * fork scope.\n *\n * @internal\n */\nexport function currentPersonalityContext(): PersonalityForkContext | undefined {\n return storage.getStore();\n}\n\n/**\n * Emit one warning per agentId stating that personality switches inside\n * a fork are no-ops. The fork inherits the parent snapshot — runtime\n * mutation is intentionally rejected to keep fork voice deterministic.\n *\n * @internal\n */\nexport function warnPersonalitySwitchInsideFork(agentId: string): void {\n warnOnce(\n `personality-switch-in-fork-${agentId}`,\n `[theokit-sdk] usePersonality is a no-op inside a fork (D168). Subagents inherit the parent's active personality at fork-construction time.`,\n );\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { LruEmbeddingCache } from './chunk-H73MEMQB.js';
2
- import { resolveMemoryRoot, defaultIndexPath, memoryIndexRoot, openMemoryDb, truncateSnippet, resolveWeights, blendScores, LanceIndex, collectMarkdownFiles, sha256 } from './chunk-SADXXGWU.js';
2
+ import { resolveMemoryRoot, defaultIndexPath, memoryIndexRoot, openMemoryDb, truncateSnippet, resolveWeights, blendScores, LanceIndex, collectMarkdownFiles, sha256 } from './chunk-BZ3YMAMP.js';
3
3
  import { sanitizeFts5Query, containsCjk } from './chunk-WE22OXQA.js';
4
4
  import { ConfigurationError } from './chunk-ALUN2B4W.js';
5
5
  import { diag } from './chunk-CZJ6Q7CW.js';
@@ -589,5 +589,5 @@ var IndexManager = class _IndexManager {
589
589
  };
590
590
 
591
591
  export { IndexManager };
592
- //# sourceMappingURL=chunk-7SZAV6QG.js.map
593
- //# sourceMappingURL=chunk-7SZAV6QG.js.map
592
+ //# sourceMappingURL=chunk-7MMTZBTT.js.map
593
+ //# sourceMappingURL=chunk-7MMTZBTT.js.map