@hawkeyexl/manni 4.4.1 → 4.5.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 (163) hide show
  1. package/README.md +1 -1
  2. package/dist/{batch-GFNLTGOH.js → batch-GOE3UXOD.js} +11 -11
  3. package/dist/{build-COYIQ25L.js → build-M7BMEHL2.js} +13 -11
  4. package/dist/{calibrate-MDBLJKEE.js → calibrate-6RRAILUY.js} +12 -12
  5. package/dist/{capture-LRML2PKV.js → capture-RJPQ6B4N.js} +12 -12
  6. package/dist/{check-EDLBYL5N.js → check-BQD64X3N.js} +11 -11
  7. package/dist/{check-HYNGXYJV.js → check-ESNS7ZBC.js} +4 -4
  8. package/dist/{check-ASPIHA6B.js → check-RQIIIURI.js} +12 -12
  9. package/dist/{chunk-NXV7WE2D.js → chunk-3R5Y3XOL.js} +3 -3
  10. package/dist/{chunk-A5ULMVHQ.js → chunk-3YHAYXBC.js} +2 -2
  11. package/dist/{chunk-57NEQRVO.js → chunk-527HHQPS.js} +4 -4
  12. package/dist/{chunk-57NEQRVO.js.map → chunk-527HHQPS.js.map} +1 -1
  13. package/dist/{chunk-6OYEI2VV.js → chunk-52PDIZKV.js} +3 -3
  14. package/dist/{chunk-UJCVAWP7.js → chunk-6XTQDFGP.js} +2 -2
  15. package/dist/{chunk-UJCVAWP7.js.map → chunk-6XTQDFGP.js.map} +1 -1
  16. package/dist/{chunk-3VK37OR2.js → chunk-7OQAU4EA.js} +5 -5
  17. package/dist/{chunk-4IUC2MNL.js → chunk-7ZUCEMCY.js} +8 -8
  18. package/dist/{chunk-M2JCK5F6.js → chunk-B7XUEQF3.js} +13 -2
  19. package/dist/chunk-B7XUEQF3.js.map +1 -0
  20. package/dist/{chunk-MYMBCTDE.js → chunk-BOIF2XGG.js} +2 -2
  21. package/dist/{chunk-YJOGUXGP.js → chunk-C3KI45RF.js} +8 -6
  22. package/dist/{chunk-YJOGUXGP.js.map → chunk-C3KI45RF.js.map} +1 -1
  23. package/dist/{chunk-MMTSSTG7.js → chunk-C6HZ6C5T.js} +2 -2
  24. package/dist/{chunk-QQUKGCAJ.js → chunk-CP4ZM43V.js} +2 -2
  25. package/dist/chunk-DE7JSWXV.js +2462 -0
  26. package/dist/chunk-DE7JSWXV.js.map +1 -0
  27. package/dist/{chunk-YB4IBW3M.js → chunk-DX32P2DT.js} +2 -2
  28. package/dist/{chunk-RL5XWQOL.js → chunk-EL2BZTDL.js} +137 -50
  29. package/dist/chunk-EL2BZTDL.js.map +1 -0
  30. package/dist/{chunk-WB3QM6PP.js → chunk-ELZ2IIOF.js} +332 -2522
  31. package/dist/chunk-ELZ2IIOF.js.map +1 -0
  32. package/dist/{chunk-MWJLZMBL.js → chunk-F2OVHJNC.js} +10 -10
  33. package/dist/{chunk-I2AH3CJJ.js → chunk-FLF6AECQ.js} +7 -7
  34. package/dist/{chunk-GCQRPUSB.js → chunk-GAZFKZHM.js} +4 -4
  35. package/dist/{chunk-QZ6LRSNV.js → chunk-HQFVJDEN.js} +7 -7
  36. package/dist/{chunk-M3W7J6MU.js → chunk-HVFR66GQ.js} +2 -2
  37. package/dist/{chunk-2B7ZNTPV.js → chunk-IA7BMIPE.js} +2 -2
  38. package/dist/{chunk-PIKOVN6W.js → chunk-JQU7FHYH.js} +6 -6
  39. package/dist/{chunk-NLXTXE5Y.js → chunk-K3U5F2QT.js} +183 -31
  40. package/dist/chunk-K3U5F2QT.js.map +1 -0
  41. package/dist/{chunk-JCDXE76J.js → chunk-MZC62HPZ.js} +2 -2
  42. package/dist/{chunk-TK3FC4RF.js → chunk-NAZRLJAK.js} +3 -3
  43. package/dist/{chunk-JXLTXMJ7.js → chunk-NGK3N6F2.js} +3 -3
  44. package/dist/{chunk-PU6DFJMY.js → chunk-NN4ASVTY.js} +3 -3
  45. package/dist/{chunk-C4SQM22E.js → chunk-OIZ3XMKB.js} +13 -11
  46. package/dist/chunk-OIZ3XMKB.js.map +1 -0
  47. package/dist/{chunk-6JSSEWBG.js → chunk-QCBICNKC.js} +6 -6
  48. package/dist/chunk-QCBICNKC.js.map +1 -0
  49. package/dist/{chunk-DXNZS72W.js → chunk-QLUMKWQQ.js} +3 -3
  50. package/dist/{chunk-EPH54CAY.js → chunk-QY3DOZMS.js} +4 -4
  51. package/dist/{chunk-FBEQCK47.js → chunk-SJO2FTPG.js} +6 -6
  52. package/dist/{chunk-PNPQTHBT.js → chunk-SNEHX4VE.js} +2 -2
  53. package/dist/{chunk-SKSDRUUK.js → chunk-TA42STP7.js} +4 -4
  54. package/dist/{chunk-CK7SKVHR.js → chunk-TBAMBLF3.js} +3 -12
  55. package/dist/chunk-TBAMBLF3.js.map +1 -0
  56. package/dist/{chunk-IDV6HJCB.js → chunk-TCC737IS.js} +3 -3
  57. package/dist/{chunk-QRWGPQKO.js → chunk-TVIX653Q.js} +3 -3
  58. package/dist/{chunk-YTURO7SI.js → chunk-UK2I3ACY.js} +3 -3
  59. package/dist/{chunk-7UKO3ASZ.js → chunk-XWFNO5PO.js} +3 -3
  60. package/dist/{chunk-37LP5HMZ.js → chunk-YA63PVWI.js} +5 -5
  61. package/dist/chunk-YGFIQ6Y5.js +17 -0
  62. package/dist/chunk-YGFIQ6Y5.js.map +1 -0
  63. package/dist/{chunk-UQISLDAV.js → chunk-ZX43SRZR.js} +3 -3
  64. package/dist/{cli-MN7PYMBI.js → cli-6PGVHP7Y.js} +15 -15
  65. package/dist/{cli-6UB5N6CU.js → cli-AAG3N4NB.js} +16 -16
  66. package/dist/{cli-6HIDIFVT.js → cli-E3H6ZP4I.js} +2 -2
  67. package/dist/{cli-RPM5PELX.js → cli-HUIMNJT6.js} +20 -15
  68. package/dist/cli-HUIMNJT6.js.map +1 -0
  69. package/dist/{cli-VI7VHWNZ.js → cli-MHTYPVOD.js} +16 -16
  70. package/dist/{cli-LFP5ZGYS.js → cli-PRZHQ3QB.js} +15 -13
  71. package/dist/{cli-LFP5ZGYS.js.map → cli-PRZHQ3QB.js.map} +1 -1
  72. package/dist/{cli-3BIBYHFK.js → cli-QKIJOXGW.js} +13 -13
  73. package/dist/{cli-PYPX6O6E.js → cli-TYGOHJOJ.js} +25 -25
  74. package/dist/{cli-673OTRGE.js → cli-YW6VWBHX.js} +9 -9
  75. package/dist/cli.js +11 -11
  76. package/dist/docmeta.js +8 -8
  77. package/dist/{github-SXPGP5DB.js → github-3WMSTNTK.js} +13 -13
  78. package/dist/{github-6QMYOHC3.js → github-OXSJQ4PS.js} +11 -11
  79. package/dist/index.d.ts +30 -8
  80. package/dist/index.js +42 -38
  81. package/dist/index.js.map +1 -1
  82. package/dist/{json-SY7KLNC7.js → json-4DCKDGUV.js} +11 -11
  83. package/dist/lint-YDHVVZHT.js +30 -0
  84. package/dist/{list-KZNVTNVC.js → list-3ZO2NIYO.js} +11 -11
  85. package/dist/{list-Q57YTFUQ.js → list-EJH6VAOW.js} +11 -11
  86. package/dist/{page-KSGV5RD4.js → page-QEDB7EVU.js} +10 -10
  87. package/dist/{pretty-A5EGTN35.js → pretty-5DGEBZSV.js} +11 -11
  88. package/dist/{pretty-CXSDXNAS.js → pretty-SQX33UM2.js} +12 -12
  89. package/dist/{reporters-HUY7UXFS.js → reporters-OHSI3RMV.js} +12 -11
  90. package/dist/{reporters-K2VUKSAK.js → reporters-YELDDYJD.js} +4 -4
  91. package/dist/{run-3DYJNRIG.js → run-IP6NZHAG.js} +11 -11
  92. package/dist/{term-BIQUPMOR.js → term-2WMDZ4PY.js} +15 -15
  93. package/dist/{validate-53RKM2XG.js → validate-G6HH3YXL.js} +5 -5
  94. package/package.json +1 -1
  95. package/plugin/manni/.claude-plugin/plugin.json +1 -1
  96. package/dist/chunk-6JSSEWBG.js.map +0 -1
  97. package/dist/chunk-C4SQM22E.js.map +0 -1
  98. package/dist/chunk-CK7SKVHR.js.map +0 -1
  99. package/dist/chunk-M2JCK5F6.js.map +0 -1
  100. package/dist/chunk-NLXTXE5Y.js.map +0 -1
  101. package/dist/chunk-RL5XWQOL.js.map +0 -1
  102. package/dist/chunk-WB3QM6PP.js.map +0 -1
  103. package/dist/cli-RPM5PELX.js.map +0 -1
  104. package/dist/lint-ASMJLLPA.js +0 -28
  105. /package/dist/{batch-GFNLTGOH.js.map → batch-GOE3UXOD.js.map} +0 -0
  106. /package/dist/{build-COYIQ25L.js.map → build-M7BMEHL2.js.map} +0 -0
  107. /package/dist/{calibrate-MDBLJKEE.js.map → calibrate-6RRAILUY.js.map} +0 -0
  108. /package/dist/{capture-LRML2PKV.js.map → capture-RJPQ6B4N.js.map} +0 -0
  109. /package/dist/{check-ASPIHA6B.js.map → check-BQD64X3N.js.map} +0 -0
  110. /package/dist/{check-EDLBYL5N.js.map → check-ESNS7ZBC.js.map} +0 -0
  111. /package/dist/{check-HYNGXYJV.js.map → check-RQIIIURI.js.map} +0 -0
  112. /package/dist/{chunk-NXV7WE2D.js.map → chunk-3R5Y3XOL.js.map} +0 -0
  113. /package/dist/{chunk-A5ULMVHQ.js.map → chunk-3YHAYXBC.js.map} +0 -0
  114. /package/dist/{chunk-6OYEI2VV.js.map → chunk-52PDIZKV.js.map} +0 -0
  115. /package/dist/{chunk-3VK37OR2.js.map → chunk-7OQAU4EA.js.map} +0 -0
  116. /package/dist/{chunk-4IUC2MNL.js.map → chunk-7ZUCEMCY.js.map} +0 -0
  117. /package/dist/{chunk-MYMBCTDE.js.map → chunk-BOIF2XGG.js.map} +0 -0
  118. /package/dist/{chunk-MMTSSTG7.js.map → chunk-C6HZ6C5T.js.map} +0 -0
  119. /package/dist/{chunk-QQUKGCAJ.js.map → chunk-CP4ZM43V.js.map} +0 -0
  120. /package/dist/{chunk-YB4IBW3M.js.map → chunk-DX32P2DT.js.map} +0 -0
  121. /package/dist/{chunk-MWJLZMBL.js.map → chunk-F2OVHJNC.js.map} +0 -0
  122. /package/dist/{chunk-I2AH3CJJ.js.map → chunk-FLF6AECQ.js.map} +0 -0
  123. /package/dist/{chunk-GCQRPUSB.js.map → chunk-GAZFKZHM.js.map} +0 -0
  124. /package/dist/{chunk-QZ6LRSNV.js.map → chunk-HQFVJDEN.js.map} +0 -0
  125. /package/dist/{chunk-M3W7J6MU.js.map → chunk-HVFR66GQ.js.map} +0 -0
  126. /package/dist/{chunk-2B7ZNTPV.js.map → chunk-IA7BMIPE.js.map} +0 -0
  127. /package/dist/{chunk-PIKOVN6W.js.map → chunk-JQU7FHYH.js.map} +0 -0
  128. /package/dist/{chunk-JCDXE76J.js.map → chunk-MZC62HPZ.js.map} +0 -0
  129. /package/dist/{chunk-TK3FC4RF.js.map → chunk-NAZRLJAK.js.map} +0 -0
  130. /package/dist/{chunk-JXLTXMJ7.js.map → chunk-NGK3N6F2.js.map} +0 -0
  131. /package/dist/{chunk-PU6DFJMY.js.map → chunk-NN4ASVTY.js.map} +0 -0
  132. /package/dist/{chunk-DXNZS72W.js.map → chunk-QLUMKWQQ.js.map} +0 -0
  133. /package/dist/{chunk-EPH54CAY.js.map → chunk-QY3DOZMS.js.map} +0 -0
  134. /package/dist/{chunk-FBEQCK47.js.map → chunk-SJO2FTPG.js.map} +0 -0
  135. /package/dist/{chunk-PNPQTHBT.js.map → chunk-SNEHX4VE.js.map} +0 -0
  136. /package/dist/{chunk-SKSDRUUK.js.map → chunk-TA42STP7.js.map} +0 -0
  137. /package/dist/{chunk-IDV6HJCB.js.map → chunk-TCC737IS.js.map} +0 -0
  138. /package/dist/{chunk-QRWGPQKO.js.map → chunk-TVIX653Q.js.map} +0 -0
  139. /package/dist/{chunk-YTURO7SI.js.map → chunk-UK2I3ACY.js.map} +0 -0
  140. /package/dist/{chunk-7UKO3ASZ.js.map → chunk-XWFNO5PO.js.map} +0 -0
  141. /package/dist/{chunk-37LP5HMZ.js.map → chunk-YA63PVWI.js.map} +0 -0
  142. /package/dist/{chunk-UQISLDAV.js.map → chunk-ZX43SRZR.js.map} +0 -0
  143. /package/dist/{cli-MN7PYMBI.js.map → cli-6PGVHP7Y.js.map} +0 -0
  144. /package/dist/{cli-6UB5N6CU.js.map → cli-AAG3N4NB.js.map} +0 -0
  145. /package/dist/{cli-6HIDIFVT.js.map → cli-E3H6ZP4I.js.map} +0 -0
  146. /package/dist/{cli-VI7VHWNZ.js.map → cli-MHTYPVOD.js.map} +0 -0
  147. /package/dist/{cli-3BIBYHFK.js.map → cli-QKIJOXGW.js.map} +0 -0
  148. /package/dist/{cli-PYPX6O6E.js.map → cli-TYGOHJOJ.js.map} +0 -0
  149. /package/dist/{cli-673OTRGE.js.map → cli-YW6VWBHX.js.map} +0 -0
  150. /package/dist/{github-6QMYOHC3.js.map → github-3WMSTNTK.js.map} +0 -0
  151. /package/dist/{github-SXPGP5DB.js.map → github-OXSJQ4PS.js.map} +0 -0
  152. /package/dist/{json-SY7KLNC7.js.map → json-4DCKDGUV.js.map} +0 -0
  153. /package/dist/{lint-ASMJLLPA.js.map → lint-YDHVVZHT.js.map} +0 -0
  154. /package/dist/{list-KZNVTNVC.js.map → list-3ZO2NIYO.js.map} +0 -0
  155. /package/dist/{list-Q57YTFUQ.js.map → list-EJH6VAOW.js.map} +0 -0
  156. /package/dist/{page-KSGV5RD4.js.map → page-QEDB7EVU.js.map} +0 -0
  157. /package/dist/{pretty-A5EGTN35.js.map → pretty-5DGEBZSV.js.map} +0 -0
  158. /package/dist/{pretty-CXSDXNAS.js.map → pretty-SQX33UM2.js.map} +0 -0
  159. /package/dist/{reporters-HUY7UXFS.js.map → reporters-OHSI3RMV.js.map} +0 -0
  160. /package/dist/{reporters-K2VUKSAK.js.map → reporters-YELDDYJD.js.map} +0 -0
  161. /package/dist/{run-3DYJNRIG.js.map → run-IP6NZHAG.js.map} +0 -0
  162. /package/dist/{term-BIQUPMOR.js.map → term-2WMDZ4PY.js.map} +0 -0
  163. /package/dist/{validate-53RKM2XG.js.map → validate-G6HH3YXL.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/shared/prompt.ts","../src/meta/commands/get.ts","../src/meta/commands/schemas.ts","../src/meta/commands/query.ts","../src/meta/commands/fill.ts","../src/meta/commands/fill-projection.ts","../src/meta/commands/fill-hints.ts","../src/shared/reference-fields.ts","../src/shared/term-labels.ts","../src/meta/core/manifest-writes.ts","../src/meta/commands/fill-prompt.ts","../src/meta/commands/derive.ts","../src/meta/reporters/fill.ts","../src/meta/reporters/derive.ts","../src/meta/commands/relocate.ts","../src/meta/reporters/get.ts","../src/meta/reporters/query.ts"],"sourcesContent":["/**\n * The one question a write asks when it needs an encryption key and there is\n * none (proposal 0045): generate one, and write it where the next run will\n * find it.\n *\n * Only on a terminal. Off one, a write that needs a key refuses (exit 2) with\n * the same line and no question, because a prompt nobody can answer is a hung\n * CI job. The CLI decides by passing `terminalConfirm()`; the command cores\n * take the `Confirm` as an option, so tests inject the answer.\n *\n * What the user reads, in order, on stderr:\n *\n * manni: /owner must be encrypted, and no encryption key is available.\n * manni: manni.config.yaml is not ignored by git: … (only when it is not)\n * Generate a key and write it to manni.config.yaml? [y/N] y\n * Encryption key written to manni.config.yaml.\n *\n * The first two are diagnostics, prefixed by the caller's `notice`. The\n * question and its answer are a dialogue with the terminal, so neither\n * carries the prefix: the confirmation line is written straight to stderr.\n */\nimport { createInterface } from \"node:readline\";\nimport type { ConfigFile } from \"./config-file.js\";\nimport { generateEncryptionKey } from \"./encryption.js\";\nimport {\n ENCRYPTION_KEY_ENV,\n committedKeyWarning,\n isIgnoredByGit,\n resolveEncryptionKey,\n writeEncryptionKey,\n} from \"./encryption-key.js\";\n\n/** Ask a yes/no question; `true` only for a yes. */\nexport type Confirm = (question: string) => Promise<boolean>;\n\n/**\n * A `Confirm` over any pair of streams. `question` is printed followed by\n * `[y/N] `; `y` or `yes` in any case is yes, and anything else, an empty\n * answer, end of input or Ctrl-C is no. When the input ends without an\n * answer, the prompt's line is ended so the next diagnostic starts clean.\n */\nexport function readlineConfirm(\n input: NodeJS.ReadableStream,\n output: NodeJS.WritableStream,\n): Confirm {\n return (question) =>\n new Promise<boolean>((resolvePromise) => {\n const rl = createInterface({ input, output });\n let settled = false;\n const finish = (answer: boolean, endLine: boolean): void => {\n if (settled) return;\n settled = true;\n if (endLine) output.write(\"\\n\");\n rl.close();\n resolvePromise(answer);\n };\n rl.on(\"close\", () => {\n finish(false, true);\n });\n rl.on(\"SIGINT\", () => {\n finish(false, true);\n });\n rl.question(`${question}[y/N] `, (answer) => {\n finish(/^y(?:es)?$/i.test(answer.trim()), false);\n });\n });\n}\n\n/**\n * The terminal's `Confirm`, asking on stderr so stdout stays the report's.\n * `undefined` unless stdin and stderr are both terminals.\n */\nexport function terminalConfirm(): Confirm | undefined {\n // Typed `boolean`, but `undefined` on a pipe; negation covers both.\n if (!process.stdin.isTTY || !process.stderr.isTTY) {\n return undefined;\n }\n return readlineConfirm(process.stdin, process.stderr);\n}\n\nexport interface EnsureKeyOptions {\n /** What must be encrypted, e.g. `/owner` or `src/limits.ts:2`. */\n subject: string;\n cwd: string;\n /** The running tool's discovered config, if any. */\n file: ConfigFile | null;\n env?: NodeJS.ProcessEnv;\n /** Injected; the CLI passes `terminalConfirm()`. Absent means no question. */\n confirm?: Confirm;\n /** A stderr diagnostic; the caller adds the `manni: ` prefix. */\n notice: (message: string) => void;\n toError: (m: string) => Error;\n}\n\n/**\n * The key a write encrypts with. The resolved one when there is one;\n * otherwise, on a terminal, a fresh key written to the config after a yes.\n *\n * With no `confirm`, or on a no, this throws the refusal and writes nothing.\n * Off a terminal the refusal is the only output: the notices lead up to a\n * question, and there is none to lead up to.\n *\n * After a write the caller's `file` is stale (its `text` and `encryptionKey`\n * predate the key): use the returned key, and rediscover before rewriting the\n * file for any other reason.\n */\nexport async function ensureEncryptionKey(\n opts: EnsureKeyOptions,\n): Promise<{ key: string; written?: { source: string; created: boolean } }> {\n const { subject, cwd, file, confirm, notice, toError } = opts;\n const resolved = resolveEncryptionKey({ env: opts.env, file, toError });\n if (resolved.key !== undefined) return { key: resolved.key };\n\n const missing = `${subject} must be encrypted, and no encryption key is available.`;\n const refusal = `${missing} Run \\`manni key set\\`, or set ${ENCRYPTION_KEY_ENV}.`;\n if (confirm === undefined) throw toError(refusal);\n\n notice(missing);\n const key = generateEncryptionKey();\n // Name the target before asking about it. This also refuses a single-tool\n // file before any question is put.\n const target = await writeEncryptionKey({ file, key, cwd, toError, dryRun: true });\n if (isIgnoredByGit(target.path) === false) {\n notice(committedKeyWarning(target.source));\n }\n if (!(await confirm(`Generate a key and write it to ${target.source}? `))) {\n throw toError(refusal);\n }\n const written = await writeEncryptionKey({ file, key, cwd, toError });\n process.stderr.write(\n written.created\n ? `Created ${written.source} with an encryption key.\\n`\n : `Encryption key written to ${written.source}.\\n`,\n );\n return { key, written: { source: written.source, created: written.created } };\n}\n","/**\n * `get` command core. Prints one or more metadata field values from each file.\n * Input handling (positional paths, globs, directories, `-` for stdin, and\n * config `paths:` fallback) mirrors `validate` so the two commands behave\n * identically.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { loadExternalMetadata, mergeWithMarks } from \"../core/external-metadata.js\";\nimport { marksValidator, pageMarks } from \"../core/page-marks.js\";\nimport { resolve, extname } from \"node:path\";\nimport { resolveElements } from \"../core/resolve-schema.js\";\nimport { memberOf, retainMembers } from \"../core/collections.js\";\nimport { DocmetaError } from \"../types.js\";\nimport {\n extractorByName,\n extractorForExtension,\n supportedExtensions,\n} from \"../extractors/index.js\";\nimport {\n assertNonEmpty,\n gitignoreOptions,\n resolveTargetSet,\n STDIN_LABEL,\n STDIN_TOKEN,\n} from \"../core/load-files.js\";\nimport {\n resolveRunConfig,\n schemaTrustRoot,\n type ConfigNotice,\n type DocmetaConfig,\n} from \"../core/config.js\";\nimport {\n assertSourcesAvailable,\n deriveMetadata,\n} from \"../core/derive/index.js\";\nimport { commandsOf, machinesOf } from \"../core/derive/config.js\";\nimport { provenanceFenced } from \"../core/derive/git.js\";\nimport {\n compareProvenance,\n provenanceEntries,\n readProvenancePage,\n type ProvenanceDerivation,\n} from \"../core/derive/provenance.js\";\nimport { readerManifests, readerPlace, stampManifests } from \"../core/derive/provenance-place.js\";\nimport {\n DERIVE_SOURCES,\n isBuiltinField,\n PROVENANCE_FIELD,\n STAMPED_DATE_FIELDS,\n type DerivableField,\n type DeriveCommand,\n type DerivedRecord,\n type DerivedValue,\n type DeriveInput,\n} from \"../core/derive/types.js\";\nimport { lazyKey } from \"../core/encrypted.js\";\nimport { STDIN_REQUIRES_AS } from \"../../shared/cli-options.js\";\n\nexport interface GetOptions {\n fields: string[];\n inputs: string[];\n as?: string;\n exclude?: string[];\n exts?: string[];\n configPath?: string;\n /** `--no-config`: skip config discovery and use the built-in defaults. */\n noConfig?: boolean;\n /**\n * `--collection <name>`, repeatable: run over the named configured\n * collections instead of every declared one (proposal 0041). Cannot be\n * combined with positional paths; `-` is allowed beside it.\n */\n collections?: string[];\n cwd?: string;\n /** Content for the `-` (stdin) input, injected by the CLI/tests. */\n stdinContent?: string;\n /** Permit an input set that resolves to zero files (see `assertNonEmpty`). */\n allowEmpty?: boolean;\n /**\n * `--no-gitignore` (false). Absent leaves config `respectGitignore:` in\n * charge, which itself defaults to on.\n */\n respectGitignore?: boolean;\n /** Diagnostics for the user; the CLI writes these to stderr. */\n onNotice?: (message: string) => void;\n /** Called once when a config governs the run, so the CLI can report it. */\n onConfigLoaded?: (info: ConfigNotice) => void;\n /**\n * `--offline`, accepted for surface parity with `validate` and `fill`.\n *\n * It has **no effect here**, and that is a property of the command rather\n * than an omission: `get` prints extracted field values and never resolves or\n * loads a schema, so it has no network dependency to suppress. Accepting it\n * keeps one flag set across the three commands, so a script can pass\n * `--offline` uniformly without knowing which subcommand needs it.\n */\n offline?: boolean;\n /**\n * `--no-cache` (false): ask GitHub or GitLab again rather than reading the\n * review cache. Only `--derived` consults it, and only for `reviewed-by`\n * and `last-reviewed`; absent leaves the cache on.\n */\n cache?: boolean;\n /**\n * Whether to resolve each requested field against the evidence — git\n * history, CODEOWNERS, the review record, a configured command (proposals\n * 0040, 0042). **On unless explicitly `false`** (proposal 0043): a read\n * says what the value is and where it came from, and `--no-derived` is the\n * way back to what the document alone stores.\n *\n * Only the requested fields a source can state are derived, so a field no\n * source claims consults nothing and spawns nothing. Stdin is included in\n * the run and simply derives nothing: a piped document has no path, so no\n * source can speak for it, and that is an answer rather than an error.\n */\n derived?: boolean;\n /** The clock an uncommitted body change is dated by. Test seam; default `new Date()`. */\n now?: () => Date;\n}\n\nexport interface GetFileResult {\n file: string;\n present: boolean;\n values: Record<string, unknown>;\n /**\n * The evidence per requested field. A derivable field is always a key\n * here: a `DerivedValue` when a source answered, `null` when every\n * consulted source had nothing to say (a file with no commits, a path no\n * CODEOWNERS rule matches). A requested field that is **not** derivable is\n * absent from the record. Absent altogether under `--no-derived`, when no\n * requested field is derivable, and on a file that did not parse.\n */\n derived?: Record<string, DerivedValue | null>;\n /**\n * The effective value per requested field (proposal 0043): the document's\n * when it **carries the key**, the derived one otherwise, and absent when\n * neither side has it. Presence is `Object.hasOwn`, not truthiness, so a\n * document writing `owner: null` has asserted a value and no derived one\n * replaces it — the same rule the `resolved` SQL view implements.\n *\n * Shaped exactly like `values`: one entry per requested field, `undefined`\n * where nothing resolved, which JSON drops. Absent under `--no-derived`,\n * and on a file that did not parse.\n */\n resolved?: Record<string, unknown>;\n /**\n * Which side answered, for the fields that resolved to something. A field\n * neither the document nor any source has is absent, which is how a reader\n * tells \"unset\" from \"unset, but derivable\". Absent under `--no-derived`,\n * and on a file that did not parse.\n */\n origin?: Record<string, \"asserted\" | \"derived\">;\n /**\n * Why this file yielded no values, when it yielded none for a reason.\n *\n * Set only when the document's metadata block could not be read at all — the\n * same throw `validate` turns into a `(parse)` finding. Absent on every file\n * that parsed, including one with no metadata block and one where every\n * requested field was unset: those are answers, and this is the absence of\n * one. A run carrying any `error` exits 1.\n */\n error?: string;\n /**\n * `provenance` only (proposal 0046), present when it was requested and the\n * file parsed. `bodyLine` is the file line body line 1 sits on, which the\n * record's body lines are shown against. `current` is whether the record\n * agrees with git as `validate` judges it, range by range; absent when\n * nothing was derived.\n */\n provenance?: { bodyLine: number; current?: boolean };\n}\n\nexport async function runGet(opts: GetOptions): Promise<GetFileResult[]> {\n const cwd = opts.cwd ?? process.cwd();\n if (opts.fields.length === 0) {\n throw new DocmetaError(\"Specify at least one field to get.\");\n }\n\n // Explicit CLI inputs win, else config `paths:`; `base` is whichever of the\n // two directories those inputs were written relative to.\n const { config, inputs, base, configDir, collections, declaredCollections, fromCollections, configFile } =\n await resolveRunConfig({\n cwd,\n configPath: opts.configPath,\n noConfig: opts.noConfig,\n inputs: opts.inputs,\n ...(opts.collections !== undefined\n ? { collections: opts.collections }\n : {}),\n onConfigLoaded: opts.onConfigLoaded,\n });\n // `get` prints what the page holds, ciphertext included; only an encrypted\n // join field is decrypted, to match its manifest entry (proposal 0045).\n const joinKey = lazyKey(configFile, undefined);\n const usingStdin = inputs.includes(STDIN_TOKEN);\n\n if (inputs.length === 0) {\n throw new DocmetaError(\n \"No files to read. Pass paths/globs, or declare a collection under `collections:` in manni.config.yaml.\",\n );\n }\n\n const forced = opts.as ? extractorByName(opts.as) : undefined;\n if (opts.as && !forced) {\n throw new DocmetaError(\n `Unknown format \"${opts.as}\". Supported extensions: ${supportedExtensions().join(\", \")}.`,\n );\n }\n\n const exts = opts.exts ?? (forced ? forced.extensions : undefined);\n const fileInputs = inputs.filter((i) => i !== STDIN_TOKEN);\n const allowEmpty = opts.allowEmpty ?? config?.allowEmpty;\n // Only `--exclude`: a collection's `exclude:` governs membership, not the\n // walk of a path someone typed (0041 rule 3).\n const exclude = opts.exclude ?? [];\n /** The collections one label belongs to, computed once per file. */\n const membersFor = (label: string): string[] =>\n memberOf(collections, configDir ?? cwd, base, label);\n const { files: walked, gitignoreSkipped } = await resolveTargetSet({\n inputs: fileInputs,\n exts,\n exclude,\n cwd: base,\n allowEmpty,\n ...gitignoreOptions({\n flag: opts.respectGitignore,\n configured: config?.respectGitignore,\n onNotice: opts.onNotice,\n }),\n });\n // Rule 9: the walk applied only the family ignores and `--exclude`, so it saw\n // just the first half of each collection's statement. Narrow it to actual\n // members, or a collection's `exclude:` would shape its SQL view and not what\n // a bare run reads. Skipped for typed paths: those are the operator's (rule 3).\n const files = fromCollections ? retainMembers(walked, membersFor) : walked;\n assertNonEmpty({\n files,\n inputs: fileInputs,\n usingStdin,\n allowEmpty,\n exclude,\n exts,\n gitignoreSkipped,\n action: \"read\",\n });\n\n const out: GetFileResult[] = [];\n // External metadata (0037), read once per run.\n const externalMetadata = await loadExternalMetadata(collections, {\n configDir: configDir ?? cwd,\n base,\n offline: opts.offline ?? config?.offline ?? false,\n // A `{page}` manifest (0058) is read for exactly the pages this run reads.\n pages: files.map((file) => resolve(base, file)),\n });\n\n // The derived channel (0040): the requested fields a source can state,\n // and one input per parsed file — the document's OWN extraction, since a\n // managed key is never manifest-owned and the git source reads its lines.\n // A field is derivable when a built-in source claims it, or when the\n // config runs a command for it (0042).\n const commands: Readonly<Record<string, DeriveCommand>> = commandsOf(config?.derive) ?? {};\n // Derivation is on unless the user said `--no-derived` (proposal 0043).\n const deriving = opts.derived !== false;\n const derivableFields: DerivableField[] = deriving\n ? opts.fields.filter((f) => isBuiltinField(f) || Object.hasOwn(commands, f))\n : [];\n const deriveInputs: DeriveInput[] = [];\n // The manifests that hold a page's `provenance` record (0046), for evidence rule 2.\n const wantsProvenance = opts.fields.includes(PROVENANCE_FIELD);\n const provenanceManifests = deriving && derivableFields.includes(PROVENANCE_FIELD)\n ? readerManifests(declaredCollections, configDir ?? cwd, base)\n : [];\n // Which requested fields each parsed file **carries**, keyed by label. It\n // is the resolution rule's whole input, and it is collected here because\n // only `readOne` holds the extracted data.\n const carried = new Map<string, Record<string, boolean>>();\n /** Where each parsed file's body starts, for `provenance` (0046). */\n const bodyLines = new Map<string, number>();\n\n // A manifest with no keys (proposal 0068) owns what each page's schemas\n // mark external. `get` validates nothing, so the schemas are loaded only\n // for a page one of those manifests covers.\n const marks = pageMarks({\n validator: marksValidator({\n config,\n cwd,\n ...(configDir !== undefined ? { configDir } : {}),\n ...(opts.offline !== undefined ? { offline: opts.offline } : {}),\n }),\n config,\n cwd,\n trustRoot: schemaTrustRoot(cwd, configDir),\n });\n\n const readOne = async (label: string, content: string, extension: string): Promise<void> => {\n const extractor = forced ?? extractorForExtension(extension);\n if (!extractor) {\n throw new DocmetaError(\n `Unsupported file type \"${extension}\" for \"${label}\". Supported: ${supportedExtensions().join(\", \")}. Use --as to override.`,\n );\n }\n const members = membersFor(label);\n let extracted;\n try {\n const own = extractor.extract(content, label, {\n elements: resolveElements(label, config, members),\n });\n const merged = await mergeWithMarks(label, own, externalMetadata, members, base, {\n encryptionKey: joinKey,\n marks,\n });\n if (deriving && label !== STDIN_LABEL) {\n const place = provenanceManifests.length === 0\n ? undefined\n : readerPlace(label, own.data, provenanceManifests, declaredCollections, configDir ?? cwd, base, merged.marked);\n // Rule 1 of 0069: the manifest that owns a dated field is read at each fact commit.\n const owned =\n declaredCollections.length === 0\n ? {}\n : stampManifests(label, own.data, declaredCollections, configDir ?? cwd, base, merged.marked, STAMPED_DATE_FIELDS);\n deriveInputs.push({\n label,\n absPath: resolve(base, label),\n content,\n extracted: own,\n ...(place !== undefined ? { provenanceManifest: place } : {}),\n ...(Object.keys(owned).length > 0 ? { stampManifests: owned } : {}),\n });\n }\n if (wantsProvenance) {\n bodyLines.set(label, readProvenancePage(content, { fenced: provenanceFenced(own) }).bodyLine);\n }\n extracted = merged.extracted;\n } catch (err) {\n // A `DocmetaError` is already operational and already carries a message\n // written for a person — rethrow it untouched, exactly as `validate`\n // does with the same call.\n if (err instanceof DocmetaError) throw err;\n // Anything else is a document that will not parse, which is a fact about\n // the document and not about the run. It is recorded against the file and\n // the walk continues, the same call `validate` turns into a `(parse)`\n // finding. Promoting it to an operational error put it on the wrong side\n // of the 0/1/2 contract and, worse, made one malformed file hide the\n // values of every other file in the directory.\n //\n // `err` is `unknown` and an extractor is not obliged to throw an `Error`,\n // so the reason is narrowed rather than cast: `(err as Error).message`\n // would record `undefined` and lose the reason entirely.\n const reason = err instanceof Error ? err.message : String(err);\n out.push({ file: label, present: false, values: {}, error: reason });\n return;\n }\n const values: Record<string, unknown> = {};\n const carries: Record<string, boolean> = {};\n for (const f of opts.fields) {\n values[f] = resolveField(extracted.data, f);\n carries[f] = carriesField(extracted.data, f);\n }\n carried.set(label, carries);\n const bodyLine = bodyLines.get(label);\n out.push({\n file: label,\n present: extracted.present,\n values,\n ...(bodyLine !== undefined ? { provenance: { bodyLine } } : {}),\n });\n };\n\n if (usingStdin) {\n if (!forced) {\n throw new DocmetaError(\n STDIN_REQUIRES_AS,\n );\n }\n await readOne(STDIN_LABEL, opts.stdinContent ?? \"\", forced.extensions[0] ?? \"\");\n }\n\n for (const file of files) {\n const content = await readFile(resolve(base, file), \"utf8\");\n await readOne(file, content, extname(file));\n }\n\n if (deriving) {\n await attachResolved(out, deriveInputs, {\n fields: opts.fields,\n derivable: derivableFields,\n carried,\n run: {\n cwd,\n base,\n configDir,\n config,\n cache: opts.cache ?? true,\n now: opts.now ?? (() => new Date()),\n },\n });\n }\n\n return out;\n}\n\n/**\n * One derivation for the run, then three records on every parsed file: the\n * evidence (`derived`), the effective value (`resolved`), and which side\n * answered (`origin`).\n *\n * Nothing is derived when no requested field is derivable, or when every\n * input is stdin — no source is consulted and no process is spawned, and\n * each file still gets its records, because the document is then the only\n * side there is and every field it carries resolves to `asserted`. A\n * consulted source that cannot answer is the run's error, with the way out.\n *\n * The resolution rule is one line, and it is the same one the `resolved` SQL\n * view implements: the document's value when the document **carries the\n * key**, the derived one otherwise. Carrying is `Object.hasOwn` (see\n * `carriesField`), so `owner: null` is an assertion and outranks CODEOWNERS.\n */\nasync function attachResolved(\n out: GetFileResult[],\n inputs: readonly DeriveInput[],\n opts: {\n /** Every requested field, in the order the user named them. */\n fields: readonly string[];\n /** The subset a source can state; only these are derived. */\n derivable: readonly DerivableField[];\n /** Which requested fields each parsed file carries, by label. */\n carried: ReadonlyMap<string, Record<string, boolean>>;\n run: {\n cwd: string;\n base: string;\n configDir: string | undefined;\n config: DocmetaConfig | null;\n cache: boolean;\n now: () => Date;\n };\n },\n): Promise<void> {\n const { run } = opts;\n const derive = run.config?.derive;\n let provenance: ReadonlyMap<string, ProvenanceDerivation> = new Map();\n const commands = commandsOf(derive);\n const records: ReadonlyMap<string, DerivedRecord> =\n opts.derivable.length === 0 || inputs.length === 0\n ? new Map<string, DerivedRecord>()\n : await (async () => {\n const result = await deriveMetadata(inputs, {\n cwd: run.cwd,\n base: run.base,\n ...(run.configDir !== undefined ? { configDir: run.configDir } : {}),\n sources: derive?.sources ?? [...DERIVE_SOURCES],\n fields: opts.derivable,\n ...(derive?.codeowners !== undefined\n ? { codeowners: derive.codeowners }\n : {}),\n ...(commands !== undefined ? { commands } : {}),\n cache: run.cache,\n now: run.now,\n machines: machinesOf(derive),\n });\n assertSourcesAvailable(\n result.sources,\n \"pass --no-derived, or narrow derive.sources\",\n );\n if (result.provenance !== undefined) provenance = result.provenance;\n return result.records;\n })();\n for (const r of out) {\n if (r.error !== undefined) continue;\n const record = records.get(r.file);\n const derived: Record<string, DerivedValue | null> = {};\n for (const field of opts.derivable) {\n derived[field] = record?.fields[field] ?? null;\n }\n const carries = opts.carried.get(r.file) ?? {};\n const resolved: Record<string, unknown> = {};\n const origin: Record<string, \"asserted\" | \"derived\"> = {};\n for (const field of opts.fields) {\n const evidence = derived[field];\n if (carries[field] === true) {\n resolved[field] = r.values[field];\n origin[field] = \"asserted\";\n } else if (evidence != null) {\n resolved[field] = evidence.value;\n origin[field] = \"derived\";\n } else {\n // Neither side has it. Shaped like `values`, which also carries the\n // key with `undefined` rather than dropping it, so a caller iterating\n // the requested fields sees the same key set on both records.\n resolved[field] = undefined;\n }\n }\n // Only when a requested field is derivable. With none there is no\n // evidence to report, and `{}` would read as \"derived, and nothing\n // answered\".\n if (opts.derivable.length > 0) r.derived = derived;\n r.resolved = resolved;\n r.origin = origin;\n // Agreement for `provenance` is the provenance comparator's (0046): a\n // record git has nothing against is current, however its entries compare\n // with the derivation as values.\n const derivation = provenance.get(r.file);\n if (r.provenance !== undefined && derivation !== undefined) {\n const comparisons = compareProvenance(provenanceEntries(r.values[PROVENANCE_FIELD]), derivation);\n r.provenance.current = comparisons.every((c) => c.status === \"current\");\n }\n }\n}\n\n/**\n * Resolve a single field reference against extracted metadata.\n *\n * A reference starting with `/` is a JSON Pointer (RFC 6901) — the same\n * convention the validator and reporters already use for nested error paths,\n * so a pointer copied from a validation error works verbatim. Any other\n * reference is dot-notation (`author.name`, `tags.0`). Pointers also escape\n * keys that contain literal dots or slashes (`/odd.key`, `/a~1b` for `a/b`).\n *\n * Returns `undefined` when any segment is missing or descends into a scalar.\n * A bare top-level key (no `/`, no `.`) resolves to a single segment, so the\n * historical `get title` behavior is unchanged.\n *\n * **A key that literally contains a dot is tried as a fallback**, after descent\n * fails. Element-derived metadata makes those ordinary — `article.title`,\n * `prolog.author`, `ms.date` — and without this, `get article.title` returned\n * an *empty* result rather than an error, which is a silent wrong answer.\n * Descent still wins wherever it resolves, so a document with a genuine\n * `author: { name: … }` object answers `author.name` exactly as it always has;\n * the fallback only fires where the old behavior was to give up.\n */\nfunction resolveField(data: Record<string, unknown>, field: string): unknown {\n const segments = field.startsWith(\"/\")\n ? parseJsonPointer(field)\n : field.split(\".\");\n const descended = descend(data, segments);\n if (descended !== undefined) return descended;\n if (\n !field.startsWith(\"/\") &&\n field.includes(\".\") &&\n Object.prototype.hasOwnProperty.call(data, field)\n ) {\n return data[field];\n }\n return undefined;\n}\n\n/**\n * Does the document **carry** this field? `resolveField`'s twin, deciding\n * presence rather than value, and it follows exactly the same three routes:\n * JSON Pointer, dot-notation descent, then the literal dotted key.\n *\n * The difference is the last step. `resolveField` reports a miss as\n * `undefined`, which a key written `owner:` — present, valued null — cannot\n * be told apart from. So the final segment is an own-property test rather\n * than a read, and an asserted null answers `true`. For a bare top-level\n * field this is `Object.hasOwn(data, field)`, which is the rule the\n * `resolved` SQL view spells `json_type(_data, '$.\"field\"') IS NOT NULL`.\n */\nfunction carriesField(data: Record<string, unknown>, field: string): boolean {\n const segments = field.startsWith(\"/\")\n ? parseJsonPointer(field)\n : field.split(\".\");\n if (carriesPath(data, segments)) return true;\n return (\n !field.startsWith(\"/\") &&\n field.includes(\".\") &&\n Object.prototype.hasOwnProperty.call(data, field)\n );\n}\n\n/** Whether `segments` names an existing member of `data`. */\nfunction carriesPath(data: Record<string, unknown>, segments: string[]): boolean {\n const last = segments.at(-1);\n if (last === undefined) return true;\n const parent =\n segments.length === 1 ? data : descend(data, segments.slice(0, -1));\n if (Array.isArray(parent)) {\n return /^\\d+$/.test(last) && Number(last) < parent.length;\n }\n if (parent !== null && typeof parent === \"object\") {\n return Object.prototype.hasOwnProperty.call(parent, last);\n }\n return false;\n}\n\n/** Walk `segments` into `data`, or `undefined` at the first miss. */\nfunction descend(data: Record<string, unknown>, segments: string[]): unknown {\n let current: unknown = data;\n for (const segment of segments) {\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) return undefined;\n current = current[Number(segment)];\n } else if (current !== null && typeof current === \"object\") {\n // Own-property check only: never resolve inherited members like\n // `toString` or `__proto__` — those are \"missing\", not values.\n if (!Object.prototype.hasOwnProperty.call(current, segment)) {\n return undefined;\n }\n current = (current as Record<string, unknown>)[segment];\n } else {\n return undefined;\n }\n }\n return current;\n}\n\n/** Decode a JSON Pointer into path segments, unescaping `~1`→`/` and `~0`→`~`. */\nfunction parseJsonPointer(pointer: string): string[] {\n return pointer\n .split(\"/\")\n .slice(1)\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n}\n","/**\n * `schemas` command core. Reports built-in schemas and supported input formats,\n * vendors a remote schema into the repository, and infers a coverage report\n * (plus a draft schema) from the metadata a docset already carries.\n */\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { loadExternalMetadata, mergeWithMarks } from \"../core/external-metadata.js\";\nimport { marksValidator, pageMarks } from \"../core/page-marks.js\";\nimport { dirname, extname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { parseDocument, parse as parseYaml, stringify } from \"yaml\";\nimport { resolveElements } from \"../core/resolve-schema.js\";\nimport { memberOf, retainMembers } from \"../core/collections.js\";\nimport { DocmetaError } from \"../types.js\";\nimport {\n fetchSchemaBytes,\n listBuiltins,\n type BuiltinInfo,\n type RegisteredSchemas,\n} from \"../core/schema-registry.js\";\nimport {\n extractorByName,\n extractorForExtension,\n listFormats,\n supportedExtensions,\n} from \"../extractors/index.js\";\nimport { isoDateValue } from \"../extractors/date-value.js\";\nimport { integrityOf } from \"../core/integrity.js\";\nimport { gitIgnored } from \"../core/gitignore.js\";\nimport {\n META_SECTION,\n parseConfig,\n parseConfigValue,\n loadConfig,\n resolveRunConfig,\n schemaTrustRoot,\n type ConfigNotice,\n type SchemaEntry,\n} from \"../core/config.js\";\nimport {\n assertNonEmpty,\n gitignoreOptions,\n resolveTargetSet,\n STDIN_LABEL,\n STDIN_TOKEN,\n} from \"../core/load-files.js\";\nimport { toJsonText } from \"../core/json-text.js\";\nimport { writeFileAtomic } from \"../core/write-file.js\";\nimport { lazyKey } from \"../core/encrypted.js\";\nimport { STDIN_REQUIRES_AS } from \"../../shared/cli-options.js\";\n\n/** One schema `meta.register` loaded: its `$id` and its file. */\nexport interface RegisteredInfo {\n id: string;\n /** Relative to the config file, with forward slashes. */\n file: string;\n}\n\nexport interface SchemasInfo {\n builtins: BuiltinInfo[];\n /** The governing config's registered schemas (proposal 0070). */\n registered: RegisteredInfo[];\n formats: {\n name: string;\n extensions: string[];\n /** Whether `manni meta fill` can write metadata back to this format. */\n writable: boolean;\n }[];\n}\n\nexport function getSchemasInfo(registered?: RegisteredSchemas): SchemasInfo {\n return {\n builtins: listBuiltins(),\n registered: [...(registered?.values() ?? [])].map(({ id, file }) => ({ id, file })),\n formats: listFormats(),\n };\n}\n\n/**\n * Where a vendored schema lands by default.\n *\n * **Not** `.docmeta/`, which is gitignored wholesale and holds the schema and\n * proposal caches. A vendored schema is the opposite kind of artifact: it has\n * to be committed, because being in the consuming repository's own history is\n * the entire point of vendoring.\n */\nexport const DEFAULT_VENDOR_DIR = \"./schema\";\n\n/**\n * The config file `vendor` creates when a repository has none: the family\n * file, with the entries under the metadata tool's own key.\n */\nexport const DEFAULT_CONFIG_NAME = \"manni.config.yaml\";\n\nexport interface VendorOptions {\n /** The `http(s)` URL to download. */\n url: string;\n /** Directory for the vendored copy, relative to `cwd`. Default `./schema`. */\n dir?: string;\n /** `-c/--config`. Absent discovers a config, or creates one in `cwd`. */\n configPath?: string;\n cwd?: string;\n /** Diagnostics for the user; the CLI writes these to stderr. */\n onNotice?: (message: string) => void;\n /** Fetch timeout, in ms. Defaults to the registry's. */\n timeoutMs?: number;\n /** Response size cap, in bytes. Defaults to the registry's. */\n maxBytes?: number;\n}\n\nexport interface VendorResult {\n /** The URL that was downloaded. */\n url: string;\n /** The vendored file, relative to `cwd`, posix-style. */\n file: string;\n /** The pin recorded for it. */\n integrity: string;\n /** Size of the vendored copy, in bytes. */\n bytes: number;\n /** The config that was written, relative to `cwd`, posix-style. */\n config: string;\n /** Whether that config had to be created. */\n configCreated: boolean;\n /** Whether an existing `schemas:` entry was replaced rather than appended. */\n replaced: boolean;\n /** Whether the downloaded bytes were identical to the copy already on disk. */\n unchanged: boolean;\n}\n\n/** A path spelled the way git and a config both want it: relative, posix. */\nexport function posixRelative(from: string, to: string): string {\n return relative(from, to).split(sep).join(\"/\");\n}\n\n/**\n * The filename for a vendored schema, derived from the URL's last path segment.\n *\n * Sanitized rather than trusted: the segment reaches the filesystem, so\n * anything that is not an ordinary filename character is replaced, and a\n * leading dot is prefixed away so the copy cannot land as a hidden file that\n * directory walks skip.\n */\nexport function vendorFileName(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new DocmetaError(`\"${url}\" is not a valid URL.`);\n }\n const segments = parsed.pathname.split(\"/\").filter(Boolean);\n const last = segments[segments.length - 1] ?? \"\";\n // `new URL` carries a malformed escape like `%zz` through untouched — the\n // WHATWG parser does not validate percent-encoding — so the segment reaches\n // here and `decodeURIComponent` throws `URIError`, which is not a\n // `DocmetaError` and escaped as an unhandled stack trace. Decoding is only a\n // nicety: the result is sanitized to `[A-Za-z0-9._-]` regardless, so an\n // undecodable segment is used as written.\n let decoded: string;\n try {\n decoded = decodeURIComponent(last);\n } catch {\n decoded = last;\n }\n let name = decoded.replace(/[^A-Za-z0-9._-]/g, \"-\");\n // No usable segment at all (`https://host/`): fall back to the host, which is\n // at least recognizable in a diff.\n if (name === \"\" || /^\\.+$/.test(name)) {\n name = parsed.hostname.replace(/[^A-Za-z0-9._-]/g, \"-\");\n }\n if (name.startsWith(\".\")) name = `schema${name}`;\n if (!name.toLowerCase().endsWith(\".json\")) name += \".json\";\n return name;\n}\n\n/**\n * Refuse a target `.gitignore` covers.\n *\n * The highest-value guard in this command. A vendored schema that git ignores\n * validates perfectly on the machine that downloaded it and is simply *absent*\n * on CI, where the failure arrives as a missing schema file in a repository\n * nobody changed.\n *\n * Three states, all of them enumerated. Git says the path is ignored — refuse,\n * naming whichever of the directory or the file matched, since the fix differs.\n * Git says it is not — proceed. Git cannot answer at all (no repository here,\n * no `git` on `PATH`) — proceed, but say so: refusing every non-repository\n * would make the command unusable in an extracted tarball, and staying silent\n * would claim a check that never ran.\n */\nexport async function assertNotIgnored(\n absFile: string,\n absDir: string,\n cwd: string,\n onNotice: ((message: string) => void) | undefined,\n text: IgnoreGuardText = VENDOR_IGNORE_TEXT,\n): Promise<void> {\n const relFile = posixRelative(cwd, absFile);\n const relDir = posixRelative(cwd, absDir);\n const candidates = [relFile];\n // \"\" is cwd itself, and a path outside cwd is not something git can be asked\n // about relative to here.\n if (relDir !== \"\" && !relDir.startsWith(\"..\")) candidates.push(relDir);\n\n const answer = await gitIgnored(candidates, cwd);\n if (!answer.available) {\n onNotice?.(text.unchecked(relDir || \".\"));\n return;\n }\n\n const ignoredDir = answer.ignored.has(relDir);\n const ignoredFile = answer.ignored.has(relFile);\n if (!ignoredDir && !ignoredFile) return;\n\n // Name the broadest thing git actually flagged. Both spellings are asked\n // about because a directory-only pattern (`vendor/`) does not match the bare\n // path `vendor` while the directory does not yet exist on disk — git can only\n // answer for the file underneath it. Which of the two matched is therefore a\n // fact about the pattern's shape, not about which rule the user should edit,\n // so the remedy names both routes rather than guessing.\n throw new DocmetaError(text.refusal(ignoredDir ? relDir : relFile));\n}\n\n/**\n * The two messages the guard above needs, so the *mechanic* is shared and the\n * *wording* is not.\n *\n * `vendor` and `infer --out` refuse for the same structural reason — a file git\n * ignores is present locally and absent in CI — but the remedy differs (`--dir`\n * versus `--out`), and a message naming the wrong flag sends the reader to the\n * wrong place. Parameterizing beat writing a second copy of the three-state\n * logic, which is where the subtle half of this check lives.\n */\nexport interface IgnoreGuardText {\n /** Git says the path is ignored. `target` is whichever spelling matched. */\n refusal(target: string): string;\n /** Git could not answer at all. `where` is the directory, or \".\". */\n unchecked(where: string): string;\n}\n\nconst VENDOR_IGNORE_TEXT: IgnoreGuardText = {\n refusal: (target) =>\n `Refusing to vendor into \"${target}\": git reports it as ignored. A vendored schema has to be committed — an ignored copy validates on this machine and is simply missing in CI, where the failure reads as a schema nobody changed. Vendor into a directory your repository tracks (\\`--dir\\`, default \\`${DEFAULT_VENDOR_DIR}\\`), or drop the .gitignore rule covering this path.`,\n unchecked: (where) =>\n `could not check .gitignore for \"${where}\" (no repository here, or no git on PATH). A vendored schema must be committed — make sure this path is tracked.`,\n};\n\nconst DRAFT_IGNORE_TEXT: IgnoreGuardText = {\n refusal: (target) =>\n `Refusing to write the draft schema into \"${target}\": git reports it as ignored. A generated schema you cannot commit validates on this machine and is simply absent in CI, where the failure reads as a schema nobody changed. Pass an --out path your repository tracks, or drop the .gitignore rule covering this one.`,\n unchecked: (where) =>\n `could not check .gitignore for \"${where}\" (no repository here, or no git on PATH). A draft schema has to be committed to be worth anything in CI — make sure this path is tracked.`,\n};\n\n/**\n * Fold the vendored entry into a `schemas:` list.\n *\n * Replaces rather than appends whenever the list already speaks about this\n * schema, in any of the three spellings it can take: the bare URL a\n * pre-vendoring config carried, an earlier vendored entry naming the same\n * `source`, or an entry already pointing at the same `ref`. Appending instead\n * would leave the URL live beside its own local copy, so the run would still\n * depend on the host being up — the exact failure vendoring removes.\n */\nfunction foldEntry(\n entries: SchemaEntry[],\n next: { ref: string; source: string; integrity: string },\n): { entries: SchemaEntry[]; replaced: boolean; displacedSource?: string } {\n const speaksAbout = (entry: SchemaEntry): boolean =>\n typeof entry === \"string\"\n ? entry === next.source || entry === next.ref\n : entry.ref === next.ref || entry.source === next.source;\n\n const index = entries.findIndex(speaksAbout);\n if (index === -1) return { entries: [...entries, next], replaced: false };\n\n // Matched on `ref` while naming a *different* origin. Two hosts serving\n // different schemas whose URLs end in the same segment both default to the\n // same filename, so this replaces one pinned contract with another and the\n // \"already exists and is not ours\" guard reads it as a re-vendor. Doing it is\n // right — the command was asked to — but the caller reports it, because a\n // pinned entry silently changing meaning is not something to find out from a\n // diff later.\n const displacedSource = entries\n .filter(speaksAbout)\n .map((entry) => (typeof entry === \"string\" ? undefined : entry.source))\n .find((source) => source !== undefined && source !== next.source);\n // Every match collapses into the one entry, not just the first. A config\n // carrying both the bare URL and an earlier vendored ref would otherwise keep\n // the one that was not replaced — leaving the list disagreeing with itself\n // about whether the schema is pinned.\n return {\n entries: entries.flatMap((entry, i) =>\n i === index ? [next] : speaksAbout(entry) ? [] : [entry],\n ),\n replaced: true,\n ...(displacedSource !== undefined ? { displacedSource } : {}),\n };\n}\n\n/**\n * Serialize the updated config, preserving everything else in the file.\n *\n * `parseDocument` keeps comments and key order, so a config someone documented\n * comes back documented — including one that is nothing *but* comments, which\n * is why an empty file is not special-cased here. Only `schemas:` is rewritten;\n * comments written *inside* the old `schemas:` list are the one thing that does\n * not survive, because the list itself is replaced.\n *\n * `section` is where the config sits in the file: under `meta:` in the family\n * file, at the top level of a pre-family one. A new file is always the family\n * shape.\n */\nfunction renderConfig(\n existing: string | null,\n entries: SchemaEntry[],\n section: string | undefined,\n): string {\n // No file at all is the one case with nothing to preserve.\n if (existing === null) {\n return stringify({ [META_SECTION]: { schemas: entries } });\n }\n const doc = parseDocument(existing);\n doc.setIn(section === undefined ? [\"schemas\"] : [section, \"schemas\"], entries);\n return doc.toString();\n}\n\n/**\n * Read back what `renderConfig` produced, the way `loadConfig` would. A\n * config the tool itself cannot read is worse than a failed vendor, and this\n * is the last moment it can be caught before it reaches disk.\n */\nfunction reparseConfig(text: string, source: string, section: string | undefined): void {\n if (section === undefined) {\n parseConfig(text, source);\n return;\n }\n const doc = parseYaml(text) as Record<string, unknown>;\n parseConfigValue(doc[section], source, section);\n}\n\n/**\n * Download a remote schema into the repository and pin it.\n *\n * The order of operations is the contract: everything that can refuse does so\n * *before* the network call or the write, so a refused run leaves the working\n * tree exactly as it found it.\n */\nexport async function runVendorSchema(\n opts: VendorOptions,\n): Promise<VendorResult> {\n const cwd = opts.cwd ?? process.cwd();\n const url = opts.url;\n\n if (!/^https?:\\/\\//i.test(url)) {\n throw new DocmetaError(\n `\\`manni meta schemas vendor\\` takes an http(s) URL to download; \"${url}\" is ${/^[a-z0-9][a-z0-9._-]*:/i.test(url) && !url.includes(\"/\") ? \"a built-in id, which is already bundled\" : \"a local reference, which is already in your repository\"}.`,\n );\n }\n\n // Load first, so a malformed or missing config fails before anything is\n // downloaded or written.\n const loaded = await loadConfig(opts.configPath, cwd);\n const configPath = loaded?.path ?? resolve(cwd, DEFAULT_CONFIG_NAME);\n const configDir = loaded?.dir ?? cwd;\n\n const absDir = resolve(cwd, opts.dir ?? DEFAULT_VENDOR_DIR);\n const absFile = join(absDir, vendorFileName(url));\n\n await assertNotIgnored(absFile, absDir, cwd, opts.onNotice);\n\n // The ref is written into the config, so it is relative to the **config**,\n // not to wherever the command was run from — that is what makes it resolve\n // the same way from a subdirectory, from the repo root, and in CI.\n const fromConfig = posixRelative(configDir, absFile);\n const ref =\n isAbsolute(fromConfig) || fromConfig === \"\"\n ? absFile\n : fromConfig.startsWith(\".\")\n ? fromConfig\n : `./${fromConfig}`;\n\n const { bytes } = await fetchSchemaBytes(url, {\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n ...(opts.maxBytes !== undefined ? { maxBytes: opts.maxBytes } : {}),\n });\n const integrity = integrityOf(bytes);\n\n const entries = loaded?.config.schemas ?? [];\n const folded = foldEntry(entries, { ref, source: url, integrity });\n if (folded.displacedSource !== undefined) {\n opts.onNotice?.(\n `\"${ref}\" was vendored from ${folded.displacedSource}; replacing it with ${url}.`,\n );\n }\n\n // Whether this path is already ours. Three states: nothing there, our own\n // earlier copy (a re-vendor, which is the update path), or a file that\n // belongs to something else — which must not be silently overwritten just\n // because two schemas share a last URL segment.\n let unchanged = false;\n if (existsSync(absFile)) {\n const current = await readFile(absFile);\n unchanged = bytes.equals(current);\n if (!unchanged && !folded.replaced) {\n throw new DocmetaError(\n `\"${posixRelative(cwd, absFile)}\" already exists and is not the copy this config points at, so vendoring ${url} here would overwrite it. Vendor into a different directory with --dir, or remove that file first.`,\n );\n }\n }\n\n await mkdir(absDir, { recursive: true });\n await writeFileAtomic(absFile, bytes);\n\n const existing = loaded ? await readFile(configPath, \"utf8\") : null;\n // A new file is the family shape, so its section is `meta:` too.\n const section = loaded ? loaded.section : META_SECTION;\n const text = renderConfig(existing, folded.entries, section);\n // Parse what is about to be written rather than trusting the serializer.\n reparseConfig(text, posixRelative(cwd, configPath) || DEFAULT_CONFIG_NAME, section);\n await writeFileAtomic(configPath, text);\n\n return {\n url,\n file: posixRelative(cwd, absFile),\n integrity,\n bytes: bytes.byteLength,\n config: posixRelative(cwd, configPath),\n configCreated: loaded === null,\n replaced: folded.replaced,\n unchanged,\n };\n}\n\n// ---------------------------------------------------------------------------\n// `manni meta schemas infer` (0010)\n//\n// Purely statistical and **offline**: no provider, no network, no schema\n// resolution. It counts the metadata keys a docset already carries, so the\n// question \"should I require this field?\" has an answer before anyone edits a\n// schema. The coverage report is the product; the draft schema is a by-product.\n//\n// Deliberate limits, stated here rather than discovered later:\n//\n// - **Top-level keys only.** Coverage of `author` is the standard-level\n// question; `author.name` is a schema-authoring detail, and reporting both\n// would bury the first under the second on any docset with nested metadata.\n// - **`-` (stdin) is accepted** for input-model parity, and yields a one-file\n// report. Not useful, not wrong: excluding it would be the exceptional case\n// needing an argument, and every other path-taking command takes it.\n// - **`--min-coverage` defaults to 0.** A default that hid the long tail would\n// hide exactly the \"3% is one team's convention, not a standard\" signal the\n// report exists to surface.\n// ---------------------------------------------------------------------------\n\n/** Draft schemas are written against the same dialect the built-ins use. */\nconst DRAFT_DIALECT = \"https://json-schema.org/draft/2020-12/schema\";\n\n/**\n * Enum thresholds — **both** must hold (0010 stress test 4).\n *\n * The absolute cap alone would turn a 10-file repo with 7 hand-written `type`\n * values into a 7-value vocabulary; the ratio alone would turn a 30-file repo\n * of unique titles into a 30-value enum for prose.\n *\n * The ratio is measured against the files that **carry the key**, not against\n * every file scanned. Against the corpus, a key present in 5 files of 1,000\n * with 5 distinct values — every single occurrence unique, which is what free\n * text looks like — passes both thresholds and gets an enum of exactly those\n * five. The sixth value anyone writes is then rejected by a schema generated\n * from their own docset, which is the opposite of a draft that \"constrains only\n * what it observed\". Against occurrences the same key needs 5 <= 0.25 and is\n * correctly refused: whether a vocabulary exists is a question about this key's\n * own values, and corpus size has no bearing on it.\n */\nconst ENUM_MAX_DISTINCT = 20;\nconst ENUM_MAX_DISTINCT_RATIO = 0.05;\n\n/**\n * How many distinct values are tracked per key before counting stops.\n *\n * Only the report's `distinct` column is affected, and it says so via\n * `distinctCapped`. The enum decision is unaffected: a key past this cap is\n * orders of magnitude past `ENUM_MAX_DISTINCT` already.\n */\nconst DISTINCT_CAP = 1000;\n\n/** Outlier locations kept per non-dominant type, so one bad key cannot blow up memory. */\nconst OUTLIER_SAMPLE_CAP = 20;\n\nexport interface InferOptions {\n /** Positional inputs: files, directories, globs, and `-` for stdin. */\n inputs: string[];\n as?: string;\n exclude?: string[];\n exts?: string[];\n configPath?: string;\n /** `--no-config`: skip config discovery and use the built-in defaults. */\n noConfig?: boolean;\n /**\n * `--collection <name>`, repeatable: run over the named configured\n * collections instead of every declared one (proposal 0041). Cannot be\n * combined with positional paths; `-` is allowed beside it.\n */\n collections?: string[];\n cwd?: string;\n /** Content for the `-` (stdin) input, injected by the CLI/tests. */\n stdinContent?: string;\n /** `--out`: write the draft schema here, relative to `cwd`. */\n out?: string;\n /** `--min-coverage`: hide keys below this percentage. 0–100, default 0. */\n minCoverage?: number;\n /** Permit an input set that resolves to zero files (see `assertNonEmpty`). */\n allowEmpty?: boolean;\n /**\n * `--no-gitignore` (false). Absent leaves config `respectGitignore:` in\n * charge, which itself defaults to on.\n */\n respectGitignore?: boolean;\n /**\n * `--offline`, accepted for surface parity with the other input-taking\n * commands.\n *\n * It has **no effect here**, and — as on `get` — that is a property of the\n * command rather than an omission: `infer` counts keys that are already\n * structured, resolves no schema and loads no provider, so there is no fetch\n * for it to suppress. 0010 stress test 2 asserts that unconditionally.\n * Accepting the flag keeps one flag set across the commands, so a script can\n * pass `--offline` uniformly without knowing which subcommand needs it.\n */\n offline?: boolean;\n /** Diagnostics for the user; the CLI writes these to stderr. */\n onNotice?: (message: string) => void;\n /** Called once when a config governs the run, so the CLI can report it. */\n onConfigLoaded?: (info: ConfigNotice) => void;\n}\n\n/** One observed type and how many files carried the key at that type. */\nexport interface InferTypeCount {\n type: string;\n count: number;\n}\n\n/** A file whose value for a key is not the dominant type. */\nexport interface InferOutlier {\n file: string;\n /** 1-based source line, when the extractor knows one. */\n line?: number;\n type: string;\n}\n\nexport interface InferKeyReport {\n key: string;\n /** Files carrying this key. */\n present: number;\n /** `present` as a percentage of every file scanned, 0–100. */\n coverage: number;\n /** Observed types with counts, most common first. */\n types: InferTypeCount[];\n /** The type the draft encodes. Never a union — see stress test 3. */\n dominantType: string;\n /** Files at some other type, with locations. Capped; see `outlierCount`. */\n outliers: InferOutlier[];\n /** Every non-dominant occurrence, including any beyond `outliers`. */\n outlierCount: number;\n /** Distinct values seen, across all types. */\n distinct: number;\n /** Whether `distinct` stopped counting at `DISTINCT_CAP`. */\n distinctCapped: boolean;\n /** The candidate vocabulary, when both enum thresholds hold. */\n enumValues?: unknown[];\n /** The most common value, for the report's sample column. */\n sample?: unknown;\n /** `date`, `date-time`, or `uri` when every observed string matched one. */\n format?: string;\n}\n\nexport interface InferResult {\n /** Every file read, including those with no metadata block. */\n filesScanned: number;\n /**\n * Files with no metadata block at all. Reported on its own line rather than\n * folded into a denominator: these pass a require-nothing schema and fail the\n * moment any key becomes required, which is the surprise worth naming.\n */\n filesWithoutMetadata: number;\n /** Files whose metadata block could not be parsed, with the reason. */\n unreadable: { file: string; message: string }[];\n /** Keys at or above `--min-coverage`, most-covered first. */\n keys: InferKeyReport[];\n /** Keys `--min-coverage` removed from `keys`. */\n hiddenByMinCoverage: number;\n /** The draft schema. Always produced; `--out` decides whether it is written. */\n draft: Record<string, unknown>;\n /** Where the draft was written, posix-relative to `cwd`. Absent without `--out`. */\n out?: string;\n /** Candidate documents `.gitignore` removed from the walk. */\n gitignoreSkipped: number;\n}\n\n/** Everything accumulated for one top-level key while scanning. */\ninterface KeyStats {\n present: number;\n /** type -> files seen at that type. */\n types: Map<string, number>;\n /** type -> where they were, capped at OUTLIER_SAMPLE_CAP each. */\n locations: Map<string, InferOutlier[]>;\n /** JSON of the value -> the value, its count, and its type. */\n values: Map<string, { value: unknown; count: number; type: string }>;\n distinctCapped: boolean;\n /** Whether an empty string was ever the value. Gates `minLength: 1`. */\n sawEmptyString: boolean;\n}\n\n/**\n * The JSON Schema type name for a runtime value.\n *\n * Integers are **not** split out from `number`. JSON Schema's `number` already\n * accepts them, and separating the two would report a key written `2` in some\n * files and `2.5` in others as having outliers it does not have.\n *\n * A `Date` reaches here only from TOML frontmatter, whose parser materializes\n * timestamps. It is reported as `string`, because that is how every other\n * frontmatter flavor carries a date and the draft describes the metadata\n * standard rather than one parser's object graph.\n */\nfunction jsonTypeOf(value: unknown): string {\n if (value === null) return \"null\";\n if (Array.isArray(value)) return \"array\";\n if (value instanceof Date) return \"string\";\n switch (typeof value) {\n case \"string\":\n return \"string\";\n case \"number\":\n case \"bigint\":\n return \"number\";\n case \"boolean\":\n return \"boolean\";\n default:\n return \"object\";\n }\n}\n\nconst FORMAT_TESTS: [string, RegExp][] = [\n [\"date\", /^\\d{4}-\\d{2}-\\d{2}$/],\n [\"date-time\", /^\\d{4}-\\d{2}-\\d{2}[Tt ]\\d{2}:\\d{2}/],\n [\"uri\", /^[a-z][a-z0-9+.-]*:\\/\\//i],\n];\n\n/**\n * A format annotation for the report's types column — `string (date)`.\n *\n * Report only. It is **not** written into the draft: whether `2026-04-01` is\n * *required* to be a date, or merely what everyone happened to write, is a\n * policy call, and the draft's rule is to encode only the shape it observed\n * (stress test 1). Skipped entirely once distinct counting was capped, since a\n * claim about \"every value\" cannot be made from a truncated sample.\n */\nfunction formatOf(stats: KeyStats, dominantType: string): string | undefined {\n if (dominantType !== \"string\" || stats.distinctCapped) return undefined;\n const strings = [...stats.values.values()]\n .filter((v) => v.type === \"string\")\n .map((v) => String(v.value));\n if (strings.length === 0) return undefined;\n for (const [name, re] of FORMAT_TESTS) {\n if (strings.every((s) => re.test(s))) return name;\n }\n return undefined;\n}\n\nfunction emptyStats(): KeyStats {\n return {\n present: 0,\n types: new Map(),\n locations: new Map(),\n values: new Map(),\n distinctCapped: false,\n sawEmptyString: false,\n };\n}\n\nfunction recordValue(\n stats: KeyStats,\n label: string,\n value: unknown,\n line: number | undefined,\n): void {\n const type = jsonTypeOf(value);\n stats.present += 1;\n stats.types.set(type, (stats.types.get(type) ?? 0) + 1);\n\n const where = stats.locations.get(type) ?? [];\n if (where.length < OUTLIER_SAMPLE_CAP) {\n where.push({ file: label, type, ...(line !== undefined ? { line } : {}) });\n }\n stats.locations.set(type, where);\n\n const normalized = isoDateValue(value);\n if (normalized === \"\") stats.sawEmptyString = true;\n\n // Objects and arrays are keyed by their JSON too, so a repeated `tags: []`\n // counts once. They are never enum candidates, so the only cost is an\n // accurate `distinct` column.\n // `toJsonText`, not `JSON.stringify`, so the `?? \"undefined\"` stays visibly\n // reachable: a hand-written value can stringify to nothing. See there.\n const key = toJsonText(normalized) ?? \"undefined\";\n const seen = stats.values.get(key);\n if (seen) {\n seen.count += 1;\n } else if (stats.values.size < DISTINCT_CAP) {\n stats.values.set(key, { value: normalized, count: 1, type });\n } else {\n stats.distinctCapped = true;\n }\n}\n\n/** The type most files used, ties broken by name so output is deterministic. */\nfunction dominantTypeOf(stats: KeyStats): string {\n return [...stats.types.entries()].sort(\n (a, b) => b[1] - a[1] || a[0].localeCompare(b[0]),\n )[0]?.[0] ?? \"string\";\n}\n\n/**\n * Propose a vocabulary, or don't.\n *\n * Candidates are the values at the **dominant** type only. Including an\n * outlier's value would write the typo into the contract — the same failure\n * `dominantTypeOf` exists to avoid, one level down.\n */\nfunction enumFor(\n stats: KeyStats,\n dominantType: string,\n): unknown[] | undefined {\n // A vocabulary is a set of scalars. An enum of objects or arrays compares by\n // deep equality and is never what someone adopting a standard meant.\n if (![\"string\", \"number\", \"boolean\"].includes(dominantType)) return undefined;\n if (stats.distinctCapped) return undefined;\n\n const candidates = [...stats.values.values()].filter(\n (v) => v.type === dominantType,\n );\n if (candidates.length === 0) return undefined;\n if (candidates.length > ENUM_MAX_DISTINCT) return undefined;\n // Against occurrences of this key, not against the corpus — see the constant.\n if (candidates.length > stats.present * ENUM_MAX_DISTINCT_RATIO) {\n return undefined;\n }\n\n return candidates\n .sort(\n (a, b) =>\n b.count - a.count ||\n JSON.stringify(a.value).localeCompare(JSON.stringify(b.value)),\n )\n .map((v) => v.value);\n}\n\n/** `sawEmptyString` is a scan detail, not part of the public report. */\ntype ReportWithEmptyFlag = InferKeyReport & { sawEmptyString: boolean };\n\n/** One key's `properties` entry: the dominant type, and nothing about policy. */\nfunction draftPropertyFor(report: ReportWithEmptyFlag): Record<string, unknown> {\n const property: Record<string, unknown> = { type: report.dominantType };\n if (report.enumValues) {\n property.enum = report.enumValues;\n } else if (report.dominantType === \"string\" && !report.sawEmptyString) {\n // Observed, not assumed: nobody in this docset wrote an empty string, so\n // requiring a non-empty one when the key *is* present rejects the\n // fat-fingered `title:` without demanding anybody supply a title.\n property.minLength = 1;\n }\n return property;\n}\n\nexport async function runInferSchema(\n opts: InferOptions,\n): Promise<InferResult> {\n const cwd = opts.cwd ?? process.cwd();\n\n const minCoverage = opts.minCoverage ?? 0;\n if (!Number.isFinite(minCoverage) || minCoverage < 0 || minCoverage > 100) {\n throw new DocmetaError(\n `--min-coverage must be a percentage between 0 and 100, got ${minCoverage}.`,\n );\n }\n\n const { config, inputs, base, configDir, collections, fromCollections, configFile } =\n await resolveRunConfig({\n cwd,\n configPath: opts.configPath,\n noConfig: opts.noConfig,\n inputs: opts.inputs,\n ...(opts.collections !== undefined\n ? { collections: opts.collections }\n : {}),\n onConfigLoaded: opts.onConfigLoaded,\n });\n // An encrypted join field is decrypted before matching (proposal 0045).\n const joinKey = lazyKey(configFile, undefined);\n const usingStdin = inputs.includes(STDIN_TOKEN);\n\n if (inputs.length === 0) {\n throw new DocmetaError(\n \"No files to scan. Pass paths/globs, or declare a collection under `collections:` in manni.config.yaml.\",\n );\n }\n\n const forced = opts.as ? extractorByName(opts.as) : undefined;\n if (opts.as && !forced) {\n throw new DocmetaError(\n `Unknown format \"${opts.as}\". Supported extensions: ${supportedExtensions().join(\", \")}.`,\n );\n }\n if (usingStdin && !forced) {\n throw new DocmetaError(\n STDIN_REQUIRES_AS,\n );\n }\n\n // Every refusal happens **before** the scan, so a refused run leaves the\n // working tree exactly as it found it — the ordering `vendor` established.\n let absOut: string | undefined;\n if (opts.out !== undefined) {\n absOut = resolve(cwd, opts.out);\n await assertNotIgnored(\n absOut,\n dirname(absOut),\n cwd,\n opts.onNotice,\n DRAFT_IGNORE_TEXT,\n );\n if (existsSync(absOut)) {\n throw new DocmetaError(\n `\"${posixRelative(cwd, absOut) || opts.out}\" already exists, and \\`schemas infer\\` will not overwrite it. The draft is a starting point you then edit, so clobbering it would throw away the edits. Pass a different --out path, or remove that file first.`,\n );\n }\n }\n\n const exts = opts.exts ?? (forced ? forced.extensions : undefined);\n const fileInputs = inputs.filter((i) => i !== STDIN_TOKEN);\n const allowEmpty = opts.allowEmpty ?? config?.allowEmpty;\n // Only `--exclude`: a collection's `exclude:` governs membership, not the\n // walk of a path someone typed (0041 rule 3).\n const exclude = opts.exclude ?? [];\n /** The collections one label belongs to, computed once per file. */\n const membersFor = (label: string): string[] =>\n memberOf(collections, configDir ?? cwd, base, label);\n const { files: walked, gitignoreSkipped } = await resolveTargetSet({\n inputs: fileInputs,\n exts,\n exclude,\n cwd: base,\n allowEmpty,\n ...gitignoreOptions({\n flag: opts.respectGitignore,\n configured: config?.respectGitignore,\n onNotice: opts.onNotice,\n }),\n });\n // Rule 9: the walk applied only the family ignores and `--exclude`, so it saw\n // just the first half of each collection's statement. Narrow it to actual\n // members, or a collection's `exclude:` would shape its SQL view and not what\n // a bare run reads. Skipped for typed paths: those are the operator's (rule 3).\n const files = fromCollections ? retainMembers(walked, membersFor) : walked;\n assertNonEmpty({\n files,\n inputs: fileInputs,\n usingStdin,\n allowEmpty,\n exclude,\n exts,\n gitignoreSkipped,\n action: \"scanned\",\n });\n\n // External metadata (0037): an inferred schema describes the merged corpus.\n // Read once the pages are known, because a `{page}` manifest (0058) is read\n // for exactly the pages this run scans.\n const externalMetadata = await loadExternalMetadata(collections, {\n configDir: configDir ?? cwd,\n base,\n offline: opts.offline ?? config?.offline ?? false,\n pages: files.map((file) => resolve(base, file)),\n });\n\n const stats = new Map<string, KeyStats>();\n const unreadable: { file: string; message: string }[] = [];\n let filesScanned = 0;\n let filesWithoutMetadata = 0;\n\n // What each page's schemas mark external, which a manifest with no keys\n // owns (proposal 0068). Loaded only for a page one of those covers.\n const marks = pageMarks({\n validator: marksValidator({\n config,\n cwd,\n ...(configDir !== undefined ? { configDir } : {}),\n ...(opts.offline !== undefined ? { offline: opts.offline } : {}),\n }),\n config,\n cwd,\n trustRoot: schemaTrustRoot(cwd, configDir),\n });\n\n const scanOne = async (label: string, content: string, extension: string): Promise<void> => {\n const extractor = forced ?? extractorForExtension(extension);\n if (!extractor) {\n throw new DocmetaError(\n `Unsupported file type \"${extension}\" for \"${label}\". Supported: ${supportedExtensions().join(\", \")}. Use --as to override.`,\n );\n }\n filesScanned += 1;\n const members = membersFor(label);\n let extracted;\n try {\n extracted = (\n await mergeWithMarks(\n label,\n extractor.extract(content, label, {\n elements: resolveElements(label, config, members),\n }),\n externalMetadata,\n members,\n base,\n { encryptionKey: joinKey, marks },\n )\n ).extracted;\n } catch (err) {\n // One malformed block must not end the scan: the coverage question is\n // about the rest of the docset, and the bad file is itself a finding.\n unreadable.push({\n file: label,\n message: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n if (!extracted.present) {\n filesWithoutMetadata += 1;\n return;\n }\n // Top-level keys only — see the note at the head of this section.\n for (const [key, value] of Object.entries(extracted.data)) {\n const stat = stats.get(key) ?? emptyStats();\n recordValue(stat, label, value, extracted.lineFor(key));\n stats.set(key, stat);\n }\n };\n\n if (usingStdin && forced) {\n await scanOne(STDIN_LABEL, opts.stdinContent ?? \"\", forced.extensions[0] ?? \"\");\n }\n for (const file of files) {\n const content = await readFile(resolve(base, file), \"utf8\");\n await scanOne(file, content, extname(file));\n }\n\n for (const u of unreadable) {\n opts.onNotice?.(`could not read metadata from \"${u.file}\": ${u.message}`);\n }\n\n const all: ReportWithEmptyFlag[] = [...stats.entries()].map(([key, stat]) => {\n const dominantType = dominantTypeOf(stat);\n const enumValues = enumFor(stat, dominantType);\n const format = formatOf(stat, dominantType);\n const outliers = [...stat.locations.entries()]\n .filter(([type]) => type !== dominantType)\n .flatMap(([, where]) => where);\n const outlierCount = [...stat.types.entries()]\n .filter(([type]) => type !== dominantType)\n .reduce((sum, [, count]) => sum + count, 0);\n // From the dominant type only. Ranked across every type, a clustered\n // *outlier* outranks unique dominant values: 50 distinct string titles and\n // three files writing `title: 42` put `42` in the sample column, because it\n // is the one value with a count above 1. The row then reported\n // `string ×50, number ×3` and offered a number as the representative value,\n // three lines above naming those same files as the outliers.\n const sample = [...stat.values.values()]\n .filter((v) => v.type === dominantType)\n .sort((a, b) => b.count - a.count)[0]?.value;\n return {\n key,\n present: stat.present,\n coverage: filesScanned === 0 ? 0 : (stat.present / filesScanned) * 100,\n types: [...stat.types.entries()]\n .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))\n .map(([type, count]) => ({ type, count })),\n dominantType,\n outliers,\n outlierCount,\n distinct: stat.values.size,\n distinctCapped: stat.distinctCapped,\n ...(enumValues ? { enumValues } : {}),\n ...(sample !== undefined ? { sample } : {}),\n ...(format !== undefined ? { format } : {}),\n sawEmptyString: stat.sawEmptyString,\n };\n });\n\n const kept = all\n .filter((k) => k.coverage >= minCoverage)\n .sort((a, b) => b.coverage - a.coverage || a.key.localeCompare(b.key));\n\n // Alphabetical in the draft, not coverage order: this file is committed and\n // hand-edited, and a stable key order keeps its diffs readable.\n const properties: Record<string, unknown> = {};\n for (const report of [...kept].sort((a, b) => a.key.localeCompare(b.key))) {\n properties[report.key] = draftPropertyFor(report);\n }\n\n const draft: Record<string, unknown> = {\n $schema: DRAFT_DIALECT,\n $comment:\n \"Generated by `manni meta schemas infer`. Nothing is required, deliberately: what your docset happens to contain is not the same as what your standard should demand. Promote keys into a `required` list yourself, one at a time, behind a baseline.\",\n type: \"object\",\n properties,\n };\n\n // Public reports carry no scan bookkeeping.\n const keys: InferKeyReport[] = kept.map(({ sawEmptyString: _drop, ...rest }) => rest);\n\n if (absOut !== undefined) {\n await mkdir(dirname(absOut), { recursive: true });\n await writeFileAtomic(absOut, `${JSON.stringify(draft, null, 2)}\\n`);\n }\n\n return {\n filesScanned,\n filesWithoutMetadata,\n unreadable,\n keys,\n hiddenByMinCoverage: all.length - kept.length,\n draft,\n ...(absOut !== undefined ? { out: posixRelative(cwd, absOut) } : {}),\n gitignoreSkipped,\n };\n}\n","/**\n * `query` command core. Runs one SQL statement over an in-memory SQLite\n * database built per run from the metadata extracted from every input file.\n * Input handling (positional paths, globs, directories, `-` for stdin, and\n * config `paths:` fallback) mirrors `get` so the two commands behave\n * identically. Proposal 0021 is the design record.\n */\nimport { isMissing } from \"../../shared/manifest-cas.js\";\nimport { randomBytes } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, open, readFile, rename, rm } from \"node:fs/promises\";\nimport type { CollectionConfig } from \"../../shared/collections.js\";\nimport {\n PATH_JOIN,\n externalMetadataJoin,\n loadExternalMetadata,\n mergeExternalMetadata,\n mergeWithMarks,\n type PageMarks,\n type ExternalMetadataIndex,\n} from \"../core/external-metadata.js\";\nimport { pageMarks } from \"../core/page-marks.js\";\nimport { dirname, isAbsolute, resolve, extname, sep } from \"node:path\";\nimport {\n FILE_SCHEMA_KEY,\n overrideGlobs,\n collectSchemaPins,\n isDefaultSetOnly,\n resolveElements,\n resolveSchemaSetWithSource,\n} from \"../core/resolve-schema.js\";\nimport { detectJsonIndent, stripBom, toJsonText } from \"../core/json-text.js\";\nimport { integrityOf } from \"../core/integrity.js\";\nimport {\n assertNotIgnored,\n posixRelative,\n type IgnoreGuardText,\n} from \"./schemas.js\";\nimport { writeFileAtomic } from \"../core/write-file.js\";\nimport { stripFrontmatter } from \"../extractors/frontmatter-write.js\";\nimport { deepEqual } from \"../extractors/patch-util.js\";\nimport {\n DocmetaError,\n type ExtractedMetadata,\n type MetadataExtractor,\n type MetadataPatch,\n} from \"../types.js\";\nimport {\n extractorByName,\n extractorForExtension,\n supportedExtensions,\n} from \"../extractors/index.js\";\nimport {\n assertNonEmpty,\n gitignoreOptions,\n resolveTargetSet,\n STDIN_TOKEN,\n STDIN_LABEL,\n} from \"../core/load-files.js\";\nimport {\n resolveRunConfig,\n schemaTrustRoot,\n type ConfigNotice,\n type DocmetaConfig,\n type SchemaTrustRoot,\n} from \"../core/config.js\";\nimport {\n RESERVED,\n SYSTEM_COLUMNS,\n assertSingleStatement,\n bindValue,\n collectNamedParameters,\n corpusDataColumns,\n createDocsTable,\n loadSqlite,\n registerLineFor,\n skipComment,\n skipStringOrIdent,\n startsComment,\n startsStringOrIdent,\n stripLeadingTrivia,\n type SqlValue,\n} from \"../core/projection.js\";\nimport {\n collectCollections,\n collectionNames,\n memberOf,\n retainMembers,\n createCollectionViews,\n} from \"../core/collections.js\";\nimport { commandsOf } from \"../core/derive/config.js\";\nimport {\n createDerivedView,\n createResolvedView,\n DERIVED_ROWS,\n DERIVED_VIEW,\n derivedColumns,\n deriveForTable,\n fieldsForSql,\n mentionsDerived,\n mentionsResolved,\n RESOLVED_VIEW,\n} from \"../core/derive/table.js\";\nimport { readerManifests, readerPlace, stampManifests } from \"../core/derive/provenance-place.js\";\nimport {\n derivableFields,\n deriveCovers,\n managedFields,\n PROVENANCE_FIELD,\n STAMPED_DATE_FIELDS,\n type DeriveInput,\n} from \"../core/derive/types.js\";\nimport type { FingerprintContext } from \"../core/baseline.js\";\nimport {\n Validator,\n stringFormatNames,\n validatesFormat,\n} from \"../core/validator.js\";\nimport {\n classifyRef,\n isPublishedBuiltinUrl,\n loadSchema,\n publishedBuiltins,\n schemaLoadOptions,\n type SchemaPin,\n} from \"../core/schema-registry.js\";\nimport {\n ENCRYPTED_PLACEHOLDER,\n EncryptionRefusal,\n META_CONTEXT,\n lazyKey,\n pointerOf,\n type KeyGetter,\n} from \"../core/encrypted.js\";\nimport {\n decryptValue,\n encryptValue,\n isEncryptedValue,\n} from \"../../shared/encryption.js\";\nimport { ensureEncryptionKey, type Confirm } from \"../../shared/prompt.js\";\nimport { parseDocument, isMap, isSeq, isScalar } from \"yaml\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport { warn } from \"../../shared/warn.js\";\nimport {\n removeManifestKey,\n renameManifestEntry,\n spliceManifestValue,\n} from \"../core/external-metadata-write.js\";\nimport {\n applyRelocation,\n keyHome,\n offerPrompt,\n planRelocation,\n relocationContext,\n type KeyHome,\n type ProposedHome,\n type RelocateResult,\n type RelocationContext,\n} from \"../core/relocation.js\";\nimport { externalWriteWarning } from \"../core/location-writes.js\";\nimport { STDIN_REQUIRES_AS } from \"../../shared/cli-options.js\";\n\nexport interface QueryOptions {\n /**\n * One SQL statement. The table is `docs`; see the system columns below.\n * May be empty when `db` is set — export without querying.\n */\n sql: string;\n /**\n * `--db`: also write the built database to this file, for any SQLite\n * front-end (sqlite3, Datasette, duckdb) to open afterwards. The file is a\n * regenerated artifact: an existing SQLite file at the path is overwritten,\n * anything else is refused.\n */\n db?: string;\n inputs: string[];\n as?: string;\n exclude?: string[];\n exts?: string[];\n configPath?: string;\n /** `--no-config`: skip config discovery and use the built-in defaults. */\n noConfig?: boolean;\n /**\n * `--collection <name>`, repeatable: run over the named configured\n * collections instead of every declared one (proposal 0041). Cannot be\n * combined with positional paths; `-` is allowed beside it.\n */\n collections?: string[];\n cwd?: string;\n /** Content for the `-` (stdin) input, injected by the CLI/tests. */\n stdinContent?: string;\n /** Permit an input set that resolves to zero files (see `assertNonEmpty`). */\n allowEmpty?: boolean;\n /**\n * `--no-gitignore` (false). Absent leaves config `respectGitignore:` in\n * charge, which itself defaults to on.\n */\n respectGitignore?: boolean;\n /** Diagnostics for the user; the CLI writes these to stderr. */\n onNotice?: (message: string) => void;\n /** Called once when a config governs the run, so the CLI can report it. */\n onConfigLoaded?: (info: ConfigNotice) => void;\n /**\n * `--offline`, accepted for surface parity with the other commands. DDL\n * statements do resolve the corpus's schema set (0024), but only from disk\n * and the bundled built-ins — a URL ref refuses with \"vendor it first\"\n * before anything could fetch — so there is still no network dependency to\n * suppress.\n */\n offline?: boolean;\n /**\n * `--no-cache` (false): ask GitHub or GitLab again rather than reading the\n * review cache. Only a statement naming the `derived` table consults it,\n * and only for `reviewed-by` and `last-reviewed`; absent leaves it on.\n */\n cache?: boolean;\n /**\n * `--dry-run`: preview the statement's per-file changes — the diff it\n * would make, files untouched. Without it a mutating statement applies,\n * matching `fill`'s convention (proposal 0025; 0022 recorded the original\n * preview-by-default surface this revises).\n */\n dryRun?: boolean;\n /**\n * Values for the statement's named parameters (`$name`, `:name`, `@name`),\n * keyed by bare name (a `$`/`:`/`@` prefix on a key is tolerated). Each\n * value passes through the same `bindValue` the projection loader uses —\n * booleans become 1/0, arrays and objects JSON text — so a bound parameter\n * compares against a stored cell under exactly the encoding the cell got\n * (proposal 0029). A parameter the SQL references with no entry here\n * refuses: unbound would silently bind NULL and match nothing.\n */\n params?: Record<string, unknown>;\n /**\n * `-s/--schema`, repeatable: the schema set the run's DDL evolves — CLI\n * precedence for the DDL planner *only* (proposal 0030). The per-file\n * resolution walk is skipped and the deduped refs are the set; every guard\n * inside the set (single local file for ADD, sole declarer for\n * DROP/RENAME, builtin fork, URL refusal, the trust boundary) runs\n * unchanged. Collection views keep following the config's resolution. A\n * run whose statement produces no DDL effect refuses before anything is\n * applied — a flag that would silently mean nothing must refuse.\n */\n schemas?: string[];\n /**\n * How to ask for a new encryption key when an `UPDATE` or `INSERT` writes\n * a column its schema marks `x-manni-encrypt` and no key is available\n * (proposal 0045). The CLI passes `terminalConfirm()`, which is\n * `undefined` off a terminal; absent, such a write refuses (exit 2). A dry\n * run never asks: it writes nothing.\n */\n confirm?: Confirm;\n /**\n * Called with relocate's result when a write's P1 offer was accepted and\n * the values moved (proposal 0047), so the CLI can print relocate's report.\n */\n onRelocated?: (result: RelocateResult) => void;\n /**\n * The environment `MANNI_ENCRYPTION_KEY` is read from. Defaults to\n * `process.env`; tests pass their own.\n */\n env?: NodeJS.ProcessEnv;\n /** The clock an uncommitted body change is dated by. Test seam; default `new Date()`. */\n now?: () => Date;\n}\n\n/**\n * One thing a statement changed, in file-space terms. Cell-level kinds carry\n * a `key` (a set, a deletion via `SET k = NULL` / `ALTER DROP COLUMN`, or a\n * key rename); file-level kinds carry the whole event (`cleared` — the block\n * stripped by DELETE; `created` — a file INSERT made; `renamed` — a `_path`\n * move). Exactly one kind per object.\n *\n * `manifest` (proposal 0047) names the external-metadata manifest the change\n * lands in, as the run reports it, when it lands in one: an owned key's set,\n * removal or rename, a created file's owned keys, a stripped document's\n * entry, or a moved document's entry.\n */\nexport type QueryChange = { file: string; written: boolean; manifest?: string } & (\n | { key: string; from: unknown; to: unknown }\n | { key: string; from: unknown; deleted: true }\n | { key: string; renamedFrom: string; to: unknown }\n | { cleared: true; from: Record<string, unknown> }\n | { created: true; to: Record<string, unknown> }\n | { renamed: string }\n | {\n /** A DDL statement edited the schema itself (0024): `file` is the\n * schema written — an in-place edit, or the fork of a builtin. */\n schema: true;\n op: \"add\" | \"drop\" | \"rename\";\n key: string;\n renamedTo?: string;\n type?: string;\n /** 0028: a declared type equal to a format name carries the format. */\n format?: string;\n /** 0028: a `CHECK (k IN (…))` on the added column carries the enum. */\n enum?: (string | number)[];\n required?: boolean;\n forkedFrom?: string;\n }\n | {\n /** A DDL side effect on the governing config file: a fork repoints the\n * `schemas:` entry (`key: \"schemas\"`), an in-place edit of a pinned\n * schema refreshes its pin (`key: \"integrity\"`). Disclosed as a change\n * because the preview must name every file `--write` will touch. */\n config: true;\n key: string;\n from: unknown;\n to: unknown;\n }\n);\n\nexport interface QueryRun {\n /** Result column names, in SELECT order — present even for zero rows. */\n columns: string[];\n rows: Record<string, unknown>[];\n /** Set when `db` was written: where, and how big the table is. */\n db?: { path: string; files: number; columns: number };\n /**\n * Present when the statement was a metadata edit: every cell it changed\n * (empty when a mutating statement matched nothing). Absent on reads.\n */\n changes?: QueryChange[];\n /**\n * Where the run stood, in the same shape `ValidateRun.frame` carries — the\n * path-normalization frame SARIF and JUnit need before they can name a file\n * the way the repository does (proposal 0026). Constructed from the run's\n * `cwd`, its config directory, and the directory file labels resolve\n * against; absent only when a caller built a `QueryRun` by hand.\n */\n frame?: FingerprintContext;\n}\n\nexport async function runQuery(opts: QueryOptions): Promise<QueryRun> {\n const cwd = opts.cwd ?? process.cwd();\n const sql = opts.sql.trim();\n if (sql === \"\" && opts.db === undefined) {\n throw new DocmetaError(\"Specify SQL to run.\");\n }\n if (sql === \"\") {\n // Export-only run. Options that speak to a statement would be silently\n // ignored past this point (runSql returns before either is consulted),\n // and an ignored option is the false green 0029's rule exists to\n // refuse. Guarded here in the core, not only in the CLI gates, so a\n // library caller gets the same refusal the flags get.\n if (opts.schemas !== undefined && opts.schemas.length > 0) {\n throw new DocmetaError(\n \"`schemas` names the schema set DDL evolves, and an export-only run (no SQL) runs no statement. Pass the SQL, or drop `schemas`.\",\n );\n }\n if (opts.params !== undefined && Object.keys(opts.params).length > 0) {\n throw new DocmetaError(\n \"`params` binds named parameters in a statement, and an export-only run (no SQL) references none. Pass the SQL, or drop `params`.\",\n );\n }\n }\n if (sql !== \"\") assertSingleStatement(sql);\n\n // The false-green guard (proposal 0029): the engine throws on an extra\n // bound parameter, but a referenced parameter with nothing bound silently\n // binds NULL and matches nothing — a zero-row `--check` from a typo is a\n // passing CI gate. Refused here, before any file is read.\n const boundParams = bindParams(opts.params);\n if (sql !== \"\") {\n // Own keys only: `\"toString\" in {}` is true, so an `in` test would read\n // $toString (or $constructor, $__proto__) as bound and let it bind NULL —\n // the exact false green this guard refuses.\n const unbound = collectNamedParameters(sql).filter(\n (token) => !Object.hasOwn(boundParams, token.slice(1)),\n );\n if (unbound.length > 0) {\n const list = unbound.join(\", \");\n throw new DocmetaError(\n `The statement references ${list} with nothing bound — an unbound parameter binds NULL and matches nothing. Bind ${\n unbound.length === 1 ? \"it\" : \"each\"\n } with --param ${unbound[0]?.slice(1) ?? \"name\"}=<value> (or \\`params\\` in the API).`,\n );\n }\n }\n\n // Explicit CLI inputs win, else config `paths:`; `base` is whichever of the\n // two directories those inputs were written relative to.\n const runConfig = await resolveRunConfig({\n cwd,\n configPath: opts.configPath,\n noConfig: opts.noConfig,\n inputs: opts.inputs,\n ...(opts.collections !== undefined\n ? { collections: opts.collections }\n : {}),\n onConfigLoaded: opts.onConfigLoaded,\n });\n const {\n config,\n inputs,\n base,\n configDir,\n configPath,\n configSection,\n collections,\n declaredCollections,\n fromCollections,\n configFile,\n } = runConfig;\n /** The collections one label belongs to, computed once per file. */\n const membersFor = (label: string): string[] =>\n memberOf(collections, configDir ?? cwd, base, label);\n const usingStdin = inputs.includes(STDIN_TOKEN);\n\n if (inputs.length === 0) {\n throw new DocmetaError(\n \"No files to read. Pass paths/globs, or declare a collection under `collections:` in manni.config.yaml.\",\n );\n }\n\n const forced = opts.as ? extractorByName(opts.as) : undefined;\n if (opts.as && !forced) {\n throw new DocmetaError(\n `Unknown format \"${opts.as}\". Supported extensions: ${supportedExtensions().join(\", \")}.`,\n );\n }\n\n const exts = opts.exts ?? (forced ? forced.extensions : undefined);\n const fileInputs = inputs.filter((i) => i !== STDIN_TOKEN);\n const allowEmpty = opts.allowEmpty ?? config?.allowEmpty;\n // Only `--exclude`: a collection's `exclude:` governs membership, not the\n // walk of a path someone typed (0041 rule 3).\n const exclude = opts.exclude ?? [];\n const { files: walked, gitignoreSkipped } = await resolveTargetSet({\n inputs: fileInputs,\n exts,\n exclude,\n cwd: base,\n allowEmpty,\n ...gitignoreOptions({\n flag: opts.respectGitignore,\n configured: config?.respectGitignore,\n onNotice: opts.onNotice,\n }),\n });\n // Rule 9: the walk applied only the family ignores and `--exclude`, so it saw\n // just the first half of each collection's statement. Narrow it to actual\n // members, or a collection's `exclude:` would shape its SQL view and not what\n // a bare run reads. Skipped for typed paths: those are the operator's (rule 3).\n const files = fromCollections ? retainMembers(walked, membersFor) : walked;\n assertNonEmpty({\n files,\n inputs: fileInputs,\n usingStdin,\n allowEmpty,\n exclude,\n exts,\n gitignoreSkipped,\n action: \"queried\",\n });\n\n const entries: QueryEntry[] = [];\n // External metadata (0037), read once per run and merged into every row.\n const externalMetadata = await loadExternalMetadata(collections, {\n configDir: configDir ?? cwd,\n base,\n offline: opts.offline ?? config?.offline ?? false,\n // A `{page}` manifest (0058) is read for exactly the pages this run reads.\n pages: files.map((file) => resolve(base, file)),\n });\n\n // Proposal 0045. The run's key, resolved when first needed; the one prompt\n // a write that needs a key asks; and the validator that finds which columns\n // a written file's schema set marks, built only when a statement writes.\n const configuredKey = lazyKey(configFile, opts.env);\n let ensuredKey: string | undefined;\n const currentKey: KeyGetter = () => ensuredKey ?? configuredKey();\n let markValidator: Validator | undefined;\n const encryption: QueryEncryption = {\n key: currentKey,\n ensure: async (subject) => {\n const have = currentKey();\n if (have !== undefined) return have;\n const { key } = await ensureEncryptionKey({\n subject,\n cwd,\n file: configFile ?? null,\n env: opts.env,\n confirm: opts.confirm,\n notice: (message) => opts.onNotice?.(message),\n toError: (message) => new EncryptionRefusal(message),\n });\n ensuredKey = key;\n return key;\n },\n validator: () =>\n (markValidator ??= new Validator(\n schemaLoadOptions({\n root: configDir ?? cwd,\n fileBase: cwd,\n ttlHours: config?.schemaCache?.ttlHours,\n offline: opts.offline ?? config?.offline,\n pins: collectSchemaPins(config),\n registered: config?.registered,\n }),\n )),\n };\n\n // Proposal 0047. Where a written key lands (a local manifest that owns it,\n // or the page), and the P1 offer for a value its schema prefers in external\n // metadata with no manifest. The context is built on first use, so a read,\n // or a write on a corpus with no manifests, pays nothing for it.\n let relocation: RelocationContext | undefined;\n const location: QueryLocation = {\n context: () =>\n (relocation ??= relocationContext(runConfig, {\n cwd,\n targets: opts.inputs,\n validator: encryption.validator(),\n noConfig: opts.noConfig ?? false,\n ...(opts.schemas !== undefined && opts.schemas.length > 0 ? { cliSchemas: opts.schemas } : {}),\n ...(opts.as !== undefined ? { as: opts.as } : {}),\n ...(opts.respectGitignore !== undefined ? { respectGitignore: opts.respectGitignore } : {}),\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n ...(opts.onNotice !== undefined ? { onNotice: opts.onNotice } : {}),\n })),\n // No question under stdin input or a dry run (0047 prompting rules).\n ...(opts.confirm !== undefined && !usingStdin && opts.dryRun !== true\n ? { confirm: opts.confirm }\n : {}),\n ...(opts.onRelocated !== undefined ? { onRelocated: opts.onRelocated } : {}),\n offline: opts.offline ?? config?.offline ?? false,\n };\n\n // What each page's schemas mark external, which a manifest with no keys\n // owns (proposal 0068). The validator is the one a write builds, on first use.\n const marks = pageMarks({\n validator: encryption.validator,\n config,\n cwd,\n trustRoot: schemaTrustRoot(cwd, configDir),\n ...(opts.schemas !== undefined && opts.schemas.length > 0 ? { cliSchemas: opts.schemas } : {}),\n });\n\n const readOne = async (label: string, content: string, extension: string): Promise<void> => {\n const extractor = forced ?? extractorForExtension(extension);\n if (!extractor) {\n throw new DocmetaError(\n `Unsupported file type \"${extension}\" for \"${label}\". Supported: ${supportedExtensions().join(\", \")}. Use --as to override.`,\n );\n }\n const members = membersFor(label);\n const own = extractor.extract(content, label, {\n elements: resolveElements(label, config, members),\n });\n const merged = await mergeWithMarks(label, own, externalMetadata, members, base, {\n encryptionKey: currentKey,\n marks,\n });\n entries.push({\n label,\n extracted: merged.extracted,\n extractor,\n own,\n content,\n ...(merged.marked !== undefined ? { marked: merged.marked } : {}),\n });\n };\n\n if (usingStdin) {\n if (!forced) {\n throw new DocmetaError(\n STDIN_REQUIRES_AS,\n );\n }\n // Unreachable while every registered extractor has at least one extension,\n // but a bare \"\" fallback here would surface as `Unsupported file type \"\"`\n // with the --as format name nowhere in it.\n const ext = forced.extensions[0];\n if (ext === undefined) {\n throw new DocmetaError(\n `Format \"${forced.name}\" registers no file extension to read stdin as.`,\n );\n }\n await readOne(STDIN_LABEL, opts.stdinContent ?? \"\", ext);\n }\n\n for (const file of files) {\n const content = await readFile(resolve(base, file), \"utf8\");\n await readOne(file, content, extname(file));\n }\n\n // The export path resolves like every positional the user typed: from\n // where they are standing, not from the config's directory.\n const db =\n opts.db === undefined\n ? undefined\n : { resolved: resolve(cwd, opts.db), display: opts.db };\n const run = await runSql(sql, entries, {\n target: db,\n params: boundParams,\n ...(opts.schemas !== undefined && opts.schemas.length > 0\n ? { cliSchemas: opts.schemas }\n : {}),\n write: !opts.dryRun,\n cache: opts.cache ?? true,\n ...(opts.now !== undefined ? { now: opts.now } : {}),\n base,\n config,\n cwd,\n configDir,\n configPath,\n configSection,\n trustRoot: schemaTrustRoot(cwd, configDir),\n externalMetadata,\n marks,\n collections,\n declaredCollections,\n memberships: membersFor,\n managed: new Set(managedFields(config?.derive)),\n onNotice: opts.onNotice,\n encryption,\n location,\n });\n // The same frame `runValidate` returns, built from query's own run context:\n // fingerprints and canonical paths must not depend on where the command was\n // run from (proposal 0026 § stress test 6).\n return { ...run, frame: { cwd, base: configDir ?? cwd, runBase: base } };\n}\n\ninterface QueryEntry {\n label: string;\n extracted: ExtractedMetadata;\n /** The extractor that read it — a write goes back through the same one. */\n extractor: MetadataExtractor;\n /**\n * The document's OWN extraction, from before the external-metadata merge,\n * and the text it came from: what the `derived` table (0040) is computed\n * over. A managed key is never manifest-owned, and the git source hashes\n * the body.\n */\n own: ExtractedMetadata;\n content: string;\n /** What the page's schemas mark external, when a keyless manifest needed asking (proposal 0068). */\n marked?: ReadonlySet<string>;\n}\n\n/**\n * `QueryOptions.params`, normalized for the engine: bare-name keys (a\n * `$`/`:`/`@` prefix is tolerated, since `node:sqlite` binds either spelling)\n * and SQL-space values via the projection's own `bindValue`.\n */\nfunction bindParams(\n params: Record<string, unknown> | undefined,\n): Record<string, SqlValue> {\n // Null prototype, so a `__proto__` key is an ordinary own entry (it passes\n // the name grammar) instead of a prototype mutation the engine never sees.\n const out: Record<string, SqlValue> = Object.create(null) as Record<\n string,\n SqlValue\n >;\n for (const [key, value] of Object.entries(params ?? {})) {\n const name = key.startsWith(\"$\") || key.startsWith(\":\") || key.startsWith(\"@\")\n ? key.slice(1)\n : key;\n out[name] = bindValue(value);\n }\n return out;\n}\n\ninterface RunContext {\n target?: { resolved: string; display: string };\n /** Named-parameter binds, bare-name keys, already through `bindValue`. */\n params: Record<string, SqlValue>;\n /**\n * `-s` refs: the DDL planner's set, in place of the per-file walk (0030).\n * INVARIANT: set only when non-empty — `runQuery` threads it only then —\n * so `!== undefined` is the one guard every consumer uses.\n */\n cliSchemas?: string[];\n write: boolean;\n /** Whether the review cache may answer a `derived` build; `--no-cache` clears it. */\n cache: boolean;\n /** The clock an uncommitted body change is dated by; default `new Date()`. */\n now?: () => Date;\n /** Directory file labels resolve against (see `resolveRunConfig`). */\n base: string;\n config: DocmetaConfig | null;\n /** The run's working directory — schema refs resolve from here. */\n cwd: string;\n /** Directory holding the governing config file, when one exists. */\n configDir?: string;\n /** Absolute path of the governing config file, when one exists. */\n configPath?: string;\n /**\n * The key that config sits under — `meta` in a family file, absent in a\n * legacy per-tool file. Only the DDL config rewrite needs it, and it needs\n * it badly: `schemas:` is one level down in a family file.\n */\n configSection?: string;\n /** The boundary a schema read or write may not escape (proposal 0015). */\n trustRoot: SchemaTrustRoot;\n /** External metadata of the run (proposal 0037); null when none are configured. */\n externalMetadata: ExternalMetadataIndex | null;\n /** What a page's schemas mark external, which a manifest with no keys owns (proposal 0068). */\n marks: PageMarks;\n /** The collections the run covers (proposal 0041); `[]` with no config. */\n collections: readonly CollectionConfig[];\n /**\n * Every collection the config declares, selected or not. The views are built\n * from this list (0041 rule 11), so a statement naming a collection\n * `--collection` left out still answers instead of failing to compile.\n */\n declaredCollections: readonly CollectionConfig[];\n /** The collections one label belongs to - `memberOf` bound to this run. */\n memberships: (label: string) => readonly string[];\n /**\n * The managed fields (`derive.fields`, proposal 0040): readable in every\n * row, writable by `manni meta derive` alone. Empty when none are configured.\n */\n managed: ReadonlySet<string>;\n /** Diagnostics for the user; the CLI writes these to stderr. */\n onNotice?: (message: string) => void;\n /** Encrypted values (proposal 0045): the key, the prompt, the marks. */\n encryption: QueryEncryption;\n /** Manifest-owned writes and the P1 offer (proposal 0047). */\n location: QueryLocation;\n}\n\n/** What a run needs to route a write to a manifest, and to offer one (proposal 0047). */\ninterface QueryLocation {\n /** The relocation context `keyHome` and the P1 plan read, built on first use. */\n context: () => RelocationContext;\n /** P1's question. Absent off a terminal, under stdin input, and on a dry run. */\n confirm?: Confirm;\n /** Relocate's result, after an accepted P1 offer. */\n onRelocated?: (result: RelocateResult) => void;\n /** Whether a URL manifest is refused rather than fetched, for the reload after a relocation. */\n offline: boolean;\n}\n\n/** What a run needs to read and write encrypted values (proposal 0045). */\ninterface QueryEncryption {\n /** The run's key, or `undefined` when none is available. */\n key: KeyGetter;\n /** The key a write encrypts with, asking for one when there is none. */\n ensure: (subject: string) => Promise<string>;\n /** The validator a written file's marks are read with. */\n validator: () => Validator;\n}\n\n/**\n * Only two byte patterns may be overwritten by `--db`: a SQLite database\n * (docmeta's own artifact, or anyone else's — both are regenerable-shaped)\n * and an empty file. Anything else at the path is somebody's data.\n */\nasync function prepareDbTarget(resolved: string, display: string): Promise<void> {\n let handle;\n try {\n handle = await open(resolved, \"r\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return;\n throw err;\n }\n try {\n const { bytesRead, buffer } = await handle.read(\n Buffer.alloc(16),\n 0,\n 16,\n 0,\n );\n const magic = Buffer.from(\"SQLite format 3\\0\", \"latin1\");\n const isSqlite = bytesRead === 16 && buffer.equals(magic);\n if (bytesRead !== 0 && !isSqlite) {\n throw new DocmetaError(\n `\"${display}\" exists and is not a SQLite database; refusing to overwrite it.`,\n );\n }\n } finally {\n await handle.close();\n }\n await rm(resolved);\n}\n\n/**\n * Internal signal for the lazy view build: the statement referenced a\n * configured collection whose view is not created yet. Never escapes\n * `runSql` — its retry catch either rebuilds once or is not reached.\n */\nclass MissingCollectionView extends Error {}\n\n/**\n * The same signal for the derived channel's two tables (0040): the statement\n * named `derived` or `resolved`, neither view is built yet, and building them\n * is worth one git walk. One class for both, because one build makes both.\n */\nclass MissingDerivedTable extends Error {}\n\n/**\n * Wrap an engine error from the user's statement — prepare-time or\n * execution-time — into the operational refusal the CLI reports. Three cases\n * get a remedy: an INSERT/rename onto a loaded `_path` (the projection's\n * primary key catches it before any disk check can), a write through a\n * collection view (0027) — SQLite's own refusal, completed with the\n * write-through-docs spelling — and a write to the `derived` or `resolved`\n * view (0040), neither of which has anything behind it to write to.\n * `resolved` gets a remedy of its own because it has two sides: a value the\n * document should state is a write to `docs`, and one the evidence should\n * state is a derive run. The view-name capture is\n * non-greedy up to the literal tail: a collection name may contain spaces,\n * which \\S+ would truncate into a remedy naming a view that does not exist.\n */\nfunction refuseSqlError(err: unknown): never {\n const message = errorMessage(err);\n if (message.includes(\"UNIQUE constraint failed: docs._path\")) {\n throw new DocmetaError(\"That _path already exists in the corpus.\");\n }\n const viewWrite = /cannot modify (.+?) because it is a view/.exec(message);\n const viewName = viewWrite?.[1];\n if (viewName !== undefined) {\n if (viewName.toLowerCase() === DERIVED_VIEW) {\n throw new DocmetaError(\n `SQL error: ${message}; a collection or the derived table is read-only — the derived table is recomputed from the evidence on every run. Change the evidence, or stamp it into the documents with manni meta derive.`,\n );\n }\n if (viewName.toLowerCase() === RESOLVED_VIEW) {\n throw new DocmetaError(\n `SQL error: ${message}; the resolved table is read-only — it is \\`docs\\` and the evidence joined, so write to docs, or stamp the evidence with manni meta derive.`,\n );\n }\n throw new DocmetaError(\n `SQL error: ${message}; a collection or the derived table is read-only — write through docs: UPDATE docs … WHERE _path IN (SELECT _path FROM \"${viewName.replaceAll('\"', '\"\"')}\").`,\n );\n }\n throw new DocmetaError(`SQL error: ${message}`);\n}\n\n/**\n * Build the `docs` table — in memory, or at the export target — run the\n * user's statement over it (none, when only exporting), and judge what the\n * statement *did*: reads return rows; metadata edits become per-file changes,\n * previewed or (with `write`) applied through the extractors' writers.\n */\nasync function runSql(\n sql: string,\n entries: QueryEntry[],\n ctx: RunContext,\n): Promise<QueryRun> {\n const target = ctx.target;\n // Data columns: the corpus's key union, plus a SET/INSERT target no file has\n // yet — that is how a corpus-new key is created. The scan is tolerant and\n // only ever *adds* empty columns: anything it misses fails exactly as before\n // (\"no such column\"), and a false positive is an all-NULL column nothing\n // diffs.\n const dataColumns = corpusDataColumns(\n entries,\n sql === \"\"\n ? []\n : [...collectSetTargets(sql), ...collectInsertTargets(sql)],\n );\n\n const { DatabaseSync } = await loadSqlite();\n if (target) {\n // SQLite creates the file but never its directories — `.docmeta/` on a\n // fresh checkout is exactly the path that does not exist yet.\n await mkdir(dirname(target.resolved), { recursive: true });\n await prepareDbTarget(target.resolved, target.display);\n }\n let db: InstanceType<typeof DatabaseSync>;\n try {\n db = new DatabaseSync(target ? target.resolved : \":memory:\");\n } catch (err) {\n throw new DocmetaError(\n `Cannot open \"${target?.display ?? \":memory:\"}\": ${errorMessage(err)}`,\n );\n }\n const dbInfo = target\n ? {\n path: target.display,\n files: entries.length,\n columns: SYSTEM_COLUMNS.length + dataColumns.length,\n }\n : undefined;\n // Whether the derived table was built this run. Held in an object, and\n // declared here rather than beside `buildDerived`, because the `finally`\n // below reads it to drop the table from a `--db` export — and a bare\n // `let` set inside a closure narrows to `false` at that read.\n const derivedTable = { built: false };\n try {\n createDocsTable(db, entries, dataColumns);\n // Collections (0041 rule 7): one view per declared collection, holding the\n // members the run loaded — built LAZILY on the normal path, because a\n // statement that never names a collection should pay nothing for the\n // membership arithmetic and the view SQL. The build happens on demand\n // (below, when the engine reports the collection's table as missing) —\n // with one eager exception: a `--db` export must carry the views (0027 §\n // stress test 5), empty-SQL export-only runs included.\n // Annotated `boolean`: assignments happen inside `buildViews`, which\n // narrowing does not track — an inferred `false` reads every later\n // `!viewsBuilt` as always-true.\n let viewsBuilt: boolean = false;\n const buildViews = (): void => {\n // Idempotent, because the eager triggers overlap: a `--db` export and\n // the catalog pre-trigger may both ask for the same build.\n if (viewsBuilt) return;\n createCollectionViews(\n db,\n collectCollections(entries, {\n collections: ctx.declaredCollections,\n ...(ctx.configDir !== undefined ? { configDir: ctx.configDir } : {}),\n base: ctx.base,\n }),\n );\n viewsBuilt = true;\n };\n if (target) buildViews();\n // The derived channel's tables (0040), `derived` and `resolved`: built\n // only when the statement names one of them, because building them spawns\n // git (and, with the github or gitlab source, gh or glab). One build makes\n // both — `resolved` is the join of `docs` with the same rows — so naming\n // either pays the walk once and a statement joining the two pays it once\n // too. Eager when the text names one as a table, and lazily on the\n // engine's `no such table: derived` / `: resolved` as the backstop for a\n // spelling the text search misses. Only the fields the statement can read are\n // derived, so only the sources those need are consulted; the view\n // keeps every column, NULL where nothing was derived. Stdin has no\n // history and no row. Transient in a `--db` export: the value is not\n // stored anywhere, and an export that froze it would be the stale stamp\n // the channel exists to catch, so both objects are dropped before the\n // handle closes (see the `finally` below).\n const buildDerived = async (): Promise<void> => {\n if (derivedTable.built) return;\n // The run's columns: the built-ins and the configured command keys\n // (0042), so a statement reading a command's field runs the command.\n const commands = commandsOf(ctx.config?.derive);\n const fields = fieldsForSql(sql, derivableFields(commands));\n // The manifests that hold a page's `provenance` record (0046), for\n // evidence rule 2, as `validate` and `get` hand them to the git source.\n // Only when provenance is derived: named, or managed by `derive.fields`.\n const provenanceDerived =\n fields.includes(PROVENANCE_FIELD) || ctx.config?.derive?.fields?.includes(PROVENANCE_FIELD) === true;\n const manifestRoot = ctx.configDir ?? ctx.cwd;\n const manifests = provenanceDerived\n ? readerManifests(ctx.declaredCollections, manifestRoot, ctx.base)\n : [];\n const inputs: DeriveInput[] = entries\n .filter((e) => e.label !== STDIN_LABEL)\n .map((e) => {\n const place = manifests.length === 0\n ? undefined\n : readerPlace(e.label, e.own.data, manifests, ctx.declaredCollections, manifestRoot, ctx.base, e.marked);\n // Rule 1 of 0069: the manifest that owns a dated field is read at each fact commit.\n const owned =\n ctx.declaredCollections.length === 0\n ? {}\n : stampManifests(e.label, e.own.data, ctx.declaredCollections, manifestRoot, ctx.base, e.marked, STAMPED_DATE_FIELDS);\n return {\n label: e.label,\n absPath: resolve(ctx.base, e.label),\n content: e.content,\n extracted: e.own,\n ...(place !== undefined ? { provenanceManifest: place } : {}),\n ...(Object.keys(owned).length > 0 ? { stampManifests: owned } : {}),\n };\n });\n const records = await deriveForTable(\n inputs,\n {\n cwd: ctx.cwd,\n base: ctx.base,\n ...(ctx.configDir !== undefined ? { configDir: ctx.configDir } : {}),\n config: ctx.config,\n cache: ctx.cache,\n ...(ctx.now !== undefined ? { now: ctx.now } : {}),\n },\n \"narrow derive.sources in manni.config.yaml\",\n fields,\n );\n createDerivedView(db, records, derivedColumns(commands));\n // `resolved` (0040) is the join of the two, so it is built from the\n // same `dataColumns` `createDocsTable` was given — the view's asserted\n // side reads those columns by name, and a list recomputed here could\n // disagree with the table's (a SET target the scan added has a column\n // in `docs` and must have one in `resolved`).\n createResolvedView(db, dataColumns, commands);\n derivedTable.built = true;\n };\n if (sql === \"\") {\n return { columns: [], rows: [], ...(dbInfo ? { db: dbInfo } : {}) };\n }\n if (mentionsDerived(sql) || mentionsResolved(sql)) await buildDerived();\n\n // ATTACH and VACUUM INTO write files of their own, outside the table the\n // effect gate below watches — the only statements refused by name. The\n // check runs on the first real token: `/* c */ ATTACH …` must not slip\n // past a first-character regex on the strength of a comment.\n //\n // Deliberately NOT `PRAGMA query_only`: writes to the projection are the\n // feature since 0022 (the effect gate below is the guard), and the\n // snapshot reads share this handle. The residue is confined to a `--db`\n // export — a statement may add its own tables or indexes to that file,\n // which is a regenerable artifact by declared contract.\n const head = stripLeadingTrivia(sql);\n if (/^(attach|vacuum)\\b/i.test(head)) {\n throw new DocmetaError(\n `${head.split(/\\s/, 1)[0]?.toUpperCase() ?? \"That statement\"} is refused: it can write outside the docs table.`,\n );\n }\n\n // Fail-safe eager build for catalog-observing statements — and any\n // statement that plausibly names a collection. A sqlite_master /\n // sqlite_schema read, a PRAGMA, and CREATE/DROP/ALTER never raise\n // `no such table` for a missing view, so the lazy retry below cannot\n // rescue them: without this they would observe a catalog with no views\n // (empty listings, table_info silence, CREATE silently shadowing a\n // collection name) where the always-eager build listed, answered, or\n // refused. The substring search deliberately OVER-triggers: a collection\n // name inside a string literal or comment costs one always-correct eager\n // build, while under-triggering is exactly this silent-miss bug class.\n // The retry stays as the backstop for the one spelling a raw-text search\n // cannot see — a name whose quoted-identifier spelling doubles a quote\n // character inside it.\n const lower = sql.toLowerCase();\n const observesCatalog =\n lower.includes(\"sqlite_master\") ||\n lower.includes(\"sqlite_schema\") ||\n lower.includes(\"pragma\") ||\n /^(create|drop|alter)\\b/i.test(head) ||\n collectionNames(ctx.declaredCollections).some((n) =>\n lower.includes(n.toLowerCase()),\n );\n if (observesCatalog) buildViews();\n\n // 0024: `SET k = NULL` is the removal spelling, so the literal `k: null`\n // gets a function instead — `explicit_null()` returns a per-run random\n // sentinel no real content can collide with and nothing can type.\n const sentinel = `manni:null:${randomBytes(16).toString(\"hex\")}`;\n db.function(\"explicit_null\", () => sentinel);\n // 0026: the statement may name the source line a key sits on.\n registerLineFor(db, entries);\n\n // 0022: the statement runs freely against this disposable projection and\n // is judged by its effects, not its syntax. A read leaves no diff. The\n // column snapshot (0024) is what makes DDL an effect too.\n //\n // One closure, so the lazy view build below can re-run it intact. The\n // ordering invariant: prepare first — compiling is effect-free, so a\n // lazy-view miss on the first attempt costs one compile and never a\n // full-corpus snapshot — then the baseline snapshots, then execution:\n // the baseline must precede the statement's effects. The snapshots\n // themselves are all docs-scoped (`SELECT * FROM docs`,\n // `PRAGMA table_info(docs)`, the catalog row named `docs`) and cannot\n // see views, so a rebuild between attempts changes nothing they record.\n const runOnce = async (): Promise<QueryRun> => {\n let stmt: ReturnType<typeof db.prepare>;\n let columns: string[];\n try {\n stmt = db.prepare(sql);\n columns = stmt.columns().map((c) => c.name);\n } catch (err) {\n const message = errorMessage(err);\n // Lazy collection views: the first time a statement names a configured\n // collection, its view does not exist yet and the engine reports the\n // table as missing (case-folded — SQLite resolves table names\n // case-insensitively). Signal the build-and-retry; on the retry\n // `viewsBuilt` is true, so a second failure surfaces normally below.\n const missing = missingTableName(message);\n if (\n missing !== undefined &&\n !viewsBuilt &&\n namesConfiguredCollection(missing, ctx.declaredCollections)\n ) {\n // INVARIANT: this signal may only ever be raised from this\n // prepare-time catch. `no such table` is a compile error — probed\n // unreachable from execution on node:sqlite — and a retry thrown\n // after execution began would re-run `stmt.all` and double-apply\n // whatever DML the first run already did.\n throw new MissingCollectionView();\n }\n // The same backstop for the derived channel's tables (0040), for the\n // one spelling the raw-text search cannot see. Either name signals the\n // one build that makes both. Same invariant: raised only from this\n // prepare-time catch.\n const missingBare = missing?.replace(/^(main|temp)\\./i, \"\").toLowerCase();\n if (\n !derivedTable.built &&\n (missingBare === DERIVED_VIEW || missingBare === RESOLVED_VIEW)\n ) {\n throw new MissingDerivedTable();\n }\n refuseSqlError(err);\n }\n const before = snapshotRows(db);\n const colBefore = snapshotColumns(db);\n // 0028: table_info cannot see a CHECK, so the stored CREATE TABLE text is\n // snapshotted alongside the column shapes and consulted for adds only.\n const catalogBefore = snapshotCatalogSql(db);\n let rows: Record<string, unknown>[];\n try {\n // The single user-SQL call site (proposal 0029): binding here is why\n // parameters work uniformly across reads, `--check` gates, and DML.\n // Passed unconditionally — probed on node:sqlite, `all({})` behaves\n // identically to `all()` for statements with and without parameters,\n // and the unbound-reference guard already refused any statement whose\n // named parameters this object does not cover.\n // node:sqlite types rows as unknown[]; each row is a name->value record.\n rows = stmt.all(ctx.params);\n } catch (err) {\n refuseSqlError(err);\n }\n let after: Map<string, Record<string, unknown>>;\n try {\n after = snapshotRows(db);\n } catch {\n // The table itself is gone. \"Delete the table definition\" is the\n // accident-shaped spelling of two real statements; name them both.\n throw new DocmetaError(\n \"DROP TABLE is refused. DELETE FROM docs WHERE … strips metadata from files; ALTER TABLE docs DROP COLUMN retires one key from the schema and every file.\",\n );\n }\n const diff = diffProjection(before, after);\n const schemaOps = columnDiffOps(\n colBefore,\n snapshotColumns(db),\n before,\n after,\n catalogBefore,\n snapshotCatalogSql(db),\n );\n // 0030: -s speaks only to the DDL planner, and DDL is judged by its\n // effects — so \"no schema-evolving effects\" is knowable only here,\n // after execution. The placement is load-bearing: the refusal must\n // land on the plan side of the all-or-nothing line, BEFORE\n // buildChanges and applyChanges, so a DML statement under -s never\n // writes files and then errors (the applies-then-refuses trap the\n // -f csv review found). Two truths in the wording: \"no\n // schema-evolving effects\" rather than \"no DDL\" (a CREATE INDEX into\n // a --db export is DDL the planner deliberately ignores), and the\n // --db residue named when it exists — the export target was written\n // before the statement ran and holds whatever the statement did.\n if (ctx.cliSchemas !== undefined && schemaOps.length === 0) {\n throw new DocmetaError(\n `-s names the schema set DDL evolves; this statement produced no schema-evolving effects (ALTER TABLE docs …), so the flag would silently mean nothing.${\n target\n ? \" No file or schema writes were applied; the --db export was still written and reflects the statement.\"\n : \" Nothing was applied.\"\n } Drop -s, or evolve the schema with ALTER TABLE docs.`,\n );\n }\n // Structural, not textual: a read always yields result columns, DML and\n // DDL (without RETURNING) never do — so `WITH … UPDATE …` classifies\n // correctly even when it matches zero rows. The residual: RETURNING DML\n // that matches nothing reads as an empty result, which is what it shows.\n const mutatingIntent = columns.length === 0;\n const hasEffects =\n diff.cells.length > 0 ||\n diff.clearedRows.length > 0 ||\n diff.createdRows.size > 0 ||\n diff.renamedFiles.length > 0 ||\n schemaOps.length > 0;\n if (!hasEffects && !mutatingIntent) {\n return { columns, rows, ...(dbInfo ? { db: dbInfo } : {}) };\n }\n\n // DDL edits the schema itself (0024); its plan carries both the schema\n // change records and — for a builtin fork — the reference repoints.\n assertDefaultsMatchDeclaredTypes(schemaOps, diff.cells);\n const schemaPlan =\n schemaOps.length > 0\n ? await planSchemaMutation(schemaOps, entries, ctx)\n : undefined;\n const renameHints = schemaOps.flatMap((op) =>\n op.op === \"rename\" && op.renamedTo !== undefined\n ? [{ from: op.key, to: op.renamedTo }]\n : [],\n );\n // 0028: a BOOLEAN add's backfill writes real booleans to the files — the\n // projection's 1/0 encoding is bind-layer, not file-layer.\n const booleanAdds = new Set(\n schemaOps.flatMap((op) =>\n op.op === \"add\" && op.type === \"boolean\" ? [op.key] : [],\n ),\n );\n const changes = [\n ...(schemaPlan?.changes ?? []),\n ...buildChanges(diff, entries, sentinel, ctx, renameHints, booleanAdds),\n ];\n await sealMarkedWrites(changes, entries, ctx);\n // 0047: an owned key's write lands in its manifest. Planned once for\n // its refusals (a URL manifest, a page with no join value, an owned\n // RENAME COLUMN) before anything can be asked or written; then the\n // P1 offer, which may move values and declare a manifest; then planned\n // again against what the offer changed.\n let manifestWrites = await planManifestEdits(changes, entries, ctx, renameHints);\n const offered = await offerRelocation(changes, entries, ctx);\n if (offered.relocated) {\n manifestWrites = await planManifestEdits(changes, entries, ctx, renameHints);\n }\n if (ctx.write) await applyChanges(changes, entries, ctx, schemaPlan, manifestWrites);\n for (const line of offered.warnings) warn(line);\n return { columns, rows, changes, ...(dbInfo ? { db: dbInfo } : {}) };\n };\n\n try {\n return await runOnce();\n } catch (err) {\n if (err instanceof MissingDerivedTable) {\n // The prepare named `derived` or `resolved` with no view yet: derive,\n // build both, and re-run the closure — the same one-retry shape as the\n // collections below, for the same reasons.\n await buildDerived();\n return await runOnce();\n }\n if (!(err instanceof MissingCollectionView)) throw err;\n // The first prepare named a collection with no view yet: build them\n // all and re-run the closure — prepare, snapshots, execution,\n // judgment. The first attempt died compiling, so nothing ran and\n // nothing was snapshotted; re-running the whole closure keeps one code\n // path with the baseline still taken before the (only) execution. A\n // write through the fresh view reaches the ordinary \"cannot modify X\n // because it is a view\" remedy on this retry; any other second failure\n // surfaces as usual.\n buildViews();\n return await runOnce();\n }\n } finally {\n // A `--db` export must not carry the derived channel's tables: they are\n // recomputed from the evidence on every run, and a file that froze one\n // would hand a later reader a stale value with no evidence behind it. In\n // memory the whole database goes with the handle, so only the export\n // needs the drop. `resolved` goes first: it reads the backing table, and\n // an export must never carry a view over a table it no longer has.\n if (target && derivedTable.built) {\n db.exec(\n `DROP VIEW IF EXISTS ${RESOLVED_VIEW}; DROP VIEW IF EXISTS ${DERIVED_VIEW}; DROP TABLE IF EXISTS ${DERIVED_ROWS}`,\n );\n }\n db.close();\n }\n}\n\n/**\n * The name after `no such table: ` in an engine message — sliced rather than\n * regexed, because a collection name may legally contain a newline, which a\n * `.`-based capture cannot span.\n */\nfunction missingTableName(message: string): string | undefined {\n const prefix = \"no such table: \";\n const at = message.indexOf(prefix);\n return at === -1 ? undefined : message.slice(at + prefix.length);\n}\n\n/**\n * Does the engine's missing-table name refer to a configured collection?\n * Case-folded, because SQLite resolves table names case-insensitively (see\n * `collectionNames` for why JS's looser fold is safe here); a `main.`/`temp.`\n * qualifier the engine may echo for a qualified reference is tolerated too.\n */\nfunction namesConfiguredCollection(\n missing: string,\n collections: readonly CollectionConfig[],\n): boolean {\n const candidates = [missing, missing.replace(/^(main|temp)\\./i, \"\")];\n return collectionNames(collections).some((n) =>\n candidates.some((c) => c.toLowerCase() === n.toLowerCase()),\n );\n}\n\n/** The one sliver of the `node:sqlite` surface the snapshots need. */\ninterface Queryable {\n prepare(sql: string): { all(): unknown[] };\n}\n\n/** Every row of the projection, keyed by `_path`. */\nfunction snapshotRows(db: Queryable): Map<string, Record<string, unknown>> {\n const rows = db.prepare(\"SELECT * FROM docs\").all() as Record<\n string,\n unknown\n >[];\n return new Map(rows.map((r) => [String(r._path), r]));\n}\n\n/** Exported with `assertDefaultsMatchDeclaredTypes`, not via the API index. */\nexport interface CellEffect {\n file: string;\n key: string;\n /** SQL-space value the statement left behind. */\n to: unknown;\n}\n\ninterface ProjectionDiff {\n cells: CellEffect[];\n /** Rows the statement removed — DELETE, meaning: strip the block. */\n clearedRows: string[];\n /** Rows the statement added — INSERT, meaning: create the file. */\n createdRows: Map<string, Record<string, unknown>>;\n /** Rows whose only change is `_path` — a file move. */\n renamedFiles: { from: string; to: string }[];\n}\n\n/**\n * What the statement did, judged by effects (0024). Common rows diff cell by\n * cell; a removed row is a DELETE (strip), an added row an INSERT (create),\n * and a removed/added pair identical in everything but `_path` is a rename.\n * Mixing a rename with cell edits in one statement refuses — each deserves\n * its own preview. Non-`_path` system columns stay read-only.\n */\nfunction diffProjection(\n before: Map<string, Record<string, unknown>>,\n after: Map<string, Record<string, unknown>>,\n): ProjectionDiff {\n const allRemoved = [...before.keys()].filter((p) => !after.has(p)).sort();\n const allAdded = [...after.keys()].filter((p) => !before.has(p)).sort();\n\n // Greedy pairing in sorted order, tracked in sets rather than spliced out\n // of the arrays — same outcome, no quadratic index churn on a bulk rename.\n const renamedFiles: { from: string; to: string }[] = [];\n const pairedFrom = new Set<string>();\n const pairedTo = new Set<string>();\n for (const from of allRemoved) {\n const was = before.get(from);\n if (!was) continue;\n const to = allAdded.find((p) => {\n if (pairedTo.has(p)) return false;\n const now = after.get(p);\n return now !== undefined && rowsEqualExceptPath(was, now);\n });\n if (to === undefined) continue;\n renamedFiles.push({ from, to });\n pairedFrom.add(from);\n pairedTo.add(to);\n }\n const removed = allRemoved.filter((p) => !pairedFrom.has(p));\n const added = allAdded.filter((p) => !pairedTo.has(p));\n if (removed.length > 0 && added.length > 0) {\n // Leftover unpaired adds and removes together can only mean a `_path`\n // change combined with cell edits — no single-statement DML produces\n // both a genuine strip and a genuine create.\n throw new DocmetaError(\n \"The statement changed _path and other cells together; rename and edit separately, so each has its own preview.\",\n );\n }\n\n const cells: CellEffect[] = [];\n for (const [path, was] of before) {\n const now = after.get(path);\n if (!now) continue; // removed — handled as a cleared row\n // The union of both sides: a column ALTER ADD introduced exists only in\n // `now`, and with a DEFAULT it backfills every row — a real change a\n // before-keys-only scan would silently miss.\n for (const key of new Set([...Object.keys(was), ...Object.keys(now)])) {\n if (Object.is(was[key], now[key])) continue;\n if (RESERVED.has(key)) {\n throw new DocmetaError(\n `The statement changed system column \"${key}\" for \"${path}\"; system columns are read-only.`,\n );\n }\n cells.push({ file: path, key, to: now[key] });\n }\n }\n cells.sort((a, b) =>\n a.file === b.file ? a.key.localeCompare(b.key) : a.file.localeCompare(b.file),\n );\n return {\n cells,\n clearedRows: removed,\n createdRows: new Map(\n added.map((p) => [p, after.get(p) ?? {}] as const),\n ),\n renamedFiles: renamedFiles.sort((a, b) => a.from.localeCompare(b.from)),\n };\n}\n\n/** Row equality over every column except `_path` — the rename signature. */\nfunction rowsEqualExceptPath(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n): boolean {\n for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {\n if (key === \"_path\") continue;\n if (!Object.is(a[key], b[key])) return false;\n }\n return true;\n}\n\n/** Declared shape of one projection column, from `PRAGMA table_info`. */\nfunction snapshotColumns(\n db: Queryable,\n): Map<string, { type: string; notnull: number }> {\n const rows = db.prepare(\"PRAGMA table_info(docs)\").all() as {\n name: string;\n type: string;\n notnull: number;\n }[];\n // The cast trusts node:sqlite's documented row shape; this catches the day\n // a Node release renames a pragma column, instead of mistyping silently.\n if (rows.length > 0 && typeof rows[0]?.name !== \"string\") {\n throw new DocmetaError(\n \"PRAGMA table_info returned an unexpected row shape; this node:sqlite build is not one manni understands.\",\n );\n }\n return new Map(rows.map((r) => [r.name, { type: r.type, notnull: r.notnull }]));\n}\n\n/** Exported with `assertDefaultsMatchDeclaredTypes`, not via the API index. */\nexport interface SchemaOp {\n op: \"add\" | \"drop\" | \"rename\";\n key: string;\n renamedTo?: string;\n type?: string;\n /** 0028: the format a declared type equal to a format name carries. */\n format?: string;\n /** 0028: the members of a `CHECK (k IN (…))` on the added column. */\n enum?: (string | number)[];\n required?: boolean;\n}\n\n/** The stored `CREATE TABLE docs` text — the only place a CHECK lives. */\nfunction snapshotCatalogSql(db: Queryable): string {\n const rows = db\n .prepare(\n \"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'docs'\",\n )\n .all() as { sql: unknown }[];\n const sql = rows[0]?.sql;\n return typeof sql === \"string\" ? sql : \"\";\n}\n\n/**\n * DDL, read as an effect: the column set changed. A removed/added pair whose\n * per-row values are identical is a column rename; the rest are drops and\n * adds, an add carrying its declared type and NOT NULL as schema intent.\n *\n * The catalog text (0028) is consulted **only for adds** — `ADD COLUMN`\n * appends the column def verbatim to docmeta-authored CREATE TABLE text, so\n * the suffix delta is extractable without parsing the user's statement. DROP\n * and RENAME rewrite the stored text mid-string and never consult it.\n */\nfunction columnDiffOps(\n before: Map<string, { type: string; notnull: number }>,\n after: Map<string, { type: string; notnull: number }>,\n rowsBefore: Map<string, Record<string, unknown>>,\n rowsAfter: Map<string, Record<string, unknown>>,\n catalogBefore: string,\n catalogAfter: string,\n): SchemaOp[] {\n const removed = [...before.keys()].filter((c) => !after.has(c));\n const added = [...after.keys()].filter((c) => !before.has(c));\n const ops: SchemaOp[] = [];\n // Same set-tracked pairing as diffProjection's file renames — one idiom for\n // both rename detectors, though DDL grammar bounds these arrays at one.\n const pairedFrom = new Set<string>();\n const pairedTo = new Set<string>();\n for (const from of removed) {\n // The size guard keeps an empty corpus from vacuously pairing every drop\n // with every add — unreachable through one ALTER today, stated anyway.\n const to = added.find(\n (a) =>\n !pairedTo.has(a) &&\n rowsBefore.size > 0 &&\n [...rowsBefore.keys()].every((path) =>\n Object.is(rowsBefore.get(path)?.[from], rowsAfter.get(path)?.[a]),\n ),\n );\n if (!to) continue;\n ops.push({ op: \"rename\", key: from, renamedTo: to });\n pairedFrom.add(from);\n pairedTo.add(to);\n }\n for (const key of removed.filter((k) => !pairedFrom.has(k))) {\n ops.push({ op: \"drop\", key });\n }\n for (const key of added.filter((k) => !pairedTo.has(k))) {\n const decl = after.get(key);\n const mapped = mapDeclaredType(decl?.type ?? \"\");\n const members = enumForAddedColumn(catalogBefore, catalogAfter, key, mapped);\n ops.push({\n op: \"add\",\n key,\n ...(mapped?.type !== undefined ? { type: mapped.type } : {}),\n ...(mapped?.format !== undefined ? { format: mapped.format } : {}),\n ...(members !== undefined ? { enum: members } : {}),\n required: decl?.notnull === 1,\n });\n }\n return ops;\n}\n\n/** What a declared column type means for the schema property it will build. */\ninterface DeclaredMapping {\n type: string;\n format?: string;\n}\n\n/**\n * SQLite declared type → JSON Schema mapping. 0024 stopped at SQLite's own\n * affinity rules; 0028 puts the format match **before** them — ordering is\n * load-bearing, or `/INT/` eats `json-POINTER` (0028 § stress test 3):\n *\n * 1. a type case-insensitively equal to a format name the validator enforces\n * (derived from the ajv-formats registration, so upgrades arrive free)\n * maps to `{type: \"string\", format: <name>}`;\n * 2. the closed alias pair `DATETIME`/`TIMESTAMP` → `format: date-time`;\n * 3. `BOOLEAN`/`BOOL` → `{type: \"boolean\"}`;\n * 4. the affinity regexes, exactly as before.\n */\nfunction mapDeclaredType(declared: string): DeclaredMapping | undefined {\n const lower = declared.toLowerCase();\n if (stringFormatNames().has(lower)) return { type: \"string\", format: lower };\n if (lower === \"datetime\" || lower === \"timestamp\") {\n return { type: \"string\", format: \"date-time\" };\n }\n if (lower === \"boolean\" || lower === \"bool\") return { type: \"boolean\" };\n if (/INT/i.test(declared)) return { type: \"integer\" };\n if (/CHAR|CLOB|TEXT/i.test(declared)) return { type: \"string\" };\n if (/REAL|FLOA|DOUB|NUMERIC|DEC/i.test(declared)) return { type: \"number\" };\n return undefined;\n}\n\n/**\n * The column definition `ADD COLUMN` appended to the stored CREATE TABLE\n * text: the after-text is the before-text with `, <def>` inserted before the\n * final `)` (verified against the engine — 0028 § stress test 2). Undefined\n * when the delta is not that shape.\n */\nfunction appendedColumnDef(before: string, after: string): string | undefined {\n const cut = before.lastIndexOf(\")\");\n if (cut === -1 || cut !== before.length - 1 || !after.endsWith(\")\")) {\n return undefined;\n }\n const prefix = before.slice(0, cut);\n if (!after.startsWith(prefix)) return undefined;\n const appended = after.slice(prefix.length, -1);\n const comma = /^\\s*,\\s*/.exec(appended);\n return comma ? appended.slice(comma[0].length) : undefined;\n}\n\n/** Index of the first non-whitespace character of `text` at or after `from`. */\nfunction skipWs(text: string, from: number): number {\n let i = from;\n while (i < text.length && /\\s/.test(text[i] ?? \"\")) i++;\n return i;\n}\n\n/**\n * Index of a `CHECK` keyword at or after `from`, outside quoted regions and\n * comments. The comment branch matters because SQLite stores an ADD COLUMN's\n * definition verbatim, comments included — a CHECK spelled inside one must\n * not satisfy the count guard or trip the one-shape refusal.\n */\nfunction indexOfCheck(text: string, from: number): number {\n let i = from;\n while (i < text.length) {\n const ch = text[i];\n if (startsStringOrIdent(text, i)) {\n i = skipStringOrIdent(text, i);\n } else if (startsComment(text, i)) {\n i = skipComment(text, i);\n } else if (ch !== undefined && /[A-Za-z_]/.test(ch)) {\n const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(text.slice(i));\n const word = m?.[0] ?? \"\";\n if (word.toUpperCase() === \"CHECK\") return i;\n i += Math.max(word.length, 1);\n } else {\n i++;\n }\n }\n return -1;\n}\n\n/**\n * Index just past `(…)` starting at `open` — paren-aware, and skipping every\n * string/identifier form, brackets included: `[a)b]` is a legal identifier\n * whose `)` must not close the group early. Comments too: a paren inside a\n * block or line comment must not move the depth. (The enum member grammar's\n * own whitespace walks stay strict on purpose — a comment between literals\n * refuses loudly per the one-shape contract, which is the designed outcome,\n * not a miscount.)\n */\nfunction matchingParenEnd(text: string, open: number): number {\n let depth = 0;\n let i = open;\n while (i < text.length) {\n const ch = text[i];\n if (startsStringOrIdent(text, i)) {\n i = skipStringOrIdent(text, i);\n continue;\n }\n if (startsComment(text, i)) {\n i = skipComment(text, i);\n continue;\n }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n if (depth === 0) return i + 1;\n }\n i++;\n }\n return -1;\n}\n\n/**\n * `enum` members for an added column, read from the catalog delta — the\n * second recorded consultation of syntax (after ATTACH/VACUUM's\n * refusal-by-name), scoped to stay small (0028 § stress test 2). The grammar\n * accepted is exactly one shape: `CHECK (<the-new-column> IN (<literals>))`\n * with the literals all strings or all numbers, agreeing with the declared\n * type. Everything else refuses, naming the shape and the hand-edit\n * alternative — a constraint silently dropped from the schema would be worse\n * than either.\n */\nfunction enumForAddedColumn(\n catalogBefore: string,\n catalogAfter: string,\n key: string,\n mapped: DeclaredMapping | undefined,\n): (string | number)[] | undefined {\n // The variable annotation (not just the return position) is what lets\n // control-flow analysis treat a `refuseShape()` call as terminating.\n const refuseShape: () => never = () => {\n throw new DocmetaError(\n `The CHECK on \"${key}\" is not the one shape DDL maps: \\`CHECK (${key} IN (…))\\` with all-string or all-number literals becomes \\`enum\\`. Anything else — an expression, another column, AND — is a hand edit to the schema file.`,\n );\n };\n const def = appendedColumnDef(catalogBefore, catalogAfter);\n if (def === undefined) {\n // Unreachable through ALTER ADD against docmeta-authored text today;\n // stated anyway so an engine that rewrites the catalog differently\n // refuses loudly instead of silently dropping a CHECK the user wrote.\n const count = (text: string): number => {\n let n = 0;\n for (let i = indexOfCheck(text, 0); i !== -1; i = indexOfCheck(text, i + 5)) {\n n++;\n }\n return n;\n };\n if (count(catalogAfter) > count(catalogBefore)) refuseShape();\n return undefined;\n }\n const checkAt = indexOfCheck(def, 0);\n if (checkAt === -1) return undefined;\n\n const i = skipWs(def, checkAt + \"CHECK\".length);\n if (def[i] !== \"(\") refuseShape();\n const end = matchingParenEnd(def, i);\n if (end === -1) refuseShape();\n // A second CHECK anywhere in the def is not the supported shape.\n if (indexOfCheck(def, end) !== -1) refuseShape();\n const inner = def.slice(i + 1, end - 1);\n\n // `<the-new-column> IN ( <literals> )`, and nothing else.\n let j = skipWs(inner, 0);\n const col = readIdentifier(inner, j);\n if (!col || col.value.toLowerCase() !== key.toLowerCase()) refuseShape();\n j = skipWs(inner, col.end);\n const kw = /^[A-Za-z]+/.exec(inner.slice(j));\n if (kw?.[0]?.toUpperCase() !== \"IN\") refuseShape();\n j = skipWs(inner, j + 2);\n if (inner[j] !== \"(\") refuseShape();\n const listEnd = matchingParenEnd(inner, j);\n if (listEnd === -1 || skipWs(inner, listEnd) !== inner.length) refuseShape();\n const list = inner.slice(j + 1, listEnd - 1);\n\n const members: (string | number)[] = [];\n let sawString = false;\n let sawNumber = false;\n let k = skipWs(list, 0);\n for (;;) {\n if (list[k] === \"'\") {\n const close = skipStringOrIdent(list, k);\n if (list[close - 1] !== \"'\" || close <= k + 1) refuseShape();\n members.push(list.slice(k + 1, close - 1).replaceAll(\"''\", \"'\"));\n sawString = true;\n k = close;\n } else {\n const m = /^[+-]?(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?/.exec(\n list.slice(k),\n );\n if (!m) refuseShape();\n members.push(Number(m[0]));\n sawNumber = true;\n k += m[0].length;\n }\n k = skipWs(list, k);\n if (k >= list.length) break;\n if (list[k] !== \",\") refuseShape();\n k = skipWs(list, k + 1);\n }\n if (members.length === 0) refuseShape();\n if (sawString && sawNumber) {\n // Homogeneity is part of the grammar, not a rule invented later.\n throw new DocmetaError(\n `The CHECK on \"${key}\" mixes string and number literals; an IN list maps to \\`enum\\` only as all strings or all numbers.`,\n );\n }\n if (mapped !== undefined) {\n const disagree = sawString\n ? mapped.type !== \"string\"\n : mapped.type === \"integer\"\n ? members.some((v) => typeof v === \"number\" && !Number.isInteger(v))\n : mapped.type !== \"number\";\n if (disagree) {\n throw new DocmetaError(\n `The CHECK on \"${key}\" lists ${sawString ? \"string\" : \"number\"} literals, but the declared type maps to ${mapped.type} — the members' JSON types must agree with the declared type, the same reconciliation the DEFAULT guard applies.`,\n );\n }\n }\n return members;\n}\n\n/**\n * The declared type and the DEFAULT are two halves of one statement, and\n * SQLite will happily store a default its own declaration cannot hold\n * (`INTEGER … DEFAULT 'high'` stores TEXT). Left unchecked, that writes a\n * schema requiring a type every backfilled file immediately violates — the\n * exact inverse of the ratchet staying green. Refused before any plan exists.\n *\n * Exported for the guard's own tests: `mapDeclaredType` always pairs a\n * format with a type today, but `SchemaOp` declares them independent, and\n * the format check below must hold for a format-only op too.\n */\nexport function assertDefaultsMatchDeclaredTypes(\n ops: SchemaOp[],\n cells: CellEffect[],\n): void {\n // JSON.stringify throws on bigint — a refusal must never crash while\n // trying to describe the value it is refusing.\n const show = (v: unknown): string =>\n typeof v === \"bigint\" ? `${String(v)}n` : (toJsonText(v) ?? \"undefined\");\n for (const op of ops) {\n // Adds only — and NOT gated on a declared type: an op with no mapped\n // type has nothing for the `ok` chain below to refuse (it falls through\n // to true), while the format check must still run.\n if (op.op !== \"add\") continue;\n for (const cell of cells) {\n if (cell.key !== op.key || cell.to === null || cell.to === undefined) {\n continue;\n }\n const to = cell.to;\n const ok =\n op.type === \"integer\"\n ? typeof to === \"bigint\" ||\n (typeof to === \"number\" && Number.isInteger(to))\n : op.type === \"number\"\n ? typeof to === \"number\" || typeof to === \"bigint\"\n : op.type === \"string\"\n ? typeof to === \"string\"\n : op.type === \"boolean\"\n ? // The reconciliation accepts only the SQL spellings 0, 1,\n // true, false — all of which the engine stores as 0/1.\n to === 0 || to === 1 || to === 0n || to === 1n\n : true;\n if (!ok) {\n throw new DocmetaError(\n op.type === \"boolean\"\n ? `ALTER declares \"${op.key}\" as boolean, but the DEFAULT backfills ${show(to)} — only 0, 1, true, or false reconcile with a boolean column.`\n : // `!ok` is unreachable with no declared type (the chain falls\n // through to true), so the fallback text never actually prints.\n `ALTER declares \"${op.key}\" as ${op.type ?? \"its declared type\"}, but the DEFAULT backfills ${show(to)} — the corpus would fail the schema it just gained. Match the DEFAULT to the declared type.`,\n );\n }\n // 0028 stress 4: `DATE DEFAULT 'yesterday'` sails through the engine\n // and through the broad-type check above; the format is validated with\n // the same ajv-formats machinery `validate` enforces it with, before\n // any plan exists. (Enums need no twin: SQLite itself refuses an ADD\n // whose DEFAULT violates its own CHECK.)\n if (\n op.format !== undefined &&\n typeof to === \"string\" &&\n !validatesFormat(op.format, to)\n ) {\n throw new DocmetaError(\n `ALTER declares \"${op.key}\" as format ${op.format}, but the DEFAULT backfills ${show(to)} — the corpus would fail the schema it just gained. Match the DEFAULT to the format.`,\n );\n }\n }\n }\n}\n\ninterface SchemaWrite {\n path: string;\n content: string;\n /**\n * Bytes the plan read from this path; apply refuses if they moved since —\n * the same contract corpus files get. Absent means the plan requires the\n * path to not exist (a fork target).\n */\n expected?: string;\n}\n\ninterface SchemaPlan {\n changes: QueryChange[];\n writes: SchemaWrite[];\n /**\n * ADD writes the schema after the corpus, so a mid-apply failure leaves\n * extra keys under an unchanged schema (still green) instead of a new\n * requirement without its backfill (red). DROP/RENAME write schema-first\n * for the mirror-image reason: files keep a key the schema merely no longer\n * declares.\n */\n schemaLast: boolean;\n}\n\n/** One schema of the resolved set, loaded exactly once. */\ntype SetMember =\n | {\n /** The ref exactly as the set spells it — what repoints must match. */\n ref: string;\n kind: \"file\";\n /** Resolved from the run's cwd, the same base `loadSchema` uses. */\n abs: string;\n /** The exact text read, for indent/EOL fidelity and pin hashing. */\n text: string;\n schema: Record<string, unknown>;\n }\n | {\n ref: string;\n kind: \"builtin\";\n /** The bundled id — the ref itself, or a published URL's alias. */\n builtinId: string;\n schema: Record<string, unknown>;\n };\n\n/** `properties`, when it is the object the mutation machinery can touch. */\nfunction propsOf(\n schema: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n const p = schema.properties;\n return p !== null && typeof p === \"object\" && !Array.isArray(p)\n ? (p as Record<string, unknown>)\n : undefined;\n}\n\n/** Does this schema constrain `key` — by declaring it, or by requiring it? */\nfunction constrains(member: SetMember, key: string): boolean {\n const props = propsOf(member.schema);\n if (props && key in props) return true;\n const required = member.schema.required;\n return Array.isArray(required) && required.some((r) => r === key);\n}\n\nconst FORK_IGNORE_TEXT: IgnoreGuardText = {\n refusal: (target) =>\n `Refusing to fork into \"${target}\": git reports it as ignored. The forked schema must be committed — an ignored copy validates on this machine and is simply missing in CI, where the failure reads as a schema nobody changed. Drop the .gitignore rule covering this path, or evolve a tracked local schema instead.`,\n unchecked: (where) =>\n `could not check .gitignore for \"${where}\" (no repository here, or no git on PATH). The forked schema must be committed — make sure this path is tracked.`,\n};\n\n/** Preserve the reference text's line endings in a freshly serialized body. */\nfunction matchEol(reference: string, text: string): string {\n return reference.includes(\"\\r\\n\") ? text.replace(/\\n/g, \"\\r\\n\") : text;\n}\n\n/** A path the way reports spell it: relative to the run's base, posix. */\nfunction displayPath(ctx: RunContext, abs: string): string {\n const rel = posixRelative(ctx.base, abs);\n return rel === \"\" || rel.startsWith(\"..\") ? abs : rel;\n}\n\n/** Refuse a schema write outside the boundary every schema *read* honors. */\nfunction assertSchemaWriteWithin(ctx: RunContext, abs: string): void {\n const within = posixRelative(ctx.trustRoot.dir, abs);\n if (within !== \"\" && !within.startsWith(\"..\") && !isAbsolute(within)) return;\n throw new DocmetaError(\n `The resolved schema \"${abs}\" lives outside ${ctx.trustRoot.dir}; DDL edits schemas inside the repository. Evolve it where it lives, or vendor a copy in.`,\n );\n}\n\n/**\n * Canonical identity of a local schema path: absolute, case-folded on win32 —\n * where `./Schemas/House.json` and `schemas/house.json` name one file — and\n * case-preserved on POSIX, where two casings really are two files.\n */\nfunction foldPath(p: string): string {\n const abs = resolve(p);\n return process.platform === \"win32\" ? abs.toLowerCase() : abs;\n}\n\n/**\n * The config's file-ref pins keyed by canonical path rather than ref text.\n * `collectSchemaPins` keys carry the config's (possibly rebased) spelling; a\n * `-s` ref typed even slightly differently — `schemas/x.json` for\n * `./schemas/x.json` — must still find its pin, or pre-edit verification\n * silently skips and the un-refreshed pin refuses every later run.\n *\n * `ctx.cwd` is the right base for these keys: `resolveRunConfig` passes every\n * loaded config through `rebaseConfigSchemaRefs`, which rewrites file refs to\n * ABSOLUTE paths whenever configDir differs from cwd (where `resolve` is the\n * identity) and leaves them cwd-relative-correct when the two coincide —\n * pinned by the configDir ≠ cwd test in query-ddl.test.ts.\n */\nfunction filePinsByPath(ctx: RunContext): Map<string, SchemaPin> {\n const byPath = new Map<string, SchemaPin>();\n for (const [ref, pin] of collectSchemaPins(ctx.config)) {\n if (classifyRef(ref).kind !== \"file\") continue;\n byPath.set(foldPath(resolve(ctx.cwd, ref)), pin);\n }\n return byPath;\n}\n\n/**\n * Load every schema in the set, through the same conventions the rest of the\n * pipeline reads them with: refs resolve from the run's cwd (the\n * `LoadSchemaOptions.fileBase` contract), text is BOM-stripped before parsing\n * only, integrity pins are verified against the exact bytes, and a published\n * built-in URL is the built-in it aliases. Any plain URL refuses: DDL cannot\n * inspect (let alone edit) a schema a server owns, and sibling-conflict\n * checks below need to see the whole set.\n */\nasync function loadSetMembers(\n refs: readonly string[],\n ctx: RunContext,\n): Promise<SetMember[]> {\n const pins = filePinsByPath(ctx);\n const members: SetMember[] = [];\n // Identity-level dedupe on top of the resolver's textual one: two -s\n // spellings of one file (`./x.json` vs `x.json`, case variants on win32)\n // must load one member, or ADD refuses naming one file twice and DROP\n // hands out an unfollowable \"evolve them separately\". Builtins dedupe by\n // id for the same reason — the raw id and its published URL are one schema.\n const seenFiles = new Set<string>();\n const seenBuiltins = new Set<string>();\n for (const ref of refs) {\n // A registered id (proposal 0070) names a local file the config vouches\n // for, hand-maintained like any path ref, so it is edited in place rather\n // than forked as a builtin, and a registered URL id is not refused.\n const registered = ctx.config?.registered?.get(ref);\n const { kind } = registered !== undefined ? { kind: \"file\" as const } : classifyRef(ref);\n if (kind === \"url\" && !isPublishedBuiltinUrl(ref)) {\n throw new DocmetaError(\n `\"${ref}\" in the resolved schema set is a URL — DDL edits local schemas only. Vendor it first (manni meta schemas vendor), then evolve the local copy.`,\n );\n }\n if (kind === \"builtin\" || kind === \"url\") {\n const builtinId =\n kind === \"url\"\n ? (publishedBuiltins().find((b) => b.url === ref || b.legacyUrl === ref)?.id ?? ref)\n : ref;\n if (seenBuiltins.has(builtinId)) continue;\n seenBuiltins.add(builtinId);\n members.push({\n ref,\n kind: \"builtin\",\n builtinId,\n schema: await loadSchema(builtinId),\n });\n continue;\n }\n const abs = registered?.path ?? resolve(ctx.cwd, ref);\n const canon = foldPath(abs);\n if (seenFiles.has(canon)) continue;\n seenFiles.add(canon);\n let text: string;\n try {\n text = await readFile(abs, \"utf8\");\n } catch {\n throw new DocmetaError(\n `Schema file not found: \"${ref}\" (looked at ${abs}).`,\n );\n }\n const pin = pins.get(canon);\n if (pin?.integrity !== undefined) {\n if (integrityOf(Buffer.from(text, \"utf8\")) !== pin.integrity) {\n throw new DocmetaError(\n `Schema \"${ref}\" does not match its recorded integrity; its contents have moved since it was vendored. Re-vendor it before evolving it.`,\n );\n }\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(stripBom(text));\n } catch {\n throw new DocmetaError(\n `Schema \"${ref}\" is not valid JSON, so DDL cannot read it. Fix the file first.`,\n );\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new DocmetaError(\n `Schema \"${ref}\" is not an object schema; DDL edits \\`properties\\` and \\`required\\`, which only an object schema carries.`,\n );\n }\n members.push({\n ref,\n kind: \"file\",\n abs,\n text,\n schema: parsed as Record<string, unknown>,\n });\n }\n return members;\n}\n\n/**\n * 0024's DDL pipeline: resolve the run's single schema set, pick the target,\n * and plan the mutation — an in-place edit for a hand-maintained local file,\n * a fork (plus reference repoints) for an immutable builtin. Every refusal\n * here costs nothing: no file has been touched.\n */\nasync function planSchemaMutation(\n ops: SchemaOp[],\n entries: QueryEntry[],\n ctx: RunContext,\n): Promise<SchemaPlan> {\n // One action per statement is SQLite's own ALTER grammar; a second op here\n // would mean the effect diff misread the projection.\n const [op, ...extraOps] = ops;\n if (!op) return { changes: [], writes: [], schemaLast: false };\n if (extraOps.length > 0) {\n throw new DocmetaError(\n \"One DDL action per statement; this statement produced several column effects, which DDL cannot attribute to one schema edit.\",\n );\n }\n if (entries.length === 0) {\n // Two rationales for one refusal: without -s the set comes from the\n // corpus, so no corpus means no set; with -s the set is known, but the\n // backfill and the corpus-satisfies-the-evolved-set reconciliation\n // still run over the loaded files (review of #139, finding 9).\n throw new DocmetaError(\n ctx.cliSchemas !== undefined\n ? \"DDL needs at least one loaded file: the statement's backfill and the check that the corpus satisfies the evolved set both run over the loaded files, and this run matched none.\"\n : \"DDL needs at least one loaded file: the schema it edits is the one the corpus resolves, and this run matched no files.\",\n );\n }\n\n // One schema set for the whole run, or nothing mutates. Resolution runs\n // with the same trust boundary as validate — a document may not name a\n // schema outside the repository, least of all as a write target.\n //\n // 0030: -s replaces the walk outright — the deduped CLI refs ARE the set\n // (source \"cli\"), unanimous by construction, so neither the split refusal\n // nor the default-set refusal below can arise. Everything after the set is\n // chosen — member loading, trust, every ownership guard — is one shared\n // path: -s picks the contract, never what the contract says.\n let refs: string[] | undefined;\n const sources = new Set<string>();\n // Some file runs on the default set alone, which names no schema of the\n // corpus's own to evolve (proposal 0070 widened the default set, so this is\n // read off the set rather than off which tier produced it).\n let defaultOnly = false;\n const groupIndexes = new Set<number>();\n let splitLabel: string | undefined;\n if (ctx.cliSchemas !== undefined) {\n // One implementation of CLI-ref handling across commands: the resolver's\n // own cli branch (textual dedupe, source \"cli\"), called exactly once for\n // the run — never per file; the counter seam in resolution-walk.test.ts\n // pins that. `filePath` feeds only override matching, which the cli\n // branch never reaches. The path-canonical dedupe file members also need\n // lives in `loadSetMembers`, where refs are resolved anyway — the\n // resolver's dedupe stays textual by design for validate.\n refs = resolveSchemaSetWithSource({\n filePath: \"\",\n cliSchemas: ctx.cliSchemas,\n config: ctx.config,\n fileBase: ctx.cwd,\n trustRoot: ctx.trustRoot,\n }).schemas;\n } else {\n for (const e of entries) {\n let resolved;\n try {\n resolved = resolveSchemaSetWithSource({\n filePath: e.label,\n fileSchema: e.extracted.data[FILE_SCHEMA_KEY],\n config: ctx.config,\n memberOf: ctx.memberships(e.label),\n fileBase: ctx.cwd,\n trustRoot: ctx.trustRoot,\n onNotice: ctx.onNotice,\n });\n } catch (err) {\n // `coerceFileSchema` throws a plain Error; either way the file that\n // carried the bad `$schema` is the one fact the user needs.\n throw new DocmetaError(`\"${e.label}\": ${errorMessage(err)}`);\n }\n sources.add(resolved.source);\n if (isDefaultSetOnly(resolved)) defaultOnly = true;\n if (resolved.overrideIndex !== undefined) {\n groupIndexes.add(resolved.overrideIndex);\n }\n if (refs === undefined) {\n refs = resolved.schemas;\n } else if (\n // Order-insensitive, like seqResolvesToRunSet below: a document that\n // lists the same refs in another order names the same contract.\n splitLabel === undefined &&\n JSON.stringify([...refs].sort()) !==\n JSON.stringify([...resolved.schemas].sort())\n ) {\n // The walk finishes before refusing, so the refusal can name every\n // override group the run spans, not only the first two it met.\n splitLabel = e.label;\n }\n }\n }\n if (splitLabel !== undefined) {\n // With named override groups (0027) the remedy is finally spellable:\n // list each group by name with its glob, so \"one group's files\" is a\n // copy-pastable next step rather than a concept.\n const overrides = ctx.config?.overrides ?? [];\n const named = [...groupIndexes]\n .sort((a, b) => a - b)\n .flatMap((i) => {\n const o = overrides[i];\n if (o?.collection === undefined) return [];\n // The globs come from the declaration now (0041): the override names a\n // collection, and the collection is where its `paths:` live.\n const declared = ctx.collections.find((c) => c.name === o.collection);\n return [\n `${o.collection} (${overrideGlobs(declared?.paths).join(\", \")})`,\n ];\n });\n const last = named[named.length - 1];\n // 0030: -s makes the set unanimous by construction, so it is the third\n // remedy — the direct one — in both spellings of this refusal.\n const remedy =\n named.length >= 2 && last !== undefined\n ? `The run spans ${[named.slice(0, -1).join(\", \"), last].join(\" and \")}; re-run over one group's files, or pass -s <schema> to name the contract directly.`\n : \"Scope the run to one override group, or pass -s <schema> to name the contract directly.\";\n throw new DocmetaError(\n `DDL needs the corpus to resolve to one schema set, and this run's is split (\"${splitLabel}\" resolves differently). ${remedy}`,\n );\n }\n if (!refs || defaultOnly) {\n throw new DocmetaError(\n \"DDL edits the resolved schema, and this corpus runs on the built-in default set. Name a schema to evolve — in the config's `schemas:`, an override group, or the files' own `$schema`. For data-only edits the UPDATE spellings cover every case: `SET k = v` (backfill via `WHERE k IS NULL`), `SET k = NULL` to remove a key, and paired SETs to rename one.\",\n );\n }\n\n const members = await loadSetMembers(refs, ctx);\n const fileMembers = members.flatMap((m) => (m.kind === \"file\" ? [m] : []));\n const builtinMembers = members.flatMap((m) =>\n m.kind === \"builtin\" ? [m] : [],\n );\n\n // The target: for ADD the single local file (else the builtin, forked); for\n // DROP/RENAME the one schema that constrains the key. \"One\" is load-bearing\n // both ways — a second declarer, or a sibling that still requires a dropped\n // key, would leave the corpus failing a schema this statement never named.\n let target: SetMember;\n if (op.op === \"add\") {\n if (fileMembers.length > 1) {\n throw new DocmetaError(\n `The resolved set names ${String(fileMembers.length)} local schema files (${fileMembers.map((m) => m.ref).join(\", \")}) — DDL cannot tell which one to evolve. Scope the run to an override group that names one, set the files' \\`$schema\\` to the schema to evolve, or pass -s <schema> to name it directly.`,\n );\n }\n // The same ambiguity rule as several local files: with no local file\n // and several builtins, \"the one to fork\" would be decided by flag or\n // list order — a silent pick where every sibling refusal names its\n // reasons (review of #139, finding 6).\n if (fileMembers.length === 0 && builtinMembers.length > 1) {\n throw new DocmetaError(\n `The resolved set names ${String(builtinMembers.length)} built-ins (${builtinMembers.map((m) => m.builtinId).join(\", \")}) and no local schema file — DDL cannot tell which one to fork. Name one with -s, or evolve a local schema.`,\n );\n }\n const chosen = fileMembers[0] ?? builtinMembers[0];\n if (!chosen) {\n throw new DocmetaError(\n `No local schema or built-in in the resolved set takes this DDL.`,\n );\n }\n target = chosen;\n const targetProps = propsOf(target.schema);\n if (target.schema.properties !== undefined && targetProps === undefined) {\n throw new DocmetaError(\n `Schema \"${target.ref}\": its \"properties\" is not an object, so DDL cannot edit it.`,\n );\n }\n if (targetProps && op.key in targetProps) {\n throw new DocmetaError(\n `\"${op.key}\" is already declared in ${target.ref}; ALTER ADD would overwrite its subschema, constraints included. Edit the schema file directly to change an existing property.`,\n );\n }\n for (const m of members) {\n if (m !== target && constrains(m, op.key)) {\n throw new DocmetaError(\n `\"${op.key}\" is already declared by ${m.ref} in the same schema set; adding it to ${target.ref} would put two contracts on one key. Evolve ${m.ref} instead, or scope the run to a set with one owner of the key.`,\n );\n }\n }\n } else {\n // Destructuring narrows without a third guard: `sole` absent IS the\n // zero-declarers case, and `rest` non-empty is the shared-key refusal.\n const [sole, ...rest] = members.filter((m) => constrains(m, op.key));\n if (!sole) {\n throw new DocmetaError(\n `No schema in the resolved set declares \"${op.key}\".`,\n );\n }\n if (rest.length > 0) {\n throw new DocmetaError(\n `\"${op.key}\" is constrained by ${String(rest.length + 1)} schemas in the set (${[sole, ...rest].map((m) => m.ref).join(\", \")}); a DDL statement edits one schema. Evolve them separately.`,\n );\n }\n target = sole;\n if (op.op === \"rename\") {\n const to = op.renamedTo ?? op.key;\n for (const m of members) {\n if (constrains(m, to)) {\n throw new DocmetaError(\n `\"${to}\" is already declared${m === target ? \"\" : ` by ${m.ref}`} in the schema set; renaming \"${op.key}\" onto it would overwrite that declaration. Pick another name, or evolve that schema first.`,\n );\n }\n }\n }\n }\n\n const writes: SchemaWrite[] = [];\n const changes: QueryChange[] = [];\n const configEdit: ConfigEditRequest = {};\n\n let baseObject: Record<string, unknown>;\n let schemaAbs: string;\n /** Indent and EOL come from the file being edited; a fork starts fresh. */\n let styleReference: string;\n let schemaExpected: string | undefined;\n let forkedFrom: string | undefined;\n if (target.kind === \"file\") {\n schemaAbs = target.abs;\n baseObject = target.schema;\n styleReference = target.text;\n schemaExpected = target.text;\n assertSchemaWriteWithin(ctx, schemaAbs);\n } else {\n // A builtin is immutable by invariant — fork it beside the config and\n // repoint every reference: the config entry, and any in-file `$schema`.\n forkedFrom = target.builtinId;\n const [, name, ver] = target.builtinId.split(\":\");\n // Segments reach the filesystem; every shipped id is [a-z0-9._-] but the\n // filename must not trust that a future one stays so.\n const safe = (s: string): string => s.replace(/[^A-Za-z0-9._-]/g, \"-\");\n const forkName = `${safe(name ?? \"schema\")}-${safe(ver ?? \"0\")}.local.json`;\n schemaAbs = resolve(ctx.configDir ?? ctx.cwd, \"schemas\", forkName);\n assertSchemaWriteWithin(ctx, schemaAbs);\n if (existsSync(schemaAbs)) {\n throw new DocmetaError(\n `\"${displayPath(ctx, schemaAbs)}\" already exists; refusing to overwrite it with a fork of ${target.builtinId}.`,\n );\n }\n await assertNotIgnored(\n schemaAbs,\n dirname(schemaAbs),\n ctx.cwd,\n ctx.onNotice,\n FORK_IGNORE_TEXT,\n );\n baseObject = { ...target.schema, $id: `${target.builtinId}+local` };\n styleReference = \"\\n\";\n // Repoints match refs that NAME THE BUILTIN — the raw id or its\n // published URL — not the spelling the run's set happened to use. A\n // cli-named set has no reason to agree textually with the config or\n // the files, and the exact-string match orphaned every fork whose\n // corpus spelled the builtin differently (review of #139, finding 1).\n const forkOf = target.builtinId;\n const builtinIdOf = (r: string): string | undefined => {\n const { kind } = classifyRef(r);\n if (kind === \"builtin\") return r;\n if (kind === \"url\" && isPublishedBuiltinUrl(r)) {\n return publishedBuiltins().find((b) => b.url === r || b.legacyUrl === r)?.id;\n }\n return undefined;\n };\n const namesFork = (r: unknown): boolean =>\n typeof r === \"string\" && builtinIdOf(r) === forkOf;\n if (ctx.configPath !== undefined && ctx.configDir !== undefined) {\n const rel = posixRelative(ctx.configDir, schemaAbs);\n configEdit.repoint = {\n oldRef: target.ref,\n newRef: rel.startsWith(\".\") ? rel : `./${rel}`,\n // The resolved-set path keeps its whole-set gate; a cli-named set\n // can never satisfy it, so it matches by builtin identity instead.\n ...(ctx.cliSchemas !== undefined ? { matchRef: namesFork } : {}),\n };\n }\n const docRel = posixRelative(ctx.cwd, schemaAbs);\n const newRefForDocs = docRel.startsWith(\".\") ? docRel : `./${docRel}`;\n for (const e of entries) {\n const fileSchema = e.extracted.data[FILE_SCHEMA_KEY];\n if (namesFork(fileSchema)) {\n changes.push({\n file: e.label,\n key: FILE_SCHEMA_KEY,\n from: fileSchema,\n to: newRefForDocs,\n written: false,\n });\n } else if (Array.isArray(fileSchema)) {\n // The documented list spelling repoints element-wise; the rest of\n // the list is not this statement's business.\n const list = fileSchema.filter(\n (r): r is string => typeof r === \"string\",\n );\n if (list.length === fileSchema.length && list.some(namesFork)) {\n changes.push({\n file: e.label,\n key: FILE_SCHEMA_KEY,\n from: fileSchema,\n to: list.map((r) => (namesFork(r) ? newRefForDocs : r)),\n written: false,\n });\n }\n }\n }\n }\n // Doc-side repoints planned so far — the fork block is the only writer of\n // `changes` up to here, so this is the count the orphan check below needs.\n const docRepoints = changes.length;\n\n // BOM-strip before sniffing: the regex anchors at the string head, and a\n // BOM'd file would silently fall back to two-space and be reformatted.\n const indent = detectJsonIndent(stripBom(styleReference));\n const mutated = mutateSchemaObject(baseObject, op);\n const content = matchEol(\n styleReference,\n `${JSON.stringify(mutated, null, indent)}\\n`,\n );\n changes.unshift({\n file: displayPath(ctx, schemaAbs),\n schema: true,\n op: op.op,\n key: op.key,\n ...(op.renamedTo !== undefined ? { renamedTo: op.renamedTo } : {}),\n ...(op.type !== undefined ? { type: op.type } : {}),\n ...(op.format !== undefined ? { format: op.format } : {}),\n ...(op.enum !== undefined ? { enum: op.enum } : {}),\n ...(op.required ? { required: true } : {}),\n ...(forkedFrom !== undefined ? { forkedFrom } : {}),\n written: false,\n });\n writes.push({\n path: schemaAbs,\n content,\n ...(schemaExpected !== undefined ? { expected: schemaExpected } : {}),\n });\n\n // An in-place edit of a pinned schema carries its pin along: the pin is a\n // promise about the bytes, and the bytes just changed on purpose. Looked\n // up by canonical path, like the verification in `loadSetMembers` — the\n // -s spelling must never decide whether a pin is found.\n if (target.kind === \"file\") {\n const pin = filePinsByPath(ctx).get(foldPath(target.abs));\n if (pin?.integrity !== undefined) {\n configEdit.integrity = {\n path: target.abs,\n value: integrityOf(Buffer.from(content, \"utf8\")),\n };\n }\n }\n\n let configRepointed = false;\n if (configEdit.repoint || configEdit.integrity) {\n const edited = await planConfigEdit(ctx, configEdit, refs);\n changes.push(...edited.changes);\n if (edited.write) writes.push(edited.write);\n configRepointed = edited.repointed;\n if (\n configEdit.repoint &&\n !edited.repointed &&\n (sources.has(\"config\") || sources.has(\"override\"))\n ) {\n throw new DocmetaError(\n `The run resolved ${configEdit.repoint.oldRef} through the config, but no \\`schemas:\\` entry in it matches — refusing to fork with a reference that cannot be repointed.`,\n );\n }\n }\n // A cli-named fork that nothing would resolve afterwards is an orphan:\n // the statement reports success while validate keeps resolving the\n // un-evolved builtin. Refused with nothing written — the mirror of the\n // config-source no-repoint refusal above (review of #139, finding 1).\n if (\n ctx.cliSchemas !== undefined &&\n forkedFrom !== undefined &&\n !configRepointed &&\n docRepoints === 0\n ) {\n throw new DocmetaError(\n `The fork of ${forkedFrom} would be orphaned: nothing in this corpus resolves it — no config \\`schemas:\\` entry and no loaded file's \\`$schema\\` names the builtin, so nothing would validate against \"${displayPath(ctx, schemaAbs)}\" after the run. No schema or file writes were applied${\n ctx.target === undefined\n ? \"\"\n : \"; the --db export was still written and reflects the statement\"\n }. Add the schema to the config (or the files' \\`$schema\\`) first, then evolve it.`,\n );\n }\n\n return { changes, writes, schemaLast: op.op === \"add\" };\n}\n\n/** Apply one DDL op to a schema object, touching properties/required only. */\nfunction mutateSchemaObject(\n schema: Record<string, unknown>,\n op: SchemaOp,\n): Record<string, unknown> {\n const without = (\n obj: Record<string, unknown>,\n key: string,\n ): Record<string, unknown> =>\n Object.fromEntries(Object.entries(obj).filter(([k]) => k !== key));\n let props = { ...(propsOf(schema) ?? {}) };\n // Spec-invalid non-string entries are dropped rather than carried: every\n // comparison below is against a string key, so they could only persist as\n // junk this rewrite pretended not to see.\n let required = Array.isArray(schema.required)\n ? (schema.required as unknown[]).filter(\n (r): r is string => typeof r === \"string\",\n )\n : [];\n switch (op.op) {\n case \"add\":\n props[op.key] = {\n ...(op.type !== undefined ? { type: op.type } : {}),\n ...(op.format !== undefined ? { format: op.format } : {}),\n ...(op.enum !== undefined ? { enum: op.enum } : {}),\n };\n if (op.required && !required.includes(op.key)) required.push(op.key);\n break;\n case \"drop\":\n props = without(props, op.key);\n required = required.filter((r) => r !== op.key);\n break;\n case \"rename\": {\n const to = op.renamedTo ?? op.key;\n const moved = props[op.key];\n props = without(props, op.key);\n // A required-only key (no `properties` entry — legal, if odd) renames\n // to a required-only key: the guard keeps the faithful shape rather\n // than fabricating an empty subschema the author never declared.\n if (moved !== undefined) props[to] = moved;\n required = required.map((r) => (r === op.key ? to : r));\n break;\n }\n }\n // Set-or-remove explicitly: a spread of the original schema would carry the\n // old `required` back in whenever the new list is empty.\n const out: Record<string, unknown> = { ...schema, properties: props };\n if (required.length > 0) out.required = required;\n else delete out.required;\n return out;\n}\n\ninterface ConfigEditRequest {\n /**\n * A builtin fork: point the entry that named the builtin at the fork.\n * With `matchRef` (a cli-named fork), every entry the predicate accepts is\n * repointed wherever it appears; without it, only entries spelled exactly\n * `oldRef` inside a sequence that resolves to the run's whole set are.\n */\n repoint?: {\n oldRef: string;\n newRef: string;\n matchRef?: (raw: string) => boolean;\n };\n /**\n * An in-place edit of a pinned schema: the pin over the new bytes. `path`\n * is the schema's absolute path — entries match by resolved path, so the\n * config's spelling and the run's never have to agree textually.\n */\n integrity?: { path: string; value: string };\n}\n\n/**\n * Plan an edit to the governing config — the file discovery actually loaded,\n * at `ctx.configPath` — through the YAML Document API, so every comment and\n * untouched line survives. Both spellings of a `schemas:` entry are handled:\n * the bare string, and the `{ref, source, integrity}` mapping.\n *\n * A repoint touches only the sequences that resolve to the run's schema set.\n * An override group with a different set is somebody else's contract; the\n * single-set guard proved it governs none of this run's files, and rewriting\n * it would change validation for files this statement never loaded.\n */\nasync function planConfigEdit(\n ctx: RunContext,\n edit: ConfigEditRequest,\n runRefs: readonly string[],\n): Promise<{ write?: SchemaWrite; changes: QueryChange[]; repointed: boolean }> {\n const { configPath, configDir } = ctx;\n if (configPath === undefined || configDir === undefined) {\n return { changes: [], repointed: false };\n }\n const text = await readFile(configPath, \"utf8\");\n // BOM-strip like every other parse of file text; `expected`/`matchEol`\n // below still see the raw bytes, which is what freshness and EOL are about.\n const doc = parseDocument(stripBom(text));\n const display = displayPath(ctx, configPath);\n\n const rawRefOf = (item: unknown): string | undefined => {\n if (isScalar(item) && typeof item.value === \"string\") return item.value;\n if (isMap(item)) {\n const ref = item.get(\"ref\");\n if (typeof ref === \"string\") return ref;\n }\n return undefined;\n };\n // The YAML holds refs as written; the run's set holds them rebased. Spell\n // the raw ones the same way before comparing.\n const rebaseRaw = (raw: string): string =>\n classifyRef(raw).kind === \"file\" && !isAbsolute(raw)\n ? resolve(configDir, raw)\n : raw;\n // Both sides through the same rebase: `runRefs` is raw whenever the config\n // sat in the working directory (rebasing was the identity there).\n const wantSet = runRefs.map(rebaseRaw).sort().join(\"\\n\");\n const seqResolvesToRunSet = (node: unknown): boolean => {\n if (!isSeq(node)) return false;\n const refs = node.items\n .map(rawRefOf)\n .flatMap((r) => (r === undefined ? [] : [rebaseRaw(r)]));\n return refs.length === node.items.length &&\n [...refs].sort().join(\"\\n\") === wantSet;\n };\n\n const repoint = (node: unknown): number => {\n if (!edit.repoint || !isSeq(node)) return 0;\n const spec = edit.repoint;\n // `matchRef` (a cli-named fork) matches entries by builtin identity in\n // every sequence: an entry naming the forked builtin is this statement's\n // business wherever it lives. The whole-set gate stays for the\n // resolved-set path, where rewriting another group's sequence would\n // change validation for files the statement never loaded.\n if (spec.matchRef === undefined && !seqResolvesToRunSet(node)) return 0;\n const wants = (raw: string): boolean =>\n spec.matchRef ? spec.matchRef(raw) : raw === spec.oldRef;\n let n = 0;\n for (const item of node.items) {\n const raw = rawRefOf(item);\n if (raw === undefined || !wants(raw)) continue;\n if (isScalar(item)) {\n item.value = spec.newRef;\n n += 1;\n } else if (isMap(item)) {\n item.set(\"ref\", spec.newRef);\n n += 1;\n }\n }\n return n;\n };\n // Where the tool's keys live in this file. A family `manni.config.yaml`\n // holds them under `meta:`; a legacy per-tool file *is* the section, so its\n // keys are at the top level. Reading the top level unconditionally finds\n // nothing in the family shape, which is the documented default since\n // proposal 0033 — every fork and every pin refresh then refused with\n // \"no `schemas:` entry in it matches\" against a config that plainly has one.\n // The suite missed it because every fixture was a legacy file until 0041.\n const root = ctx.configSection === undefined ? doc : doc.get(ctx.configSection, true);\n const keyOf = (key: string): unknown =>\n root === doc ? doc.get(key, true) : isMap(root) ? root.get(key, true) : undefined;\n\n const topSeq = keyOf(\"schemas\");\n let repointCount = repoint(topSeq);\n const overrides = keyOf(\"overrides\");\n if (isSeq(overrides)) {\n for (const entry of overrides.items) {\n if (isMap(entry)) repointCount += repoint(entry.get(\"schemas\", true));\n }\n }\n const repointed = repointCount > 0;\n\n let pinFrom: unknown;\n let pinned = false;\n if (edit.integrity && isSeq(topSeq)) {\n // Pins live on top-level mapping entries only — that is where\n // `collectSchemaPins` reads them from. Matching is by resolved path (a\n // raw config ref is config-relative), so no spelling has to agree.\n const wantPath = foldPath(edit.integrity.path);\n for (const item of topSeq.items) {\n if (!isMap(item)) continue;\n const raw = rawRefOf(item);\n if (raw === undefined || classifyRef(raw).kind !== \"file\") continue;\n const abs = isAbsolute(raw) ? raw : resolve(configDir, raw);\n if (foldPath(abs) !== wantPath) continue;\n pinFrom = item.get(\"integrity\");\n item.set(\"integrity\", edit.integrity.value);\n pinned = true;\n }\n }\n\n const changes: QueryChange[] = [];\n if (repointed && edit.repoint) {\n changes.push({\n file: display,\n config: true,\n key: \"schemas\",\n from: edit.repoint.oldRef,\n to: edit.repoint.newRef,\n written: false,\n });\n }\n if (pinned && edit.integrity) {\n changes.push({\n file: display,\n config: true,\n key: \"integrity\",\n from: pinFrom,\n to: edit.integrity.value,\n written: false,\n });\n }\n if (!repointed && !pinned) return { changes: [], repointed };\n return {\n write: {\n path: configPath,\n content: matchEol(text, doc.toString({ lineWidth: 0 })),\n expected: text,\n },\n changes,\n repointed,\n };\n}\n\ntype FileType = \"boolean\" | \"number\" | \"bigint\" | \"string\" | \"array\" | \"object\";\n\nfunction fileTypeOf(value: unknown): FileType | undefined {\n if (value === null || value === undefined) return undefined;\n if (Array.isArray(value)) return \"array\";\n const t = typeof value;\n if (t === \"boolean\" || t === \"number\" || t === \"bigint\" || t === \"string\") {\n return t;\n }\n return t === \"object\" ? \"object\" : undefined;\n}\n\n/**\n * File-space changes from the projection diff — 0022's inverse map plus\n * 0024's file-level kinds. Type precedence for a restored cell: the file's\n * own original type, then the column's dominant type, then storage as-is.\n * Failures refuse by file and key rather than guess.\n */\nfunction buildChanges(\n diff: ProjectionDiff,\n entries: QueryEntry[],\n sentinel: string,\n ctx: RunContext,\n renameHints: readonly { from: string; to: string }[] = [],\n /** Keys a DDL add declared boolean: their backfill restores as booleans. */\n booleanAdds: ReadonlySet<string> = new Set(),\n): QueryChange[] {\n const effects = diff.cells;\n const originals = new Map(entries.map((e) => [e.label, e.extracted.data]));\n const meta = new Map(entries.map((e) => [e.label, e.extracted]));\n const dominant = new Map<string, FileType | undefined>();\n const dominantFor = (key: string): FileType | undefined => {\n if (dominant.has(key)) return dominant.get(key);\n const counts = new Map<FileType, number>();\n for (const e of entries) {\n const t = fileTypeOf(e.extracted.data[key]);\n if (t) counts.set(t, (counts.get(t) ?? 0) + 1);\n }\n let best: FileType | undefined;\n let bestN = 0;\n let tied = false;\n for (const [t, n] of counts) {\n if (n > bestN) [best, bestN, tied] = [t, n, false];\n else if (n === bestN) tied = true;\n }\n const result = tied ? undefined : best;\n dominant.set(key, result);\n return result;\n };\n\n const restoreValue = (\n file: string,\n key: string,\n to: unknown,\n targetType: FileType | undefined,\n ): unknown => {\n // The variable annotation (not just the return position) is what lets\n // control-flow analysis treat a `refuse(...)` call as terminating.\n const refuse: (why: string) => never = (why) => {\n throw new DocmetaError(`\"${key}\" in ${file}: ${why}`);\n };\n // JSON.stringify throws on bigint — a refusal must never crash while\n // trying to describe the value it is refusing.\n const show = (v: unknown): string =>\n typeof v === \"bigint\" ? `${String(v)}n` : (toJsonText(v) ?? \"undefined\");\n if (to instanceof Uint8Array) refuse(\"a BLOB cannot be written back\");\n if (to === null || targetType === undefined) return to;\n switch (targetType) {\n case \"boolean\":\n // A SQL expression can come back as bigint; 1n is as boolean as 1.\n if (to === 1 || to === 1n) return true;\n if (to === 0 || to === 0n) return false;\n refuse(`${show(to)} is not a boolean`);\n case \"array\":\n case \"object\": {\n if (typeof to !== \"string\") {\n refuse(`${show(to)} is not JSON text for a ${targetType}`);\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(to);\n } catch {\n refuse(`the new value is not valid JSON for a ${targetType}`);\n }\n const kind = Array.isArray(parsed) ? \"array\" : typeof parsed;\n if (kind !== targetType) {\n refuse(`the new value is ${kind}, and the key holds ${targetType}`);\n }\n return parsed;\n }\n case \"number\":\n case \"bigint\":\n if (typeof to !== \"number\" && typeof to !== \"bigint\") {\n refuse(`${show(to)} is not a number`);\n }\n return to;\n case \"string\":\n if (typeof to !== \"string\") {\n refuse(`${show(to)} is not a string; quote it in the statement`);\n }\n return to;\n }\n return to;\n };\n\n // Key-rename pairing pre-pass (per file): a deletion of `a` and a creation\n // of `b` whose SQL value equals `bindValue(original a)` is a rename, and it\n // carries the original file value verbatim — an array must never round-trip\n // through its JSON-text projection (0024 § stress test 1).\n type Pair = { key: string; renamedFrom: string; to: unknown };\n const consumedDeletes = new Set<CellEffect>();\n const pairForCreate = new Map<CellEffect, Pair>();\n const byFile = new Map<string, CellEffect[]>();\n for (const e of effects) {\n const list = byFile.get(e.file) ?? [];\n list.push(e);\n byFile.set(e.file, list);\n }\n // A DDL column rename is authoritative before any value matching: the pair\n // comes from the column diff, so it carries an explicit-null value the\n // generic pass below cannot see (a NULL cell is a deletion, not an add).\n for (const hint of renameHints) {\n for (const [file, list] of byFile) {\n const data = originals.get(file) ?? {};\n if (data[hint.from] === undefined) continue;\n const del = list.find(\n (e) =>\n e.key === hint.from &&\n (e.to === null || e.to === undefined) &&\n !consumedDeletes.has(e),\n );\n const add = list.find(\n (e) => e.key === hint.to && !pairForCreate.has(e),\n );\n if (!del || !add) continue;\n consumedDeletes.add(del);\n pairForCreate.set(add, {\n key: hint.to,\n renamedFrom: hint.from,\n to: data[hint.from],\n });\n }\n }\n for (const [file, list] of byFile) {\n const data = originals.get(file) ?? {};\n const dels = list.filter(\n (e) =>\n (e.to === null || e.to === undefined) &&\n data[e.key] !== undefined &&\n !consumedDeletes.has(e),\n );\n const adds = list.filter(\n (e) => data[e.key] === undefined && e.to != null && e.to !== sentinel,\n );\n for (const d of dels) {\n const bound = bindValue(data[d.key]);\n const match = adds.find(\n (a) => !pairForCreate.has(a) && Object.is(a.to, bound),\n );\n if (!match) continue;\n consumedDeletes.add(d);\n pairForCreate.set(match, {\n key: match.key,\n renamedFrom: d.key,\n to: data[d.key],\n });\n }\n }\n\n const changes: QueryChange[] = [];\n for (const effect of effects) {\n const { file, key, to } = effect;\n if (consumedDeletes.has(effect)) continue;\n const pair = pairForCreate.get(effect);\n if (pair) {\n changes.push({ file, ...pair, written: false });\n continue;\n }\n const original = originals.get(file)?.[key];\n // `explicit_null()` bypasses the type map by design: the statement asked\n // for the literal, whatever type the key held.\n if (to === sentinel) {\n changes.push({ file, key, from: original, to: null, written: false });\n continue;\n }\n // Deletion: `SET k = NULL` (0024's standard spelling) or a dropped\n // column. Deleting a key the file never had is a no-op, not a change.\n if (to === null || to === undefined) {\n if (original !== undefined) {\n changes.push({ file, key, from: original, deleted: true, written: false });\n }\n continue;\n }\n // A boolean DDL add is authoritative for a key no file had: without the\n // hint the backfill's 1/0 would land in the files as numbers (0028).\n const targetType =\n fileTypeOf(original) ??\n (booleanAdds.has(key) ? \"boolean\" : dominantFor(key));\n // `from` stays `undefined` for a key the file never had — JSON output\n // omits it — which keeps \"absent\" distinguishable from an explicit null.\n changes.push({\n file,\n key,\n from: original,\n to: restoreValue(file, key, to, targetType),\n written: false,\n });\n }\n\n // DELETE: a removed row strips the block. A file that had none is a no-op,\n // unless a manifest supplies its metadata: then its entry goes (0047).\n const extractorOf = new Map(entries.map((e) => [e.label, e.extractor]));\n const ownOf = new Map(entries.map((e) => [e.label, e.own.data]));\n for (const file of diff.clearedRows) {\n const extracted = meta.get(file);\n if (!extracted) continue;\n if (!extracted.present) {\n const own = ownOf.get(file) ?? {};\n if (Object.keys(extracted.data).some((k) => !Object.hasOwn(own, k))) {\n changes.push({ file, cleared: true, from: extracted.data, written: false });\n }\n continue;\n }\n // Refused at plan time, not discovered at apply: this extraction did not\n // come from a fenced block — element-backed metadata, or an RST/AsciiDoc\n // file read through its native-header fallback — so there is nothing\n // whose removal leaves the document whole, and the preview must never\n // promise a strip the writer refuses. Per-file truth, not extractor\n // capability: the same RST extractor answers both ways.\n if (extracted.fenced !== true) {\n const name = extractorOf.get(file)?.name ?? extracted.format;\n throw new DocmetaError(\n `\"${file}\": the ${name} format has no front matter block to strip.`,\n );\n }\n changes.push({ file, cleared: true, from: extracted.data, written: false });\n }\n\n // INSERT: an added row creates a file.\n for (const [file, row] of diff.createdRows) {\n // An *omitted* _path never reaches here — the PRIMARY KEY's NOT NULL\n // rejects it in SQLite. What does arrive and still refuses: the empty\n // string (NOT NULL admits it) and a BLOB (TEXT affinity never coerces\n // blobs), neither of which names a file.\n if (typeof row._path !== \"string\" || row._path === \"\") {\n throw new DocmetaError(\"INSERT requires a non-empty _path.\");\n }\n for (const sys of SYSTEM_COLUMNS) {\n if (sys !== \"_path\" && row[sys] != null) {\n throw new DocmetaError(\n `INSERT may not set system column \"${sys}\".`,\n );\n }\n }\n validateNewPath(file, ctx.base);\n // Refused at plan time so the preview never promises a file the writer\n // cannot build — the same courtesy every other refusal here extends.\n if (!extractorForExtension(extname(file))?.apply) {\n throw new DocmetaError(\n `\"${file}\": no writable format for that extension.`,\n );\n }\n if (existsSync(resolve(ctx.base, file))) {\n throw new DocmetaError(\n `\"${file}\" already exists; INSERT creates new files only.`,\n );\n }\n const to: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(row)) {\n if (RESERVED.has(key) || value === null || value === undefined) continue;\n to[key] =\n value === sentinel\n ? null\n : restoreValue(file, key, value, dominantFor(key));\n }\n changes.push({ file, created: true, to, written: false });\n }\n\n // A `_path` move renames the file.\n for (const { from, to } of diff.renamedFiles) {\n validateNewPath(to, ctx.base);\n if (extname(to).toLowerCase() !== extname(from).toLowerCase()) {\n throw new DocmetaError(\n `\"${from}\" -> \"${to}\": a rename may not change the extension.`,\n );\n }\n if (existsSync(resolve(ctx.base, to))) {\n throw new DocmetaError(\n `\"${to}\" already exists; the rename would overwrite it.`,\n );\n }\n changes.push({ file: from, renamed: to, written: false });\n }\n\n refuseJoinFieldChanges(changes, entries, ctx);\n refuseManagedWrites(changes, entries, ctx);\n return changes;\n}\n\n/**\n * Only `derive` writes a managed field (0040): that is what makes the stamp\n * trustworthy, so every other writer refuses it by name, at plan time, the\n * way a manifest-owned key is refused. Every change kind that would touch\n * one: a set (or a `SET k = NULL` deletion), a rename onto or away from it,\n * an INSERT that carries it, and a DELETE that would strip a document's\n * block along with the stamp in it.\n */\nfunction refuseManagedWrites(\n changes: readonly QueryChange[],\n entries: readonly QueryEntry[],\n ctx: RunContext,\n): void {\n if (ctx.managed.size === 0) return;\n const refuse = (key: string): never => {\n throw new DocmetaError(\n `\"${key}\" is managed by derive; run manni meta derive instead.`,\n );\n };\n const data = new Map(entries.map((e) => [e.label, e.extracted.data]));\n for (const c of changes) {\n if (\"schema\" in c || \"config\" in c || \"renamed\" in c) continue;\n const keys =\n \"cleared\" in c\n ? Object.keys(data.get(c.file) ?? {})\n : \"created\" in c\n ? Object.keys(c.to)\n : \"renamedFrom\" in c\n ? [c.key, c.renamedFrom]\n : [c.key];\n // A file outside `derive.collections` has no managed fields (0070).\n if (!deriveCovers(ctx.config?.derive, ctx.memberships(c.file))) continue;\n for (const key of keys) if (ctx.managed.has(key)) refuse(key);\n }\n}\n\n/** A path an INSERT or rename may target: relative, contained, no traversal. */\nfunction validateNewPath(p: string, base: string): void {\n const refuse = (why: string): never => {\n throw new DocmetaError(`\"${p}\" is not a usable path: ${why}.`);\n };\n if (isAbsolute(p)) refuse(\"it is absolute\");\n if (p.split(/[\\\\/]/).some((segment) => segment === \"..\")) {\n refuse(\"it traverses upward\");\n }\n const abs = resolve(base, p);\n // Named before the escape check: `.` resolves to the base itself, and\n // \"escapes the corpus\" would be a baffling description of that.\n if (abs === resolve(base)) refuse(\"it points at the corpus root, not a file\");\n if (!abs.startsWith(resolve(base) + sep)) refuse(\"it escapes the corpus\");\n}\n\n/**\n * All-or-nothing apply: phase one computes every file's new content — any\n * refusal (unwritable format, a corpus that moved underneath the run, or the\n * writer's own re-parse verification) aborts before a single byte lands;\n * phase two writes atomically. A half-applied bulk edit would leave the\n * corpus in a state no statement describes.\n */\n\n/**\n * The join field of a document that matched a field entry (0039) cannot\n * change: the entry would be orphaned, which the next corpus run reports. A\n * `_path` move, by contrast, is exactly what a field join permits. Refused at\n * plan time, before anything is written. Every other write to a key a\n * manifest owns is planned into the manifest by `planManifestEdits` (0047).\n */\nfunction refuseJoinFieldChanges(\n changes: readonly QueryChange[],\n entries: readonly QueryEntry[],\n ctx: RunContext,\n): void {\n const index = ctx.externalMetadata;\n if (!index) return;\n const data = new Map(entries.map((e) => [e.label, e.extracted.data]));\n for (const c of changes) {\n if (\"schema\" in c || \"config\" in c || \"cleared\" in c || \"created\" in c || \"renamed\" in c) continue;\n const keys = \"renamedFrom\" in c ? [c.key, c.renamedFrom] : [c.key];\n for (const key of keys) {\n const byValue = index.byField.get(key);\n if (byValue === undefined) continue;\n const raw = readableJoinValue(data.get(c.file)?.[key], ctx);\n const value =\n typeof raw === \"string\"\n ? raw\n : typeof raw === \"number\" || typeof raw === \"boolean\"\n ? String(raw)\n : undefined;\n const entry = value === undefined ? undefined : byValue.get(value);\n if (entry !== undefined) {\n const manifest = entry.values().next().value?.file ?? \"manifest\";\n throw new DocmetaError(\n `\"${c.file}\": \"${key}\" is the field manifest ${manifest} joins on, and this document has an entry; change the manifest first.`,\n );\n }\n }\n }\n // A join value this statement sets, or an INSERT gives a new page, that\n // names an entry the document did not already match would take that entry\n // over: the page would merge another document's values, and a write to an\n // owned key would overwrite them.\n for (const c of changes) {\n if (\"schema\" in c || \"config\" in c || \"cleared\" in c || \"renamed\" in c || \"deleted\" in c) continue;\n const set: [string, unknown][] = \"created\" in c ? Object.entries(c.to) : [[c.key, c.to]];\n const members = ctx.memberships(c.file);\n for (const [key, to] of set) {\n const value = joinString(to);\n if (value === undefined) continue;\n if (!(\"created\" in c) && joinString(readableJoinValue(data.get(c.file)?.[key], ctx)) === value) continue;\n const taken = index.entries.find(\n (e) => e.join === key && e.spelled === value && members.includes(e.collection),\n );\n if (taken !== undefined) {\n throw new DocmetaError(\n `\"${c.file}\": \"${key}\" \"${value}\" names the entry of another document in manifest ${taken.file}; choose another value.`,\n );\n }\n }\n }\n}\n\n/** The string a join field's value matches entries by, as the merge compares it. */\nfunction joinString(raw: unknown): string | undefined {\n if (typeof raw === \"string\") return raw;\n if (typeof raw === \"number\" || typeof raw === \"boolean\") return String(raw);\n return undefined;\n}\n\n/**\n * What a change does to its page once the keys a manifest owns are routed to\n * the manifest (proposal 0047). Kept off the change objects, as the sealed\n * values are, so `json` output never carries it. A change with no entry here\n * writes its page the way it always did.\n */\ninterface PageOps {\n patch: MetadataPatch;\n deletions: string[];\n /** A created file's page keys: the ones no manifest owns. */\n created?: Record<string, unknown>;\n /** Whether a DELETE strips the page's block; false when only manifest entries go. */\n strip?: boolean;\n}\n\nconst pageRoutes = new WeakMap<QueryChange, PageOps>();\n\n/** One manifest a statement edits: its new text, and the text that was computed from. */\ninterface ManifestWrite {\n path: string;\n /** As the run reports it. */\n display: string;\n text: string;\n /** The text phase one read, or null for a `{page}` manifest that did not exist (proposal 0058). */\n expected: string | null;\n}\n\n\n/**\n * Each written file's metadata as the statement leaves it: the merged data,\n * with every set, removal and rename applied, or a created file's own.\n */\nfunction postChangeData(\n changes: readonly QueryChange[],\n entries: readonly QueryEntry[],\n): Map<string, Record<string, unknown>> {\n const original = new Map(entries.map((e) => [e.label, e.extracted.data]));\n const out = new Map<string, Record<string, unknown>>();\n for (const c of changes) {\n if (\"schema\" in c || \"config\" in c || \"cleared\" in c || \"renamed\" in c) continue;\n if (\"created\" in c) {\n out.set(c.file, { ...c.to });\n continue;\n }\n let data = out.get(c.file);\n if (data === undefined) {\n data = { ...(original.get(c.file) ?? {}) };\n out.set(c.file, data);\n }\n if (\"deleted\" in c) {\n Reflect.deleteProperty(data, c.key);\n continue;\n }\n if (\"renamedFrom\" in c) Reflect.deleteProperty(data, c.renamedFrom);\n data[c.key] = c.to;\n }\n return out;\n}\n\n/**\n * The run's pages as absolute paths, for a `{page}` manifest (proposal 0058):\n * every row the statement read, and every document a change names. A schema\n * or config change names a file that is not a page, and stdin has no path.\n */\nfunction runPages(\n changes: readonly QueryChange[],\n entries: readonly QueryEntry[],\n base: string,\n): string[] {\n const labels = new Set(entries.map((e) => e.label));\n for (const c of changes) if (!(\"schema\" in c) && !(\"config\" in c)) labels.add(c.file);\n labels.delete(STDIN_LABEL);\n return [...labels].map((label) => resolve(base, label));\n}\n\n/**\n * Plan every manifest edit the statement makes (proposal 0047), in phase one:\n * each change to a key a local manifest owns is routed to the document's\n * entry, `pageRoutes` records what is left for the page, and `manifest` is set\n * on the change. Every manifest's new text is computed, composed across the\n * statement and read back by the writers; nothing is written.\n *\n * Refuses, before anything is written: any write a URL manifest would have to\n * take (M6), an owned key on a field-joined page with no join value, an\n * `ALTER TABLE … RENAME COLUMN` of an owned key (`keys:` would need renaming),\n * and a `_path` move that takes a named document out of its manifest's\n * collection.\n */\nasync function planManifestEdits(\n changes: readonly QueryChange[],\n entries: readonly QueryEntry[],\n ctx: RunContext,\n renameHints: readonly { from: string; to: string }[],\n): Promise<ManifestWrite[]> {\n for (const c of changes) {\n delete c.manifest;\n pageRoutes.delete(c);\n }\n if (!ctx.declaredCollections.some((col) => col.externalMetadata.length > 0)) return [];\n const loc = ctx.location.context();\n const byLabel = new Map(entries.map((e) => [e.label, e]));\n const after = postChangeData(changes, entries);\n const ddlRenames = new Set(renameHints.map((h) => `${h.from}\\0${h.to}`));\n\n const homes = new Map<string, KeyHome>();\n const homeOf = async (file: string, key: string, data: Readonly<Record<string, unknown>>): Promise<KeyHome> => {\n const id = `${file}\\0${key}`;\n let home = homes.get(id);\n if (home === undefined) {\n home = await keyHome(loc, file, data, key);\n homes.set(id, home);\n }\n return home;\n };\n const fetched: (key: string, url: string) => never = (key, url) => {\n throw new DocmetaError(\n `\"${key}\" is owned by manifest ${url}, which is fetched and cannot be written; set it in that repository.`,\n );\n };\n type Owned = Extract<KeyHome, { kind: \"manifest\" }> & { entry: string };\n /**\n * The local manifest entry a key of `file` lives in, or undefined when the\n * page holds it. `strict` refuses an owned key on a page with no join value,\n * which a value being written needs; a removal only needs to know there is\n * no entry to remove it from.\n */\n const owned = async (\n file: string,\n key: string,\n data: Readonly<Record<string, unknown>>,\n strict: boolean,\n ): Promise<Owned | undefined> => {\n if (file === STDIN_LABEL || key === FILE_SCHEMA_KEY) return undefined;\n const home = await homeOf(file, key, data);\n if (home.kind === \"unowned\") return undefined;\n // The rows were merged from the selected collections' manifests only, so\n // a manifest of a collection `--collection` left out was never read: a\n // write there would act on a value the statement could not see.\n if (!ctx.memberships(file).includes(home.collection)) {\n throw new DocmetaError(\n `\"${file}\": \"${key}\" is owned by manifest ${home.file} of collection ${home.collection}, which --collection leaves out; include it or edit the manifest.`,\n );\n }\n if (home.kind === \"url\") return fetched(key, home.file);\n if (home.entry === undefined) {\n if (!strict) return undefined;\n throw new DocmetaError(\n `\"${file}\": \"${key}\" is owned by manifest ${home.file}, which joins on \"${home.join}\", and this document has no ${home.join}; set ${home.join} first.`,\n );\n }\n return { ...home, entry: home.entry };\n };\n\n const texts = new Map<string, ManifestWrite>();\n const edit = async (home: Owned, change: (text: string) => string): Promise<void> => {\n let write = texts.get(home.absPath);\n if (write === undefined) {\n let text: string;\n let expected: string | null;\n try {\n text = await readFile(home.absPath, \"utf8\");\n expected = text;\n } catch (err) {\n // A `{page}` manifest (proposal 0058) that does not exist yet reads\n // as empty and is created. `expected: null` records the absence, so\n // phase two refuses if the file appeared since.\n if (!home.perPage || !isMissing(err)) {\n throw new DocmetaError(`Manifest ${home.file} could not be read: ${errorMessage(err)}`);\n }\n text = \"\";\n expected = null;\n }\n write = { path: home.absPath, display: home.file, text, expected };\n texts.set(home.absPath, write);\n }\n write.text = change(write.text);\n };\n const where = (home: Owned): { entry: string; join: string; file: string } => ({\n entry: home.entry,\n join: home.join,\n file: home.file,\n });\n\n // The local manifests of the collections `--collection` left out. The rows\n // were merged without them, so the rename and DELETE handling below never\n // sees their entries; loaded only when a statement moves or clears a page.\n const selected = new Set(ctx.collections.map((col) => col.name));\n let leftOut: Promise<ExternalMetadataIndex | null> | undefined;\n /**\n * An entry for `file` in a local manifest of a collection the file belongs\n * to that `--collection` left out: a path entry, or with `joins` also a\n * field entry the page's own join value matches. Moving the page would\n * orphan a path entry, and stripping its block would orphan either.\n */\n const leftOutEntry = async (\n file: string,\n own: ExtractedMetadata | undefined,\n joins: boolean,\n ): Promise<{ file: string; collection: string } | undefined> => {\n if (file === STDIN_LABEL) return undefined;\n const excluded = memberOf(ctx.declaredCollections, ctx.configDir ?? ctx.cwd, ctx.base, file).filter(\n (name) => !selected.has(name),\n );\n if (excluded.length === 0) return undefined;\n leftOut ??= loadExternalMetadata(\n ctx.declaredCollections\n .filter((col) => !selected.has(col.name))\n .map((col) => ({\n ...col,\n externalMetadata: col.externalMetadata.filter((m) => classifyRef(m.file).kind !== \"url\"),\n })),\n { configDir: ctx.configDir ?? ctx.cwd, base: ctx.base, pages: runPages(changes, entries, ctx.base) },\n );\n const index = await leftOut;\n if (index === null) return undefined;\n const abs = resolve(ctx.base, file);\n const named = index.entries.find(\n (e) => e.join === PATH_JOIN && e.abs === abs && excluded.includes(e.collection),\n );\n if (named !== undefined) return named;\n if (!joins || own === undefined) return undefined;\n return mergeExternalMetadata(file, own, index, excluded, ctx.base, { encryptionKey: ctx.encryption.key })\n .joins[0];\n };\n\n for (const c of changes) {\n if (\"schema\" in c || \"config\" in c) continue;\n const entry = byLabel.get(c.file);\n const own = entry?.own.data ?? {};\n\n if (\"cleared\" in c || \"renamed\" in c) {\n const cleared = \"cleared\" in c;\n const named = await leftOutEntry(c.file, entry?.own, cleared);\n if (named !== undefined) {\n throw new DocmetaError(\n `\"${c.file}\": manifest ${named.file} of collection ${named.collection} names it, which --collection leaves out; include it or ${cleared ? \"remove\" : \"rename\"} the entry first.`,\n );\n }\n }\n\n if (\"cleared\" in c) {\n // Every key the document has: the ones a manifest supplies lose their\n // entry with the block, and a URL manifest refuses.\n for (const key of Object.keys(c.from)) {\n const home = await owned(c.file, key, own, false);\n if (home === undefined) continue;\n c.manifest ??= home.file;\n await edit(home, (t) => removeManifestKey(t, { ...where(home), key }).text);\n }\n pageRoutes.set(c, { patch: {}, deletions: [], strip: entry?.extracted.present === true });\n continue;\n }\n\n if (\"created\" in c) {\n const page: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(c.to)) {\n const written = writtenValue(c, key, value);\n const home = await owned(c.file, key, c.to, true);\n if (home === undefined) {\n page[key] = written;\n continue;\n }\n c.manifest ??= home.file;\n await edit(home, (t) => spliceManifestValue(t, { ...where(home), key, value: written }).text);\n }\n pageRoutes.set(c, { patch: {}, deletions: [], created: page });\n continue;\n }\n\n if (\"renamed\" in c) {\n // A path-joined manifest names the document by path: its entry moves\n // with it. A field join has nothing to rename.\n const supplied = ctx.externalMetadata?.byPath.get(resolve(ctx.base, c.file));\n const seen = new Set<string>();\n for (const [key, sv] of supplied ?? []) {\n if (seen.has(sv.file) || !ctx.memberships(c.file).includes(sv.collection)) continue;\n seen.add(sv.file);\n const home = await homeOf(c.file, key, own);\n if (home.kind === \"url\") {\n throw new DocmetaError(\n `\"${c.file}\": manifest ${home.file} names it, which is fetched and cannot be written; rename the entry in that repository.`,\n );\n }\n // A `{page}` manifest (proposal 0058) is named after the page's path,\n // so the entry cannot follow the page into a file of the new name.\n if (home.kind === \"manifest\" && home.perPage) {\n throw new DocmetaError(\n `${c.file} cannot move to ${c.renamed}, because its \"${key}\" lives in ${home.file}, a {page} manifest named after the page's path. Move the page and its manifest together, then rename the entry's key.`,\n );\n }\n if (home.kind !== \"manifest\" || home.join !== PATH_JOIN || home.entry === undefined) continue;\n const moved = await keyHome(loc, c.renamed, own, key);\n if (moved.kind !== \"manifest\" || moved.absPath !== home.absPath || moved.entry === undefined) {\n throw new DocmetaError(\n `\"${c.file}\" -> \"${c.renamed}\": manifest ${home.file} names it, and the new path is not a page of collection ${home.collection}; keep the move inside the collection, or edit the manifest first.`,\n );\n }\n const from = { ...home, entry: home.entry };\n const to = moved.entry;\n c.manifest ??= home.file;\n await edit(from, (t) => renameManifestEntry(t, { entry: from.entry, to, join: from.join, file: from.file }).text);\n }\n continue;\n }\n\n const data = after.get(c.file) ?? {};\n const ops: PageOps = { patch: {}, deletions: [] };\n const dropFromPage = (key: string): void => {\n if (Object.hasOwn(own, key)) ops.deletions.push(key);\n };\n\n if (\"renamedFrom\" in c) {\n if (ddlRenames.has(`${c.renamedFrom}\\0${c.key}`)) {\n for (const key of [c.renamedFrom, c.key]) {\n const home = await homeOf(c.file, key, data);\n if (home.kind !== \"unowned\") {\n throw new DocmetaError(\n `\"${c.file}\": \"${key}\" is owned by manifest ${home.file}; edit the manifest instead.`,\n );\n }\n }\n }\n const source = await owned(c.file, c.renamedFrom, own, false);\n if (source !== undefined) {\n await edit(source, (t) => removeManifestKey(t, { ...where(source), key: c.renamedFrom }).text);\n }\n dropFromPage(c.renamedFrom);\n const target = await owned(c.file, c.key, data, true);\n const written = writtenValue(c, c.key, c.to);\n if (target === undefined) {\n ops.patch[c.key] = written;\n } else {\n await edit(target, (t) => spliceManifestValue(t, { ...where(target), key: c.key, value: written }).text);\n }\n const manifest = target?.file ?? source?.file;\n if (manifest !== undefined) c.manifest = manifest;\n } else if (\"deleted\" in c) {\n const home = await owned(c.file, c.key, own, false);\n if (home !== undefined) {\n c.manifest = home.file;\n await edit(home, (t) => removeManifestKey(t, { ...where(home), key: c.key }).text);\n }\n dropFromPage(c.key);\n } else {\n const home = await owned(c.file, c.key, data, true);\n const written = writtenValue(c, c.key, c.to);\n if (home === undefined) {\n ops.patch[c.key] = written;\n } else {\n c.manifest = home.file;\n await edit(home, (t) => spliceManifestValue(t, { ...where(home), key: c.key, value: written }).text);\n // A page that carries the key too would still win at merge.\n dropFromPage(c.key);\n }\n }\n pageRoutes.set(c, ops);\n }\n // A manifest that does not exist yet is written only when it gains text.\n return [...texts.values()].filter((w) => w.text !== (w.expected ?? \"\"));\n}\n\n/** One key a statement writes to a page that its schema prefers in external metadata, with no manifest. */\ninterface Unhomed {\n file: string;\n key: string;\n home: ProposedHome;\n /** The page is one an INSERT creates, so it is not on disk for relocate to read. */\n created: boolean;\n}\n\n/**\n * The keys a statement writes whose schemas prefer external metadata and\n * that no manifest owns (proposal 0047), with the home §3 would give each.\n * Preferences are read over the data each file will hold, from the schema set\n * `validate` would resolve for it. A field join's own field stays in the page.\n */\nasync function unhomedWrites(\n changes: readonly QueryChange[],\n entries: readonly QueryEntry[],\n ctx: RunContext,\n): Promise<Unhomed[]> {\n const written = new Map<string, { keys: string[]; created: boolean }>();\n for (const c of changes) {\n if (c.file === STDIN_LABEL) continue;\n if (\"schema\" in c || \"config\" in c || \"cleared\" in c || \"renamed\" in c || \"deleted\" in c) continue;\n const slot = written.get(c.file) ?? { keys: [], created: \"created\" in c };\n slot.keys.push(...(\"created\" in c ? Object.keys(c.to) : [c.key]).filter((k) => k !== FILE_SCHEMA_KEY));\n written.set(c.file, slot);\n }\n if (written.size === 0) return [];\n const after = postChangeData(changes, entries);\n const original = new Map(entries.map((e) => [e.label, e.extracted.data]));\n const loc = ctx.location.context();\n const validator = ctx.encryption.validator();\n const out: Unhomed[] = [];\n for (const [file, w] of written) {\n const data = after.get(file) ?? {};\n const refs = resolveSchemaSetWithSource({\n filePath: file,\n fileSchema: w.created ? data[FILE_SCHEMA_KEY] : original.get(file)?.[FILE_SCHEMA_KEY],\n cliSchemas: ctx.cliSchemas,\n config: ctx.config,\n memberOf: [...ctx.memberships(file)],\n fileBase: ctx.cwd,\n trustRoot: ctx.trustRoot,\n }).schemas;\n if (refs.length === 0) continue;\n const prefs = await validator.locationPreferences(data, refs);\n const joins = new Set(\n memberOf(loc.declaredCollections, loc.configDir ?? ctx.cwd, ctx.base, file).flatMap((name) =>\n (loc.declaredCollections.find((col) => col.name === name)?.externalMetadata ?? [])\n .map((m) => externalMetadataJoin(m))\n .filter((j) => j !== PATH_JOIN),\n ),\n );\n for (const key of new Set(w.keys)) {\n if (prefs.get(key)?.location !== \"external\" || joins.has(key)) continue;\n const home = await keyHome(loc, file, data, key);\n if (home.kind === \"unowned\") out.push({ file, key, home: home.home, created: w.created });\n }\n }\n return out;\n}\n\n/**\n * P1, then W1 and W2 (proposal 0047). On a terminal and not a dry run, each\n * collection the unhomed keys would join is offered once; on yes relocate\n * runs for those keys, over every member page, and the run's collections and\n * manifests are brought up to date so the statement's write lands in the\n * manifest. What is still unhomed afterwards (declined, off a terminal, a\n * dry run, an INSERT's page with no page on disk yet, or no possible home)\n * is written to the page, and the returned lines say so, one per collection.\n */\nasync function offerRelocation(\n changes: readonly QueryChange[],\n entries: readonly QueryEntry[],\n ctx: RunContext,\n): Promise<{ relocated: boolean; warnings: string[] }> {\n let unhomed = await unhomedWrites(changes, entries, ctx);\n let relocated = false;\n const { confirm } = ctx.location;\n if (unhomed.length > 0 && ctx.write && confirm !== undefined) {\n const loc = ctx.location.context();\n const groups = new Map<string, Unhomed[]>();\n for (const u of unhomed) {\n if (u.home.kind !== \"collection\" || u.created) continue;\n const group = groups.get(u.home.collection) ?? [];\n group.push(u);\n groups.set(u.home.collection, group);\n }\n for (const group of groups.values()) {\n const require = new Map<string, string[]>();\n for (const u of group) require.set(u.file, [...(require.get(u.file) ?? []), u.key]);\n const plan = await planRelocation(loc, {\n files: [...require.keys()],\n fields: [...new Set(group.map((u) => u.key))],\n require,\n });\n if (plan.offers.length === 0) continue;\n let accepted = true;\n for (const offer of plan.offers) {\n const { notice, question } = offerPrompt(offer, \"write\");\n ctx.onNotice?.(notice);\n if (!(await confirm(question))) {\n accepted = false;\n break;\n }\n }\n if (!accepted) continue;\n const result = await applyRelocation(loc, plan);\n ctx.location.onRelocated?.(result);\n relocated = true;\n }\n if (relocated) {\n ctx.externalMetadata = await loadExternalMetadata(loc.collections, {\n configDir: loc.configDir ?? ctx.cwd,\n base: ctx.base,\n offline: ctx.location.offline,\n pages: runPages(changes, entries, ctx.base),\n });\n ctx.memberships = (label) => memberOf(loc.collections, loc.configDir ?? ctx.cwd, ctx.base, label);\n unhomed = await unhomedWrites(changes, entries, ctx);\n }\n }\n return { relocated, warnings: unhomedWarnings(unhomed, ctx.write) };\n}\n\n/** W1 and W2: one line per collection (or per reason there is none) for what was written to pages. */\nfunction unhomedWarnings(unhomed: readonly Unhomed[], write: boolean): string[] {\n const verb = write ? \"wrote\" : \"would write\";\n const groups = new Map<string, { home: ProposedHome; keys: Set<string>; files: Set<string> }>();\n for (const u of unhomed) {\n const id =\n u.home.kind === \"collection\"\n ? `c\\0${u.home.collection}\\0${String(u.home.createsCollection || u.home.addsPath !== undefined)}`\n : `n\\0${u.home.reason}\\0${String(u.home.collections)}`;\n const group = groups.get(id) ?? { home: u.home, keys: new Set<string>(), files: new Set<string>() };\n group.keys.add(u.key);\n group.files.add(u.file);\n groups.set(id, group);\n }\n return [...groups.values()].map(({ home, keys, files }) =>\n externalWriteWarning({\n verb,\n keys: [...keys],\n pages: files.size,\n home,\n createsHome: home.kind === \"collection\" && (home.createsCollection || home.addsPath !== undefined),\n }),\n );\n}\n\n/**\n * A join field as a manifest entry is keyed: its plaintext, when the page\n * holds it encrypted and the key can read it (proposal 0045).\n */\nfunction readableJoinValue(held: unknown, ctx: RunContext): unknown {\n if (!isEncryptedValue(held)) return held;\n const key = ctx.encryption.key();\n if (key === undefined) return held;\n const opened = decryptValue(held, key, META_CONTEXT);\n return opened.ok ? opened.value : held;\n}\n\n/**\n * What a write puts in a file where it differs from what its change reports:\n * the ciphertext of a value the change prints as `(encrypted)` (proposal\n * 0045). Keyed by change and key, because a created file's one change can\n * carry several such values. Kept off the change objects so `json` output,\n * which prints them whole, never carries it.\n */\nconst sealedWrites = new WeakMap<QueryChange, Map<string, unknown>>();\n\nfunction writtenValue(change: QueryChange, key: string, value: unknown): unknown {\n const sealed = sealedWrites.get(change)?.get(key);\n return sealed === undefined ? value : sealed;\n}\n\n/**\n * Encrypt what a statement writes into a column its schema marks\n * `x-manni-encrypt`, and print `(encrypted)` for it (proposal 0045).\n *\n * Each written file's schema set is resolved exactly as `validate` resolves\n * it — config `schemas:`, overrides, the file's `$schema`, `-s` — over the\n * data the file will hold, so the marks are the ones the next `validate` will\n * read. A value that is already a ciphertext is written as it is. A dry run\n * encrypts nothing and asks for no key: it writes nothing. Whatever the page\n * held as a ciphertext prints as `(encrypted)` too.\n */\nasync function sealMarkedWrites(\n changes: QueryChange[],\n entries: readonly QueryEntry[],\n ctx: RunContext,\n): Promise<void> {\n const original = new Map(entries.map((e) => [e.label, e.extracted.data]));\n interface FileWrites {\n after: Record<string, unknown>;\n /**\n * The `$schema` the file is resolved with: the one it holds as the run\n * read it, or a created file's own. Not a `$schema` the statement writes:\n * a DDL fork repoints `$schema` cells at a schema that is written only\n * when the statement applies, and a fork of a built-in marks nothing.\n */\n fileSchema: unknown;\n writes: { change: QueryChange; key: string; value: unknown }[];\n }\n const files = new Map<string, FileWrites>();\n const slot = (file: string, from: Record<string, unknown>): FileWrites => {\n let found = files.get(file);\n if (found === undefined) {\n found = { after: { ...from }, fileSchema: from[FILE_SCHEMA_KEY], writes: [] };\n files.set(file, found);\n }\n return found;\n };\n // `$schema` is the run's wiring, never metadata a schema could mark.\n const writable = (key: string, value: unknown): boolean =>\n key !== FILE_SCHEMA_KEY && value !== null && value !== undefined;\n for (const c of changes) {\n if (\"schema\" in c || \"config\" in c || \"cleared\" in c || \"renamed\" in c) continue;\n if (\"created\" in c) {\n const f = slot(c.file, c.to);\n for (const [key, value] of Object.entries(c.to)) {\n if (writable(key, value)) f.writes.push({ change: c, key, value });\n }\n continue;\n }\n const f = slot(c.file, original.get(c.file) ?? {});\n if (\"deleted\" in c) {\n Reflect.deleteProperty(f.after, c.key);\n continue;\n }\n if (\"renamedFrom\" in c) Reflect.deleteProperty(f.after, c.renamedFrom);\n f.after[c.key] = c.to;\n if (writable(c.key, c.to)) f.writes.push({ change: c, key: c.key, value: c.to });\n }\n\n for (const [file, f] of files) {\n if (f.writes.length === 0) continue;\n const refs = resolveSchemaSetWithSource({\n filePath: file,\n fileSchema: f.fileSchema,\n cliSchemas: ctx.cliSchemas,\n config: ctx.config,\n memberOf: [...ctx.memberships(file)],\n fileBase: ctx.cwd,\n trustRoot: ctx.trustRoot,\n onNotice: ctx.onNotice,\n }).schemas;\n const marks = await ctx.encryption.validator().markedPointers(f.after, refs);\n for (const w of f.writes) {\n const pointer = pointerOf(w.key);\n const already = isEncryptedValue(w.value);\n if (!already && !marks.has(pointer)) continue;\n if (ctx.write) {\n const sealed = already\n ? w.value\n : encryptValue(w.value, await ctx.encryption.ensure(pointer), META_CONTEXT);\n const byKey = sealedWrites.get(w.change) ?? new Map<string, unknown>();\n byKey.set(w.key, sealed);\n sealedWrites.set(w.change, byKey);\n }\n if (\"created\" in w.change) w.change.to[w.key] = ENCRYPTED_PLACEHOLDER;\n else if (\"to\" in w.change) w.change.to = ENCRYPTED_PLACEHOLDER;\n }\n }\n\n for (const c of changes) {\n if (\"cleared\" in c) {\n c.from = Object.fromEntries(\n Object.entries(c.from).map(([k, v]) => [\n k,\n isEncryptedValue(v) ? ENCRYPTED_PLACEHOLDER : v,\n ]),\n );\n } else if (\"from\" in c && !(\"config\" in c) && isEncryptedValue(c.from)) {\n c.from = ENCRYPTED_PLACEHOLDER;\n }\n }\n}\n\nasync function applyChanges(\n changes: QueryChange[],\n entries: QueryEntry[],\n ctx: RunContext,\n schemaPlan?: SchemaPlan,\n /** The manifest texts `planManifestEdits` computed (0047), written with the pages. */\n manifestWrites: readonly ManifestWrite[] = [],\n): Promise<void> {\n const schemaWrites = schemaPlan?.writes ?? [];\n if (changes.length === 0 && schemaWrites.length === 0) return;\n const byLabel = new Map(entries.map((e) => [e.label, e]));\n interface FileOps {\n patch: MetadataPatch;\n deletions: string[];\n cleared?: boolean;\n created?: Record<string, unknown>;\n renamedTo?: string;\n }\n const grouped = new Map<string, FileOps>();\n for (const c of changes) {\n if (c.file === STDIN_LABEL) {\n throw new DocmetaError(\n \"A write cannot touch <stdin>: there is no file behind it.\",\n );\n }\n if (\"schema\" in c || \"config\" in c) continue; // satisfied by schemaWrites\n const group = grouped.get(c.file) ?? { patch: {}, deletions: [] };\n grouped.set(c.file, group);\n // What is left for the page once the manifest-owned keys were routed to\n // their manifest (0047); values it writes are already the written ones.\n const route = pageRoutes.get(c);\n // A value the change prints as `(encrypted)` writes its ciphertext.\n if (\"cleared\" in c) {\n if (route?.strip !== false) group.cleared = true;\n } else if (\"created\" in c) {\n group.created =\n route?.created ??\n Object.fromEntries(\n Object.entries(c.to).map(([k, v]) => [k, writtenValue(c, k, v)]),\n );\n } else if (\"renamed\" in c) group.renamedTo = c.renamed;\n else if (route !== undefined) {\n Object.assign(group.patch, route.patch);\n group.deletions.push(...route.deletions);\n }\n else if (\"deleted\" in c) group.deletions.push(c.key);\n else if (\"renamedFrom\" in c) {\n group.patch[c.key] = writtenValue(c, c.key, c.to);\n group.deletions.push(c.renamedFrom);\n } else group.patch[c.key] = writtenValue(c, c.key, c.to);\n }\n\n const pendingWrites: { path: string; content: string; ensureDir?: boolean }[] =\n [];\n const pendingRenames: { from: string; to: string }[] = [];\n for (const [label, ops] of grouped) {\n const path = resolve(ctx.base, label);\n\n if (ops.renamedTo !== undefined) {\n if (!existsSync(path)) {\n throw new DocmetaError(\n `\"${label}\" is gone from disk since it was read; re-run the query.`,\n );\n }\n // The destination gets the same appeared-since-the-plan re-check the\n // created files do: rename(2) overwrites silently on POSIX.\n const toDisk = resolve(ctx.base, ops.renamedTo);\n if (existsSync(toDisk)) {\n throw new DocmetaError(\n `\"${ops.renamedTo}\" appeared on disk since the plan; re-run the query.`,\n );\n }\n pendingRenames.push({ from: path, to: toDisk });\n continue;\n }\n\n if (ops.created !== undefined) {\n const extractor = extractorForExtension(extname(label));\n if (!extractor?.apply) {\n throw new DocmetaError(\n `\"${label}\": no writable format for that extension.`,\n );\n }\n // Same moved-underneath contract the schema writes get: a file that\n // materialized here since the plan is somebody's data, not a target.\n if (existsSync(path)) {\n throw new DocmetaError(\n `\"${label}\" appeared on disk since the plan; re-run the query.`,\n );\n }\n pendingWrites.push({\n path,\n content: extractor.apply(\"\", ops.created, {\n filePath: label,\n // The new file's memberships, from its path alone. An INSERT has to\n // write through the element set a read of that file would use.\n elements: resolveElements(label, ctx.config, ctx.memberships(label)),\n }),\n ensureDir: true,\n });\n continue;\n }\n\n // Every change to this document landed in a manifest (0047): the page\n // itself is not written, and so need not be writable.\n if (!ops.cleared && Object.keys(ops.patch).length === 0 && ops.deletions.length === 0) {\n continue;\n }\n\n const entry = byLabel.get(label);\n if (!entry) throw new DocmetaError(`No loaded entry for \"${label}\".`);\n const content = await readFile(path, \"utf8\");\n // The change was computed against load-time data; if the file moved\n // since, applying it would encode a state nobody previewed.\n const members = ctx.memberships(label);\n const current = (\n await mergeWithMarks(\n label,\n entry.extractor.extract(content, label, {\n elements: resolveElements(label, ctx.config, members),\n }),\n ctx.externalMetadata,\n members,\n ctx.base,\n { encryptionKey: ctx.encryption.key, marks: ctx.marks },\n )\n ).extracted;\n\n if (ops.cleared) {\n if (!deepEqual(current.data, entry.extracted.data)) {\n throw new DocmetaError(\n `\"${label}\" changed on disk since it was read; re-run the query.`,\n );\n }\n const stripped = stripFrontmatter(content);\n if (stripped === content) {\n // No fenced block to remove — element-backed metadata, or a native\n // header the fence writer does not own. Effect-judged, no name list.\n throw new DocmetaError(\n `\"${label}\": the ${entry.extractor.name} format has no front matter block to strip.`,\n );\n }\n pendingWrites.push({ path, content: stripped });\n continue;\n }\n\n if (!entry.extractor.apply) {\n throw new DocmetaError(\n `\"${label}\": the ${entry.extractor.name} format is read-only.`,\n );\n }\n for (const key of [...Object.keys(ops.patch), ...ops.deletions]) {\n if (!deepEqual(current.data[key], entry.extracted.data[key])) {\n throw new DocmetaError(\n `\"${label}\" changed on disk since it was read (\"${key}\" moved); re-run the query.`,\n );\n }\n }\n const applied = entry.extractor.apply(content, ops.patch, {\n filePath: label,\n // The memberships the read above used. Without them a collection-scoped\n // element the read found has nowhere to be written.\n elements: resolveElements(label, ctx.config, members),\n deletions: ops.deletions,\n });\n if (ops.deletions.length > 0) {\n // `deletions` is advisory in the ApplyOptions contract — a writer that\n // cannot remove a key ignores it. Certainty comes from reading back.\n // The page's own extraction, not the merge: a key a manifest also\n // supplies (0047) is gone from the page even while the manifest,\n // edited in the same apply, still holds it on the old index.\n const check = entry.extractor.extract(applied, label, {\n elements: resolveElements(label, ctx.config, members),\n });\n for (const key of ops.deletions) {\n if (check.data[key] !== undefined) {\n throw new DocmetaError(\n `\"${label}\": the ${entry.extractor.name} writer cannot delete \"${key}\".`,\n );\n }\n }\n }\n pendingWrites.push({ path, content: applied });\n }\n // Phase two opens by re-checking the plan-time schema/config reads — the\n // same moved-underneath refusal corpus files got in phase one. Nothing has\n // landed yet, so a refusal here still leaves every file untouched.\n for (const w of schemaWrites) {\n const display = displayPath(ctx, w.path);\n if (w.expected === undefined) {\n if (existsSync(w.path)) {\n throw new DocmetaError(\n `\"${display}\" appeared on disk since the plan; re-run the query.`,\n );\n }\n continue;\n }\n let now: string | undefined;\n try {\n now = await readFile(w.path, \"utf8\");\n } catch {\n now = undefined;\n }\n if (now !== w.expected) {\n throw new DocmetaError(\n `\"${display}\" changed on disk since it was read; re-run the query.`,\n );\n }\n }\n // The same re-check for every manifest the statement edits (0047).\n for (const m of manifestWrites) {\n // Null for a file that is not there, which is what a `{page}` manifest\n // phase one found missing expects (proposal 0058).\n let now: string | null;\n try {\n now = await readFile(m.path, \"utf8\");\n } catch {\n now = null;\n }\n if (now !== m.expected) {\n throw new DocmetaError(\n `\"${m.display}\" changed on disk since it was read; re-run the query.`,\n );\n }\n }\n // Parent directories once each, and only where one can be missing: a\n // fork's schemas/ dir, an INSERT into a new subtree, a rename into one.\n // Files that were read from disk this run prove their directories exist.\n const dirs = new Set<string>();\n for (const w of schemaWrites) dirs.add(dirname(w.path));\n for (const r of pendingRenames) dirs.add(dirname(r.to));\n for (const p of pendingWrites) {\n if (p.ensureDir) dirs.add(dirname(p.path));\n }\n // A `{page}` manifest that did not exist may be the first file in its directory (0058).\n for (const m of manifestWrites) {\n if (m.expected === null) dirs.add(dirname(m.path));\n }\n for (const d of dirs) await mkdir(d, { recursive: true });\n\n // ADD writes the schema after the corpus so a mid-apply failure leaves\n // extra keys under an unchanged schema (green); DROP/RENAME write it first\n // so files at worst keep a key the schema no longer declares.\n const writeSchema = async (): Promise<void> => {\n for (const w of schemaWrites) await writeFileAtomic(w.path, w.content);\n };\n const schemaLast = schemaPlan?.schemaLast ?? false;\n if (!schemaLast) await writeSchema();\n // Content before moves: a statement may rename one file while editing\n // others, and writes are the failure-prone step (disk full, permissions).\n // With renames last, a write failure leaves every file under its old name\n // with some new values — the statement re-runs to convergence — instead of\n // a completed rename whose \"already exists\" guard blocks the re-run.\n // Manifests first (0047), as relocate writes them: a page that lost a key\n // to its manifest never lands before the manifest holds it.\n for (const m of manifestWrites) await writeFileAtomic(m.path, m.text);\n for (const p of pendingWrites) await writeFileAtomic(p.path, p.content);\n for (const r of pendingRenames) {\n try {\n await rename(r.from, r.to);\n } catch (err) {\n // EXDEV and friends arrive as raw fs errors; name the move and keep\n // the operational exit code instead of an \"Unexpected error\" trace.\n throw new DocmetaError(\n `Cannot move \"${r.from}\" to \"${r.to}\": ${errorMessage(err)}`,\n );\n }\n }\n if (schemaLast) await writeSchema();\n for (const c of changes) c.written = true;\n}\n\n/**\n * Column names a statement SETs, so the table can be widened before it runs.\n * Tolerant by design: it walks strings and comments with the same rules as\n * the semicolon scan, and bails out at anything unexpected — a miss merely\n * leaves today's \"no such column\" error in place.\n *\n * Exported for the scanner parity suite, not via the API index.\n */\nexport function collectSetTargets(sql: string): string[] {\n const targets: string[] = [];\n let i = 0;\n const n = sql.length;\n const isWord = (ch: string | undefined): boolean =>\n ch !== undefined && /[A-Za-z0-9_]/.test(ch);\n while (i < n) {\n const ch = sql[i];\n if (startsStringOrIdent(sql, i)) {\n i = skipStringOrIdent(sql, i);\n } else if (startsComment(sql, i)) {\n i = skipComment(sql, i);\n } else if (\n (ch === \"s\" || ch === \"S\") &&\n /^set$/i.test(sql.slice(i, i + 3)) &&\n !isWord(sql[i - 1]) &&\n !isWord(sql[i + 3])\n ) {\n i += 3;\n // Assignment list: identifier `=` expression, comma-separated, ending\n // at a top-level WHERE/FROM/RETURNING or the end of the statement.\n for (;;) {\n while (i < n && /\\s/.test(sql[i] ?? \"\")) i++;\n const name = readIdentifier(sql, i);\n if (!name) return targets;\n targets.push(name.value);\n i = name.end;\n while (i < n && /\\s/.test(sql[i] ?? \"\")) i++;\n if (sql[i] !== \"=\") return targets;\n const next = skipExpression(sql, i + 1);\n if (next.terminator !== \",\") return targets;\n i = next.end + 1;\n }\n } else {\n i++;\n }\n }\n return targets;\n}\n\n/**\n * Column names an INSERT's column list carries, so a corpus-new key can be\n * introduced by creation too. Same tolerance contract as `collectSetTargets`.\n *\n * Exported for the scanner parity suite, not via the API index.\n */\nexport function collectInsertTargets(sql: string): string[] {\n const head = stripLeadingTrivia(sql);\n if (!/^(insert|replace)\\b/i.test(head)) return [];\n const open = head.indexOf(\"(\");\n if (open === -1) return [];\n const targets: string[] = [];\n let i = open + 1;\n for (;;) {\n while (i < head.length && /\\s/.test(head[i] ?? \"\")) i++;\n const id = readIdentifier(head, i);\n if (!id) return targets;\n targets.push(id.value);\n i = id.end;\n while (i < head.length && /\\s/.test(head[i] ?? \"\")) i++;\n if (head[i] === \",\") {\n i++;\n continue;\n }\n return targets;\n }\n}\n\nfunction readIdentifier(\n sql: string,\n from: number,\n): { value: string; end: number } | undefined {\n const ch = sql[from];\n if (ch === '\"' || ch === \"`\") {\n const end = skipStringOrIdent(sql, from);\n const raw = sql.slice(from + 1, end - 1);\n return { value: raw.replaceAll(ch + ch, ch), end };\n }\n if (ch === \"[\") {\n // The bracket skip's unterminated-at-EOF return (length + 1) is what\n // keeps `end - 1` the content boundary HERE. The quote path above has no\n // such contract: unterminated, the skip returns length, and `end - 1`\n // drops the final character — long-standing behavior, unchanged.\n const end = skipStringOrIdent(sql, from);\n return { value: sql.slice(from + 1, end - 1), end };\n }\n const m = /^[A-Za-z_][A-Za-z0-9_]*/.exec(sql.slice(from));\n return m ? { value: m[0], end: from + m[0].length } : undefined;\n}\n\n/**\n * Skip one SET-clause expression. Ends at a top-level `,` (another\n * assignment) or a top-level WHERE/FROM/RETURNING keyword or end-of-string.\n */\nfunction skipExpression(\n sql: string,\n from: number,\n): { end: number; terminator: \",\" | \"end\" } {\n let depth = 0;\n let i = from;\n const n = sql.length;\n while (i < n) {\n const ch = sql[i];\n // Every string/identifier form, brackets included — a bracket identifier\n // may contain the `,`/`(`/`)` this scan otherwise acts on. Comments too:\n // `SET k = /* a, b */ 1` must not read the comment's comma as a\n // target separator.\n if (startsStringOrIdent(sql, i)) {\n i = skipStringOrIdent(sql, i);\n continue;\n }\n if (startsComment(sql, i)) {\n i = skipComment(sql, i);\n continue;\n }\n if (ch === \"(\") depth++;\n else if (ch === \")\") depth--;\n else if (depth === 0) {\n if (ch === \",\") return { end: i, terminator: \",\" };\n if (/^(where|from|returning)\\b/i.test(sql.slice(i, i + 10)) &&\n !/[A-Za-z0-9_]/.test(sql[i - 1] ?? \"\")) {\n return { end: i, terminator: \"end\" };\n }\n }\n i++;\n }\n return { end: i, terminator: \"end\" };\n}\n\n// `quoteIdent`, `bindValue`, `assertSingleStatement`, and `loadSqlite` moved\n// to ../core/projection.ts (proposal 0026), where the named checks share them.\n","/**\n * `fill` — infer missing or invalid metadata and write back the values it is\n * confident about.\n *\n * The gate order matters, and it is deliberate: **confidence is the last check,\n * not the only one.** A self-reported score is a weak, uncalibrated signal, so\n * three mechanical checks run first and cannot be overridden by a high score:\n *\n * 1. The proposal must satisfy the target property's own subschema. The model\n * is shown a projection of it (`fill-projection.ts`), and each value is\n * then checked against the whole subschema on its own, with Ajv's type\n * coercion. A value that fails is asked for once more, alone, naming the\n * rule it broke; one that fails again is skipped as `schema-mismatch`,\n * and the file's other proposals stand.\n * 2. It must name a property that was actually a candidate; the envelope's\n * `additionalProperties: false` makes inventing keys impossible, and a\n * response that is not the envelope's shape fails the file.\n * 3. After merging, the document must still validate. Anything that would\n * leave the page failing its own schema is reverted.\n *\n * Only then does the confidence threshold apply. Confidence itself is\n * report-only — it is never written into the document.\n */\nimport { readFile } from \"node:fs/promises\";\nimport {\n loadExternalMetadata,\n mergeWithMarks,\n pageOwners,\n type MergedMetadata,\n} from \"../core/external-metadata.js\";\nimport { pageMarks } from \"../core/page-marks.js\";\nimport { keyHome, relocationContext, type KeyHome } from \"../core/relocation.js\";\nimport {\n externalWriteWarnings,\n offerExternalHomes,\n type ExternalWrite,\n} from \"../core/location-writes.js\";\nimport { warn } from \"../../shared/warn.js\";\nimport { memberOf, retainMembers } from \"../core/collections.js\";\nimport { resolve, extname, join } from \"node:path\";\nimport {\n completeValidatedJSON,\n makeProvider,\n JsonCache,\n buildCacheKey,\n sha256,\n pricingFor,\n costOfUsage,\n InferenceError,\n type InferenceProvider,\n type ProviderSelector,\n type ProviderSpec,\n type TokenUsage,\n} from \"@hawkeyexl/inference\";\nimport {\n DocmetaError,\n type ApplyOptions,\n type ExtractedMetadata,\n type FieldError,\n type MetadataExtractor,\n type MetadataPatch,\n} from \"../types.js\";\nimport { resolveRunConfig, schemaTrustRoot, urlManifestMessage } from \"../core/config.js\";\nimport {\n assertNonEmpty,\n gitignoreOptions,\n resolveTargetSet,\n STDIN_TOKEN,\n} from \"../core/load-files.js\";\nimport {\n extractorByName,\n extractorForExtension,\n listFormats,\n supportedExtensions,\n} from \"../extractors/index.js\";\nimport {\n collectSchemaPins,\n resolveSchemaSetWithSource,\n type ResolvedSchemaSet,\n FILE_SCHEMA_KEY,\n resolveElements,\n} from \"../core/resolve-schema.js\";\nimport { classifyRef, loadSchema, schemaLoadOptions } from \"../core/schema-registry.js\";\nimport type { CollectionConfig } from \"../../shared/collections.js\";\nimport { Validator, compileWithFormats } from \"../core/validator.js\";\nimport type { ValidateFunction } from \"ajv/dist/2020.js\";\nimport { toJsonText } from \"../core/json-text.js\";\nimport { canonical } from \"./fill-projection.js\";\nimport {\n fieldHints,\n offered,\n pageIdReader,\n termValueCheck,\n type TermIndex,\n} from \"./fill-hints.js\";\nimport { PAGE_FIELDS, TERM_FIELDS, type FieldPath } from \"../../shared/reference-fields.js\";\nimport { termLabelSource } from \"../../shared/term-labels.js\";\nimport { writeFileAtomic } from \"../core/write-file.js\";\nimport {\n ENCRYPTED_PLACEHOLDER,\n EncryptionRefusal,\n META_CONTEXT,\n encryptionView,\n lazyKey,\n pointerOf,\n redactForModel,\n settleFindings,\n topLevelKeyOf,\n type EncryptionView,\n} from \"../core/encrypted.js\";\nimport { encryptValue } from \"../../shared/encryption.js\";\nimport { ensureEncryptionKey } from \"../../shared/prompt.js\";\nimport {\n applyManifestOp,\n holdManifestFile,\n recordManifestOp,\n settleManifest,\n type MetaHeldManifest,\n type MetaManifestOp,\n} from \"../core/manifest-writes.js\";\nimport {\n FILL_PROMPT_VERSION,\n FILL_SYSTEM_PROMPT,\n buildEnvelopeSchema,\n buildRetryPrompt,\n buildUserPrompt,\n splitBody,\n mergeProposals,\n DEFAULT_CHUNK_CHARS,\n type Envelope,\n} from \"./fill-prompt.js\";\nimport type {\n Candidate,\n FieldHint,\n FillFileResult,\n FillOptions,\n FillRun,\n FilledField,\n MetaProvenanceReport,\n Proposal,\n ProposalSet,\n} from \"./fill-types.js\";\nimport { mergeMetaProvenance } from \"../core/meta-provenance.js\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport {\n assertKnownProvider as assertKnownProviderFor,\n assertLocalFlag,\n assertModelHasProvider as assertModelHasProviderFor,\n localNotice,\n providerSpecFor,\n resolveIdentity as resolveIdentityFor,\n selectProvider,\n} from \"../../shared/providers.js\";\nimport { deriveCovers, managedFields } from \"../core/derive/types.js\";\nimport { STDIN_REQUIRES_AS } from \"../../shared/cli-options.js\";\nimport { mapConcurrent } from \"../../shared/concurrency.js\";\n\nexport type {\n Candidate,\n FillFileResult,\n FillOptions,\n FillRun,\n FillSummary,\n FilledField,\n MetaProvenanceEntry,\n MetaProvenanceReport,\n Proposal,\n SkipReason,\n} from \"./fill-types.js\";\n\n/** The key `fill` records the fields it wrote in (proposal 0046). */\nconst META_PROVENANCE_KEY = \"meta-provenance\";\n/**\n * Machine attribution, never proposed and never shown to the model (0046). A\n * schema that defines either would otherwise ask a model to invent hashes and\n * to attribute itself.\n */\nconst PROVENANCE_KEYS: ReadonlySet<string> = new Set([\"provenance\", META_PROVENANCE_KEY]);\n\nconst DEFAULT_THRESHOLD = 0.7;\nconst DEFAULT_CONCURRENCY = 4;\nconst CACHE_DIR = \".manni/meta/cache\";\n\n/**\n * Whether a provider error reads like \"the prompt did not fit\".\n *\n * Deliberately loose, and deliberately a *safety net* rather than the mechanism:\n * chunking is bounded by docmeta's own budget, and this only catches the case\n * where that budget was still too generous for the model in play. No provider\n * exposes its input limit ahead of time, and four providers word the failure\n * four ways, so matching on wording is the only option — a miss costs a per-file\n * error the user can act on, not a corrupted document.\n */\nfunction looksLikeOverflow(message: string): boolean {\n // `exceeds`, not `exceed`, and that one letter is load-bearing. Review\n // suggested dropping it because it would match \"rate limit exceeded\" and\n // \"quota exceeded\" — which matters, since the response to an overflow is to\n // halve the budget, and halving *doubles* the call count. Answering a rate\n // limit with twice the requests would be a real fault.\n //\n // But it does not match them: \"exceeded\" does not contain \"exceeds\". Checked\n // against both, plus \"429 Too Many Requests\" — none match. Dropping it lost a\n // genuine overflow instead: \"Your input exceeds the maximum allowed length\"\n // matched before and would not after. Kept deliberately, and written down so\n // the next reader does not re-derive the wrong half of this.\n return /context|too long|too large|token limit|maximum.*tokens|exceeds/i.test(\n message,\n );\n}\n\n/**\n * Add one call's usage to a running total.\n *\n * A chunked document costs several calls, so caching the last one's usage would\n * understate the file by roughly the number of chunks. Nothing reads it back\n * today, which is exactly why it is worth keeping honest now rather than after\n * something does.\n */\nfunction addUsage(\n total: TokenUsage | undefined,\n next: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (next === undefined) return total;\n if (total === undefined) return next;\n return {\n ...total,\n inputTokens: total.inputTokens + next.inputTokens,\n outputTokens: total.outputTokens + next.outputTokens,\n };\n}\n\n/** A manifest a write lands in, with the page's entry there (proposal 0047). */\ntype ManifestHome = Extract<KeyHome, { kind: \"manifest\" }> & { entry: string };\n\n/** One file read, validated and given its candidates, before any model request. */\ninterface ReadyFile {\n ready: true;\n label: string;\n content: string;\n extractor: MetadataExtractor;\n apply: NonNullable<MetadataExtractor[\"apply\"]>;\n elements: string[];\n extracted: ExtractedMetadata;\n merged: MergedMetadata;\n schemaSet: string[];\n schemas: Record<string, unknown>[];\n view: EncryptionView;\n managedSkips: FilledField[];\n candidates: Candidate[];\n inPlace: { key: string; pointer: string; value: unknown }[];\n probeMarks: ReadonlySet<string>;\n sealedCandidates: Candidate[];\n /** Candidates a local manifest owns, and where each is written. */\n destinations: ReadonlyMap<string, ManifestHome>;\n /** Where `meta-provenance` lives for this page. */\n metaHome: KeyHome | undefined;\n /** Candidates that prefer external metadata and have no manifest. */\n flags: ExternalWrite[];\n}\n\n/** What the cache stores: the raw, *pre-gating* proposal for one file. */\ninterface CachedProposal {\n proposals: ProposalSet;\n usage?: TokenUsage;\n}\n\nexport async function runFill(opts: FillOptions): Promise<FillRun> {\n const cwd = opts.cwd ?? process.cwd();\n // Explicit CLI inputs win, else config `paths:`; `base` is whichever of the\n // two directories those inputs were written relative to.\n const runConfig = await resolveRunConfig({\n cwd,\n configPath: opts.configPath,\n noConfig: opts.noConfig,\n inputs: opts.inputs,\n ...(opts.collections !== undefined\n ? { collections: opts.collections }\n : {}),\n onConfigLoaded: opts.onConfigLoaded,\n });\n const { config, inputs, base, collections, fromCollections, configFile } = runConfig;\n // Reassigned when an accepted relocation (0047) creates the config file.\n let configDir = runConfig.configDir;\n // How every schema in this run is loaded: the cross-run cache and\n // `--offline`. `fill` calls `loadSchema` directly as well as through the\n // validator, so both have to be handed the same settings.\n const schemaOptions = schemaLoadOptions({\n root: configDir ?? cwd,\n // A relative file ref belongs to the run's directory, not the cache root.\n fileBase: cwd,\n ttlHours: config?.schemaCache?.ttlHours,\n offline: opts.offline ?? config?.offline,\n pins: collectSchemaPins(config),\n registered: config?.registered,\n });\n // Settled once per run, not per file: finding it is a filesystem walk, and\n // every file in one run shares the same repository.\n const trustRoot = schemaTrustRoot(cwd, configDir);\n const usingStdin = inputs.includes(STDIN_TOKEN);\n if (inputs.length === 0) {\n throw new DocmetaError(\n \"No files to fill. Pass paths/globs, or declare a collection under `collections:` in manni.config.yaml.\",\n );\n }\n\n const forcedExtractor = opts.as ? extractorByName(opts.as) : undefined;\n if (opts.as && !forcedExtractor) {\n // `--as` takes an extractor name (\"markdown\"), so list names — listing\n // extensions here would point the user at the wrong kind of value.\n throw new DocmetaError(\n `Unknown format \"${opts.as}\". Known formats: ${listFormats()\n .map((f) => f.name)\n .join(\", \")}.`,\n );\n }\n if (usingStdin && !forcedExtractor) {\n throw new DocmetaError(\n STDIN_REQUIRES_AS,\n );\n }\n\n // The CLI range-checks its flags, but runFill is also a public API and is\n // called directly from config values, so it validates rather than trusting.\n // A NaN threshold would silently skip every field; a fractional concurrency\n // would be silently truncated by Array.from's ToLength coercion.\n const threshold = requireNumber(\n opts.confidence ?? config?.fill?.confidenceThreshold ?? DEFAULT_THRESHOLD,\n \"confidence\",\n { min: 0, max: 1 },\n );\n const concurrency = requireNumber(\n opts.concurrency ?? config?.fill?.concurrency ?? DEFAULT_CONCURRENCY,\n \"concurrency\",\n { min: 1, max: 64, integer: true },\n );\n const maxTurns = opts.maxTurns ?? config?.fill?.maxTurns;\n if (maxTurns !== undefined) {\n requireNumber(maxTurns, \"maxTurns\", {\n min: 1,\n max: Number.MAX_SAFE_INTEGER,\n integer: true,\n });\n }\n const chunkBudget = requireNumber(\n opts.chunkChars ?? config?.fill?.chunkChars ?? DEFAULT_CHUNK_CHARS,\n \"chunkChars\",\n { min: 1, max: Number.MAX_SAFE_INTEGER, integer: true },\n );\n const dryRun = Boolean(opts.dryRun);\n const only = opts.fields != null ? new Set(opts.fields) : undefined;\n /** The managed fields (0040): read everywhere, written only by `derive`. */\n const managed = new Set<string>(managedFields(config?.derive));\n\n // The flag, then `meta.fill`, then the family's `providers:`, then `auto`,\n // each level's model carried only to the provider that level names.\n //\n // `--local` is llama-cpp over every level, so detection never runs under it\n // and never announces a hosted provider it found. A `--provider` it\n // contradicts is refused by name; a configured one is set aside, and said.\n const flags = { provider: opts.provider, model: opts.model, local: opts.local };\n assertLocalFlag(flags, toDocmetaError);\n const family = configFile?.providers ?? {};\n const selection = selectProvider(flags, [\n { provider: config?.fill?.provider, model: config?.fill?.model, origin: \"fill.provider\" },\n { provider: family.provider, model: family.model, origin: \"providers.provider\" },\n ]);\n const { provider: providerName, model } = selection;\n\n // Check the name up front, and regardless of whether a provider was injected:\n // it costs nothing, and construction is lazy, so a typo would otherwise exit 0\n // on any run where no file happened to need inference.\n assertKnownProvider(providerName);\n assertModelHasProvider(providerName, model);\n const replaced = localNotice(selection);\n if (replaced !== undefined) opts.onNotice?.(replaced);\n // Connection settings are the family's, for whichever provider is in force,\n // and under `auto` they are what detection reads.\n const spec = providerSpecFor(family, { provider: providerName, model: model ?? null });\n\n // Resolve targets BEFORE identity. Under `auto`, resolving identity probes the\n // environment, the Claude CLI and the local runtime, and that last probe is\n // slow on a machine holding no credentials — so a mistyped glob would spend\n // seconds detecting a provider it is never going to use before failing. The\n // work is wasted in exactly the case where the user most wants a fast answer.\n //\n // Identity is still resolved unconditionally below, so an `--allow-empty` run\n // that legitimately matches nothing still reports which provider it would have\n // used.\n const fileInputs = inputs.filter((i) => i !== STDIN_TOKEN);\n const allowEmpty = opts.allowEmpty ?? config?.allowEmpty;\n const fillExts = opts.exts ?? forcedExtractor?.extensions;\n // Only `--exclude`: a collection's `exclude:` governs membership, not the\n // walk of a path someone typed (0041 rule 3).\n const fillExclude = opts.exclude ?? [];\n /** The collections one label belongs to, computed once per file. */\n const membersFor = (label: string): string[] =>\n memberOf(collections, configDir ?? cwd, base, label);\n const { files: walked, gitignoreSkipped } = await resolveTargetSet({\n inputs: fileInputs,\n exts: fillExts,\n exclude: fillExclude,\n cwd: base,\n allowEmpty,\n ...gitignoreOptions({\n flag: opts.respectGitignore,\n configured: config?.respectGitignore,\n onNotice: opts.onNotice,\n }),\n });\n // Rule 9: the walk applied only the family ignores and `--exclude`, so it saw\n // just the first half of each collection's statement. Narrow it to actual\n // members, or a collection's `exclude:` would shape its SQL view and not what\n // a bare run reads. Skipped for typed paths: those are the operator's (rule 3).\n const files = fromCollections ? retainMembers(walked, membersFor) : walked;\n assertNonEmpty({\n files,\n inputs: fileInputs,\n usingStdin,\n allowEmpty,\n exclude: fillExclude,\n exts: fillExts,\n gitignoreSkipped,\n action: \"filled\",\n });\n\n // Identity comes from the spec, not a constructed provider, so a fully cached\n // run needs no API key at all. Under `auto` this is also where detection runs\n // — it probes the environment, the Claude CLI and the local runtime, but never\n // authenticates, so the no-key property survives.\n //\n // The two branches are kept apart rather than merged behind a cast: an\n // injected provider's `provider()` is a free-form string, and only the\n // resolved path yields a name `makeProvider` can be trusted with.\n let identity: { provider: string; model: string };\n let construct: () => InferenceProvider;\n\n if (opts.inferenceProvider) {\n const injected = opts.inferenceProvider;\n identity = { provider: injected.provider(), model: injected.modelName() };\n construct = () => injected;\n } else {\n const resolved = await resolveIdentity(spec);\n identity = resolved;\n // Build from the RESOLVED identity, never the spec we started with: under\n // `auto` that spec still says \"auto\", and the synchronous `makeProvider`\n // rightly refuses to guess. Detection has already run, so the concrete name\n // is known — which keeps construction synchronous and lazy, and that is what\n // lets a fully cached run finish without a key.\n const concrete: ProviderSpec = providerSpecFor(family, resolved);\n construct = () => makeProvider(concrete);\n }\n\n let provider: InferenceProvider | undefined;\n const getProvider = (): InferenceProvider => {\n if (!provider) {\n try {\n provider = construct();\n } catch (err) {\n // Missing API key / unknown provider is operational, not per-file.\n throw new DocmetaError(\n err instanceof InferenceError\n ? err.message\n : `Could not construct the \"${providerName}\" provider: ${errorMessage(err)}`,\n );\n }\n }\n return provider;\n };\n\n const cache =\n opts.cache === false\n ? undefined\n : new JsonCache<CachedProposal>(join(cwd, CACHE_DIR), true, \"manni\");\n const pricing = pricingFor(identity.model);\n\n const validator = new Validator(schemaOptions);\n // What each page's schemas mark external, which a manifest with no keys\n // owns (proposal 0068). Resolved over the run's collections, as below.\n const marks = pageMarks({\n validator,\n config,\n cwd,\n trustRoot,\n ...(opts.cliSchemas !== undefined ? { cliSchemas: opts.cliSchemas } : {}),\n memberOf: (label) => membersFor(label),\n });\n let costUsd = 0;\n let cachedCount = 0;\n let turnsSpent = false;\n let turnsUsed = 0;\n let inFlight = 0;\n\n /**\n * Whether the call cap is spent.\n *\n * Counts **calls, not files**: chunking a long document costs several, and a\n * cap that counted files would silently under-count exactly the pages that\n * cost the most. Checked before each call rather than each file for the same\n * reason.\n */\n const turnsExhausted = (): boolean =>\n maxTurns != null && turnsUsed + inFlight >= maxTurns;\n\n // External metadata (0037), read once per run, and again after an accepted\n // relocation (0047) declares a manifest. Merged so the schema sees one\n // object; a candidate a local manifest owns is written into that manifest.\n //\n // Every declared collection's local manifests are read, not only the ones\n // `--collection` selects: a write lands in whichever manifest owns the key\n // for the page (0047), so what the page already holds, and the\n // `meta-provenance` list a write extends, must be read from that manifest\n // too. Otherwise a curated value in a collection the run left out reads as\n // missing and is overwritten. A URL manifest of an unselected collection is\n // not fetched: fill cannot write one, and refuses the file that would.\n const mergedCollections = (): CollectionConfig[] => {\n const selected = new Set(collections.map((c) => c.name));\n return runConfig.declaredCollections.map((c) =>\n selected.has(c.name)\n ? c\n : { ...c, externalMetadata: c.externalMetadata.filter((m) => classifyRef(m.file).kind !== \"url\") },\n );\n };\n const loadManifests = () =>\n loadExternalMetadata(mergedCollections(), {\n configDir: configDir ?? cwd,\n base,\n offline: opts.offline ?? config?.offline ?? false,\n // A `{page}` manifest (0058) is read for exactly the pages this run fills.\n pages: files.map((file) => resolve(base, file)),\n });\n /** The declared collections one label belongs to, for the merge. */\n const mergeMembersFor = (label: string): string[] =>\n memberOf(runConfig.declaredCollections, configDir ?? cwd, base, label);\n let externalMetadata = await loadManifests();\n\n // The values offered for the fields that name a glossary term or a page\n // (`fill-hints.ts`). The termbase is read once per run and each collection\n // walked once, and only when some file has a field that needs them.\n let termbase: Promise<TermIndex | undefined> | undefined;\n const readTermbase = async (): Promise<TermIndex | undefined> => {\n if (opts.termLabels !== undefined) return { labels: [...opts.termLabels], ids: [] };\n const source = termLabelSource();\n if (source === undefined) return undefined;\n try {\n const terms = await source({\n cwd,\n ...(opts.configPath === undefined ? {} : { configPath: opts.configPath }),\n ...(opts.noConfig === true ? { noConfig: true } : {}),\n });\n return { labels: terms.map((t) => t.label), ids: terms.map((t) => t.id) };\n } catch (err) {\n // A termbase that cannot be read offers nothing, so the field is asked\n // for as it is where there is no termbase at all. Said once, because\n // otherwise the run looks like one with no termbase and gives no reason.\n opts.onNotice?.(\n `The termbase could not be read, so fill offers no glossary labels: ${errorMessage(err)}`,\n );\n return undefined;\n }\n };\n const respectGitignore = opts.respectGitignore ?? config?.respectGitignore;\n const pageIds = pageIdReader({\n collections: runConfig.declaredCollections,\n configDir: configDir ?? cwd,\n ...(respectGitignore === undefined ? {} : { respectGitignore }),\n });\n /** One file's offered values, and the termbase its term values are checked against. */\n const hintsFor = async (\n label: string,\n candidates: readonly Candidate[],\n ): Promise<{ hints: FieldHint[]; termIndex: TermIndex | undefined }> => {\n const keys = new Set(candidates.map((c) => c.key));\n const wants = (fields: readonly FieldPath[]): boolean =>\n fields.some(([key]) => key !== undefined && keys.has(key));\n const termIndex = wants(TERM_FIELDS) ? await (termbase ??= readTermbase()) : undefined;\n const pages = wants(PAGE_FIELDS)\n ? await pageIds(resolve(base, label), mergeMembersFor(label))\n : [];\n const hints = fieldHints(candidates, {\n terms: termIndex === undefined ? undefined : offered(termIndex.labels),\n pages: offered(pages),\n });\n return { hints, termIndex };\n };\n // A schema notice names its file. Preparing runs again after an accepted\n // relocation, and relocation reads the same schemas, so each is said once.\n const noticed = new Set<string>();\n const noticeOnce =\n opts.onNotice === undefined\n ? undefined\n : (message: string): void => {\n if (noticed.has(message)) return;\n noticed.add(message);\n opts.onNotice?.(message);\n };\n const ctx = relocationContext(runConfig, {\n cwd,\n targets: fromCollections ? [] : fileInputs,\n validator,\n ...(opts.noConfig === true ? { noConfig: true } : {}),\n ...(opts.cliSchemas !== undefined && opts.cliSchemas.length > 0 ? { cliSchemas: opts.cliSchemas } : {}),\n ...(opts.as !== undefined ? { as: opts.as } : {}),\n ...(opts.respectGitignore !== undefined ? { respectGitignore: opts.respectGitignore } : {}),\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n ...(noticeOnce !== undefined ? { onNotice: noticeOnce } : {}),\n });\n /**\n * Each manifest this run writes, read once and spliced in memory. It is\n * saved after each file that changes it, once that file's page is written,\n * so a run that aborts on a later file keeps the entries of the pages it\n * already wrote. `saving` is the queue those saves run on.\n *\n * Files are filled concurrently, so the edits go on the queue too rather\n * than onto the held text where they were computed. A save reads the held\n * text, re-reads the file and writes; another file splicing into that text\n * across one of those awaits would be written by a save that had already\n * decided it was done. On the queue, each file's edits and its save are one\n * turn, and nothing interleaves with them.\n */\n interface Holding {\n held: MetaHeldManifest;\n saving: Promise<void>;\n }\n const heldManifests = new Map<string, Holding>();\n const holding = new Map<string, Promise<Holding>>();\n /** Queue one file's edits to one manifest, and the save that lands them. */\n const saveManifest = (h: Holding, ops: readonly MetaManifestOp[]): Promise<void> => {\n h.saving = h.saving.then(async () => {\n for (const op of ops) {\n const after = applyManifestOp(h.held.text, op);\n if (after === h.held.text) continue;\n recordManifestOp(h.held, op);\n h.held.text = after;\n }\n if (!dryRun) await settleManifest(h.held);\n });\n return h.saving;\n };\n /**\n * Put a page back after a refused manifest write, and say which happened.\n * `relocate` words a failed restore the same way: the run cannot fix it, so\n * it names the file and hands the reader to version control.\n */\n const restorePage = async (label: string, before: string): Promise<string> => {\n try {\n await writeFileAtomic(resolve(base, label), before);\n return `${label} was restored.`;\n } catch (err) {\n return `${label} could not be restored: ${errorMessage(err)}. Restore it from version control.`;\n }\n };\n const holdManifest = (home: { absPath: string; file: string; perPage: boolean }): Promise<Holding> => {\n let held = holding.get(home.absPath);\n if (held === undefined) {\n held = holdManifestFile(home.absPath, home.file, home.perPage).then((m) => {\n const h: Holding = { held: m, saving: Promise.resolve() };\n heldManifests.set(home.absPath, h);\n return h;\n });\n holding.set(home.absPath, held);\n }\n return held;\n };\n\n // Proposal 0045. The key encrypted values are read and written with: the\n // configured one, resolved when first needed, or the one this run's prompt\n // wrote. The prompt is asked once, whichever worker needs it first, and\n // every other worker awaits the same answer.\n const configuredKey = lazyKey(configFile, opts.env);\n let ensuredKey: string | undefined;\n let ensuring: Promise<string> | undefined;\n const currentKey = (): string | undefined => ensuredKey ?? configuredKey();\n const writeKey = async (subject: string): Promise<string> => {\n const have = currentKey();\n if (have !== undefined) return have;\n ensuring ??= ensureEncryptionKey({\n subject,\n cwd,\n file: configFile ?? null,\n ...(opts.env === undefined ? {} : { env: opts.env }),\n ...(opts.confirm === undefined ? {} : { confirm: opts.confirm }),\n notice: (message) => opts.onNotice?.(message),\n toError: (message) => new EncryptionRefusal(message),\n }).then(({ key }) => {\n ensuredKey = key;\n return key;\n });\n return ensuring;\n };\n /**\n * A marked value as it lands in the patch. A dry run writes nothing and\n * reports `(encrypted)`, so it neither prompts nor refuses: it encrypts\n * under a key it already has, and otherwise holds the placeholder, as\n * `query --dry-run` does.\n */\n const seal = async (value: unknown, pointer: string): Promise<unknown> => {\n if (dryRun) {\n const key = currentKey();\n return key === undefined ? ENCRYPTED_PLACEHOLDER : encryptValue(value, key, META_CONTEXT);\n }\n return encryptValue(value, await writeKey(pointer), META_CONTEXT);\n };\n\n const prepareOne = async (\n label: string,\n content: string,\n extension: string,\n ): Promise<FillFileResult | ReadyFile> => {\n const extractor = forcedExtractor ?? extractorForExtension(extension);\n if (!extractor) {\n return errorResult(\n label,\n \"unknown\",\n `Unsupported file type \"${extension}\". Supported: ${supportedExtensions().join(\", \")}. Use --as to override.`,\n );\n }\n const apply = extractor.apply;\n if (typeof apply !== \"function\") {\n return errorResult(\n label,\n extractor.name,\n `The \"${extractor.name}\" format is read-only; manni meta fill cannot write metadata back to it.`,\n );\n }\n\n // Resolved once per file. It walks every `overrides:` entry and dedupes,\n // and the three call sites below — extract, the write pre-flight, and the\n // write itself — all want the same answer for the same file.\n // The selected collections this file belongs to, computed once per file:\n // both resolution calls below ask the same question of it. The merge\n // reads every declared collection's manifests (see `loadManifests`).\n const members = membersFor(label);\n const elements = resolveElements(label, config, members);\n\n let extracted;\n let merged;\n try {\n merged = await mergeWithMarks(\n label,\n extractor.extract(content, label, { elements }),\n externalMetadata,\n mergeMembersFor(label),\n base,\n { encryptionKey: currentKey, marks },\n );\n extracted = merged.extracted;\n } catch (err) {\n // A refusal about the run's key is the run's, not this file's.\n if (err instanceof EncryptionRefusal) throw err;\n return errorResult(label, extractor.name, errorMessage(err));\n }\n\n let resolved: ResolvedSchemaSet;\n try {\n resolved = resolveSchemaSetWithSource({\n filePath: label,\n fileSchema: extracted.data[FILE_SCHEMA_KEY],\n cliSchemas: opts.cliSchemas,\n config,\n memberOf: members,\n // Same trust boundary as `validate`: `fill` writes metadata back into\n // the document, so a schema a document chose for itself decides what\n // gets written — if anything, a stronger reason to guard it.\n fileBase: cwd,\n trustRoot,\n onNotice: noticeOnce,\n });\n } catch (err) {\n return errorResult(label, extractor.name, errorMessage(err));\n }\n\n const schemaSet = resolved.schemas;\n let schemas: Record<string, unknown>[];\n let existingErrors;\n let view: EncryptionView;\n try {\n schemas = await Promise.all(\n schemaSet.map((ref) => loadSchema(ref, schemaOptions)),\n );\n // Validated as `validate` does (proposal 0045): marked values as their\n // plaintext, on a copy, and nothing at or under a value no key could\n // read. A ciphertext that fails its enum is not a missing value, and\n // fill must never overwrite it with a guess.\n view = await encryptionView({\n data: extracted.data,\n refs: schemaSet,\n validator,\n key: currentKey,\n locate: merged.locate,\n });\n existingErrors = settleFindings(\n await validator.validate(\n view.data,\n schemaSet,\n extracted.lineFor,\n extracted.colFor,\n merged.locate,\n ),\n view,\n extracted,\n merged.locate,\n );\n } catch (err) {\n if (err instanceof EncryptionRefusal) throw err;\n // Same rule as `validate`: a schema the *document* chose failing to load\n // is that document's failure and is reported as one, so one file cannot\n // abort the run. Every other source stays operational, because a schema\n // the operator configured invalidates every file, not just this one.\n if (!(err instanceof DocmetaError) || resolved.source !== \"document\") {\n throw err;\n }\n return errorResult(label, extractor.name, err.message);\n }\n const proposed = collectCandidates(\n schemas,\n view.data,\n existingErrors,\n only,\n );\n // A managed field (0040) is never a candidate: only `derive` writes it,\n // and a model's guess at a date git already knows would be exactly the\n // stamp the channel exists to make trustworthy. Reported rather than\n // dropped, so the omission is visible and a required one still fails\n // the run — the fix being `manni meta derive`, not a better model.\n // A file outside `derive.collections` has no managed fields (0070).\n const managedHere = deriveCovers(config?.derive, members) ? managed : new Set<string>();\n const managedSkips: FilledField[] = proposed\n .filter((c) => managedHere.has(c.key))\n .map((c) => ({\n field: pointerOf(c.key),\n required: c.required,\n confidence: 0,\n reasoning: \"managed by derive\",\n written: false,\n skipReason: \"managed\",\n }));\n const candidates = proposed.filter((c) => !managedHere.has(c.key));\n // Proposal 0047: a candidate a manifest of this page's collections owns\n // is written into the page's entry there. A URL manifest cannot be\n // written, and a field join the page lacks has no entry, so either\n // refuses the file before any model request. A candidate its schema\n // prefers in external metadata that no manifest owns is flagged, for the\n // P1 offer or the W1 and W2 warnings. `meta-provenance` follows its own\n // location the same way, and never fails the file.\n const destinations = new Map<string, ManifestHome>();\n const flags: ExternalWrite[] = [];\n let metaHome: KeyHome | undefined;\n if (label !== \"<stdin>\" && candidates.length > 0) {\n const located: Record<string, unknown> = { ...view.data };\n for (const c of candidates) {\n if (!Object.hasOwn(located, c.key)) located[c.key] = \"\";\n }\n if (!Object.hasOwn(located, META_PROVENANCE_KEY)) located[META_PROVENANCE_KEY] = [];\n const prefs = await validator.locationPreferences(located, schemaSet);\n for (const key of [...candidates.map((c) => c.key), META_PROVENANCE_KEY]) {\n const home = await keyHome(ctx, label, extracted.data, key);\n const meta = key === META_PROVENANCE_KEY;\n if (meta) metaHome = home;\n if (home.kind === \"url\") {\n if (meta) continue;\n return errorResult(label, extractor.name, urlManifestMessage(key, home.file), schemaSet);\n }\n if (home.kind === \"manifest\") {\n if (home.entry === undefined) {\n if (meta) continue;\n return errorResult(\n label,\n extractor.name,\n `${label} carries no ${home.join}, which ${home.file} joins on, so its ${key} has no entry there.`,\n schemaSet,\n );\n }\n if (!meta) destinations.set(key, { ...home, entry: home.entry });\n continue;\n }\n if (prefs.get(key)?.location === \"external\") flags.push({ label, key, home: home.home });\n }\n }\n // Proposal 0045: which of this file's writes must be encrypted. A valid\n // value the page holds in plain text in a marked property is encrypted\n // where it stands, with no proposal; a candidate is one when the schema\n // marks it, asked with a placeholder in its place, because an absent\n // property is one Ajv never evaluates.\n const inPlace = view.plain.flatMap((pointer) => {\n const key = topLevelKeyOf(pointer);\n if (key === undefined || (only !== undefined && !only.has(key))) return [];\n if (PROVENANCE_KEYS.has(key)) return [];\n if (externalMetadata?.owners.has(key) === true) return [];\n if (pageOwners(externalMetadata, key, mergeMembersFor(label), merged.marked).length > 0) return [];\n if (candidates.some((c) => c.key === key)) return [];\n return [{ key, pointer, value: extracted.data[key] }];\n });\n const probe: Record<string, unknown> = { ...view.data };\n for (const c of candidates) {\n if (!Object.hasOwn(probe, c.key)) probe[c.key] = \"\";\n }\n const probeMarks: ReadonlySet<string> =\n candidates.length > 0\n ? await validator.markedPointers(probe, schemaSet)\n : new Set<string>();\n const sealedCandidates = candidates.filter((c) =>\n probeMarks.has(pointerOf(c.key)),\n );\n\n if (candidates.length === 0 && inPlace.length === 0) {\n return {\n file: label,\n format: extractor.name,\n schemas: schemaSet,\n fields: managedSkips,\n changed: false,\n ...(opts.includeContent ? { content } : {}),\n };\n }\n\n // Probe writability with an empty patch *before* paying for inference.\n // rst/asciidoc accept `apply` but reject documents that use their native\n // metadata syntax, and finding that out afterwards means the call is\n // billed for a file that could never have been written.\n try {\n apply(content, {}, { filePath: label, elements });\n } catch (err) {\n return errorResult(label, extractor.name, errorMessage(err), schemaSet);\n }\n\n return {\n ready: true,\n label,\n content,\n extractor,\n apply,\n elements,\n extracted,\n merged,\n schemaSet,\n schemas,\n view,\n managedSkips,\n candidates,\n inPlace,\n probeMarks,\n sealedCandidates,\n destinations,\n metaHome,\n flags,\n };\n };\n\n const finishOne = async (ready: ReadyFile): Promise<FillFileResult> => {\n const {\n label,\n content,\n extractor,\n apply,\n elements,\n extracted,\n merged,\n schemaSet,\n schemas,\n view,\n managedSkips,\n candidates,\n inPlace,\n probeMarks,\n sealedCandidates,\n destinations,\n metaHome,\n } = ready;\n // The key before the first model request, so a refused prompt never\n // wastes a paid run. A dry run writes nothing, so it needs no key.\n const firstSealed =\n inPlace[0]?.pointer ??\n (sealedCandidates[0] === undefined ? undefined : pointerOf(sealedCandidates[0].key));\n if (firstSealed !== undefined && !dryRun) await writeKey(firstSealed);\n\n const { hints, termIndex } =\n candidates.length > 0 ? await hintsFor(label, candidates) : { hints: [], termIndex: undefined };\n\n // ---- Propose (cache first) -------------------------------------------\n const cacheKey = buildCacheKey([\n identity.provider,\n identity.model,\n `fill-v${FILL_PROMPT_VERSION}`,\n // The chunk budget decides how the document was split, and so which\n // proposals came back. Without it two runs at different budgets share a\n // key and the second silently replays the first — and the halve-and-retry\n // path above makes that a real collision, not a hypothetical one.\n `chunk-${chunkBudget}`,\n schemaSet.join(\",\"),\n candidates.map((c) => c.key).join(\",\"),\n // The values offered, so a new term or page asks again.\n `hints-${sha256(canonical(hints))}`,\n sha256(content),\n ]);\n const hit = candidates.length > 0 ? cache?.get(cacheKey) : undefined;\n\n // What the model is told the page already holds: neither the plaintext\n // nor the ciphertext of a marked field (0017's egress rule), and neither\n // provenance key (0046).\n const existing = Object.fromEntries(\n Object.entries(redactForModel(extracted.data, [...view.marked, ...probeMarks])).filter(\n ([key]) => !PROVENANCE_KEYS.has(key),\n ),\n );\n\n // The envelope is built on a cache hit too. The cache holds the model's\n // raw answers, and each is checked, and coerced, again on every read.\n //\n // `envelope`, `check` and `validateShape` are set together, only when\n // there are candidates to ask about, and never reassigned afterward. Every\n // use below narrows on that instead of assuming a placeholder that is\n // never actually called.\n let envelope: Envelope | undefined;\n let check: ValueCheck | undefined;\n let validateShape: ValidateFunction | undefined;\n if (candidates.length > 0) {\n // The library's own Ajv has no ajv-formats, so a lifted subschema with\n // `format: \"date-time\"` would fail to compile. Compile it ourselves — and\n // keep the failure per-file, since an unresolvable `$ref` in one schema\n // must not abort a whole directory walk.\n try {\n envelope = buildEnvelopeSchema(candidates, collectDefs(schemas), hints);\n check = valueCheck(\n compileWithFormats(envelope.full, config?.registered, { coerce: true }),\n termIndex === undefined ? undefined : termValueCheck(hints, termIndex),\n );\n validateShape = compileWithFormats(envelope.skeleton);\n } catch (err) {\n return errorResult(\n label,\n extractor.name,\n `Could not build a proposal schema from ${schemaSet.join(\", \")}: ${errorMessage(err)}`,\n schemaSet,\n );\n }\n }\n\n // No candidates means the only work is encrypting what the page holds.\n let proposals: ProposalSet = {};\n if (hit) {\n cachedCount++;\n proposals = hit.proposals;\n } else if (\n envelope !== undefined &&\n check !== undefined &&\n validateShape !== undefined &&\n envelope.asked.length > 0\n ) {\n if (turnsExhausted()) {\n turnsSpent = true;\n return errorResult(\n label,\n extractor.name,\n \"Skipped: --max-turns reached before this file was processed.\",\n schemaSet,\n );\n }\n const { asked, sent } = envelope;\n const shape = validateShape;\n // The whole file goes out, in as many calls as the chunk budget takes.\n // An overflow means the budget was too generous for this model — there is\n // no way to ask a model its input limit ahead of time — so halve it once\n // and retry rather than failing a file for being long.\n // The page as the model reads it: marked values and every ciphertext\n // read `(encrypted)` in the body too, not only in the metadata above.\n const modelContent = contentForModel(\n content,\n extractor,\n existing,\n extracted.data,\n (pointer) => merged.locate(pointer) !== undefined,\n { filePath: label, elements },\n );\n let chunkChars = chunkBudget;\n let attempt = 0;\n let sets: ProposalSet[] | undefined;\n let usageTotal: TokenUsage | undefined;\n let partsRead: { read: number; total: number } | undefined;\n let failure: string | undefined;\n // Set when the call cap stopped a retry, so the set is not cached: a\n // later run with room for it would otherwise replay the failed values.\n let retrySkipped = false;\n while (attempt < 2 && sets === undefined) {\n attempt++;\n const chunks = splitBody(modelContent, chunkChars);\n const collected: ProposalSet[] = [];\n let overflowed = false;\n let cutShort = false;\n for (const [i, chunk] of chunks.entries()) {\n if (turnsExhausted()) {\n turnsSpent = true;\n // Stopping mid-document is not a partial success. Proposals merged\n // from the chunks that did run would describe part of the page\n // while reading as though they described all of it — the silent\n // truncation this change exists to remove, reintroduced by another\n // route. Report the file as not processed instead.\n cutShort = true;\n break;\n }\n const part =\n chunks.length > 1 ? { part: { index: i + 1, total: chunks.length } } : {};\n inFlight++;\n let run;\n try {\n run = await completeValidatedJSON<ProposalSet>({\n provider: getProvider(),\n system: FILL_SYSTEM_PROMPT,\n user: buildUserPrompt({\n filePath: label,\n existing,\n candidates: asked,\n body: chunk,\n ...part,\n }),\n schema: sent,\n validate: shape,\n });\n costUsd += costOfUsage(run.usage, pricing);\n turnsUsed++;\n } finally {\n inFlight--;\n }\n if (run.error != null && looksLikeOverflow(run.error)) {\n overflowed = true;\n failure = run.error;\n break;\n }\n if (run.error != null || run.result == null) {\n failure = run.error ?? \"The model returned no proposal.\";\n break;\n }\n usageTotal = addUsage(usageTotal, run.usage);\n let set = run.result;\n\n // One more request for the values that failed their rules, and\n // only for those. It never asks a second time, and a retry that\n // errors leaves the first answers to fail as `schema-mismatch`.\n const failed = asked.flatMap((candidate) => {\n const proposal = set[candidate.key];\n if (proposal == null || proposal.value === null) return [];\n const checked = check(candidate.key, proposal);\n return checked.ok ? [] : [{ candidate, errors: checked.errors }];\n });\n if (failed.length > 0 && turnsExhausted()) {\n retrySkipped = true;\n } else if (failed.length > 0) {\n const again = buildEnvelopeSchema(\n failed.map((f) => f.candidate),\n collectDefs(schemas),\n hints,\n );\n inFlight++;\n let retry;\n try {\n retry = await completeValidatedJSON<ProposalSet>({\n provider: getProvider(),\n system: FILL_SYSTEM_PROMPT,\n user: buildRetryPrompt({\n filePath: label,\n existing,\n candidates: again.asked,\n body: chunk,\n ...part,\n rejected: failed.flatMap((f) => f.errors),\n }),\n schema: again.sent,\n // The skeleton checks the response's shape only; `check`\n // judges each value, with the registered schemas.\n validate: compileWithFormats(again.skeleton),\n attempts: 1,\n });\n costUsd += costOfUsage(retry.usage, pricing);\n turnsUsed++;\n } finally {\n inFlight--;\n }\n const answers = retry.result;\n if (retry.error == null && answers != null) {\n usageTotal = addUsage(usageTotal, retry.usage);\n const retried = new Set(failed.map((f) => f.candidate.key));\n // A retried key the model left out is declined, as a `null` is.\n set = Object.fromEntries([\n ...Object.entries(set).filter(([key]) => !retried.has(key)),\n ...Object.entries(answers),\n ]);\n }\n }\n collected.push(set);\n }\n if (overflowed && attempt < 2) {\n // The calls this attempt already made stay counted against\n // `--max-turns`. They were made — the provider billed them — so\n // rolling them back would make the cap describe something other than\n // what happened. It does mean a document that triggers the retry\n // costs more turns than its final chunk count suggests.\n //\n // The cached *usage* is reset, though, because it describes the\n // document rather than the run: leaving the abandoned attempt's\n // tokens in would double-count the content both attempts covered.\n usageTotal = undefined;\n retrySkipped = false;\n chunkChars = Math.max(1, Math.floor(chunkChars / 2));\n continue;\n }\n if (cutShort) {\n return errorResult(\n label,\n extractor.name,\n `Skipped: --max-turns reached ${chunks.length > 1 ? `part-way through this document (${collected.length} of ${chunks.length} parts read)` : \"before this file was processed\"}.`,\n schemaSet,\n );\n }\n // Only a document read end to end is usable. Anything short of that —\n // a transient provider error on chunk 3, or an overflow that survived\n // the one retry — would otherwise be merged and written as though it\n // described the whole page, which is the silent truncation this change\n // exists to remove. `cutShort` catches the turn-cap route above; this\n // catches the rest.\n partsRead = { read: collected.length, total: chunks.length };\n if (collected.length < chunks.length) break;\n sets = collected;\n }\n\n if (sets === undefined || sets.length === 0) {\n return errorResult(\n label,\n extractor.name,\n failure ?? \"The model returned no proposal.\",\n schemaSet,\n );\n }\n /* c8 ignore next 3 -- the loop only assigns a complete set. */\n if (partsRead !== undefined && partsRead.read < partsRead.total) {\n throw new DocmetaError(\"Internal error: incomplete proposal set.\");\n }\n // The raw answers are kept, so coercion runs again on every read. That\n // is deliberate here too, not only for the cache: the merge checks each\n // answer to pick a winner, and `gate` checks the winner again to get the\n // coerced value it writes. Coercion is idempotent and runs on a copy.\n proposals = mergeProposals(sets, (key, proposal) => check(key, proposal).ok);\n if (!retrySkipped) {\n cache?.set(cacheKey, { proposals, ...(usageTotal ? { usage: usageTotal } : {}) });\n }\n }\n\n // ---- Gate -------------------------------------------------------------\n const unsatisfiable = new Set(envelope?.unsatisfiable.map((c) => c.key));\n // `check` is set exactly when there are candidates (see above), which is\n // exactly when `gate` would ever call it, so no candidates gates to no\n // fields rather than needing a value that is never actually used.\n const fields = [\n ...managedSkips,\n ...(check === undefined ? [] : gate(candidates, proposals, threshold, check, unsatisfiable)),\n ];\n\n // ---- Re-validate, and revert anything that makes the page worse -------\n const accepted = fields.filter((f) => f.written);\n if (accepted.length > 0) {\n // The decrypted copy, so a marked value is judged as its plaintext.\n const revalidationData = { ...view.data, ...patchOf(accepted) };\n const after = settleFindings(\n await validator.validate(\n revalidationData,\n schemaSet,\n extracted.lineFor,\n extracted.colFor,\n ),\n view,\n extracted,\n );\n const broken = new Set(\n after.map((e) => topKey(e.instancePath)).filter((k) => k !== \"\"),\n );\n for (const f of accepted) {\n if (broken.has(keyOf(f))) {\n f.written = false;\n f.skipReason = \"schema-mismatch\";\n delete f.value;\n }\n }\n }\n\n const writable = fields.filter((f) => f.written);\n if (writable.length === 0 && inPlace.length === 0) {\n return {\n file: label,\n format: extractor.name,\n schemas: schemaSet,\n fields,\n changed: false,\n ...(opts.includeContent ? { content } : {}),\n };\n }\n\n // Proposal 0045: a marked value is written encrypted and reported as\n // `(encrypted)`. The marks are read again over the values about to land,\n // since a proposal can take an `if` branch the page did not.\n const plainPatch = patchOf(writable);\n const finalMarks: ReadonlySet<string> =\n writable.length > 0\n ? await validator.markedPointers({ ...view.data, ...plainPatch }, schemaSet)\n : new Set<string>();\n const patch: MetadataPatch = {};\n for (const f of writable) {\n const key = keyOf(f);\n const pointer = pointerOf(key);\n if (finalMarks.has(pointer) || probeMarks.has(pointer)) {\n patch[key] = await seal(f.value, pointer);\n f.value = ENCRYPTED_PLACEHOLDER;\n f.encrypted = true;\n } else {\n patch[key] = f.value;\n }\n }\n const required = requiredKeys(schemas);\n for (const f of inPlace) {\n patch[f.key] = await seal(f.value, f.pointer);\n fields.push({\n field: f.pointer,\n required: required.has(f.key),\n confidence: 1,\n reasoning: IN_PLACE_REASONING,\n value: ENCRYPTED_PLACEHOLDER,\n written: true,\n encrypted: true,\n });\n }\n\n // ---- meta-provenance (0046) --------------------------------------------\n // The fields this run proposed, in the same write. Re-encrypting in place\n // is not a proposal, so a run that only did that records nothing. Nothing\n // here fails the file: a side record that could block filling would be\n // worse than none.\n let metaProvenance: MetaProvenanceReport | undefined;\n /** The `meta-provenance` list, when a manifest owns it (0047). */\n let metaWrite: { value: unknown; home: ManifestHome } | undefined;\n if (writable.length > 0) {\n const metaManifest = metaHome?.kind === \"manifest\" ? metaHome : undefined;\n const metaEntry = metaManifest?.entry;\n // The merged metadata: the manifest's list when one owns the key.\n const mergedProvenance =\n metaHome?.kind === \"url\" || (metaManifest !== undefined && metaEntry === undefined)\n ? undefined\n : mergeMetaProvenance(\n extracted.data[META_PROVENANCE_KEY],\n identity.model,\n \"fields\",\n writable.map((f) => ({ name: f.field, confidence: f.confidence })),\n );\n if (metaHome?.kind === \"url\") {\n metaProvenance = { written: false, skipReason: \"manifest-owned\", manifest: metaHome.file };\n } else if (metaManifest !== undefined && metaEntry === undefined) {\n // A field join the page lacks: the manifest has no entry to hold it.\n metaProvenance = { written: false, skipReason: \"unwritable\" };\n } else if (\n mergedProvenance === undefined ||\n (await addsFindings(\n (data) =>\n validator\n .validate(data, schemaSet, extracted.lineFor, extracted.colFor)\n .then((errors) => settleFindings(errors, view, extracted)),\n { ...view.data, ...plainPatch },\n mergedProvenance.list,\n ))\n ) {\n // The re-check above ignores root errors, which is where\n // `additionalProperties`, `unevaluatedProperties` and `propertyNames`\n // report, so the entry is checked on its own.\n metaProvenance = { written: false, skipReason: \"schema-mismatch\" };\n } else if (metaManifest !== undefined && metaEntry !== undefined) {\n metaWrite = { value: mergedProvenance.list, home: { ...metaManifest, entry: metaEntry } };\n metaProvenance = {\n written: true,\n entry: { ...mergedProvenance.entry, fields: mergedProvenance.names },\n destination: metaManifest.file,\n };\n } else {\n patch[META_PROVENANCE_KEY] = mergedProvenance.list;\n metaProvenance = { written: true, entry: { ...mergedProvenance.entry, fields: mergedProvenance.names } };\n }\n }\n\n // Proposal 0047: a value a manifest owns leaves the page's patch for the\n // page's entry in that manifest, ciphertext and all.\n const entryWrites: { key: string; value: unknown; home: ManifestHome }[] = [];\n for (const f of fields) {\n const key = keyOf(f);\n const home = destinations.get(key);\n if (!f.written || home === undefined || !Object.hasOwn(patch, key)) continue;\n entryWrites.push({ key, value: patch[key], home });\n f.destination = home.file;\n }\n if (metaWrite !== undefined) entryWrites.push({ key: META_PROVENANCE_KEY, ...metaWrite });\n const pagePatch: MetadataPatch = Object.fromEntries(\n Object.entries(patch).filter(([key]) => !destinations.has(key)),\n );\n\n let next: string;\n try {\n next = apply(content, pagePatch, {\n filePath: label,\n elements,\n });\n } catch (err) {\n // A format whose writer cannot hold the entry (an HTML attribute holds\n // one line) still gets its fields.\n const withoutEntry = metaProvenance?.written === true && metaWrite === undefined\n ? tryApply(extractor, content, withoutKey(pagePatch, META_PROVENANCE_KEY), {\n filePath: label,\n elements,\n })\n : undefined;\n if (withoutEntry === undefined) {\n return errorResult(\n label,\n extractor.name,\n errorMessage(err),\n schemaSet,\n fields,\n );\n }\n next = withoutEntry;\n metaProvenance = { written: false, skipReason: \"unwritable\" };\n }\n\n // Every manifest this file writes is held first, and each edit is kept as\n // the descriptor that made it rather than as the text it produced, so a\n // manifest another command moved under the run can be replayed onto. The\n // edits are applied once to refuse the file before its page is written,\n // then again over the held text once the page is: from there to the save\n // nothing awaits, so no other file's edit can interleave, and a page that\n // was never written leaves no entry behind.\n const helds = await Promise.all(entryWrites.map((w) => holdManifest(w.home)));\n const ops: { at: Holding; op: MetaManifestOp }[] = [];\n for (const [i, w] of entryWrites.entries()) {\n const at = helds[i];\n /* c8 ignore next -- one hold per write, by construction. */\n if (at === undefined) continue;\n ops.push({\n at,\n op: {\n kind: \"splice\",\n entry: w.home.entry,\n key: w.key,\n value: w.value,\n join: w.home.join,\n file: w.home.file,\n },\n });\n }\n let manifestChanged = false;\n try {\n const texts = new Map<string, string>();\n for (const { at, op } of ops) {\n texts.set(at.held.path, applyManifestOp(texts.get(at.held.path) ?? at.held.text, op));\n }\n manifestChanged = [...texts].some(([path, text]) => heldManifests.get(path)?.held.text !== text);\n } catch (err) {\n if (!(err instanceof DocmetaError)) throw err;\n return errorResult(label, extractor.name, err.message, schemaSet, fields);\n }\n\n const changed = next !== content || manifestChanged;\n const pageWritten = next !== content && !dryRun && label !== \"<stdin>\";\n if (pageWritten) {\n await writeFileAtomic(resolve(base, label), next);\n }\n if (manifestChanged) {\n const perManifest = new Map<Holding, MetaManifestOp[]>();\n for (const { at, op } of ops) {\n const list = perManifest.get(at);\n if (list === undefined) perManifest.set(at, [op]);\n else list.push(op);\n }\n const saves = [...perManifest].map(([at, list]) => saveManifest(at, list));\n try {\n await Promise.all(saves);\n } catch (err) {\n // The page goes first, so a refused manifest leaves it changed with\n // nothing recorded about it. Put it back, and say which happened.\n if (!pageWritten) throw err;\n const note = await restorePage(label, content);\n if (err instanceof DocmetaError) throw new DocmetaError(`${err.message} ${note}`);\n throw err;\n }\n }\n return {\n file: label,\n format: extractor.name,\n schemas: schemaSet,\n fields,\n changed,\n ...(opts.includeContent ? { content: next } : {}),\n ...(metaProvenance === undefined ? {} : { metaProvenance }),\n };\n };\n\n // ---- Drive ---------------------------------------------------------------\n // Files are prepared and inferred in parallel — one network round trip each\n // would make a large retrofit unusable in series — but collected by index so\n // the report is deterministic regardless of completion order. Preparing\n // reads, validates and picks candidates and spends no model request, so\n // P1 (0047) is asked between the two, before the first request.\n const prepareAll = async (): Promise<{\n stdin: FillFileResult | ReadyFile | undefined;\n files: (FillFileResult | ReadyFile)[];\n }> => ({\n stdin: usingStdin\n ? await prepareOne(\"<stdin>\", opts.stdinContent ?? \"\", forcedExtractor?.extensions[0] ?? \"\")\n : undefined,\n files: await mapConcurrent(files, concurrency, async (file) => {\n const content = await readFile(resolve(base, file), \"utf8\");\n return prepareOne(file, content, extname(file));\n }),\n });\n const flagsOf = (all: (FillFileResult | ReadyFile)[]): ExternalWrite[] =>\n all.flatMap((p) => (\"ready\" in p ? p.flags : []));\n let prepared = await prepareAll();\n let flagged = flagsOf(prepared.files);\n if (flagged.length > 0 && !dryRun && opts.confirm !== undefined) {\n const applied = await offerExternalHomes(ctx, flagged, {\n confirm: opts.confirm,\n ...(opts.onNotice !== undefined ? { onNotice: opts.onNotice } : {}),\n ...(opts.onRelocated !== undefined ? { onRelocated: opts.onRelocated } : {}),\n });\n if (applied.size > 0) {\n configDir = ctx.configDir ?? configDir;\n externalMetadata = await loadManifests();\n prepared = await prepareAll();\n flagged = flagsOf(prepared.files);\n }\n }\n\n const finish = (p: FillFileResult | ReadyFile): Promise<FillFileResult> =>\n \"ready\" in p ? finishOne(p) : Promise.resolve(p);\n const results: FillFileResult[] = [];\n if (prepared.stdin !== undefined) results.push(await finish(prepared.stdin));\n results.push(...(await mapConcurrent(prepared.files, concurrency, finish)));\n\n // Each manifest was saved after each file that changed it; wait for the\n // last save of each.\n await Promise.all([...heldManifests.values()].map((h) => h.saving));\n\n // W1 and W2 (0047): a value its schema prefers in external metadata that\n // went to the page, or would have. One line per collection, not per page.\n if (flagged.length > 0) {\n const landed = flagged.filter((w) => {\n const r = results.find((x) => x.file === w.label);\n if (r === undefined || r.error !== undefined) return false;\n if (w.key === META_PROVENANCE_KEY) {\n return r.metaProvenance?.written === true && r.metaProvenance.destination === undefined;\n }\n const f = r.fields.find((x) => keyOf(x) === w.key);\n return f !== undefined && f.written && f.destination === undefined;\n });\n for (const line of externalWriteWarnings(landed, dryRun)) warn(line);\n }\n\n return {\n results,\n summary: summarize(results, costUsd, cachedCount),\n threshold,\n dryRun,\n provider: identity.provider,\n model: identity.model,\n turnsSpent,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Candidates\n// ---------------------------------------------------------------------------\n\n/** First pointer segment of an Ajv instancePath (\"/tags/0\" -> \"tags\"). */\nfunction topKey(instancePath: string): string {\n if (instancePath === \"\") return \"\";\n const seg = instancePath.slice(1).split(\"/\")[0] ?? \"\";\n return seg.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\n/** The top-level key a field's pointer names, un-escaped (RFC 6901). */\nconst keyOf = (f: FilledField): string => topKey(f.field);\n\n/**\n * Whether the `meta-provenance` entry brings a finding the same metadata\n * without it does not have: then the schema does not allow it, whichever\n * keyword says so (`additionalProperties`, `unevaluatedProperties`,\n * `propertyNames`, or a rule under the key). Findings are counted, not just\n * matched, so a root error the page already had does not hide a second one\n * of the same kind that the entry adds.\n */\nasync function addsFindings(\n validate: (data: Record<string, unknown>) => Promise<readonly FieldError[]>,\n without: Record<string, unknown>,\n list: unknown,\n): Promise<boolean> {\n const identity = (e: FieldError): string =>\n JSON.stringify([e.schema, e.instancePath, e.keyword, e.subject ?? null, e.message]);\n const before = new Map<string, number>();\n for (const e of await validate(without)) {\n const key = identity(e);\n before.set(key, (before.get(key) ?? 0) + 1);\n }\n for (const e of await validate({ ...without, [META_PROVENANCE_KEY]: list })) {\n const key = identity(e);\n const left = before.get(key) ?? 0;\n if (left === 0) return true;\n before.set(key, left - 1);\n }\n return false;\n}\n\nfunction withoutKey(patch: MetadataPatch, key: string): MetadataPatch {\n return Object.fromEntries(Object.entries(patch).filter(([k]) => k !== key));\n}\n\n/** `apply`, or `undefined` where the writer refuses. */\nfunction tryApply(\n extractor: MetadataExtractor,\n content: string,\n patch: MetadataPatch,\n options: ApplyOptions,\n): string | undefined {\n try {\n return extractor.apply?.(content, patch, options);\n } catch {\n return undefined;\n }\n}\n\n/** Why a value fill did not propose was written: it was encrypted where it stood. */\nconst IN_PLACE_REASONING =\n \"The page held this value in plain text; its schema marks it x-manni-encrypt, so it was encrypted.\";\n\n/** A ciphertext anywhere in a document's text. */\nconst CIPHERTEXT_IN_TEXT = /~[A-Za-z0-9_-]{82,}/g;\n\n/**\n * The document as the model reads it (proposal 0045, 0017's egress rule).\n * Every marked value the page itself holds, plain or encrypted, is rewritten\n * to `(encrypted)` through the format's own writer, and a text pass then\n * hides any ciphertext the writer did not reach. `existing` is the redacted\n * metadata; a key whose value it changed is one to rewrite. A value a\n * manifest supplied is not in the text, so it is left out of the patch.\n */\nfunction contentForModel(\n content: string,\n extractor: MetadataExtractor,\n existing: Record<string, unknown>,\n held: Record<string, unknown>,\n supplied: (pointer: string) => boolean,\n options: ApplyOptions,\n): string {\n const patch: MetadataPatch = {};\n for (const [key, value] of Object.entries(existing)) {\n if (!Object.hasOwn(held, key) || supplied(pointerOf(key))) continue;\n if (toJsonText(value) !== toJsonText(held[key])) patch[key] = value;\n }\n // The provenance keys (0046) are removed from the text as from `existing`.\n // A writer that cannot remove a key ignores the option.\n const deletions = [...PROVENANCE_KEYS].filter(\n (key) => Object.hasOwn(held, key) && !supplied(pointerOf(key)),\n );\n let text = content;\n if (\n (Object.keys(patch).length > 0 || deletions.length > 0) &&\n extractor.apply !== undefined\n ) {\n try {\n text = extractor.apply(content, patch, { ...options, deletions });\n } catch {\n // The text pass below still hides every ciphertext.\n }\n }\n return text.replace(CIPHERTEXT_IN_TEXT, ENCRYPTED_PLACEHOLDER);\n}\n\n/** Every top-level property some schema in the set requires. */\nfunction requiredKeys(schemas: Record<string, unknown>[]): Set<string> {\n const out = new Set<string>();\n for (const schema of schemas) {\n if (!Array.isArray(schema.required)) continue;\n for (const r of schema.required as unknown[]) if (typeof r === \"string\") out.add(r);\n }\n return out;\n}\n\nfunction patchOf(fields: FilledField[]): MetadataPatch {\n const patch: MetadataPatch = {};\n for (const f of fields) patch[keyOf(f)] = f.value;\n return patch;\n}\n\n/**\n * A property is a candidate when it is absent from the metadata, or present but\n * invalid.\n *\n * \"Missing\" is derived from the schema objects rather than from validation\n * errors on purpose: Ajv reports a `required` violation with an empty\n * `instancePath` and names the property only inside the message text, so\n * recovering the key would mean parsing prose.\n *\n * When several schemas in the set define the same property, their subschemas\n * are **merged**, not raced. Picking one — the first named, say — would make the\n * proposal depend on flag order: stack a vocabulary that pins `type` to an enum\n * with OKF, which accepts any non-empty string, and whichever came first would\n * decide whether the model ever saw the enum. Since `validate` always runs every\n * schema, a value that only satisfies one of them was never writable anyway.\n */\nexport function collectCandidates(\n schemas: Record<string, unknown>[],\n data: Record<string, unknown>,\n errors: FieldError[],\n only?: Set<string>,\n): Candidate[] {\n const invalid = new Set(\n errors.map((e) => topKey(e.instancePath)).filter((k) => k !== \"\"),\n );\n const required = new Set<string>();\n for (const schema of schemas) {\n if (Array.isArray(schema.required)) {\n for (const r of schema.required) if (typeof r === \"string\") required.add(r);\n }\n }\n\n // Two schemas may define `#/$defs/Slug` differently, and the envelope has room\n // for only one of each name. Renaming the losers keeps each lifted subschema\n // pointing at its own definition.\n const { renames } = plannedFor(schemas);\n\n const seen = new Map<string, Candidate>();\n for (const [index, schema] of schemas.entries()) {\n const properties = schema.properties;\n if (typeof properties !== \"object\" || properties === null) continue;\n const renamed = renames.get(index);\n for (const [key, raw] of Object.entries(\n properties as Record<string, unknown>,\n )) {\n // `$schema` is docmeta's schema wiring, not document metadata, and the\n // provenance keys are machine attribution (0046).\n if (key === FILE_SCHEMA_KEY || PROVENANCE_KEYS.has(key)) continue;\n if (only && !only.has(key)) continue;\n if (typeof raw !== \"object\" || raw === null || Array.isArray(raw)) continue;\n\n const present = Object.prototype.hasOwnProperty.call(data, key);\n if (present && !invalid.has(key)) continue; // already valid — leave it alone\n\n const sub = renamed\n ? withRenamedRefs(raw as Record<string, unknown>, renamed)\n : (raw as Record<string, unknown>);\n const already = seen.get(key);\n if (already) {\n already.subschema = mergeSubschemas(already.subschema, sub);\n continue;\n }\n seen.set(key, {\n key,\n subschema: sub,\n required: required.has(key),\n present,\n });\n }\n }\n return [...seen.values()];\n}\n\n/**\n * Combine two subschemas for one property into a single schema that satisfies\n * both, via `allOf`.\n *\n * `allOf` rather than a structural merge because it is the only combination that\n * is correct for every keyword pair without knowing what the keywords mean: two\n * `enum`s intersect, two `minLength`s take the maximum, two `pattern`s must both\n * match. Ajv already resolves all of that, and the envelope schema built around\n * the result is compiled by Ajv before any proposal is accepted.\n *\n * Two things are done on top of the bare wrapper. Identical branches are dropped,\n * so the common \"both schemas say `{type: \"string\"}`\" case still lifts a plain\n * subschema. And the `description`s are combined and carried to the outside,\n * because that is where `fill-prompt` looks when it tells the model what the\n * property is for. Keeping only one of them would leave the prompt — and so the\n * proposal — dependent on schema order, which is the whole point of merging; the\n * combined text is deduplicated and sorted so it reads the same either way.\n */\nfunction mergeSubschemas(\n a: Record<string, unknown>,\n b: Record<string, unknown>,\n): Record<string, unknown> {\n const branches: Record<string, unknown>[] = [];\n for (const part of [...branchesOf(a), ...branchesOf(b)]) {\n if (!branches.some((seen) => canonical(seen) === canonical(part))) {\n branches.push(part);\n }\n }\n const joined = joinDescriptions([...describedBy(a), ...describedBy(b)]);\n const description = joined === \"\" ? undefined : joined;\n\n const [first] = branches;\n if (branches.length === 1 && first !== undefined) {\n return description === undefined || first.description === description\n ? first\n : { ...first, description };\n }\n return {\n ...(description !== undefined ? { description } : {}),\n allOf: branches,\n };\n}\n\n/** How descriptions from different schemas are strung together for the prompt. */\nconst DESCRIPTION_JOIN = \" \";\n\n/** Deduplicate, drop blanks, and order by text so the result is order-free. */\nfunction joinDescriptions(parts: string[]): string {\n return [...new Set(parts.map((p) => p.trim()))]\n .filter((p) => p !== \"\")\n .sort()\n .join(DESCRIPTION_JOIN);\n}\n\n/**\n * Every distinct sentence describing a subschema, including the ones on the\n * branches of an `allOf`.\n *\n * A wrapper this module built already carries exactly the join of its branches'\n * descriptions, so re-collecting it would fold the joined text back in as a\n * phrase of its own and make a third merge repeat itself. An author's wrapper\n * carries prose that is nowhere else, which is why the two are told apart by\n * comparison rather than by assuming the wrapper is ours.\n */\nfunction describedBy(schema: Record<string, unknown>): string[] {\n const own =\n typeof schema.description === \"string\" ? schema.description : undefined;\n const branches = branchesOf(schema);\n if (branches.length === 1 && branches[0] === schema) {\n return own === undefined ? [] : [own];\n }\n const nested = branches.flatMap(describedBy);\n if (own !== undefined && own !== joinDescriptions(nested)) nested.push(own);\n return nested;\n}\n\n/**\n * A JSON *object*, in the sense JSON Schema uses the word: `null` and arrays\n * are `typeof \"object\"` too and neither is a schema.\n *\n * A predicate rather than the inline test plus a cast, because the cast was the\n * only thing carrying `object` across to `Record<string, unknown>` and nothing\n * checked that it still matched the test beside it.\n */\nfunction isJsonObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The branches a subschema contributes to a merge — its own `allOf` entries if\n * it is a wrapper, otherwise itself. An author-written `{description, allOf}` is\n * unfolded on the same terms as one of ours; `describedBy` is what keeps its\n * description from being lost in the process.\n *\n * The unwrapping is deliberately narrow: an author-written schema may carry\n * `allOf` *alongside* other keywords, and flattening that would drop them.\n */\nfunction branchesOf(schema: Record<string, unknown>): Record<string, unknown>[] {\n const keys = Object.keys(schema);\n const isWrapper =\n Array.isArray(schema.allOf) &&\n keys.every((k) => k === \"allOf\" || k === \"description\");\n if (!isWrapper) return [schema];\n return (schema.allOf as unknown[]).flatMap((branch) => {\n if (isJsonObject(branch)) {\n return [branch];\n }\n // JSON Schema allows a boolean where a schema belongs. `true` constrains\n // nothing and disappears into the merge; `false` accepts nothing, and\n // dropping it would quietly turn a property nothing can satisfy into one\n // `fill` proposes for. `{not: {}}` says \"never valid\" in object form.\n return branch === false ? [{ not: {} }] : [];\n });\n}\n\nconst DEF_BLOCKS = [\"$defs\", \"definitions\"] as const;\ntype DefBlock = (typeof DEF_BLOCKS)[number];\n\ninterface DefsPlan {\n defs: Record<DefBlock, Record<string, unknown>>;\n /** Schema index -> `\"<block>/<name>\"` -> the name that schema's defs got. */\n renames: Map<number, Map<string, string>>;\n}\n\n/**\n * Decide what the envelope's `$defs`/`definitions` blocks hold, and which\n * schemas need their `$ref`s pointed somewhere else to get there.\n *\n * The envelope is one document, so the two blocks are flat namespaces that every\n * schema in the set shares. Names collide: `Slug` in a house schema and `Slug` in\n * a vocabulary are unrelated definitions, and letting the first one win would\n * silently validate half the set against the wrong rule. A colliding definition\n * therefore gets its own name, and everything that pointed at it — the lifted\n * subschemas *and* the other definitions of the same schema — is rewritten to\n * match. That second part is why names are allocated for the whole set before\n * anything is rewritten: a definition may point at one that is renamed later in\n * the walk, and a pointer left behind resolves to another schema's rule.\n *\n * Definitions two schemas write identically share a slot, since there is nothing\n * to tell apart and a copy would only make the envelope noisier. That is settled\n * on the text alone, so it is offered only to definitions that resolve to\n * nothing else: `{$ref: \"#/$defs/Inner\"}` reads the same in both schemas while\n * meaning whatever each one's `Inner` says.\n *\n * The two blocks are kept **separate**: draft-07 schemas (which `dialectOf` in\n * validator.ts explicitly supports) write `$ref: \"#/definitions/X\"`, and folding\n * those entries into `$defs` would leave the pointer dangling.\n */\nfunction planDefs(schemas: Record<string, unknown>[]): DefsPlan {\n const defs: Record<DefBlock, Record<string, unknown>> = {\n $defs: {},\n definitions: {},\n };\n const renames = new Map<number, Map<string, string>>();\n const placed: { index: number; block: DefBlock; emitted: string }[] = [];\n\n for (const [index, schema] of schemas.entries()) {\n for (const block of DEF_BLOCKS) {\n const entries = schema[block];\n if (typeof entries !== \"object\" || entries === null) continue;\n for (const [name, value] of Object.entries(\n entries as Record<string, unknown>,\n )) {\n const taken = defs[block];\n if (!(name in taken)) {\n taken[name] = value;\n placed.push({ index, block, emitted: name });\n continue;\n }\n if (!pointsInward(value) && canonical(taken[name]) === canonical(value)) {\n continue;\n }\n\n let emitted = `${name}__${index}`;\n while (emitted in taken) emitted += \"_\";\n taken[emitted] = value;\n placed.push({ index, block, emitted });\n let map = renames.get(index);\n if (!map) {\n map = new Map();\n renames.set(index, map);\n }\n map.set(`${block}/${name}`, emitted);\n }\n }\n }\n\n // Now that every name is settled, point each definition at the ones belonging\n // to the schema it came from.\n for (const { index, block, emitted } of placed) {\n const map = renames.get(index);\n if (map) defs[block][emitted] = withRenamedRefs(defs[block][emitted], map);\n }\n return { defs, renames };\n}\n\n/**\n * Every keyword that can send a definition back into its own document.\n * `$dynamicRef` (2020-12) and `$recursiveRef` (2019-09) resolve against the\n * schema they were written in just as `$ref` does, so a definition using one is\n * no more interchangeable between schemas than a `$ref` chain is.\n */\nconst INWARD_REFS = new Set([\"$ref\", \"$dynamicRef\", \"$recursiveRef\"]);\n\n/** Whether a definition depends on some other part of its own document. */\nfunction pointsInward(node: unknown): boolean {\n if (Array.isArray(node)) return node.some(pointsInward);\n if (typeof node !== \"object\" || node === null) return false;\n return Object.entries(node).some(([key, value]) =>\n INWARD_REFS.has(key) && typeof value === \"string\"\n ? value.startsWith(\"#\")\n : pointsInward(value),\n );\n}\n\n/**\n * Carry `$defs`/`definitions` across so a lifted subschema's `$ref` resolves.\n *\n * Memoized on the array itself: `collectCandidates` needs the same plan to know\n * which refs to rewrite, and both are handed the one array `processOne` built\n * for the file.\n */\nexport function collectDefs(schemas: Record<string, unknown>[]): {\n $defs: Record<string, unknown>;\n definitions: Record<string, unknown>;\n} {\n return plannedFor(schemas).defs;\n}\n\nconst planCache = new WeakMap<Record<string, unknown>[], DefsPlan>();\n\nfunction plannedFor(schemas: Record<string, unknown>[]): DefsPlan {\n let plan = planCache.get(schemas);\n if (!plan) {\n plan = planDefs(schemas);\n planCache.set(schemas, plan);\n }\n return plan;\n}\n\n/**\n * Deep-copy a subschema with its local `$ref`s repointed at the names its\n * definitions were emitted under. Only called for schemas that actually lost a\n * name collision, so the ordinary case keeps the original object.\n */\nfunction withRenamedRefs<T>(node: T, renames: Map<string, string>): T {\n if (Array.isArray(node)) {\n // `Array.isArray` narrows a generic to `T & any[]`, so the mapped result is\n // `any[]` and the cast below would launder it. Restate the element type as\n // `unknown` first: the recursion accepts it, and the only assertion left is\n // the `as T` that was always there.\n const items: unknown[] = node;\n return items.map((item) => withRenamedRefs(item, renames)) as T;\n }\n if (typeof node !== \"object\" || node === null) return node;\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(node)) {\n out[key] =\n key === \"$ref\" && typeof value === \"string\"\n ? renameRef(value, renames)\n : withRenamedRefs(value, renames);\n }\n return out as T;\n}\n\n/**\n * Repoint one local pointer: `#/$defs/Slug` and `#/$defs/Slug/properties/x` both\n * follow the rename of `Slug`. Anything else — an absolute URI, a `$id`-relative\n * ref, a pointer into some other part of the document — is left alone.\n */\nfunction renameRef(ref: string, renames: Map<string, string>): string {\n const match = /^#\\/(\\$defs|definitions)\\/([^/]+)(\\/.*)?$/.exec(ref);\n const block = match?.[1];\n const name = match?.[2];\n if (block === undefined || name === undefined) return ref;\n const emitted = renames.get(`${block}/${unescapePointer(name)}`);\n if (emitted === undefined) return ref;\n return `#/${block}/${escapePointer(emitted)}${match?.[3] ?? \"\"}`;\n}\n\nconst unescapePointer = (segment: string): string =>\n segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n\nconst escapePointer = (name: string): string =>\n name.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n\n// ---------------------------------------------------------------------------\n// The gate\n// ---------------------------------------------------------------------------\n\n/** Whether one proposed value meets its property's rules, and as what. */\ntype Checked = { ok: true; value: unknown } | { ok: false; errors: string[] };\ntype ValueCheck = (key: string, proposal: Proposal) => Checked;\n\n/**\n * Check each value on its own against the full envelope, compiled with\n * coercion. The probe holds one key, so a failing neighbour never fails it,\n * and the value is a copy, so the coerced form is what comes back and the\n * model's raw answer is left as it was for the cache.\n *\n * Errors read as Ajv words them under the field's pointer, such as\n * `/resource: must match format \"uri\"`, which is what a retry is shown.\n *\n * `terms` is the check for the fields offered glossary terms\n * (`fill-hints.ts`), whose errors read the same way:\n * `/concepts/1: must be a glossary term label`.\n */\nfunction valueCheck(\n validate: ValidateFunction,\n terms?: (key: string, value: unknown) => string[],\n): ValueCheck {\n return (key, proposal) => {\n const entry = {\n value: structuredClone(proposal.value),\n confidence: proposal.confidence,\n reasoning: proposal.reasoning,\n };\n const valid = validate({ [key]: entry });\n const field = pointerOf(key);\n const prefix = `${field}/value`;\n const errors = valid\n ? []\n : (validate.errors ?? []).map((e) => {\n const at = e.instancePath.startsWith(prefix)\n ? `${field}${e.instancePath.slice(prefix.length)}`\n : field;\n return `${at}: ${e.message ?? e.keyword}`;\n });\n errors.push(...(terms?.(key, entry.value) ?? []));\n if (errors.length === 0) return { ok: true, value: entry.value };\n return { ok: false, errors: [...new Set(errors)] };\n };\n}\n\nfunction gate(\n candidates: Candidate[],\n proposals: ProposalSet,\n threshold: number,\n check: ValueCheck,\n unsatisfiable: ReadonlySet<string>,\n): FilledField[] {\n return candidates.map((c): FilledField => {\n const field = pointerOf(c.key);\n const proposal: Proposal | undefined = proposals[c.key];\n // No value can satisfy every schema's rules for this key, so the model\n // was never asked.\n if (unsatisfiable.has(c.key)) {\n return {\n field,\n required: c.required,\n confidence: 0,\n reasoning: \"\",\n written: false,\n skipReason: \"schema-mismatch\",\n };\n }\n // A `null` value is the model declining, as an omitted key is.\n if (proposal == null || proposal.value === null) {\n return {\n field,\n required: c.required,\n confidence: 0,\n reasoning: \"\",\n written: false,\n skipReason: \"no-proposal\",\n };\n }\n const checked = check(c.key, proposal);\n if (!checked.ok) {\n return {\n field,\n required: c.required,\n confidence: proposal.confidence,\n reasoning: proposal.reasoning,\n written: false,\n skipReason: \"schema-mismatch\",\n };\n }\n const passes = proposal.confidence >= threshold;\n return {\n field,\n required: c.required,\n confidence: proposal.confidence,\n reasoning: proposal.reasoning,\n written: passes,\n ...(passes ? { value: checked.value } : { skipReason: \"low-confidence\" as const }),\n };\n });\n}\n\n// ---------------------------------------------------------------------------\n// Plumbing\n// ---------------------------------------------------------------------------\n\n/**\n * `schemas` is passed once resolution has succeeded, so a JSON consumer can\n * tell \"the schema set was never resolved\" from \"it resolved and then writing\n * was refused\" — the two need different follow-up.\n */\nfunction errorResult(\n file: string,\n format: string,\n message: string,\n schemas: string[] = [],\n fields: FilledField[] = [],\n): FillFileResult {\n return { file, format, schemas, fields, changed: false, error: message };\n}\n\n/**\n * Range-check a numeric option. Every comparison against NaN is false, so the\n * finite check has to be explicit or garbage passes silently.\n */\nfunction requireNumber(\n value: number,\n name: string,\n bounds: { min: number; max: number; integer?: boolean },\n): number {\n const { min, max, integer } = bounds;\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) {\n throw new DocmetaError(\n `fill: \"${name}\" must be a number between ${min} and ${max}, got ${String(value)}.`,\n );\n }\n if (integer === true && !Number.isInteger(value)) {\n throw new DocmetaError(\n `fill: \"${name}\" must be a whole number, got ${String(value)}.`,\n );\n }\n return value;\n}\n\n/** The shared refusals, in meta's error class and naming meta's config key. */\nconst toDocmetaError = (message: string): Error => new DocmetaError(message);\n\nfunction assertKnownProvider(name: string): asserts name is ProviderSelector {\n assertKnownProviderFor(name, toDocmetaError);\n}\n\nfunction assertModelHasProvider(\n name: ProviderSelector,\n model: string | undefined,\n): void {\n assertModelHasProviderFor(name, model, \"fill.provider\", toDocmetaError);\n}\n\nfunction resolveIdentity(spec: ProviderSpec): ReturnType<typeof resolveIdentityFor> {\n return resolveIdentityFor(spec, toDocmetaError);\n}\n\nfunction summarize(\n results: FillFileResult[],\n costUsd: number,\n cached: number,\n): FillRun[\"summary\"] {\n let written = 0;\n let skipped = 0;\n let requiredSkipped = 0;\n for (const r of results) {\n for (const f of r.fields) {\n if (f.written) written++;\n else {\n skipped++;\n if (f.required) requiredSkipped++;\n }\n }\n }\n return {\n files: results.length,\n changed: results.filter((r) => r.changed).length,\n written,\n skipped,\n requiredSkipped,\n errors: results.filter((r) => r.error != null).length,\n costUsd,\n cached,\n };\n}\n","/**\n * What `fill` shows the model for one candidate's `value`.\n *\n * A merged subschema is correct, and a poor thing to send. A local provider\n * compiles the response schema into a grammar, and node-llama-cpp's compiler\n * ignores `allOf`, `if`/`then`/`else`, `pattern` and `not`. It turns an untyped\n * node into a rule that accepts only `null`, and `format: uri` into one that\n * accepts only `\"\"`. Since `mergeSubschemas` joins two schemas' views of one\n * property with `allOf`, most properties under a stacked schema set could only\n * be answered `null`.\n *\n * So the model is shown a **projection**: a plain, typed node that every\n * grammar compiler reads the same way. It is a hint, never the rule. The full\n * subschema still checks each answer (see `fill.ts`), which is what lets this\n * module drop what it cannot express rather than approximate it.\n *\n * The rules, numbered as the plan that introduced them numbers them:\n *\n * 1. A `$ref` is replaced by its target from the envelope's definitions. A\n * cycle stops at the second visit, as an untyped node.\n * 2. An `allOf` is merged into one node: types, `enum` and `const` intersect,\n * `properties` merge key by key, `required` is the union, `items` merge.\n * 3. An `anyOf` or `oneOf` keeps its branches, each projected. The keywords\n * beside it are carried into every branch.\n * 4. Kept: `type`, `enum`, `const`, `properties`, `required`, `items`,\n * `additionalProperties: false`, `description`, `pattern`, the length,\n * bound and item-count keywords, and a `date`, `date-time` or `time`\n * format. The strictest bound wins; two different patterns (or formats)\n * leave neither. Everything else is dropped, a tuple-form `items` array\n * included: the list is sent as a plain array.\n * 5. An untyped node is sent as any non-null JSON value, one branch per type,\n * each carrying the keywords that constrain it.\n * 6. When no value can pass, the candidate is reported as unsatisfiable and\n * never asked.\n * 7. The projection is wrapped as `oneOf: [<projection>, {type: \"null\"}]`, so\n * a model can decline under a grammar that makes every key required.\n *\n * After projection, `withOffer` puts the values `fill` offers for a field\n * that names a glossary term or a page (`fill-hints.ts`) on the field's\n * strings. It works on the emitted schema, so it never changes what a rule\n * above decides.\n *\n * Alternatives are written `oneOf`, never `anyOf`, wherever they come from.\n * node-llama-cpp's compiler reads `oneOf` and ignores `anyOf`, which it\n * compiles to `null` as it does an untyped node. Nothing validates against\n * this schema, so `oneOf`'s \"exactly one\" never judges an answer: the full\n * subschema does that.\n */\n\nimport { toJsonText } from \"../core/json-text.js\";\n\n/** The envelope's definition blocks, as `collectDefs` builds them. */\nexport interface ProjectionDefs {\n $defs: Record<string, unknown>;\n definitions: Record<string, unknown>;\n}\n\nexport type Projection =\n | { schema: Record<string, unknown> }\n /** Rule 6: no value satisfies the subschema, so the model is not asked. */\n | { unsatisfiable: true };\n\n/** Project one candidate's merged subschema, wrapped per rule 7. */\nexport function projectValue(subschema: unknown, defs: ProjectionDefs): Projection {\n const shape = project(subschema, defs, new Set());\n if (shape === undefined) return { unsatisfiable: true };\n return { schema: { oneOf: [emit(shape), { type: \"null\" }] } };\n}\n\n// ---------------------------------------------------------------------------\n// The working form\n// ---------------------------------------------------------------------------\n\n/** Rule 5's order, which is also the order an untyped node's branches take. */\nconst ANY_TYPES = [\"string\", \"number\", \"boolean\", \"array\", \"object\"] as const;\nconst JSON_TYPES = new Set<string>([...ANY_TYPES, \"integer\", \"null\"]);\n/** Formats a grammar compiler renders as the format rather than as `\"\"`. */\nconst DATE_FORMATS = new Set([\"date\", \"date-time\", \"time\"]);\n\n/** A marker for \"two branches disagree, so the model sees neither\". */\nconst CONFLICT = Symbol(\"conflict\");\ntype Agreed = string | typeof CONFLICT;\n\ntype BoundKey = \"minLength\" | \"maxLength\" | \"minimum\" | \"maximum\" | \"minItems\" | \"maxItems\";\nconst LOWER_BOUNDS: readonly BoundKey[] = [\"minLength\", \"minimum\", \"minItems\"];\nconst UPPER_BOUNDS: readonly BoundKey[] = [\"maxLength\", \"maximum\", \"maxItems\"];\n\n/**\n * One node, normalized. Every field absent means \"unconstrained\". A function\n * that returns `Shape | undefined` uses `undefined` for rule 6: nothing passes.\n */\ninterface Shape {\n types?: string[];\n values?: unknown[];\n properties?: Map<string, Shape>;\n required?: string[];\n closed?: boolean;\n items?: Shape;\n description?: string;\n pattern?: Agreed;\n format?: Agreed;\n bounds?: Partial<Record<BoundKey, number>>;\n /** Alternatives. The other fields have already been carried into each. */\n branches?: Shape[];\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n// ---------------------------------------------------------------------------\n// Projecting a schema into a Shape\n// ---------------------------------------------------------------------------\n\nfunction project(\n node: unknown,\n defs: ProjectionDefs,\n seen: ReadonlySet<string>,\n): Shape | undefined {\n if (node === false) return undefined;\n if (!isObject(node)) return {};\n // `branchesOf` in fill.ts writes a `false` branch as `{not: {}}`. Every\n // other `not` is dropped (rule 4), but this one says \"nothing passes\", and\n // dropping it would ask the model for a property it cannot fill.\n if (node.not === true || (isObject(node.not) && Object.keys(node.not).length === 0)) {\n return undefined;\n }\n\n const own = ownShape(node, defs, seen);\n if (own === undefined) return undefined;\n\n const parts: Shape[] = [own];\n if (typeof node.$ref === \"string\") {\n const target = followRef(node.$ref, defs, seen);\n if (target === undefined) return undefined;\n parts.push(target);\n }\n if (Array.isArray(node.allOf)) {\n for (const branch of node.allOf) {\n const projected = project(branch, defs, seen);\n if (projected === undefined) return undefined;\n parts.push(projected);\n }\n }\n let acc: Shape | undefined = parts.reduce<Shape | undefined>(\n (held, part) => (held === undefined ? undefined : merge(held, part)),\n {},\n );\n // A node with both keywords distributes one over the other, so the shapes\n // multiply: two branches each give four. Nested alternatives compound the\n // same way. Metadata schemas stay shallow, so this is left unbounded.\n for (const keyword of [\"anyOf\", \"oneOf\"] as const) {\n const branches = node[keyword];\n if (acc === undefined || !Array.isArray(branches)) continue;\n const projected = branches\n .map((branch) => project(branch, defs, seen))\n .filter((shape): shape is Shape => shape !== undefined);\n acc = distribute(acc, projected);\n }\n return acc === undefined ? undefined : possible(acc);\n}\n\n/** Which pair of bounds constrains each type, lower then upper. */\nconst BOUND_PAIRS: Readonly<Record<string, readonly [BoundKey, BoundKey]>> = {\n string: [\"minLength\", \"maxLength\"],\n number: [\"minimum\", \"maximum\"],\n integer: [\"minimum\", \"maximum\"],\n array: [\"minItems\", \"maxItems\"],\n};\n\n/**\n * Rule 6 for bounds: a type whose own lower bound exceeds its upper bound\n * admits no value, so it leaves the shape. A shape with no type left admits\n * nothing. Bounds judge only the type they constrain: `minLength` over\n * `maxLength` rules out strings and leaves a number free. An enum's values\n * are already typed, so its bounds are left to the full check.\n */\nfunction possible(shape: Shape): Shape | undefined {\n if (shape.branches !== undefined) {\n const kept = shape.branches\n .map(possible)\n .filter((branch): branch is Shape => branch !== undefined);\n return alternatives(kept, shape.description);\n }\n if (shape.values !== undefined) return shape;\n const bounds = shape.bounds ?? {};\n const contradicts = (type: string): boolean => {\n const pair = BOUND_PAIRS[type];\n if (pair === undefined) return false;\n const low = bounds[pair[0]];\n const high = bounds[pair[1]];\n return low !== undefined && high !== undefined && low > high;\n };\n const types = shape.types ?? [...ANY_TYPES];\n const allowed = types.filter((type) => !contradicts(type));\n if (allowed.length === 0) return undefined;\n return allowed.length === types.length ? shape : { ...shape, types: allowed };\n}\n\n/** Rule 1: a local pointer into the envelope's definitions, followed once. */\nfunction followRef(\n ref: string,\n defs: ProjectionDefs,\n seen: ReadonlySet<string>,\n): Shape | undefined {\n if (seen.has(ref)) return {};\n const target = resolvePointer(ref, defs);\n // A ref this module cannot follow is untyped here; the full check still\n // resolves it.\n if (target === undefined) return {};\n return project(target, defs, new Set([...seen, ref]));\n}\n\nfunction resolvePointer(ref: string, defs: ProjectionDefs): unknown {\n const match = /^#\\/(\\$defs|definitions)\\/(.+)$/.exec(ref);\n const block = match?.[1];\n const rest = match?.[2];\n if (rest === undefined) return undefined;\n let at: unknown = block === \"$defs\" ? defs.$defs : defs.definitions;\n for (const raw of rest.split(\"/\")) {\n const segment = decodeSegment(raw);\n if (Array.isArray(at)) {\n at = /^\\d+$/.test(segment) ? at[Number(segment)] : undefined;\n } else if (isObject(at) && Object.hasOwn(at, segment)) {\n at = at[segment];\n } else {\n return undefined;\n }\n }\n return at;\n}\n\n/**\n * One JSON Pointer segment, as a URI fragment writes it. A `$ref` is a URI,\n * so RFC 6901 section 6 applies: percent-decode the fragment first, then\n * undo `~1` and `~0`. `%7E1` therefore reads as `/`, exactly as `~1` does.\n */\nfunction decodeSegment(raw: string): string {\n let text = raw;\n try {\n text = decodeURIComponent(raw);\n } catch {\n // A stray `%` is a literal one.\n }\n return text.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n}\n\n/** The kept keywords (rule 4) of one node, without its combinators. */\nfunction ownShape(\n node: Record<string, unknown>,\n defs: ProjectionDefs,\n seen: ReadonlySet<string>,\n): Shape | undefined {\n const shape: Shape = {};\n const declared = typeof node.type === \"string\" ? [node.type] : node.type;\n if (Array.isArray(declared)) {\n shape.types = declared.filter(\n (t): t is string => typeof t === \"string\" && JSON_TYPES.has(t),\n );\n if (shape.types.length === 0) return undefined;\n }\n if (Array.isArray(node.enum)) {\n const listed: unknown[] = node.enum;\n shape.values = [...listed];\n }\n if (Object.hasOwn(node, \"const\")) {\n shape.values = intersectValues(shape.values, [node.const]);\n }\n if (shape.values !== undefined) {\n shape.values = typedValues(shape.values, shape.types);\n if (shape.values.length === 0) return undefined;\n }\n if (Array.isArray(node.required)) {\n shape.required = node.required.filter((k): k is string => typeof k === \"string\");\n }\n if (isObject(node.properties)) {\n shape.properties = new Map();\n for (const [key, sub] of Object.entries(node.properties)) {\n const projected = project(sub, defs, seen);\n if (projected !== undefined) shape.properties.set(key, projected);\n else if (shape.required?.includes(key) === true) return undefined;\n }\n }\n if (node.additionalProperties === false) shape.closed = true;\n if (isObject(node.items) || typeof node.items === \"boolean\") {\n const items = project(node.items, defs, seen);\n if (items === undefined) {\n // Nothing may be an item, so only the empty list passes.\n shape.bounds = { maxItems: 0 };\n } else {\n shape.items = items;\n }\n }\n if (typeof node.description === \"string\") shape.description = node.description;\n if (typeof node.pattern === \"string\") shape.pattern = node.pattern;\n if (typeof node.format === \"string\" && DATE_FORMATS.has(node.format)) {\n shape.format = node.format;\n }\n for (const key of [...LOWER_BOUNDS, ...UPPER_BOUNDS]) {\n const value = node[key];\n if (typeof value === \"number\") {\n shape.bounds = tighten(shape.bounds, { [key]: value });\n }\n }\n return shape;\n}\n\n// ---------------------------------------------------------------------------\n// Merging two Shapes (the allOf of rule 2)\n// ---------------------------------------------------------------------------\n\nfunction merge(a: Shape, b: Shape): Shape | undefined {\n if (a.branches !== undefined || b.branches !== undefined) {\n const results: Shape[] = [];\n for (const x of a.branches ?? [a]) {\n for (const y of b.branches ?? [b]) {\n const merged = merge(x, y);\n if (merged !== undefined) results.push(merged);\n }\n }\n return alternatives(results, a.description ?? b.description);\n }\n\n const out: Shape = {};\n const types = intersectTypes(a.types, b.types);\n if (types !== undefined) {\n if (types.length === 0) return undefined;\n out.types = types;\n }\n const values = intersectValues(a.values, b.values);\n if (values !== undefined) {\n out.values = typedValues(values, out.types);\n if (out.values.length === 0) return undefined;\n }\n const required = union(a.required, b.required);\n if (required !== undefined) out.required = required;\n if (a.properties !== undefined || b.properties !== undefined) {\n out.properties = new Map(a.properties);\n for (const [key, shape] of b.properties ?? []) {\n const held = out.properties.get(key);\n if (held === undefined) {\n out.properties.set(key, shape);\n continue;\n }\n const merged = mergedPart(held, shape);\n if (merged !== undefined) out.properties.set(key, merged);\n else if (required?.includes(key) === true) return undefined;\n else out.properties.delete(key);\n }\n }\n if (a.closed === true || b.closed === true) out.closed = true;\n let bounds = tighten(a.bounds, b.bounds);\n if (a.items !== undefined && b.items !== undefined) {\n const items = mergedPart(a.items, b.items);\n // Nothing may be an item, so only the empty list passes.\n if (items === undefined) bounds = tighten(bounds, { maxItems: 0 });\n else out.items = items;\n } else {\n const items = a.items ?? b.items;\n if (items !== undefined) out.items = items;\n }\n if (bounds !== undefined) out.bounds = bounds;\n const description = a.description ?? b.description;\n if (description !== undefined) out.description = description;\n const pattern = agree(a.pattern, b.pattern);\n if (pattern !== undefined) out.pattern = pattern;\n const format = agree(a.format, b.format);\n if (format !== undefined) out.format = format;\n return out;\n}\n\n/**\n * A property or item two branches both define, merged and then judged by\n * rule 6's bounds check, which otherwise runs only on a node `project` built.\n */\nfunction mergedPart(a: Shape, b: Shape): Shape | undefined {\n const merged = merge(a, b);\n return merged === undefined ? undefined : possible(merged);\n}\n\n/** Rule 3: carry a node's keywords into each of its alternatives. */\nfunction distribute(held: Shape, branches: Shape[]): Shape | undefined {\n const results = branches\n .map((branch) => merge(withoutDescription(held), branch))\n .filter((shape): shape is Shape => shape !== undefined);\n return alternatives(results, held.description);\n}\n\nfunction alternatives(results: Shape[], description: string | undefined): Shape | undefined {\n const [only] = results;\n if (only === undefined) return undefined;\n if (results.length === 1) {\n return description === undefined ? only : { ...only, description };\n }\n return { branches: results, ...(description !== undefined ? { description } : {}) };\n}\n\nfunction withoutDescription(shape: Shape): Shape {\n const { description: _dropped, ...rest } = shape;\n return rest;\n}\n\nfunction intersectTypes(\n a: string[] | undefined,\n b: string[] | undefined,\n): string[] | undefined {\n if (a === undefined) return b;\n if (b === undefined) return a;\n const out: string[] = [];\n for (const t of a) {\n if (b.includes(t)) out.push(t);\n // `integer` is the common member of `number` and `integer`.\n else if (t === \"number\" && b.includes(\"integer\")) out.push(\"integer\");\n else if (t === \"integer\" && b.includes(\"number\")) out.push(\"integer\");\n }\n return [...new Set(out)];\n}\n\nfunction intersectValues(\n a: unknown[] | undefined,\n b: unknown[] | undefined,\n): unknown[] | undefined {\n if (a === undefined) return b;\n if (b === undefined) return a;\n const inB = new Set(b.map(canonical));\n return a.filter((value) => inB.has(canonical(value)));\n}\n\n/** The values that have one of the declared types. */\nfunction typedValues(values: unknown[], types: string[] | undefined): unknown[] {\n if (types === undefined) return values;\n return values.filter((value) => types.some((t) => hasType(value, t)));\n}\n\nfunction hasType(value: unknown, type: string): boolean {\n switch (type) {\n case \"null\":\n return value === null;\n case \"array\":\n return Array.isArray(value);\n case \"object\":\n return isObject(value);\n case \"integer\":\n return typeof value === \"number\" && Number.isInteger(value);\n default:\n return typeof value === type;\n }\n}\n\nfunction union(a: string[] | undefined, b: string[] | undefined): string[] | undefined {\n if (a === undefined) return b;\n if (b === undefined) return a;\n return [...new Set([...a, ...b])];\n}\n\nfunction agree(a: Agreed | undefined, b: Agreed | undefined): Agreed | undefined {\n if (a === undefined) return b;\n if (b === undefined) return a;\n return a === b ? a : CONFLICT;\n}\n\n/** The strictest of two sets of bounds. */\nfunction tighten(\n a: Shape[\"bounds\"],\n b: Shape[\"bounds\"],\n): Shape[\"bounds\"] {\n if (a === undefined) return b;\n if (b === undefined) return a;\n const out: Partial<Record<BoundKey, number>> = { ...a };\n for (const key of LOWER_BOUNDS) {\n const x = a[key];\n const y = b[key];\n if (y !== undefined) out[key] = x === undefined ? y : Math.max(x, y);\n }\n for (const key of UPPER_BOUNDS) {\n const x = a[key];\n const y = b[key];\n if (y !== undefined) out[key] = x === undefined ? y : Math.min(x, y);\n }\n return out;\n}\n\n/**\n * Key-order-independent text, so equal enum values compare equal.\n *\n * Exported for `fill.ts`, which needs the same comparison over schema\n * branches and already-taken values, and would otherwise carry a second,\n * independently-drifting copy.\n */\nexport function canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (isObject(value)) {\n const entries = Object.keys(value)\n .sort()\n .map((k) => `${JSON.stringify(k)}:${canonical(value[k])}`);\n return `{${entries.join(\",\")}}`;\n }\n return toJsonText(value) ?? `(${typeof value})`;\n}\n\n// ---------------------------------------------------------------------------\n// Emitting a Shape as JSON Schema\n// ---------------------------------------------------------------------------\n\nfunction emit(shape: Shape): Record<string, unknown> {\n const described = shape.description === undefined ? {} : { description: shape.description };\n if (shape.branches !== undefined) {\n return { ...described, oneOf: shape.branches.map(emit) };\n }\n const values = shape.values;\n if (values !== undefined) {\n const [only] = shape.types ?? [];\n const typed = shape.types?.length === 1 && only !== undefined ? { type: only } : {};\n const [single] = values;\n return {\n ...typed,\n ...(values.length === 1 ? { const: single } : { enum: values }),\n ...described,\n };\n }\n const types = shape.types ?? [...ANY_TYPES];\n const [only] = types;\n if (types.length === 1 && only !== undefined) {\n return { ...typed(shape, only), ...described };\n }\n return { ...described, oneOf: types.map((t) => typed(shape, t)) };\n}\n\n/** One type's node, with the keywords that constrain that type (rule 5). */\nfunction typed(shape: Shape, type: string): Record<string, unknown> {\n const out: Record<string, unknown> = { type };\n const bounds = shape.bounds ?? {};\n const put = (key: BoundKey): void => {\n const value = bounds[key];\n if (value !== undefined) out[key] = value;\n };\n switch (type) {\n case \"string\":\n if (typeof shape.pattern === \"string\") out.pattern = shape.pattern;\n if (typeof shape.format === \"string\") out.format = shape.format;\n put(\"minLength\");\n put(\"maxLength\");\n break;\n case \"number\":\n case \"integer\":\n put(\"minimum\");\n put(\"maximum\");\n break;\n case \"array\":\n if (shape.items !== undefined) out.items = emit(shape.items);\n put(\"minItems\");\n put(\"maxItems\");\n break;\n case \"object\":\n if (shape.properties !== undefined) {\n out.properties = Object.fromEntries(\n [...shape.properties].map(([key, sub]) => [key, emit(sub)]),\n );\n }\n if (shape.required !== undefined) out.required = shape.required;\n if (shape.closed === true) out.additionalProperties = false;\n // An object that names no properties takes any. Said outright, because\n // node-llama-cpp reads a bare `{type: \"object\"}` as `{}` alone.\n else if (shape.properties === undefined) out.additionalProperties = true;\n break;\n default:\n break;\n }\n return out;\n}\n\n// ---------------------------------------------------------------------------\n// Offering values on the emitted schema\n// ---------------------------------------------------------------------------\n\n/** The values offered for one field, and whether they are the only ones allowed. */\nexport interface ValueOffer {\n values: readonly string[];\n /** True replaces the field's strings with the values; false offers them beside a free string. */\n firm: boolean;\n}\n\n/**\n * Offer values on the field at `path` below a projected `value` schema. The\n * path is followed through object `properties`, and every alternative of a\n * `oneOf` is followed. At the field, each string node, and each list's items,\n * takes the offer: the values as an `enum` when it is firm, or `oneOf` of that\n * `enum` and the string as it was when it is not. A string already limited to\n * an `enum` or a `const` keeps its own values.\n */\nexport function withOffer(\n schema: Record<string, unknown>,\n path: readonly string[],\n offer: ValueOffer,\n): Record<string, unknown> {\n return single(offerAt(schema, path, offer));\n}\n\n/**\n * What one node becomes under the offer, as alternatives. A string under a\n * soft offer becomes two, which a `oneOf` above it takes as two of its own\n * branches rather than as a nested `oneOf`. So a `oneOf` grows by one\n * branch for each of its branches that holds the field, and only those.\n */\nfunction offerAt(\n node: Record<string, unknown>,\n path: readonly string[],\n offer: ValueOffer,\n): Record<string, unknown>[] {\n const branches = node.oneOf;\n if (Array.isArray(branches)) {\n return [\n {\n ...node,\n oneOf: branches.flatMap((branch: unknown) => (isObject(branch) ? offerAt(branch, path, offer) : [branch])),\n },\n ];\n }\n const [head, ...rest] = path;\n if (head !== undefined) {\n const properties = node.properties;\n const field = isObject(properties) ? properties[head] : undefined;\n if (node.type !== \"object\" || !isObject(properties) || !isObject(field)) return [node];\n return [{ ...node, properties: { ...properties, [head]: single(offerAt(field, rest, offer)) } }];\n }\n if (node.type === \"array\") {\n // A list with no items is a list of strings here: the reference fields are\n // string lists whose projection left `items` out. Any other `items`, such\n // as `true`, is not narrowed, since the offer would over-restrict it.\n if (node.items === undefined) {\n return [{ ...node, items: single(offerAt({ type: \"string\" }, [], offer)) }];\n }\n if (!isObject(node.items)) return [node];\n return [{ ...node, items: single(offerAt(node.items, [], offer)) }];\n }\n if (node.type !== \"string\" || Object.hasOwn(node, \"enum\") || Object.hasOwn(node, \"const\")) {\n return [node];\n }\n const listed = { type: \"string\", enum: [...offer.values] };\n if (!offer.firm) return [listed, node];\n return [typeof node.description === \"string\" ? { ...listed, description: node.description } : listed];\n}\n\n/** One node from alternatives: the only one, or a `oneOf` of them all. */\nfunction single(alternatives: Record<string, unknown>[]): Record<string, unknown> {\n // An empty list would emit `{ oneOf: [] }`, which admits nothing.\n /* c8 ignore next -- offerAt always returns at least the node it was given. */\n if (alternatives.length === 0) throw new Error(\"Internal error: an offer produced no alternatives.\");\n const [only] = alternatives;\n return alternatives.length === 1 && only !== undefined ? only : { oneOf: alternatives };\n}\n","/**\n * The values `fill` offers for the fields that name something else in the\n * docset (`src/shared/reference-fields.ts`).\n *\n * - A term field is offered the termbase's labels. The offer is firm: a value\n * that is not a term fails its per-value check, as `term check` would fail\n * it, and gets the one retry every failing value gets.\n * - A page field is offered the ids of the page's fellow collection members.\n * The offer is a hint: a URL or a line of prose stays valid, as the schema\n * says.\n *\n * An empty list is never offered, since an empty `enum` admits nothing. Nor\n * is a list over `MAX_OFFERED`, which keeps the prompt bounded. Either way the\n * field is asked for as it would be with no offer at all.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { extname, resolve } from \"node:path\";\nimport { isMember, type CollectionConfig } from \"../../shared/collections.js\";\nimport {\n CONCEPT_FIELDS,\n PAGE_FIELDS,\n TERM_FIELDS,\n fieldPointer,\n samePath,\n valueAt,\n type FieldPath,\n} from \"../../shared/reference-fields.js\";\nimport { resolveTargetSet } from \"../core/load-files.js\";\nimport { extractorForExtension } from \"../extractors/index.js\";\nimport type { Candidate, FieldHint } from \"./fill-types.js\";\n\n/**\n * The most values one field is offered. Past it, the field gets no hint at\n * all, so its term check lapses too and any string passes. A termbase this\n * large is not in sight; revisit the cap before one is.\n */\nexport const MAX_OFFERED = 500;\n\n/** What a term value that names no term fails with, after its pointer. */\nexport const NOT_A_TERM = \"must be a glossary term label\";\n\n/** The values as offered: deduped and sorted, or `undefined` when empty or too many. */\nexport function offered(values: Iterable<string>): string[] | undefined {\n const list = [...new Set(values)].filter((value) => value.trim() !== \"\").sort();\n if (list.length === 0 || list.length > MAX_OFFERED) return undefined;\n return list;\n}\n\n/** The run's offers, each already through `offered`. */\nexport interface Offer {\n terms?: readonly string[] | undefined;\n pages?: readonly string[] | undefined;\n}\n\n/** The hint for each table field one of the candidates holds, in table order. */\nexport function fieldHints(candidates: readonly Candidate[], offer: Offer): FieldHint[] {\n const keys = new Set(candidates.map((c) => c.key));\n const hints: FieldHint[] = [];\n const add = (fields: readonly FieldPath[], kind: FieldHint[\"kind\"], values: readonly string[] | undefined): void => {\n if (values === undefined) return;\n for (const path of fields) {\n const [key] = path;\n if (key !== undefined && keys.has(key)) hints.push({ path: [...path], kind, values });\n }\n };\n add(TERM_FIELDS, \"term\", offer.terms);\n add(PAGE_FIELDS, \"page\", offer.pages);\n return hints;\n}\n\n/** The termbase a term value is checked against. */\nexport interface TermIndex {\n labels: readonly string[];\n ids: readonly string[];\n}\n\n/**\n * The per-value check for term fields: one error per value that names no term,\n * such as `/concepts/1: must be a glossary term label`. Labels and ids compare\n * ignoring case, as `term check` compares them. A concept field takes a label\n * only, since `term check` resolves a page's `concepts` by label. A term\n * relation takes a label or an id, as `term check` resolves those.\n *\n * The offer itself lists labels only, so a model held to it never proposes an\n * id. Accepting ids here keeps an id a provider proposes anyway, as `term\n * check` would. A schema that requires ids would see every label refused.\n */\nexport function termValueCheck(\n hints: readonly FieldHint[],\n index: TermIndex,\n): (key: string, value: unknown) => string[] {\n const fold = (value: string): string => value.toLowerCase();\n const labels = new Set(index.labels.map(fold));\n const either = new Set([...labels, ...index.ids.map(fold)]);\n const terms = hints.filter((hint) => hint.kind === \"term\");\n return (key, value) =>\n terms\n .filter((hint) => hint.path[0] === key)\n .flatMap((hint) => {\n const accepted = CONCEPT_FIELDS.some((path) => samePath(path, hint.path)) ? labels : either;\n const pointer = fieldPointer(hint.path);\n const held = valueAt(value, hint.path.slice(1));\n if (typeof held === \"string\") {\n return accepted.has(fold(held)) ? [] : [`${pointer}: ${NOT_A_TERM}`];\n }\n // Anything else, null included, is not this check's to judge: the\n // full subschema refuses a wrong type, and fill reads a null value as\n // the model declining before any value is checked.\n if (!Array.isArray(held)) return [];\n const items: unknown[] = held;\n return items.flatMap((item, i) =>\n typeof item === \"string\" && !accepted.has(fold(item)) ? [`${pointer}/${String(i)}: ${NOT_A_TERM}`] : [],\n );\n });\n}\n\nexport interface PageIdReaderOptions {\n /** The declared collections. */\n collections: readonly CollectionConfig[];\n /** What the collections' globs are measured from. */\n configDir: string;\n /** Skip files `.gitignore` covers when walking a collection. Default true. */\n respectGitignore?: boolean;\n}\n\n/**\n * Reads page ids by collection: the `id` of every member, read with the\n * extractor for its extension. Each collection is walked once, on first\n * need. A member that cannot be read or parsed, or carries no `id`, is not\n * offered. The reader returns the ids of every member of the named\n * collections, except `file` itself, sorted.\n */\nexport function pageIdReader(\n opts: PageIdReaderOptions,\n): (file: string, collections: readonly string[]) => Promise<string[]> {\n const walked = new Map<string, Promise<ReadonlyMap<string, string>>>();\n const idsOf = (collection: CollectionConfig): Promise<ReadonlyMap<string, string>> => {\n let held = walked.get(collection.name);\n if (held === undefined) {\n held = readIds(collection, opts);\n walked.set(collection.name, held);\n }\n return held;\n };\n return async (file, names) => {\n const self = resolve(file);\n const ids = new Set<string>();\n for (const name of names) {\n const collection = opts.collections.find((c) => c.name === name);\n if (collection === undefined) continue;\n for (const [path, id] of await idsOf(collection)) {\n if (path !== self) ids.add(id);\n }\n }\n return [...ids].sort();\n };\n}\n\n/** Each member's absolute path and its `id`. */\nasync function readIds(\n collection: CollectionConfig,\n opts: PageIdReaderOptions,\n): Promise<ReadonlyMap<string, string>> {\n const { files } = await resolveTargetSet({\n inputs: collection.paths,\n cwd: opts.configDir,\n allowEmpty: true,\n respectGitignore: opts.respectGitignore ?? true,\n });\n const ids = new Map<string, string>();\n for (const file of files) {\n if (!isMember(collection, file)) continue;\n const extractor = extractorForExtension(extname(file));\n if (extractor === undefined) continue;\n const path = resolve(opts.configDir, file);\n let id: unknown;\n try {\n id = extractor.extract(await readFile(path, \"utf8\"), file).data.id;\n } catch {\n continue;\n }\n if (typeof id === \"string\" && id.trim() !== \"\") ids.set(path, id);\n }\n return ids;\n}\n","/**\n * The fields whose values name something else in the docset: a glossary term,\n * or a page. Stated once, so `term` and `meta` read the same list. `term check`\n * reads the concept fields as references into the termbase, and `meta fill`\n * offers each kind its valid values.\n *\n * A field is a path from the page root, so `graph.concepts` is\n * `[\"graph\", \"concepts\"]`.\n */\n\n/** A field, as the keys from the page root down to it. */\nexport type FieldPath = readonly string[];\n\n/** The fields a page names the glossary terms it is about in. */\nexport const CONCEPT_FIELDS: readonly FieldPath[] = [[\"concepts\"], [\"graph\", \"concepts\"]];\n\n/** A term entry's fields that name other entries. */\nexport const TERM_RELATION_FIELDS = [\"broader\", \"narrower\", \"related-terms\", \"see\"] as const;\n\n/** Every field whose values are glossary terms. */\nexport const TERM_FIELDS: readonly FieldPath[] = [\n ...CONCEPT_FIELDS,\n ...TERM_RELATION_FIELDS.map((field) => [field]),\n];\n\n/** Every field whose values are pages, by id or URL. */\nexport const PAGE_FIELDS: readonly FieldPath[] = [\n [\"related-pages\"],\n [\"next-steps\"],\n [\"prerequisites\"],\n [\"replaced-by\"],\n [\"supersedes\"],\n];\n\n/** The field's JSON Pointer: `/graph/concepts`. */\nexport function fieldPointer(path: FieldPath): string {\n return path.map((key) => `/${key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\")}`).join(\"\");\n}\n\n/** Whether two paths name the same field. */\nexport function samePath(a: FieldPath, b: FieldPath): boolean {\n return a.length === b.length && a.every((key, i) => key === b[i]);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * The value at `path` below `root`, or `undefined` when a key on the way is\n * missing or is not a mapping. An empty path is `root` itself.\n */\nexport function valueAt(root: unknown, path: FieldPath): unknown {\n let node = root;\n for (const key of path) {\n if (!isRecord(node) || !Object.hasOwn(node, key)) return undefined;\n node = node[key];\n }\n return node;\n}\n","/**\n * Where `meta fill` gets the termbase's labels from.\n *\n * The layering runs one way: `term` imports `meta`, and nothing under\n * `src/meta` imports `term`. So the term domain registers a source here when\n * its module loads, and `fill` reads it when one is registered. Under the\n * `manni` bin the umbrella loads the term domain, so a source is there. Under\n * the `docmeta` bin, or a library call that loads no term module, there is\n * none, and `fill` offers no term values.\n */\n\n/** One term: its preferred label, and its id. */\nexport interface TermLabel {\n label: string;\n id: string;\n}\n\n/** What a run tells the source, so it reads the termbase `term check` reads. */\nexport interface TermLabelRequest {\n /** The directory config discovery starts from. */\n cwd: string;\n /** `-c/--config`. */\n configPath?: string;\n /** `--no-config`. */\n noConfig?: boolean;\n}\n\n/** Loads the termbase's terms for one run. */\nexport type TermLabelSource = (request: TermLabelRequest) => Promise<readonly TermLabel[]>;\n\nlet registered: TermLabelSource | undefined;\n\n/** Register the source, or clear it with `undefined`. The last one registered wins. */\nexport function registerTermLabelSource(source: TermLabelSource | undefined): void {\n registered = source;\n}\n\n/** The registered source, or `undefined` when nothing registered one. */\nexport function termLabelSource(): TermLabelSource | undefined {\n return registered;\n}\n","/**\n * The metadata tool's half of the shared manifest compare-and-swap.\n *\n * `src/shared/manifest-cas.ts` owns hold, re-read, replay and refuse, and\n * cannot own the splice: rewriting one key of a manifest is this tool's, and\n * the shared layer does not import a tool's module. So this file supplies the\n * codec, and the two commands that write manifests — `fill` and `derive` —\n * record their edits as the descriptors it applies rather than as the text\n * those descriptors produced.\n *\n * `relocate` and `query` re-read and abort on their own, so neither goes\n * through here.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { DocmetaError } from \"../types.js\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport {\n heldManifest,\n isMissing,\n rebaseable,\n rebaseline,\n settle,\n type HeldManifest,\n type ManifestCodec,\n type ManifestOp,\n} from \"../../shared/manifest-cas.js\";\nimport { writeFileAtomic } from \"./write-file.js\";\nimport {\n readManifestValue,\n removeManifestKey,\n spliceManifestValue,\n} from \"./external-metadata-write.js\";\n\n/**\n * One edit `fill` or `derive` makes to a manifest: a key of an entry set to a\n * value, or taken out. Plain data, so it replays onto bytes read later.\n */\nexport type MetaManifestOp = ManifestOp &\n ({ kind: \"splice\"; value: unknown } | { kind: \"remove\" });\n\n/** One manifest held for the length of a `fill` or `derive` run. */\nexport type MetaHeldManifest = HeldManifest<MetaManifestOp>;\n\n/** One recorded edit, and one key read back, over a manifest's text. */\nexport const manifestCodec: ManifestCodec<MetaManifestOp> = {\n apply(text, op) {\n const where = { entry: op.entry, key: op.key, join: op.join, file: op.file };\n return op.kind === \"remove\"\n ? removeManifestKey(text, where).text\n : spliceManifestValue(text, { ...where, value: op.value }).text;\n },\n read(text, at) {\n return readManifestValue(text, at);\n },\n};\n\n/** One recorded edit, against whatever text it is handed. */\nexport function applyManifestOp(text: string, op: MetaManifestOp): string {\n return manifestCodec.apply(text, op);\n}\n\n/**\n * Read a manifest, ready to be spliced and later settled. A `perPage`\n * manifest (proposal 0058) that does not exist yet is a page with nothing\n * kept there: it is held as empty text marked absent, and the settle creates\n * it. A missing concrete manifest is refused, as it always was.\n */\nexport async function holdManifestFile(\n path: string,\n file: string,\n perPage = false,\n): Promise<MetaHeldManifest> {\n let before: string;\n try {\n before = await readFile(path, \"utf8\");\n } catch (err) {\n if (perPage && isMissing(err)) return heldManifest<MetaManifestOp>(path, file, \"\", true);\n throw new DocmetaError(`Manifest ${file} could not be read: ${errorMessage(err)}`);\n }\n return heldManifest<MetaManifestOp>(path, file, before);\n}\n\n/**\n * Commit one edit to the held text: note what the key held before this run\n * first touched it, keep the descriptor for a replay, and advance the text.\n */\nexport function recordManifestOp(held: MetaHeldManifest, op: MetaManifestOp): void {\n rebaseable(held, op, manifestCodec);\n held.ops.push(op);\n}\n\n/** What a caller may substitute for the bytes a settle reads and writes. */\nexport interface ManifestSettleIo {\n write?: (path: string, text: string) => Promise<void>;\n read?: (path: string) => Promise<string>;\n}\n\n/**\n * Write one held manifest, compare-and-swap, and take the written bytes as the\n * new base. Answers whether anything was written; a manifest the run left as\n * it found it is not rewritten.\n */\nexport async function settleManifest(\n held: MetaHeldManifest,\n io: ManifestSettleIo = {},\n): Promise<boolean> {\n if (held.text === held.before) return false;\n await settle(held, {\n codec: manifestCodec,\n // A per-page manifest (proposal 0058) may be the first file in its directory.\n write: io.write ?? ((at: string, text: string) => writeFileAtomic(at, text, { createParents: true })),\n read: io.read ?? ((at: string): Promise<string> => readFile(at, \"utf8\")),\n toError: (message) => new DocmetaError(message),\n });\n rebaseline(held);\n return true;\n}\n","/**\n * Prompt and schema construction for `fill`.\n *\n * The central idea is the **envelope schema**: each candidate property is asked\n * for as a `{ value, confidence, reasoning }` object, and the whole response is\n * one object keyed by property. `buildEnvelopeSchema` builds three views of\n * that envelope from one candidate list:\n *\n * - **sent**, what the provider is given. Each `value` is the projection of the\n * property's subschema (`fill-projection.ts`): a plain typed shape a local\n * grammar can represent, since a merged `allOf` would compile to `null`.\n * - **skeleton**, which checks the response's shape and nothing else. A\n * response that fails it is a whole-file error.\n * - **full**, each property's own subschema lifted verbatim, which checks every\n * value on its own. A malformed `date-time` fails that one field, never the\n * file, which is what lets confidence be the *last* check rather than the\n * only one.\n */\nimport { projectValue, withOffer, type ProjectionDefs } from \"./fill-projection.js\";\nimport type { Candidate, FieldHint, Proposal, ProposalSet } from \"./fill-types.js\";\n\n/**\n * Part of the cache key: bump whenever the prompt wording or the envelope\n * schema construction changes, so stale proposals are not replayed.\n */\nexport const FILL_PROMPT_VERSION = 6;\n\n/**\n * Characters of document sent per inference call.\n *\n * This was the point at which the document stopped being read: anything past it\n * was replaced with `[body truncated]`, so a long reference page was described\n * from its introduction and its own conclusion was never seen. Same number, but\n * it now bounds a *chunk* — the whole file is sent, in as many calls as it takes.\n *\n * It is docmeta's budget rather than the model's because no per-model input\n * context size is discoverable: the inference catalog publishes `uri`,\n * `sizeBytes`, `license` and tier, and its `maxTokens` is an *output* cap. So\n * overflow cannot be predicted, only hit — which is why the caller treats a\n * provider overflow as a signal to shrink this and retry, rather than trying to\n * compute the right value up front.\n */\nexport const DEFAULT_CHUNK_CHARS = 12000;\n\n/**\n * Split a document into chunks of at most `chunkChars`.\n *\n * Splits on a line boundary when there is one inside the budget, so a chunk\n * rarely ends mid-sentence; a single line longer than the budget is cut anyway,\n * because a minified file has no boundary to prefer. Concatenating the result\n * reproduces the input exactly — the test asserts that, because \"the whole file\n * is sent\" is the entire point of the change.\n */\nexport function splitBody(body: string, chunkChars: number): string[] {\n if (body.length <= chunkChars) return [body];\n const chunks: string[] = [];\n let at = 0;\n while (at < body.length) {\n const end = Math.min(at + chunkChars, body.length);\n let cut = end;\n if (end < body.length) {\n const nl = body.lastIndexOf(\"\\n\", end - 1);\n // Only honour the boundary if it makes progress; otherwise the line is\n // longer than the budget and there is nothing to prefer.\n if (nl > at) cut = nl + 1;\n }\n chunks.push(body.slice(at, cut));\n at = cut;\n }\n return chunks;\n}\n\n/**\n * Combine per-chunk proposals, keeping the most confident value for each key.\n *\n * Confidence is already the accept/reject axis — `gate()` compares each\n * proposal against the threshold — so choosing between two proposals spends the\n * same currency once more rather than introducing a second one. (It is a\n * threshold, not a ranking: this is the first place two proposals are compared\n * against each other.) A value found in a page's conclusion therefore competes\n * on equal terms with one guessed from its introduction, which is the whole\n * point of reading past the first chunk. Ties keep the earlier chunk —\n * arbitrary, but stable across runs.\n *\n * `passes` says whether a value meets its property's rules. A passing value\n * beats a failing one whatever their confidence, since a failing value is\n * never written. A `null` value is the model declining and is never kept.\n */\nexport function mergeProposals(\n sets: ProposalSet[],\n passes: (key: string, proposal: Proposal) => boolean = () => true,\n): ProposalSet {\n const merged: ProposalSet = {};\n const held = new Map<string, boolean>();\n for (const set of sets) {\n for (const [key, proposal] of Object.entries(set)) {\n if (proposal.value === null) continue;\n const ok = passes(key, proposal);\n const current = merged[key];\n const heldOk = held.get(key);\n if (\n current === undefined ||\n heldOk === undefined ||\n (ok && !heldOk) ||\n (ok === heldOk && proposal.confidence > current.confidence)\n ) {\n merged[key] = proposal;\n held.set(key, ok);\n }\n }\n }\n return merged;\n}\n\nexport const FILL_SYSTEM_PROMPT = [\n \"You infer document metadata from the document itself.\",\n \"\",\n \"You are given a page's existing metadata, the JSON Schema properties that are\",\n \"missing or currently invalid, and the page body. Propose a value for each\",\n \"property you can determine from the page.\",\n \"\",\n \"Rules:\",\n \"- Base every value on evidence in the page. Never invent facts, URLs, dates,\",\n \" authors, or identifiers that the page does not support.\",\n \"- Omit a property, or answer null as its value, rather than guessing at it. A\",\n \" missing property is a normal, expected outcome.\",\n \"- Report an honest confidence between 0 and 1 that the value is correct and\",\n \" that a careful human reviewer would agree with it. Do not inflate it.\",\n \" Reserve values above 0.9 for values the page states plainly.\",\n \"- Keep `reasoning` to one sentence naming the evidence you used.\",\n \"- Match each property's described purpose, not just its type.\",\n].join(\"\\n\");\n\nconst DIALECT = \"https://json-schema.org/draft/2020-12/schema\";\n\n/** JSON Schema for one proposal, wrapping `value`, the schema its value takes. */\nfunction proposalSchema(\n candidate: Candidate,\n value: Record<string, unknown>,\n): Record<string, unknown> {\n const described =\n typeof candidate.subschema.description === \"string\"\n ? candidate.subschema.description\n : undefined;\n return {\n type: \"object\",\n additionalProperties: false,\n required: [\"value\", \"confidence\", \"reasoning\"],\n description: described\n ? `Proposed value for \"${candidate.key}\": ${described}`\n : `Proposed value for \"${candidate.key}\".`,\n properties: {\n value,\n confidence: {\n type: \"number\",\n minimum: 0,\n maximum: 1,\n description:\n \"Honest self-reported confidence that this value is correct. Do not inflate.\",\n },\n reasoning: {\n type: \"string\",\n description: \"One sentence naming the evidence in the page.\",\n },\n },\n };\n}\n\n/** One envelope: every candidate optional, and no key nobody asked about. */\nfunction envelopeOf(\n properties: [string, Record<string, unknown>][],\n defs?: ProjectionDefs,\n): Record<string, unknown> {\n return {\n $schema: DIALECT,\n type: \"object\",\n additionalProperties: false,\n // Both blocks are reproduced under their original names so a lifted\n // subschema's `$ref` (`#/$defs/X` on 2020-12, `#/definitions/X` on\n // draft-07) still resolves against the envelope root.\n ...(defs !== undefined && Object.keys(defs.$defs).length > 0 ? { $defs: defs.$defs } : {}),\n ...(defs !== undefined && Object.keys(defs.definitions).length > 0\n ? { definitions: defs.definitions }\n : {}),\n properties: Object.fromEntries(properties),\n };\n}\n\n/** The three views of one file's envelope. See the module comment. */\nexport interface Envelope {\n /** What the provider is given: each asked candidate's projected `value`. */\n sent: Record<string, unknown>;\n /** The response's shape alone. Every `value` is `{}`. */\n skeleton: Record<string, unknown>;\n /** Every candidate's full subschema, which checks each value on its own. */\n full: Record<string, unknown>;\n /** The candidates the model is asked about. */\n asked: Candidate[];\n /** Candidates no value can satisfy. The model is never asked about them. */\n unsatisfiable: Candidate[];\n}\n\n/**\n * Build one file's envelope. Every candidate is optional so the model can\n * decline; `additionalProperties: false` means it cannot invent keys. The\n * definitions from the source schemas go with the full view, so any `$ref`\n * inside a lifted subschema still resolves. The sent view needs none: the\n * projection has already followed every `$ref`.\n *\n * `hints` are the values offered for the fields that name a glossary term or\n * a page (`fill-hints.ts`). They change the sent view only: the full view,\n * which checks each value, is the subschema as written.\n */\nexport function buildEnvelopeSchema(\n candidates: Candidate[],\n defs: ProjectionDefs,\n hints: readonly FieldHint[] = [],\n): Envelope {\n const asked: Candidate[] = [];\n const unsatisfiable: Candidate[] = [];\n const sent: [string, Record<string, unknown>][] = [];\n for (const candidate of candidates) {\n const projected = projectValue(candidate.subschema, defs);\n if (\"schema\" in projected) {\n asked.push(candidate);\n const value = hints\n .filter((hint) => hint.path[0] === candidate.key)\n .reduce(\n (schema, hint) =>\n withOffer(schema, hint.path.slice(1), { values: hint.values, firm: hint.kind === \"term\" }),\n projected.schema,\n );\n sent.push([candidate.key, proposalSchema(candidate, value)]);\n } else {\n unsatisfiable.push(candidate);\n }\n }\n return {\n sent: envelopeOf(sent),\n skeleton: envelopeOf(asked.map((c) => [c.key, proposalSchema(c, {})])),\n full: envelopeOf(\n candidates.map((c) => [c.key, proposalSchema(c, c.subschema)]),\n defs,\n ),\n asked,\n unsatisfiable,\n };\n}\n\nexport interface UserPromptParams {\n filePath: string;\n existing: Record<string, unknown>;\n candidates: Candidate[];\n body: string;\n /** Set when the document was split, so the model knows it sees a slice. */\n part?: { index: number; total: number };\n}\n\n/**\n * The second request for values that failed their properties' rules. It asks\n * only for those properties, and names what each value broke, in Ajv's words:\n * `/resource: must match format \"uri\"`.\n */\nexport function buildRetryPrompt(\n params: UserPromptParams & { rejected: string[] },\n): string {\n return buildUserPrompt(params, [\n \"# Rejected values\",\n \"Each value below broke a rule of its property's schema. Propose it again,\",\n \"following the rule, or answer null.\",\n ...params.rejected.map((line) => `- ${line}`),\n \"\",\n ]);\n}\n\nexport function buildUserPrompt(\n params: UserPromptParams,\n /** Lines placed before the page body. */\n before: string[] = [],\n): string {\n const { filePath, existing, candidates, body, part } = params;\n const wanted = candidates.map((c) => {\n const description =\n typeof c.subschema.description === \"string\"\n ? ` — ${c.subschema.description}`\n : \"\";\n const why = c.present\n ? \"currently invalid, propose a replacement\"\n : \"missing\";\n return `- ${c.key} (${why})${description}`;\n });\n\n return [\n `# File`,\n filePath,\n \"\",\n \"# Existing metadata\",\n Object.keys(existing).length > 0\n ? JSON.stringify(existing, null, 2)\n : \"(none)\",\n \"\",\n \"# Properties to propose\",\n ...wanted,\n \"\",\n ...before,\n part === undefined\n ? \"# Page body\"\n : `# Page body (part ${part.index} of ${part.total})`,\n body,\n ].join(\"\\n\");\n}\n","/**\n * `derive` — stamp the managed stewardship fields into each document from\n * evidence: git history, CODEOWNERS, and the review record on GitHub or GitLab.\n *\n * The shape is `fill`'s (load, extract, decide, write through the extractor)\n * with the deciding step replaced by the derived channel: every requested\n * field is compared with what the sources say, and a field that is `stale`\n * or `unset` is written. `current` and `unknown` fields are left alone. Under\n * `--check` nothing is written and every stale or unset field becomes a\n * finding, which is how CI turns a forgotten stamp into a red run.\n *\n * Three refusals are operational (exit 2) rather than per-file, because each\n * leaves the run with no honest verdict: stdin, which has no history behind\n * it; a field or source the channel does not know; and a consulted source\n * that cannot answer, since a skipped source would let a stale stamp read as\n * current — the false green the whole channel exists to end.\n */\nimport { readFile } from \"node:fs/promises\";\nimport { extname, relative, resolve, sep } from \"node:path\";\nimport {\n DocmetaError,\n type FieldError,\n type MetadataExtractor,\n type MetadataPatch,\n} from \"../types.js\";\nimport {\n resolveRunConfig,\n schemaTrustRoot,\n urlManifestMessage,\n urlManifestOwning,\n type ConfigNotice,\n} from \"../core/config.js\";\nimport type { FingerprintContext } from \"../core/baseline.js\";\nimport {\n assertNonEmpty,\n gitignoreOptions,\n resolveTargetSet,\n STDIN_TOKEN,\n} from \"../core/load-files.js\";\nimport { memberOf, retainMembers } from \"../core/collections.js\";\nimport {\n extractorByName,\n extractorForExtension,\n listFormats,\n supportedExtensions,\n} from \"../extractors/index.js\";\nimport {\n collectSchemaPins,\n FILE_SCHEMA_KEY,\n resolveElements,\n resolveSchemaSetWithSource,\n type ResolvedSchemaSet,\n} from \"../core/resolve-schema.js\";\nimport { schemaLoadOptions } from \"../core/schema-registry.js\";\nimport { Validator } from \"../core/validator.js\";\nimport {\n ENCRYPTED_PLACEHOLDER,\n EncryptionRefusal,\n META_CONTEXT,\n encryptionView,\n isAtOrUnder,\n lazyKey,\n pointerOf,\n redactedDerived,\n unreadableMessage,\n valueAt,\n withValueAt,\n} from \"../core/encrypted.js\";\nimport { encryptValue } from \"../../shared/encryption.js\";\nimport { ENCRYPTION_KEY_ENV } from \"../../shared/encryption-key.js\";\nimport { ensureEncryptionKey, type Confirm } from \"../../shared/prompt.js\";\nimport { writeFileAtomic } from \"../core/write-file.js\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport { assertSourcesAvailable, deriveMetadata } from \"../core/derive/index.js\";\nimport { commandsOf, machinesOf } from \"../core/derive/config.js\";\nimport { provenanceFenced } from \"../core/derive/git.js\";\nimport {\n compareProvenance,\n parseProvenanceTarget,\n planProvenanceWrite,\n provenanceEntries,\n provenanceFindings,\n rangeResults,\n readProvenancePage,\n type ProvenanceComparison,\n type ProvenanceDerivation,\n type ProvenanceEntry,\n} from \"../core/derive/provenance.js\";\nimport {\n provenanceManifests,\n provenancePlace,\n stampManifests,\n type ProvenanceManifest,\n type ProvenancePlace,\n} from \"../core/derive/provenance-place.js\";\nimport {\n loadExternalMetadata,\n mergeWithMarks,\n type ExternalMetadataIndex,\n type SourceLocation,\n} from \"../core/external-metadata.js\";\nimport { pageClaims, pageMarks } from \"../core/page-marks.js\";\nimport { classifyRef } from \"../core/schema-registry.js\";\nimport type { FieldLocation } from \"../core/location.js\";\nimport type { CollectionConfig } from \"../../shared/collections.js\";\nimport { warn } from \"../../shared/warn.js\";\nimport {\n keyHome,\n relocationContext,\n type KeyHome,\n type RelocateResult,\n} from \"../core/relocation.js\";\nimport {\n externalWriteWarnings,\n manifestKeyLine,\n offerExternalHomes,\n type ExternalWrite,\n} from \"../core/location-writes.js\";\nimport {\n applyManifestOp,\n holdManifestFile,\n recordManifestOp,\n settleManifest,\n type MetaHeldManifest,\n type MetaManifestOp,\n} from \"../core/manifest-writes.js\";\nimport { lineSpec, parseLines } from \"../../shared/pin.js\";\nimport {\n compareDerived,\n DERIVABLE_FIELDS,\n DERIVE_SOURCES,\n isBuiltinField,\n isDeriveSource,\n MERGE_SAFE_FIELDS,\n deriveCovers,\n PROVENANCE_FIELD,\n staleFindings,\n type DerivableField,\n type DeriveCommand,\n type DerivedField,\n type DerivedRecord,\n type DerivedStatus,\n type DerivedValue,\n type DeriveInput,\n type DeriveSource,\n type ReviewClient,\n type SourceStatus,\n} from \"../core/derive/types.js\";\n\nexport interface DeriveOptions {\n inputs: string[];\n /**\n * `--collection <name>`, repeatable: stamp only the named configured\n * collections instead of every declared one (proposal 0041). Cannot be\n * combined with paths.\n */\n collections?: string[];\n /** `--fields`: the managed fields to stamp this run; config `derive.fields` otherwise. */\n fields?: string[];\n /** `--sources`: the sources to consult; config `derive.sources`, else all four. */\n sources?: string[];\n /** `--dry-run`: report what would change and write nothing. */\n dryRun?: boolean;\n /** `--check`: implies `dryRun`; stale and unset fields are findings. */\n check?: boolean;\n /** Use the on-disk GitHub or GitLab review cache. Default true. */\n cache?: boolean;\n /** `--as` format override (extractor name). */\n as?: string;\n exts?: string[];\n exclude?: string[];\n configPath?: string;\n /** `--no-config`: skip config discovery and use the built-in defaults. */\n noConfig?: boolean;\n cwd?: string;\n /** Permit an input set that resolves to zero files (see `assertNonEmpty`). */\n allowEmpty?: boolean;\n /**\n * `--no-gitignore` (false). Absent leaves config `respectGitignore:` in\n * charge, which itself defaults to on.\n */\n respectGitignore?: boolean;\n /** Diagnostics for the user; the CLI writes these to stderr. */\n onNotice?: (message: string) => void;\n /** Called once when a config governs the run, so the CLI can report it. */\n onConfigLoaded?: (info: ConfigNotice) => void;\n /** The clock an uncommitted body change is dated by. Test seam; default `new Date()`. */\n now?: () => Date;\n /** The review client, for every repository in the run. Test seam; default `gh` / `glab`. */\n reviews?: ReviewClient;\n /**\n * How to ask for a new encryption key when a field its schema marks\n * `x-manni-encrypt` is about to be stamped and no key is available\n * (proposal 0045). The CLI passes `terminalConfirm()`, which is `undefined`\n * off a terminal; absent, such a stamp refuses (exit 2). A dry run never\n * asks: it writes nothing.\n */\n confirm?: Confirm;\n /**\n * The environment `MANNI_ENCRYPTION_KEY` is read from. Defaults to\n * `process.env`; tests pass their own.\n */\n env?: NodeJS.ProcessEnv;\n /**\n * `--generated-by <name>` (proposal 0046): the machine uncommitted body\n * lines go to, or the lines a `<path>:L1-L2` positional names. Absent reads\n * `MANNI_GENERATED_BY` from `env`; an empty value is unset either way.\n */\n generatedBy?: string;\n /**\n * Called with relocate's result after the user accepts a P1 offer\n * (proposal 0047), so the CLI can print what moved before the report.\n */\n onRelocated?: (result: RelocateResult) => void;\n}\n\n/** The variable `--generated-by` defaults to (proposal 0046). */\nexport const GENERATED_BY_ENV = \"MANNI_GENERATED_BY\";\n\nexport interface DeriveFileResult {\n file: string;\n /** Extractor/format used; `unknown` when none matched the file. */\n format: string;\n /** One entry per requested field, in the requested order. Empty on `error`. */\n fields: DerivedField[];\n /**\n * Whether writing the stale and unset fields changed the document, or\n * would have but for `dryRun`. Computed from the writer's output, so a\n * patch the format serializes to the same bytes is not a change.\n */\n changed: boolean;\n /** Why the file could not be derived or written; the run goes on without it. */\n error?: string;\n /**\n * Under `check`, the findings for this file: one per stale or unset field,\n * at the field's line, plus one for an `error`. Absent otherwise.\n */\n findings?: FieldError[];\n}\n\nexport interface DeriveSummary {\n files: number;\n /** Files whose document changed, or would have under `dryRun`. */\n changed: number;\n /** Fields whose write reached the disk: always 0 under `dryRun` and `check`. */\n written: number;\n /**\n * `provenance` ranges whose write reached the disk (proposal 0046): always\n * 0 under `dryRun` and `check`. Present only when the run derives\n * `provenance`.\n */\n ranges?: number;\n stale: number;\n unset: number;\n unknown: number;\n errors: number;\n}\n\nexport interface DeriveRun {\n results: DeriveFileResult[];\n summary: DeriveSummary;\n dryRun: boolean;\n check: boolean;\n /** One status per source the run consulted; a source nobody asked for is absent. */\n sources: Partial<Record<DeriveSource, SourceStatus>>;\n /** Where the run stood, for the SARIF reporter under `check`. See `ValidateRun.frame`. */\n frame: FingerprintContext;\n}\n\n/** The hint `assertSourcesAvailable` appends: this command's own way out. */\nconst SOURCE_HINT = \"narrow --sources or --fields\";\n\nexport async function runDerive(opts: DeriveOptions): Promise<DeriveRun> {\n const cwd = opts.cwd ?? process.cwd();\n // Proposal 0046: `<path>:L` and `<path>:L1-L2` scope `--generated-by` to\n // file lines of one page. Split before anything resolves the inputs, so the\n // walk sees the page, and a range on stdin (`-:9`) is stdin all the same.\n const targets: { target: string; page: string }[] = [];\n const typedInputs = opts.inputs.map((arg) => {\n if (arg === STDIN_TOKEN) return arg;\n const { page, lines } = parseProvenanceTarget(arg);\n if (lines === undefined) return arg;\n if (page === STDIN_TOKEN) return STDIN_TOKEN;\n targets.push({ target: arg, page });\n return page;\n });\n const env = opts.env ?? process.env;\n // The option, once given, wins over the variable even when it is empty.\n // Either is trimmed, since trailer evidence is compared trimmed, and a\n // value that is blank after trimming is unset.\n const flagGeneratedBy = machineName(opts.generatedBy);\n const generatedBy =\n opts.generatedBy !== undefined ? flagGeneratedBy : machineName(env[GENERATED_BY_ENV]);\n\n const runConfig = await resolveRunConfig({\n cwd,\n configPath: opts.configPath,\n noConfig: opts.noConfig,\n inputs: typedInputs,\n ...(opts.collections !== undefined ? { collections: opts.collections } : {}),\n onConfigLoaded: opts.onConfigLoaded,\n });\n const { config, inputs, base, collections, declaredCollections, fromCollections, configFile } =\n runConfig;\n // Reassigned when an accepted relocation (0047) creates the config file.\n let configDir = runConfig.configDir;\n // Refused before any file is read: every other command takes `-`\n // as one more input, but a piped document has no commits, no path a\n // CODEOWNERS rule could match, and no pull request. There is nothing to\n // derive from, so the answer would be \"unknown\" for every field — and a\n // run that cannot answer is exit 2, not a quiet no-op.\n if (inputs.includes(STDIN_TOKEN)) {\n throw new DocmetaError(\"cannot derive <stdin>: no history behind it\");\n }\n if (inputs.length === 0) {\n throw new DocmetaError(\n \"No files to derive. Pass paths/globs, or declare a collection under `collections:` in manni.config.yaml.\",\n );\n }\n\n // The configured commands (0042): a key of theirs is as derivable as a\n // built-in field, and the source runs them where the config lives.\n const commands = commandsOf(config?.derive);\n // Proposal 0069: no `--fields` and no config `fields` is the merge-safe\n // default, which each page narrows to the fields its schemas claim once it\n // is read. Written fields are managed exactly as written.\n const defaulted = opts.fields === undefined && config?.derive?.fields === undefined;\n const fields: DerivableField[] = defaulted\n ? [...MERGE_SAFE_FIELDS]\n : resolveFields(opts.fields, config?.derive?.fields, commands);\n const wantsProvenance = fields.includes(PROVENANCE_FIELD);\n const firstTarget = targets[0];\n if (firstTarget !== undefined && generatedBy === undefined) {\n throw new DocmetaError(\n `${firstTarget.target} names lines, which only --generated-by uses. Pass --generated-by, or drop the range.`,\n );\n }\n // The variable alone never refuses: an agent session exports it once, and\n // a run that manages other fields has nothing for it to attribute.\n if ((flagGeneratedBy !== undefined || firstTarget !== undefined) && !wantsProvenance) {\n throw new DocmetaError(\n \"--generated-by attributes provenance, which is not in --fields. Add provenance, or drop --generated-by.\",\n );\n }\n // `loadConfig` refuses a `derive.fields` entry a URL manifest owns (0047,\n // M6); the same rule holds for `--fields`, which bypasses the config. A\n // local manifest that owns a field is where derive writes it. Every\n // declared collection counts, not only the selected ones, and the config's\n // `keys:` list is the whole claim, so no manifest is loaded. `provenance`\n // keeps its own refusal, raised where its record is placed (0046). The\n // merge-safe default names no field, so it refuses none: a page whose\n // field a URL manifest owns is that file's error when it is written.\n for (const field of defaulted ? [] : fields) {\n if (field === PROVENANCE_FIELD) continue;\n const owner = urlManifestOwning(field, declaredCollections);\n if (owner !== undefined) throw new DocmetaError(urlManifestMessage(field, owner.file));\n }\n const sources = resolveSources(opts.sources, config?.derive?.sources);\n const check = Boolean(opts.check);\n // `--check` judges and exits; it never writes.\n const dryRun = Boolean(opts.dryRun) || check;\n\n // Proposal 0045: a managed field its schema marks `x-manni-encrypt` is\n // compared by its plaintext and stamped encrypted, as every other write of\n // a marked value is. The schemas are read for their marks alone; `derive`\n // judges nothing else about the document.\n const schemaOptions = schemaLoadOptions({\n root: configDir ?? cwd,\n // A relative file ref belongs to the run's directory, not the cache root.\n fileBase: cwd,\n ttlHours: config?.schemaCache?.ttlHours,\n offline: config?.offline,\n pins: collectSchemaPins(config),\n registered: config?.registered,\n });\n const trustRoot = schemaTrustRoot(cwd, configDir);\n const validator = new Validator(schemaOptions);\n // What each page's schemas mark external, which a manifest with no keys\n // owns (proposal 0068).\n const marks = pageMarks({ validator, config, cwd, trustRoot, memberOf: (label) => membersFor(label) });\n // What each page's schemas claim, which narrows the merge-safe default (0069).\n const claims = pageClaims({ validator, config, cwd, trustRoot, memberOf: (label) => membersFor(label) });\n /** The fields the run derives: `fields`, narrowed under the default to what some page claims. */\n let runFields: readonly DerivableField[] = fields;\n /** Under the default, each page's own managed fields. */\n let pageFields = new Map<string, readonly DerivableField[]>();\n // A file outside `derive.collections` manages nothing (proposal 0070).\n const fieldsOf = (label: string): readonly DerivableField[] =>\n deriveCovers(config?.derive, membersFor(label)) ? (pageFields.get(label) ?? runFields) : [];\n const configuredKey = lazyKey(configFile, opts.env);\n let ensuredKey: string | undefined;\n const currentKey = (): string | undefined => ensuredKey ?? configuredKey();\n /**\n * A marked value as it lands in the patch. A dry run writes nothing, so it\n * neither prompts nor refuses: it encrypts under a key it already has, and\n * otherwise holds `(encrypted)`, as `fill --dry-run` does.\n */\n const seal = async (value: unknown, pointer: string): Promise<unknown> => {\n const have = currentKey();\n if (have !== undefined) return encryptValue(value, have, META_CONTEXT);\n if (dryRun) return ENCRYPTED_PLACEHOLDER;\n const { key } = await ensureEncryptionKey({\n subject: pointer,\n cwd,\n file: configFile ?? null,\n ...(opts.env === undefined ? {} : { env: opts.env }),\n ...(opts.confirm === undefined ? {} : { confirm: opts.confirm }),\n notice: (message) => opts.onNotice?.(message),\n toError: (message) => new EncryptionRefusal(message),\n });\n ensuredKey = key;\n return encryptValue(value, key, META_CONTEXT);\n };\n\n const forcedExtractor = opts.as ? extractorByName(opts.as) : undefined;\n if (opts.as && !forcedExtractor) {\n throw new DocmetaError(\n `Unknown format \"${opts.as}\". Known formats: ${listFormats()\n .map((f) => f.name)\n .join(\", \")}.`,\n );\n }\n\n const allowEmpty = opts.allowEmpty ?? config?.allowEmpty;\n const exts = opts.exts ?? forcedExtractor?.extensions;\n // Only `--exclude`: a collection's `exclude:` governs membership, not the\n // walk of a path someone typed (0041 rule 3).\n const exclude = opts.exclude ?? [];\n /** The collections one label belongs to, computed once per file. */\n const membersFor = (label: string): string[] =>\n memberOf(collections, configDir ?? cwd, base, label);\n const { files: walked, gitignoreSkipped } = await resolveTargetSet({\n inputs,\n exts,\n exclude,\n cwd: base,\n allowEmpty,\n ...gitignoreOptions({\n flag: opts.respectGitignore,\n configured: config?.respectGitignore,\n onNotice: opts.onNotice,\n }),\n });\n // Rule 9: narrow the walk to actual members, or a collection's `exclude:`\n // would shape its SQL view and not what a bare run stamps. Skipped for\n // typed paths: those are the operator's (rule 3).\n const files = fromCollections ? retainMembers(walked, membersFor) : walked;\n // A range names lines of one file, and that file must be one this run\n // reads. A directory, a glob, or a file --ext, --exclude or .gitignore\n // dropped would otherwise leave the range unused, and --generated-by would\n // attribute every uncommitted line of every page instead.\n const rangesByPage = new Map<string, string[]>();\n for (const t of targets) {\n const label = relative(base, resolve(base, t.page)).split(sep).join(\"/\");\n if (!files.includes(label)) {\n throw new DocmetaError(\n `${t.target} does not name one file that derive reads; a range names lines of one file.`,\n );\n }\n const named = rangesByPage.get(label) ?? [];\n if (!named.includes(t.target)) named.push(t.target);\n rangesByPage.set(label, named);\n }\n assertNonEmpty({\n files,\n inputs,\n usingStdin: false,\n allowEmpty,\n exclude,\n exts,\n gitignoreSkipped,\n action: \"derived\",\n });\n\n // ---- Load and extract ----------------------------------------------------\n // A document that will not parse is that file's error, not the run's: the\n // rest of the corpus still gets its stamps. Only the parseable ones go to\n // the sources.\n interface Loaded extends DeriveInput {\n format: string;\n elements: string[];\n apply: MetadataExtractor[\"apply\"];\n }\n interface Prepared {\n loaded: Map<string, Loaded>;\n errors: Map<string, { format: string; message: string }>;\n places: Map<string, ProvenancePlace>;\n provenanceCollections: CollectionConfig[];\n provenanceIndex: ExternalMetadataIndex | null;\n /** Collections with a local manifest owning a managed field other than `provenance` (0047). */\n ownedCollections: CollectionConfig[];\n ownedIndex: ExternalMetadataIndex | null;\n derived: Awaited<ReturnType<typeof deriveMetadata>>;\n }\n let sourcesNoted = false;\n /**\n * Read every page, place each `provenance` record, load the manifests that\n * own a managed field, and derive. Run again after an accepted relocation\n * (0047) moves values and declares manifests, so nothing below reads a page\n * or a config from before the move.\n */\n const prepare = async (): Promise<Prepared> => {\n const loaded = new Map<string, Loaded>();\n const errors = new Map<string, { format: string; message: string }>();\n for (const label of files) {\n const absPath = resolve(base, label);\n const extractor = forcedExtractor ?? extractorForExtension(extname(label));\n if (!extractor) {\n errors.set(label, {\n format: \"unknown\",\n message: `Unsupported file type \"${extname(label)}\". Supported: ${supportedExtensions().join(\", \")}. Use --as to override.`,\n });\n continue;\n }\n const content = await readFile(absPath, \"utf8\");\n const elements = resolveElements(label, config, membersFor(label));\n try {\n loaded.set(label, {\n label,\n absPath,\n content,\n format: extractor.name,\n elements,\n extracted: extractor.extract(content, label, { elements }),\n apply: extractor.apply,\n });\n } catch (err) {\n errors.set(label, { format: extractor.name, message: errorMessage(err) });\n }\n }\n\n // ---- The merge-safe default (0069): what each page manages ---------------\n if (defaulted) {\n const claimedBy = new Map<string, readonly DerivableField[]>();\n /** Pages whose schema set could not be read, so what they claim is unknown. */\n const unreadable: string[] = [];\n for (const doc of loaded.values()) {\n if (!deriveCovers(config?.derive, membersFor(doc.label))) {\n claimedBy.set(doc.label, []);\n continue;\n }\n const claimed = await claims(doc.label, doc.extracted.data, membersFor(doc.label));\n if (claimed === undefined) unreadable.push(doc.label);\n claimedBy.set(doc.label, fields.filter((f) => claimed?.has(f) === true));\n }\n const union = fields.filter((f) => [...claimedBy.values()].some((own) => own.includes(f)));\n // With no page read, nothing is known about what the schemas claim; the\n // parse errors are the diagnosis, and they are reported per file below.\n if (union.length === 0 && loaded.size > 0) {\n const [first] = unreadable;\n if (first !== undefined) {\n const more = unreadable.length > 1 ? ` and ${String(unreadable.length - 1)} more` : \"\";\n throw new DocmetaError(\n `nothing to derive: the schemas of ${first}${more} could not be read, so what they claim is unknown; fix them or pass --fields`,\n );\n }\n throw new DocmetaError(NOTHING_CLAIMED);\n }\n pageFields = claimedBy;\n runFields = union;\n }\n\n // ---- Provenance (0046): where each record lives, and what it says ------\n const provenanceRoot = configDir ?? cwd;\n // A `{page}` manifest (0058) is read for exactly the pages this run derives.\n const pages = files.map((label) => resolve(base, label));\n const manifests = runFields.includes(PROVENANCE_FIELD)\n ? provenanceManifests(declaredCollections, provenanceRoot, base)\n : [];\n // Only the manifests that own `provenance` are read, as cite reads only\n // the ones that own `citations`: a sibling manifest is none of derive's\n // business, and a URL one is never fetched here.\n // A keyless manifest (proposal 0068) may hold a page's record, when the\n // page's schemas mark it; a URL one is never fetched here.\n const provenanceCollections = declaredCollections\n .map((c) => ({\n ...c,\n externalMetadata: c.externalMetadata.filter((m) =>\n m.keys === undefined ? classifyRef(m.file).kind !== \"url\" : m.keys.includes(PROVENANCE_FIELD),\n ),\n }))\n .filter((c) => c.externalMetadata.length > 0);\n const provenanceIndex =\n manifests.length === 0\n ? null\n : await loadExternalMetadata(provenanceCollections, { configDir: provenanceRoot, base, pages });\n const places = new Map<string, ProvenancePlace>();\n for (const doc of loaded.values()) {\n // Rule 1 of 0069: a manifest that owns a dated field is read at each fact commit.\n const dated = fieldsOf(doc.label).filter((f) => f === \"created\" || f === \"last-updated\");\n if (dated.length > 0 && declaredCollections.length > 0) {\n const probe = { ...doc.extracted.data };\n for (const f of dated) if (!Object.hasOwn(probe, f)) probe[f] = null;\n const datedMarks = await marks(doc.label, probe, membersFor(doc.label));\n const owned = stampManifests(doc.label, doc.extracted.data, declaredCollections, provenanceRoot, base, datedMarks, dated);\n // Set after the object is built, unlike validate, get and query: which\n // fields a page manages is known only once its schemas' claims are read.\n if (Object.keys(owned).length > 0) doc.stampManifests = owned;\n }\n if (!fieldsOf(doc.label).includes(PROVENANCE_FIELD)) continue;\n // Asked with the record in place, since a mark counts only on a present value.\n const marked = manifests.some((m) => m.implied !== undefined)\n ? await marks(\n doc.label,\n Object.hasOwn(doc.extracted.data, PROVENANCE_FIELD)\n ? doc.extracted.data\n : { ...doc.extracted.data, [PROVENANCE_FIELD]: null },\n membersFor(doc.label),\n )\n : undefined;\n const place = provenancePlace(\n doc.label,\n doc.extracted.data,\n manifests,\n declaredCollections,\n provenanceRoot,\n base,\n marked,\n );\n if (place !== undefined) {\n places.set(doc.label, place);\n doc.provenanceManifest = { absPath: place.absPath, entry: place.entry, join: place.join };\n }\n // Every range named for the page, each refused on its own terms; ranges\n // that overlap attribute their union.\n const named = rangesByPage.get(doc.label);\n if (named !== undefined && generatedBy !== undefined) {\n doc.attribution = { targets: named, generatedBy };\n }\n }\n\n // ---- Manifests that own a managed field (0047) ---------------------------\n // Read so a field kept in a manifest is compared by the manifest's value.\n // Only local manifests owning one of this run's fields: a URL manifest\n // cannot own one (the config and `--fields` refuse it), and a sibling\n // manifest is none of derive's business.\n const ownedCollections = declaredCollections\n .map((c) => ({\n ...c,\n externalMetadata: c.externalMetadata.filter(\n (m) =>\n classifyRef(m.file).kind !== \"url\" &&\n // A keyless manifest (proposal 0068) owns what each page marks.\n (m.keys === undefined || m.keys.some((k) => k !== PROVENANCE_FIELD && runFields.includes(k))),\n ),\n }))\n .filter((c) => c.externalMetadata.length > 0);\n const ownedIndex =\n ownedCollections.length === 0\n ? null\n : await loadExternalMetadata(ownedCollections, { configDir: provenanceRoot, base, pages });\n\n // ---- Derive ------------------------------------------------------------\n const derived = await deriveMetadata([...loaded.values()], {\n cwd,\n base,\n configDir,\n sources,\n fields: runFields,\n codeowners: config?.derive?.codeowners,\n commands,\n cache: opts.cache ?? true,\n now: opts.now ?? (() => new Date()),\n reviews: opts.reviews,\n machines: machinesOf(config?.derive),\n ...(generatedBy !== undefined ? { generatedBy } : {}),\n });\n assertSourcesAvailable(derived.sources, SOURCE_HINT);\n // A source that answered, with a caveat worth one line: a repository with\n // no CODEOWNERS file derives null owners rather than failing.\n if (!sourcesNoted) {\n sourcesNoted = true;\n for (const [name, status] of Object.entries(derived.sources)) {\n if (status.available && status.reason !== undefined) {\n opts.onNotice?.(`${name}: ${status.reason}`);\n }\n }\n }\n return {\n loaded,\n errors,\n places,\n provenanceCollections,\n provenanceIndex,\n ownedCollections,\n ownedIndex,\n derived,\n };\n };\n let prepared = await prepare();\n /** The page's `provenance` as its record holds it: the manifest's, or the page's own. */\n const stampOf = async (doc: Loaded): Promise<unknown> => {\n if (!prepared.places.has(doc.label)) return doc.extracted.data[PROVENANCE_FIELD];\n const root = configDir ?? cwd;\n const members = memberOf(prepared.provenanceCollections, root, base, doc.label);\n return (await mergeWithMarks(doc.label, doc.extracted, prepared.provenanceIndex, members, base, { marks }))\n .extracted.data[PROVENANCE_FIELD];\n };\n\n // ---- Encryption (0045) -----------------------------------------------------\n /**\n * What encryption makes of one document's managed fields. `data` is the\n * page's metadata with every readable encrypted value decrypted, and\n * `marked` the pointers its schema marks, read over the page as it would\n * be stamped: an absent property is one Ajv never evaluates, so an unset\n * field's mark only shows once its value is in place. A managed field\n * holding a ciphertext no key can read cannot be compared, so it is the\n * file's error rather than a guess either way.\n */\n interface Marks {\n data: Record<string, unknown>;\n marked: string[];\n /** Where a value a manifest supplied lives (0047), for a finding's line. */\n locate: (pointer: string) => SourceLocation | undefined;\n /** Each top-level key's `x-manni-location`, read over the page as it would be stamped (0047). */\n prefs: ReadonlyMap<string, FieldLocation>;\n }\n // A schema notice names its file. Each page's marks are read for the P1\n // offer and again for its write, and relocation reads the same schemas, so\n // each notice is said once.\n const noticed = new Set<string>();\n const noticeOnce =\n opts.onNotice === undefined\n ? undefined\n : (message: string): void => {\n if (noticed.has(message)) return;\n noticed.add(message);\n opts.onNotice?.(message);\n };\n const markFields = async (\n doc: Loaded,\n record: DerivedRecord | undefined,\n ): Promise<Marks | { error: string }> => {\n // Proposal 0047: a managed field a manifest owns is compared by the\n // manifest's value, so the page's own metadata is merged with it first.\n let own = doc.extracted;\n let locate: Marks[\"locate\"] = () => undefined;\n if (prepared.ownedIndex !== null) {\n try {\n const members = memberOf(prepared.ownedCollections, configDir ?? cwd, base, doc.label);\n const merged = await mergeWithMarks(doc.label, doc.extracted, prepared.ownedIndex, members, base, {\n encryptionKey: currentKey,\n marks,\n });\n own = merged.extracted;\n locate = merged.locate;\n } catch (err) {\n if (err instanceof EncryptionRefusal || !(err instanceof DocmetaError)) throw err;\n return { error: err.message };\n }\n }\n let resolved: ResolvedSchemaSet;\n try {\n resolved = resolveSchemaSetWithSource({\n filePath: doc.label,\n fileSchema: doc.extracted.data[FILE_SCHEMA_KEY],\n config,\n memberOf: membersFor(doc.label),\n // The trust boundary `validate` and `fill` apply to a document's own\n // `$schema`, since that schema decides what gets encrypted.\n fileBase: cwd,\n trustRoot,\n onNotice: noticeOnce,\n });\n } catch (err) {\n return { error: errorMessage(err) };\n }\n try {\n const view = await encryptionView({\n data: own.data,\n refs: resolved.schemas,\n validator,\n key: currentKey,\n locate,\n });\n for (const field of fieldsOf(doc.label)) {\n const at = pointerOf(field);\n if (view.unverified.some((p) => isAtOrUnder(p, at))) {\n return {\n error: `${at} is encrypted, and no encryption key is available to compare it. Set ${ENCRYPTION_KEY_ENV}, or run \\`manni key set\\`.`,\n };\n }\n const unreadable = view.unreadable.find((p) => isAtOrUnder(p, at));\n if (unreadable !== undefined) return { error: unreadableMessage(unreadable) };\n }\n const stamped: Record<string, unknown> = { ...view.data };\n for (const field of fieldsOf(doc.label)) {\n const d = record?.fields[field];\n if (d != null) stamped[field] = d.value;\n }\n const marks = await validator.markedPointers(stamped, resolved.schemas);\n const prefs = new Map<string, FieldLocation>();\n for (const [key, p] of await validator.locationPreferences(stamped, resolved.schemas)) {\n prefs.set(key, p.location);\n }\n return { data: view.data, marked: [...new Set([...view.marked, ...marks])], locate, prefs };\n } catch (err) {\n if (err instanceof EncryptionRefusal) throw err;\n // As in `validate` and `fill`: a schema the document chose failing to\n // load is that document's failure; one the operator configured is the\n // run's.\n if (!(err instanceof DocmetaError) || resolved.source !== \"document\") throw err;\n return { error: err.message };\n }\n };\n /**\n * A value about to be stamped, with every marked pointer at or under its\n * field encrypted, shallowest first: a mark inside a value already sealed\n * is covered by the one on the whole.\n */\n const sealField = async (\n field: string,\n value: unknown,\n marked: readonly string[],\n ): Promise<unknown> => {\n const at = pointerOf(field);\n let holder: Record<string, unknown> = { [field]: value };\n const sealed: string[] = [];\n const under = marked.filter((p) => isAtOrUnder(p, at)).sort((a, b) => a.length - b.length);\n for (const pointer of under) {\n if (sealed.some((s) => isAtOrUnder(pointer, s))) continue;\n const inner = valueAt(holder, pointer);\n if (inner === undefined) continue;\n holder = withValueAt(holder, pointer, await seal(inner, pointer));\n sealed.push(pointer);\n }\n return holder[field];\n };\n\n const stale = (f: DerivedField): boolean => f.status === \"stale\" || f.status === \"unset\";\n\n // ---- Location (0047): a field that prefers external metadata -------------\n // A stale or unset field whose schema prefers external metadata, and which\n // no manifest owns, is offered a manifest on a terminal (P1) before anything\n // is written. A yes relocates, and the run re-reads what the move changed.\n // Otherwise the value goes to the page, and W1 or W2 says so afterwards.\n const ctx = relocationContext(runConfig, {\n cwd,\n targets: fromCollections ? [] : typedInputs,\n validator,\n ...(opts.noConfig === true ? { noConfig: true } : {}),\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n ...(noticeOnce !== undefined ? { onNotice: noticeOnce } : {}),\n });\n const externalWrites = async (): Promise<ExternalWrite[]> => {\n const out: ExternalWrite[] = [];\n for (const doc of prepared.loaded.values()) {\n const record = prepared.derived.records.get(doc.label);\n const marks = await markFields(doc, record);\n if (\"error\" in marks) continue;\n for (const field of fieldsOf(doc.label)) {\n if (field === PROVENANCE_FIELD || marks.prefs.get(field) !== \"external\") continue;\n if (!stale(compareDerived(field, marks.data[field], record?.fields[field]))) continue;\n const home = await keyHome(ctx, doc.label, doc.extracted.data, field);\n if (home.kind === \"unowned\") out.push({ label: doc.label, key: field, home: home.home });\n }\n }\n return out;\n };\n // `--check` judges; it neither asks nor warns about where a write would go.\n let flagged = check ? [] : await externalWrites();\n if (flagged.length > 0 && !dryRun && opts.confirm !== undefined) {\n const applied = await offerExternalHomes(ctx, flagged, {\n confirm: opts.confirm,\n ...(opts.onNotice !== undefined ? { onNotice: opts.onNotice } : {}),\n ...(opts.onRelocated !== undefined ? { onRelocated: opts.onRelocated } : {}),\n });\n if (applied.size > 0) {\n configDir = ctx.configDir ?? configDir;\n prepared = await prepare();\n flagged = flagged.filter((w) => !(w.home.kind === \"collection\" && applied.has(w.home.collection)));\n }\n }\n const { loaded, errors, places, derived } = prepared;\n\n // ---- Compare, and write ----------------------------------------------------\n /**\n * Each manifest this run writes, read once and spliced in memory (as cite\n * holds them). `text` holds every committed edit, and the edits themselves\n * are kept as descriptors, so a manifest another command wrote while this\n * run was working can be replayed onto rather than overwritten.\n */\n const heldManifests = new Map<string, MetaHeldManifest>();\n /** A field written into a manifest, whose line the report names once the manifest is settled. */\n const lineRequests: { field: DerivedField; absPath: string; entry: string; join: string }[] = [];\n const holdManifest = async (\n manifest: Pick<ProvenanceManifest, \"absPath\" | \"file\" | \"perPage\">,\n ): Promise<MetaHeldManifest> => {\n const already = heldManifests.get(manifest.absPath);\n if (already !== undefined) return already;\n const held = await holdManifestFile(manifest.absPath, manifest.file, manifest.perPage);\n heldManifests.set(manifest.absPath, held);\n return held;\n };\n const results: DeriveFileResult[] = [];\n /** Save every held manifest a committed edit changed, compare-and-swap. */\n const saveManifests = async (): Promise<void> => {\n for (const held of heldManifests.values()) await settleManifest(held);\n };\n // A run that aborts part-way (a declined key prompt on a later file) still\n // saves the manifest edits of the pages it already wrote; a dry run saves\n // nothing either way. That save is still a compare-and-swap, and a refusal\n // there is still swallowed: the run is already unwinding the error that\n // stopped it, and the refusal's own guarantee is that it wrote nothing, so\n // reporting it would replace the reason the run stopped with a symptom.\n let settled = false;\n try {\n for (const label of files) {\n const failure = errors.get(label);\n if (failure) {\n results.push(errorResult(label, failure.format, failure.message, check));\n continue;\n }\n const doc = loaded.get(label);\n /* c8 ignore next -- every file is in exactly one of the two maps. */\n if (!doc) continue;\n\n const record = derived.records.get(label);\n // A marked field (0045) is compared by its plaintext, stamped encrypted,\n // and reported as `(encrypted)`, as `fill` and `query` report one.\n const marks = await markFields(doc, record);\n if (\"error\" in marks) {\n results.push(errorResult(label, doc.format, marks.error, check));\n continue;\n }\n const isMarked = (field: string): boolean => {\n const at = pointerOf(field);\n return marks.marked.some((p) => isAtOrUnder(p, at));\n };\n // Proposal 0046: `provenance` is judged range by range against the\n // record wherever it lives, never by `compareDerived`.\n const place = places.get(label);\n const managed = fieldsOf(label);\n const provenance = managed.includes(PROVENANCE_FIELD)\n ? judgeProvenance(await stampOf(doc), derived.provenance?.get(label), record?.fields[PROVENANCE_FIELD] ?? null, place)\n : undefined;\n const compared = managed.map((field) =>\n field === PROVENANCE_FIELD && provenance !== undefined\n ? provenance.field\n : compareDerived(field, marks.data[field], record?.fields[field]),\n );\n // Read when reporting, after `written` is set on `compared` below.\n const shown = (): DerivedField[] =>\n compared.map((f) =>\n f.field !== PROVENANCE_FIELD && isMarked(f.field) ? redactedDerived(f) : f,\n );\n const findingsOf = (reported: readonly DerivedField[]): FieldError[] =>\n reported.flatMap((f) =>\n f.field === PROVENANCE_FIELD && provenance?.judged !== undefined\n ? provenanceFindings(provenance.judged.comparisons, provenance.judged.derivation.page.bodyLine)\n : staleFindings([f], doc.extracted.lineFor, marks.locate),\n );\n if (\n provenance?.judged !== undefined &&\n flagGeneratedBy !== undefined &&\n doc.attribution === undefined &&\n ![...provenance.judged.derivation.evidenceByLine.values()].some((e) => e.rule === 1)\n ) {\n opts.onNotice?.(\n `${label}: no uncommitted body lines; --generated-by attributes only what is not yet committed.`,\n );\n }\n // A manifest-held record is written into the manifest, not the page.\n const toManifest =\n provenance !== undefined && place !== undefined && stale(provenance.field) ? provenance : undefined;\n const due = compared.filter((f) => stale(f) && !(f.field === PROVENANCE_FIELD && toManifest !== undefined));\n // Proposal 0047: a field a manifest of the page's collections owns is\n // written into the page's entry there, whatever its schema prefers; the\n // config's ownership decides where a write lands. A URL manifest cannot\n // be written, and a field join the page lacks has no entry to write to.\n const toEntries: { f: DerivedField; home: Extract<KeyHome, { kind: \"manifest\" }>; entry: string }[] = [];\n let refusal: string | undefined;\n for (const f of due) {\n if (f.field === PROVENANCE_FIELD) continue;\n const home = await keyHome(ctx, label, doc.extracted.data, f.field);\n if (home.kind === \"url\") {\n refusal = urlManifestMessage(f.field, home.file);\n break;\n }\n if (home.kind !== \"manifest\") continue;\n if (home.entry === undefined) {\n refusal = `${label} carries no ${home.join}, which ${home.file} joins on, so its ${f.field} has no entry there.`;\n break;\n }\n f.destination = home.file;\n toEntries.push({ f, home, entry: home.entry });\n }\n if (refusal !== undefined) {\n results.push(errorResult(label, doc.format, refusal, check, shown()));\n continue;\n }\n const pending = due.filter((f) => !toEntries.some((t) => t.f === f));\n const onPage = pending.find((f) => f.field === PROVENANCE_FIELD);\n // Stress test 8: where the metadata is part of the body, a stamp on the\n // page would change the very lines it pins.\n if (onPage !== undefined && !provenanceFenced(doc.extracted)) {\n results.push(\n errorResult(\n label,\n doc.format,\n `provenance cannot be stamped into the page: in the \"${doc.format}\" format the metadata is part of the body it pins. Keep provenance in an externalMetadata manifest.`,\n check,\n shown(),\n ),\n );\n continue;\n }\n // `changed` is what the writer would do, not what the comparison found:\n // as in `fill`, the patch is applied and the result compared with the\n // document, so a field is `written` only when bytes went to disk. Under\n // `dryRun` the same patch is computed and nothing is written.\n let changed = false;\n // This file's manifest edits are staged over the held texts and committed\n // only once its page write has succeeded (or it had none to make), so a\n // file that fails contributes no manifest edit.\n const staged = new Map<string, string>();\n // The edit is recorded as the descriptor that made it, not as the text\n // it produced, so the commit can replay it onto bytes read later. An\n // edit that changes nothing records nothing: it is not this run's claim\n // on that key, so another command writing the key is no conflict.\n const stagedOps: { held: MetaHeldManifest; op: MetaManifestOp }[] = [];\n const stage = async (\n manifest: Pick<ProvenanceManifest, \"absPath\" | \"file\" | \"perPage\">,\n op: MetaManifestOp,\n ): Promise<boolean> => {\n const held = await holdManifest(manifest);\n const before = staged.get(held.path) ?? held.text;\n const after = applyManifestOp(before, op);\n staged.set(held.path, after);\n if (after === before) return false;\n stagedOps.push({ held, op });\n return true;\n };\n /** Fields a staged manifest edit writes, marked written at the commit. */\n const manifestWritten: DerivedField[] = [];\n const entryWritten: DerivedField[] = [];\n if (toManifest?.judged !== undefined && place !== undefined) {\n const where = { entry: place.entry, key: PROVENANCE_FIELD, join: place.join, file: place.manifest.file };\n const plan = toManifest.judged.plan;\n // An empty record is no record, as on the page: `provenance` has\n // `minItems: 1`, so the key leaves the entry rather than holding `[]`.\n const edited = await stage(\n place.manifest,\n plan.length === 0\n ? { ...where, kind: \"remove\" }\n : { ...where, kind: \"splice\", value: plan },\n );\n if (edited) {\n changed = true;\n manifestWritten.push(toManifest.field);\n }\n }\n try {\n for (const { f, home, entry } of toEntries) {\n const value = isMarked(f.field) ? await sealField(f.field, f.derived, marks.marked) : f.derived;\n const edited = await stage(home, {\n kind: \"splice\",\n entry,\n key: f.field,\n value,\n join: home.join,\n file: home.file,\n });\n if (edited) {\n changed = true;\n manifestWritten.push(f);\n entryWritten.push(f);\n }\n }\n } catch (err) {\n if (err instanceof EncryptionRefusal || !(err instanceof DocmetaError)) throw err;\n results.push(errorResult(label, doc.format, err.message, check, shown()));\n continue;\n }\n if (pending.length > 0) {\n // Same writer `fill` and `query` use, so a format they cannot write is\n // refused here the same way — and refused loudly, as this file's error,\n // rather than by leaving a stale stamp in place with exit 0. Under\n // `check` a read-only format still gets its findings, since nothing was\n // going to be written anyway.\n if (typeof doc.apply !== \"function\") {\n if (!dryRun) {\n results.push(\n errorResult(\n label,\n doc.format,\n `The \"${doc.format}\" format is read-only; manni meta derive cannot write metadata back to it.`,\n check,\n shown(),\n ),\n );\n continue;\n }\n changed = true;\n } else {\n const patch: MetadataPatch = {};\n const deletions: string[] = [];\n for (const f of pending) {\n if (f.field === PROVENANCE_FIELD) {\n // An empty record is no record: `provenance` has `minItems: 1`.\n if (Array.isArray(f.derived) && f.derived.length === 0) deletions.push(f.field);\n else patch[f.field] = f.derived;\n continue;\n }\n patch[f.field] = isMarked(f.field)\n ? await sealField(f.field, f.derived, marks.marked)\n : f.derived;\n }\n const apply = doc.apply;\n const write = (value: MetadataPatch): string =>\n apply(doc.content, value, {\n filePath: label,\n elements: doc.elements,\n ...(deletions.length > 0 ? { deletions } : {}),\n });\n let next: string;\n try {\n next = write(patch);\n // A page with no block yet gets one, and the writer may leave a\n // blank line after it: the body then starts a line later, and every\n // body line the stamp names moves with it.\n const plan = patch[PROVENANCE_FIELD];\n const shift = bodyShift(doc.content, next);\n if (shift > 0 && Array.isArray(plan)) {\n next = write({ ...patch, [PROVENANCE_FIELD]: shiftEntries(provenanceEntries(plan), shift) });\n }\n } catch (err) {\n results.push(errorResult(label, doc.format, errorMessage(err), check, shown()));\n continue;\n }\n changed = changed || next !== doc.content;\n if (next !== doc.content && !dryRun) {\n await writeFileAtomic(doc.absPath, next);\n for (const f of pending) markWritten(f);\n }\n }\n }\n\n // The page is written (or needed no write): commit this file's manifest\n // edits to the held texts, and to the replay the save will need.\n for (const { held, op } of stagedOps) recordManifestOp(held, op);\n for (const [path, text] of staged) {\n const held = heldManifests.get(path);\n if (held !== undefined) held.text = text;\n }\n if (!dryRun) for (const f of manifestWritten) markWritten(f);\n\n const reported = shown();\n for (const { f, home, entry } of toEntries) {\n const shownField = reported.find((r) => r.field === f.field);\n if (shownField !== undefined && entryWritten.includes(f)) {\n lineRequests.push({ field: shownField, absPath: home.absPath, entry, join: home.join });\n }\n }\n results.push({\n file: label,\n format: doc.format,\n fields: reported,\n changed,\n ...(check ? { findings: findingsOf(reported) } : {}),\n });\n }\n settled = true;\n } finally {\n if (!dryRun && !settled) {\n await saveManifests().catch(() => undefined);\n }\n }\n\n // One write per manifest, after every page that touches it is settled.\n if (!dryRun) {\n await saveManifests();\n for (const req of lineRequests) {\n const held = heldManifests.get(req.absPath);\n const line = held === undefined ? undefined : manifestKeyLine(held.text, req.entry, req.field.field, req.join);\n if (line !== undefined) req.field.destinationLine = line;\n }\n }\n\n // W1 and W2 (0047): a value its schema prefers in external metadata that\n // went to the page, or would have. One line per collection, not per page.\n if (flagged.length > 0) {\n const landed = flagged.filter((w) => {\n const r = results.find((x) => x.file === w.label);\n const f = r?.fields.find((x) => x.field === w.key);\n if (r === undefined || r.error !== undefined || f === undefined || f.destination !== undefined) return false;\n return dryRun ? stale(f) && r.changed : f.written;\n });\n for (const line of externalWriteWarnings(landed, dryRun)) warn(line);\n }\n\n const summary = summarize(results);\n return {\n results,\n summary: runFields.includes(PROVENANCE_FIELD) ? { ...summary, ranges: countRanges(results) } : summary,\n dryRun,\n check,\n sources: derived.sources,\n frame: { cwd, base: configDir ?? cwd, runBase: base },\n };\n}\n\n/**\n * Whether the run fails, exit 1. A file the run could not read or write fails\n * it whether or not it wrote the rest, as it does for `fill`: a stamp that was\n * never applied must not read as done. Under `check`, any finding fails it,\n * which is exactly what `validate` would file. A moved `provenance` pin is\n * `stale` so that `derive` rewrites its lines, but it files no finding and\n * does not fail `--check`. An applied run is the work done.\n */\nexport function deriveFailed(run: Pick<DeriveRun, \"results\" | \"summary\" | \"check\">): boolean {\n if (run.summary.errors > 0) return true;\n return run.check && run.results.some((r) => (r.findings ?? []).length > 0);\n}\n\n/** A `--generated-by` or `MANNI_GENERATED_BY` value, trimmed; blank is unset. */\nfunction machineName(value: string | undefined): string | undefined {\n const name = value?.trim();\n return name === undefined || name === \"\" ? undefined : name;\n}\n\n/** Exit 2 when the merge-safe default applies and no page claims any of it (0069). */\nconst NOTHING_CLAIMED = `nothing to derive: no page's schemas claim a merge-safe field (${MERGE_SAFE_FIELDS.join(\", \")}); set derive.fields or pass --fields`;\n\n/**\n * The fields this run stamps: `--fields`, else config `derive.fields`.\n * Validated here as well as in the config parser, because `--fields` is typed\n * by a person and `runDerive` is public API.\n */\nfunction resolveFields(\n flag: string[] | undefined,\n configured: readonly DerivableField[] | undefined,\n commands: Readonly<Record<string, DeriveCommand>> | undefined,\n): DerivableField[] {\n const names = flag ?? configured;\n if (names === undefined || names.length === 0) {\n throw new DocmetaError(\n \"nothing to derive: set derive.fields in manni.config.yaml or pass --fields\",\n );\n }\n const out: DerivableField[] = [];\n for (const name of names) {\n if (!isBuiltinField(name) && !(commands !== undefined && Object.hasOwn(commands, name))) {\n throw new DocmetaError(\n `\"${name}\" is not derivable; derivable fields are ${DERIVABLE_FIELDS.join(\", \")}, or any key with an entry in derive.commands`,\n );\n }\n if (!out.includes(name)) out.push(name);\n }\n return out;\n}\n\n/** The sources this run consults: `--sources`, else config `derive.sources`, else all four. */\nfunction resolveSources(\n flag: string[] | undefined,\n configured: readonly DeriveSource[] | undefined,\n): DeriveSource[] {\n const names = flag ?? configured ?? DERIVE_SOURCES;\n const out: DeriveSource[] = [];\n for (const name of names) {\n if (!isDeriveSource(name)) {\n throw new DocmetaError(\n `\"${name}\" is not a source; sources are ${DERIVE_SOURCES.join(\", \")}`,\n );\n }\n if (!out.includes(name)) out.push(name);\n }\n return out;\n}\n\n/**\n * A file the run could not derive or write. Under `check` the error is a\n * finding too, shaped as `validate` shapes a parse failure, so the reporters\n * give it the reserved `manni/parse-error` rule rather than inventing one.\n */\nfunction errorResult(\n file: string,\n format: string,\n message: string,\n check: boolean,\n fields: DerivedField[] = [],\n): DeriveFileResult {\n return {\n file,\n format,\n fields,\n changed: false,\n error: message,\n ...(check\n ? {\n findings: [\n { schema: \"(parse)\", instancePath: \"\", message, keyword: \"parse\" },\n ],\n }\n : {}),\n };\n}\n\nfunction summarize(results: DeriveFileResult[]): DeriveSummary {\n const summary: DeriveSummary = {\n files: results.length,\n changed: 0,\n written: 0,\n stale: 0,\n unset: 0,\n unknown: 0,\n errors: 0,\n };\n for (const r of results) {\n if (r.changed) summary.changed++;\n if (r.error !== undefined) summary.errors++;\n for (const f of r.fields) {\n if (f.written) summary.written++;\n if (f.status === \"stale\") summary.stale++;\n else if (f.status === \"unset\") summary.unset++;\n else if (f.status === \"unknown\") summary.unknown++;\n }\n }\n return summary;\n}\n\n/** A field marked written, and for `provenance` every range that was not already current. */\nfunction markWritten(field: DerivedField): void {\n field.written = true;\n for (const range of field.ranges ?? []) {\n if (range.status !== \"current\") range.written = true;\n }\n}\n\n/** Ranges written across the run. */\nfunction countRanges(results: readonly DeriveFileResult[]): number {\n let n = 0;\n for (const r of results) {\n for (const f of r.fields) n += (f.ranges ?? []).filter((range) => range.written).length;\n }\n return n;\n}\n\ninterface JudgedProvenance {\n derivation: ProvenanceDerivation;\n comparisons: ProvenanceComparison[];\n /** What `derive` writes: current entries kept, moved ones re-lined, the rest re-derived. */\n plan: ProvenanceEntry[];\n}\n\n/**\n * One page's `provenance` as a `DerivedField`: the record against the\n * derivation, range by range (proposal 0046). `status` is `current` when\n * every range is, and otherwise `unset` for a page with no record or\n * `stale` for one whose record is wrong; `unknown` when git had nothing to\n * say about the page at all.\n */\nfunction judgeProvenance(\n asserted: unknown,\n derivation: ProvenanceDerivation | undefined,\n value: DerivedValue | null,\n place: ProvenancePlace | undefined,\n): { field: DerivedField; judged?: JudgedProvenance } {\n const base = {\n field: PROVENANCE_FIELD,\n ...(asserted !== undefined ? { asserted } : {}),\n ...(place !== undefined ? { manifest: place.manifest.file } : {}),\n };\n if (derivation === undefined) {\n return { field: { ...base, derived: null, status: \"unknown\", written: false } };\n }\n const comparisons = compareProvenance(provenanceEntries(asserted), derivation);\n const plan = planProvenanceWrite(comparisons, derivation);\n const settled = comparisons.every((c) => c.status === \"current\");\n const status: DerivedStatus = settled\n ? \"current\"\n : asserted === undefined || comparisons.every((c) => c.status === \"unset\")\n ? \"unset\"\n : \"stale\";\n return {\n field: {\n ...base,\n derived: plan,\n source: \"git\",\n ...(value !== null ? { evidence: value.evidence } : {}),\n status,\n written: false,\n ranges: rangeResults(comparisons, derivation.page.bodyLine),\n },\n judged: { derivation, comparisons, plan },\n };\n}\n\n/**\n * How many lines further down the body starts after a write: a writer that\n * adds a block may leave a blank line after it. Zero when the body is the\n * same, and when it changed in some other way.\n */\nfunction bodyShift(before: string, after: string): number {\n const was = readProvenancePage(before).body;\n const now = readProvenancePage(after).body;\n const shift = now.length - was.length;\n if (shift <= 0) return 0;\n return now.slice(shift).join(\"\\n\") === was.join(\"\\n\") ? shift : 0;\n}\n\nfunction shiftEntries(entries: readonly ProvenanceEntry[], shift: number): ProvenanceEntry[] {\n return entries.map((e) => {\n const span = parseLines(e.lines);\n if (span === undefined) return e;\n return { ...e, lines: lineSpec({ start: span.start + shift, end: span.end + shift }) };\n });\n}\n","/**\n * Reporter for `fill`.\n *\n * `render()` in ./index.ts is keyed to ValidationResult/RunSummary, so `fill`\n * gets its own renderer rather than a fourth branch there. The colour palette is\n * shared, so NO_COLOR and TTY behaviour stay identical across commands.\n *\n * The report always states the threshold and names the fields that fell below\n * it. A skipped field that is invisible is indistinguishable from a field the\n * model never considered, and the difference matters to whoever has to fill it\n * in by hand.\n */\nimport { DocmetaError } from \"../types.js\";\nimport type { FillRun } from \"../commands/fill-types.js\";\nimport { toJsonText } from \"../core/json-text.js\";\nimport { palette } from \"../../shared/color.js\";\nimport {\n escapeWorkflowCommandMessage,\n escapeWorkflowCommandProperty,\n} from \"./github.js\";\nimport { formatList } from \"./index.js\";\n\n/**\n * Every value `fill -f` accepts, in the order help and error messages list\n * them. Derived union, one statement of the list — the same rule\n * `REPORT_FORMATS` documents at length in ./index.ts, which this file used to\n * break by spelling `\"pretty\" | \"json\"` out a second time.\n *\n * `sarif` and `junit` are deliberately absent: they describe *findings in\n * files*, and a skipped optional property is a proposal with a confidence\n * score, not a finding. See 0003 § stress test 8.\n */\nexport const FILL_FORMATS = [\"pretty\", \"json\", \"github\"] as const;\n\nexport type FillReportFormat = (typeof FILL_FORMATS)[number];\n\n/** `\"pretty, json, or github\"`, for messages and help text. */\nexport const FILL_FORMAT_LIST = formatList(FILL_FORMATS);\n\nexport function isFillFormat(value: string): value is FillReportFormat {\n return (FILL_FORMATS as readonly string[]).includes(value);\n}\n\nexport interface FillReportOptions {\n color?: boolean;\n /**\n * In pretty output, omit files with nothing to report.\n *\n * \"Nothing\" is narrow on purpose — see `renderFillPretty`.\n */\n quiet?: boolean;\n}\n\nexport function renderFillJson(run: FillRun): string {\n return JSON.stringify(run, null, 2);\n}\n\nconst score = (n: number): string => n.toFixed(2);\n\nexport function renderFillPretty(\n run: FillRun,\n opts: FillReportOptions = {},\n): string {\n const c = palette(opts.color ?? false);\n const lines: string[] = [];\n\n for (const result of run.results) {\n if (result.error != null) {\n lines.push(`${c.red(\"✗\")} ${result.file}`);\n lines.push(` ${result.error}`);\n continue;\n }\n if (result.fields.length === 0) continue;\n\n const written = result.fields.filter((f) => f.written);\n // What `--quiet` may hide, and it is a short list. \"Files with no\n // proposals\" would be a no-op — the guard above already drops those — so\n // the only files left to drop are the ones with nothing *written*, and\n // those are precisely the files carrying a required skip, which is what\n // makes the run exit 1. Hiding them would hide the reason for the failure,\n // so a required skip (like an error, handled above) always prints.\n const requiredSkipped = result.fields.some((f) => f.required && !f.written);\n if (opts.quiet && written.length === 0 && !requiredSkipped) continue;\n const low = result.fields.filter((f) => f.skipReason === \"low-confidence\");\n const other = result.fields.filter(\n (f) => !f.written && f.skipReason !== \"low-confidence\",\n );\n\n const mark = written.length > 0 ? c.green(\"✓\") : c.dim(\"·\");\n lines.push(`${mark} ${result.file}`);\n for (const f of written) {\n lines.push(\n ` ${c.cyan(f.field)} ${formatValue(f.value)} ${c.dim(score(f.confidence))}${f.destination === undefined ? \"\" : ` → ${f.destination}`}`,\n );\n }\n const record = result.metaProvenance;\n if (record?.written === true) {\n lines.push(\n ` ${c.cyan(\"meta-provenance\")} ${record.entry[\"generated-by\"]}: ${record.entry.fields.join(\", \")}${record.destination === undefined ? \"\" : ` → ${record.destination}`}`,\n );\n } else if (record?.skipReason === \"schema-mismatch\") {\n lines.push(\n c.dim(\" meta-provenance not written: this page's schemas do not allow it\"),\n );\n } else if (record?.skipReason === \"manifest-owned\") {\n lines.push(\n c.dim(\n ` meta-provenance not written: owned by manifest ${record.manifest}, which is fetched and cannot be written`,\n ),\n );\n } else if (record?.skipReason === \"unwritable\") {\n lines.push(\n c.dim(` meta-provenance not written: ${result.format} metadata cannot hold it`),\n );\n }\n if (low.length > 0) {\n lines.push(\n c.dim(\n ` below ${run.threshold}: ${low\n .map((f) => `${f.field} ${score(f.confidence)}`)\n .join(\", \")}`,\n ),\n );\n }\n for (const f of other) {\n lines.push(c.dim(` ${f.skipReason ?? \"skipped\"}: ${f.field}`));\n }\n }\n\n const { summary } = run;\n const verb = run.dryRun ? \"would be written\" : \"written\";\n const parts = [\n // Which provider ran decides what the proposals and the cost mean, and\n // under `auto` it is not something the user chose — so say it rather than\n // making them pass -f json to find out.\n `${run.provider}/${run.model}`,\n `Threshold ${run.threshold}`,\n `${summary.files} file${summary.files === 1 ? \"\" : \"s\"}`,\n `${summary.written} field${summary.written === 1 ? \"\" : \"s\"} ${verb}`,\n `${summary.skipped} skipped`,\n ];\n if (summary.errors > 0) parts.push(`${summary.errors} errored`);\n if (summary.cached > 0) parts.push(`${summary.cached} cached`);\n // claude-cli reports no token usage, so a $0.00 there means \"unknown\", not\n // \"free\" — say nothing rather than imply a verified zero.\n if (summary.costUsd > 0) parts.push(`$${summary.costUsd.toFixed(4)}`);\n\n if (lines.length > 0) lines.push(\"\");\n const footer = parts.join(\" · \");\n lines.push(summary.requiredSkipped > 0 ? c.yellow(footer) : footer);\n\n if (summary.requiredSkipped > 0) {\n lines.push(\n c.yellow(\n `${summary.requiredSkipped} required field${summary.requiredSkipped === 1 ? \"\" : \"s\"} could not be filled confidently — fill ${summary.requiredSkipped === 1 ? \"it\" : \"them\"} in by hand.`,\n ),\n );\n }\n if (run.turnsSpent) {\n lines.push(\n c.yellow(\"--max-turns reached; some files were not processed.\"),\n );\n }\n\n return lines.join(\"\\n\");\n}\n\n/** Named to avoid shadowing `renderFill`'s `format` parameter. */\nfunction formatValue(value: unknown): string {\n if (typeof value === \"string\") return value;\n // `toJsonText`, not `JSON.stringify`, so the `String(value)` fallback stays\n // visibly reachable — see there.\n return toJsonText(value) ?? String(value);\n}\n\n/**\n * GitHub Actions annotations for the work `fill` could **not** do.\n *\n * One `::error` per property the schema requires that was not filled — the same\n * set that drives `fill`'s exit code 1. Optional skips stay silent, matching\n * the exit-code rule: a skipped optional property is a normal outcome, and\n * annotating it would make every run look broken.\n *\n * No `line=`. A `FilledField` carries no location — unlike a validation error,\n * a proposal is about a property that is *missing* from the document, so there\n * is nothing to point at. GitHub anchors a file-only annotation to line 1.\n *\n * The escaping is `escapeWorkflowCommandMessage`, shared with `validate`'s\n * renderer rather than re-derived: the `%`-before-newline ordering is the part\n * that is easy to get wrong.\n */\nexport function renderFillGithub(run: FillRun): string {\n const lines: string[] = [];\n for (const result of run.results) {\n const file = escapeWorkflowCommandProperty(result.file);\n // A file-level error — an unparseable document, a read-only format, a\n // provider failure — counts toward `summary.errors` and so drives exit 1\n // exactly as a required skip does. Emitting nothing for it left a red run\n // with no annotation anywhere: CI fails, and the Files tab is clean.\n if (result.error != null) {\n lines.push(\n `::error file=${file}::${escapeWorkflowCommandMessage(`[fill] ${result.error}`)}`,\n );\n continue;\n }\n for (const f of result.fields) {\n if (!f.required || f.written) continue;\n const why =\n f.skipReason === \"low-confidence\"\n ? `confidence ${score(f.confidence)} is below the ${run.threshold} threshold`\n : (f.skipReason ?? \"skipped\");\n const msg = escapeWorkflowCommandMessage(\n `[fill] ${f.field} is required and was not filled (${why})`,\n );\n lines.push(`::error file=${file}::${msg}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function renderFill(\n format: FillReportFormat,\n run: FillRun,\n opts: FillReportOptions = {},\n): string {\n switch (format) {\n case \"json\":\n return renderFillJson(run);\n case \"github\":\n return renderFillGithub(run);\n case \"pretty\":\n return renderFillPretty(run, opts);\n default: {\n // Exhaustive, like `render()`: adding a format to `FILL_FORMATS` without\n // a case here is a compile error, and the throw covers the runtime half —\n // `renderFill` is public API, and a caller asking for a machine format\n // must not be handed a human report instead.\n const unreachable: never = format;\n throw new DocmetaError(\n `Unknown report format ${JSON.stringify(unreachable)}. Use ${FILL_FORMAT_LIST}.`,\n );\n }\n }\n}\n","/**\n * Reporter for `derive`.\n *\n * Two shapes, decided by the run. An apply or dry run reports *changes* —\n * what each field went from and to, with the evidence — and has its own\n * `pretty` and `json`. A `--check` run reports *findings*, and every format\n * including `pretty` and `json` is handed to `render()` in ./index.ts, so\n * `github`, `sarif` and `junit` come for free and a stale stamp lands in the\n * same annotation, rule id (`derived:stale/derived`) and JUnit case shape a\n * schema violation does. That is why the findings formats are refused\n * without `--check`: they describe findings, and only `--check` produces any.\n */\nimport { DocmetaError, type RunSummary, type ValidationResult } from \"../types.js\";\nimport type { DeriveFileResult, DeriveRun } from \"../commands/derive.js\";\nimport type { DerivedField } from \"../core/derive/types.js\";\nimport type { RangeResult } from \"../core/derive/provenance.js\";\nimport { toJsonText } from \"../core/json-text.js\";\nimport { palette, type Colors } from \"../../shared/color.js\";\nimport { formatList, render, type ReportOptions } from \"./index.js\";\n\n/**\n * Every value `derive -f` accepts: the same five as `validate`, because a\n * `--check` run renders through validate's reporters. Stated as its own list\n * so the two can grow apart without either edit reaching the other.\n */\nexport const DERIVE_FORMATS = [\"pretty\", \"json\", \"github\", \"sarif\", \"junit\"] as const;\n\nexport type DeriveReportFormat = (typeof DERIVE_FORMATS)[number];\n\n/** `\"pretty, json, github, sarif, or junit\"`, for messages and help text. */\nexport const DERIVE_FORMAT_LIST = formatList(DERIVE_FORMATS);\n\nexport function isDeriveFormat(value: string): value is DeriveReportFormat {\n return (DERIVE_FORMATS as readonly string[]).includes(value);\n}\n\n/** The JUnit `classname` a derive finding ships under, not validate's. */\nconst JUNIT_CLASSNAME = \"manni.derive\";\n\nexport type DeriveReportOptions = ReportOptions;\n\nexport function renderDerive(\n run: DeriveRun,\n format: DeriveReportFormat,\n opts: DeriveReportOptions = {},\n): string {\n if (run.check) {\n const { results, summary } = asValidation(run);\n return render(format, results, summary, {\n classname: JUNIT_CLASSNAME,\n ...opts,\n });\n }\n switch (format) {\n case \"json\":\n return JSON.stringify(run, null, 2);\n case \"pretty\":\n return renderDerivePretty(run, opts);\n case \"github\":\n case \"sarif\":\n case \"junit\":\n throw new DocmetaError(\n `${format} is a findings format, which only --check produces`,\n );\n default: {\n // Exhaustive, like `render()`: a format added to `DERIVE_FORMATS`\n // without a case here is a compile error, and the throw covers a\n // caller of the public API handing in a string the union does not name.\n const unreachable: never = format;\n throw new DocmetaError(\n `Unknown report format ${JSON.stringify(unreachable)}. Use ${DERIVE_FORMAT_LIST}.`,\n );\n }\n }\n}\n\n/** A `--check` run as `validate` would report it: one result per file, its findings as errors. */\nfunction asValidation(run: DeriveRun): { results: ValidationResult[]; summary: RunSummary } {\n const results = run.results.map((r): ValidationResult => {\n const errors = r.findings ?? [];\n return { file: r.file, format: r.format, ok: errors.length === 0, schemas: [], errors };\n });\n const failed = results.filter((r) => !r.ok).length;\n return {\n results,\n summary: {\n files: results.length,\n passed: results.length - failed,\n failed,\n errors: results.reduce((n, r) => n + r.errors.length, 0),\n },\n };\n}\n\nconst plural = (n: number, noun: string): string => `${n} ${noun}${n === 1 ? \"\" : \"s\"}`;\n\nexport function renderDerivePretty(run: DeriveRun, opts: DeriveReportOptions = {}): string {\n const c = palette(opts.color ?? false);\n const lines: string[] = [];\n\n for (const result of run.results) {\n if (result.error !== undefined) {\n lines.push(`${c.red(\"✗\")} ${result.file}`);\n lines.push(` ${result.error}`);\n continue;\n }\n const pending = result.fields.filter((f) => f.status === \"stale\" || f.status === \"unset\");\n if (pending.length === 0) {\n if (opts.quiet) continue;\n lines.push(`${result.file} ${c.dim(\"current\")}${unknownNote(result, c.dim)}`);\n continue;\n }\n // One row per stale or unset field, and for `provenance` one per range\n // that is not current (proposal 0046). A record a manifest holds gets\n // the manifest's own header, since that is the file that changes.\n const page: Row[] = [];\n const held = new Map<string, Row[]>();\n for (const f of pending) {\n if (f.ranges === undefined) {\n page.push(fieldRow(f, c));\n continue;\n }\n const rows = f.ranges.filter((r) => r.status !== \"current\").map((r) => rangeRow(f, r, c));\n if (f.manifest === undefined) page.push(...rows);\n else held.set(f.manifest, [...(held.get(f.manifest) ?? []), ...rows]);\n }\n const all = [...page, ...[...held.values()].flat()];\n const nameWidth = Math.max(...all.map((r) => r.name.length));\n const changeWidth = Math.max(...all.map((r) => r.plain.length));\n const print = (row: Row): void => {\n const pad = \" \".repeat(changeWidth - row.plain.length);\n lines.push(` ${c.cyan(row.name.padEnd(nameWidth))} ${row.change}${pad} ${row.trail}`);\n };\n if (page.length > 0 || held.size === 0) lines.push(result.file);\n page.forEach(print);\n for (const [manifest, rows] of held) {\n lines.push(`${manifest} ${c.dim(`(for ${result.file})`)}`);\n rows.forEach(print);\n }\n const note = unknownNote(result, c.dim);\n if (note !== \"\") lines.push(` ${note}`);\n }\n\n const s = run.summary;\n const parts = [plural(s.files, \"file\")];\n // `provenance` counts ranges beside the fields it would otherwise hide in.\n const provenance = run.results.flatMap((r) => r.fields.filter((f) => f.ranges !== undefined));\n const provenanceFields = provenance.filter((f) => (run.dryRun ? f.status === \"stale\" || f.status === \"unset\" : f.written)).length;\n if (run.dryRun) {\n const ranges = provenance.reduce((n, f) => n + (f.ranges ?? []).filter((r) => r.status !== \"current\").length, 0);\n const fields = s.stale + s.unset - provenanceFields;\n parts.push(`${s.changed} would change`);\n if (fields > 0 || ranges === 0) parts.push(plural(fields, \"field\"));\n if (ranges > 0) parts.push(plural(ranges, \"range\"));\n } else {\n const ranges = s.ranges ?? 0;\n const fields = s.written - provenanceFields;\n parts.push(`${s.changed} changed`);\n if (fields > 0 || ranges === 0) parts.push(`${plural(fields, \"field\")} written`);\n if (ranges > 0) parts.push(`${plural(ranges, \"range\")} written`);\n }\n if (s.errors > 0) parts.push(plural(s.errors, \"error\"));\n let footer = parts.join(\", \");\n if (run.dryRun) footer += \" — dry run, nothing written\";\n\n if (lines.length > 0) lines.push(\"\");\n lines.push(s.errors > 0 ? c.yellow(footer) : footer);\n return lines.join(\"\\n\");\n}\n\n/** One printed change: the field, the change colored and plain (for the column), and the evidence. */\ninterface Row {\n name: string;\n change: string;\n plain: string;\n trail: string;\n}\n\nfunction fieldRow(f: DerivedField, c: Colors): Row {\n const from = f.status === \"unset\" ? \"(unset)\" : fmt(f.asserted);\n const to = fmt(f.derived);\n return {\n name: f.field,\n change: `${c.dim(from)} → ${c.green(to)}`,\n plain: `${from} → ${to}`,\n trail: `${c.dim(`(${f.source ?? \"a source\"}: ${f.evidence ?? \"no evidence\"})`)}${destinationOf(f)}`,\n };\n}\n\n/**\n * Where a field kept in a manifest was written (proposal 0047):\n * ` → docs-meta.yaml:14`, without the line under a dry run.\n */\nfunction destinationOf(f: DerivedField): string {\n if (f.destination === undefined) return \"\";\n return ` → ${f.destination}${f.destinationLine === undefined ? \"\" : `:${String(f.destinationLine)}`}`;\n}\n\n/**\n * A `provenance` range, in file lines: `(unset) → machine` for lines no\n * record covered, `old → new` for a machine the evidence contradicts,\n * `moved from 12-31` for a pin found elsewhere, and `machine → re-derived`\n * for a pin whose text changed.\n */\nfunction rangeRow(f: DerivedField, r: RangeResult, c: Colors): Row {\n const head = `lines ${r.lines}: `;\n const machine = r[\"generated-by\"];\n let from: string;\n let to: string;\n switch (r.status) {\n case \"moved\":\n from = \"\";\n to = `moved from ${r.from?.lines ?? r.lines}`;\n break;\n case \"stale\":\n from = r.from?.[\"generated-by\"] ?? \"(unset)\";\n to = machine;\n break;\n case \"changed\":\n from = machine;\n to = \"re-derived\";\n break;\n case \"unset\":\n case \"current\":\n from = \"(unset)\";\n to = machine;\n break;\n }\n const arrow = from === \"\" ? \"\" : `${from} → `;\n return {\n name: f.field,\n change: `${head}${from === \"\" ? \"\" : `${c.dim(from)} → `}${c.green(to)}`,\n plain: `${head}${arrow}${to}`,\n trail: c.dim(`(${f.source ?? \"git\"}: ${r.evidence})`),\n };\n}\n\n/** Which of a file's fields no source could answer, so silence is not mistaken for agreement. */\nfunction unknownNote(result: DeriveFileResult, dim: (s: string) => string): string {\n const unknown = result.fields.filter((f) => f.status === \"unknown\").map((f) => f.field);\n if (unknown.length === 0) return \"\";\n return dim(` (${unknown.join(\", \")}: no source could answer)`);\n}\n\n/** Strings bare, everything else as compact JSON. */\nfunction fmt(value: unknown): string {\n if (typeof value === \"string\") return value;\n // `toJsonText`, not `JSON.stringify`, so the `String(value)` fallback stays\n // visibly reachable — see there.\n return toJsonText(value) ?? String(value);\n}\n","/**\n * `relocate` (proposal 0047): move every value to where its schema's\n * `x-manni-location` mark and the config's manifests say it belongs.\n *\n * Out of the page and into a manifest go the values a schema prefers in\n * external metadata and the values a manifest already owns. Out of a manifest\n * and into the page go the values a schema prefers on the page. The\n * collection, manifest file and config entry a value needs are created on the\n * way, and a change to a manifest's `keys:` covers every member page of its\n * collection. The planning and writing live in `core/relocation.ts`, which the\n * writers' and validate's offers share; this is the command around it.\n *\n * Two refusals come before the config is read, because each rules out the\n * whole run: stdin, which is not a document a manifest can name, and\n * `--no-config`, which leaves nowhere to declare a manifest.\n */\nimport { resolveRunConfig, type ConfigNotice } from \"../core/config.js\";\nimport { memberOf, retainMembers } from \"../core/collections.js\";\nimport { assertNonEmpty, gitignoreOptions, resolveTargetSet, STDIN_TOKEN } from \"../core/load-files.js\";\nimport { collectSchemaPins } from \"../core/resolve-schema.js\";\nimport { schemaLoadOptions } from \"../core/schema-registry.js\";\nimport { Validator } from \"../core/validator.js\";\nimport { extractorByName, listFormats } from \"../extractors/index.js\";\nimport { DocmetaError } from \"../types.js\";\nimport {\n applyRelocation,\n planRelocation,\n relocationContext,\n type RelocateResult,\n} from \"../core/relocation.js\";\n\nexport type {\n RelocateConfigResult,\n RelocateFileResult,\n RelocateManifestResult,\n RelocateMove,\n RelocateMoveReason,\n RelocateResult,\n RelocateStay,\n RelocateStayReason,\n RelocateSummary,\n} from \"../core/relocation.js\";\nexport { relocateFailed } from \"../core/relocation.js\";\n\nexport interface RelocateOptions {\n /** Files, directories and globs. Empty falls back to the configured collections. `-` is refused. */\n inputs: string[];\n /** `--fields`: only these keys. Each must carry a mark, or be manifest-owned, for some file. */\n fields?: string[];\n /** `--collection <name>`, repeatable: run over these configured collections. */\n collections?: string[];\n /** `-s/--schema`, repeatable: the schema set every page is judged by. */\n cliSchemas?: string[];\n /** `--dry-run`: report what would move and be created; write nothing. */\n dryRun?: boolean;\n /** `--as`: force an extractor. */\n as?: string;\n exts?: string[];\n exclude?: string[];\n configPath?: string;\n /** `--no-config`: refused, since relocate writes the config. */\n noConfig?: boolean;\n cwd?: string;\n allowEmpty?: boolean;\n /** `--no-gitignore` (false). Absent leaves config `respectGitignore:` in charge. */\n respectGitignore?: boolean;\n onNotice?: (message: string) => void;\n onConfigLoaded?: (info: ConfigNotice) => void;\n /** Where `MANNI_ENCRYPTION_KEY` is read, for an encrypted join field. Defaults to `process.env`. */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runRelocate(opts: RelocateOptions): Promise<RelocateResult> {\n const cwd = opts.cwd ?? process.cwd();\n if (opts.inputs.includes(STDIN_TOKEN)) {\n throw new DocmetaError(\n \"relocate moves values between documents and a collection's manifest, and stdin is not a document on disk.\",\n );\n }\n if (opts.noConfig === true) {\n throw new DocmetaError(\n \"relocate writes collections: and externalMetadata: to the config file, and --no-config rules one out.\",\n );\n }\n const run = await resolveRunConfig({\n cwd,\n ...(opts.configPath !== undefined ? { configPath: opts.configPath } : {}),\n inputs: opts.inputs,\n ...(opts.collections !== undefined ? { collections: opts.collections } : {}),\n ...(opts.onConfigLoaded !== undefined ? { onConfigLoaded: opts.onConfigLoaded } : {}),\n });\n const { config, inputs, base, configDir, collections, fromCollections } = run;\n if (inputs.length === 0) {\n throw new DocmetaError(\n \"No files to relocate. Pass paths/globs, or declare a collection under `collections:` in manni.config.yaml.\",\n );\n }\n const forced = opts.as !== undefined ? extractorByName(opts.as) : undefined;\n if (opts.as !== undefined && forced === undefined) {\n throw new DocmetaError(\n `Unknown format \"${opts.as}\". Known formats: ${listFormats()\n .map((f) => f.name)\n .join(\", \")}.`,\n );\n }\n\n const allowEmpty = opts.allowEmpty ?? config?.allowEmpty;\n const exts = opts.exts ?? forced?.extensions;\n const exclude = opts.exclude ?? [];\n const membersFor = (label: string): string[] => memberOf(collections, configDir ?? cwd, base, label);\n const { files: walked, gitignoreSkipped } = await resolveTargetSet({\n inputs,\n ...(exts !== undefined ? { exts } : {}),\n exclude,\n cwd: base,\n ...(allowEmpty !== undefined ? { allowEmpty } : {}),\n ...gitignoreOptions({\n ...(opts.respectGitignore !== undefined ? { flag: opts.respectGitignore } : {}),\n ...(config?.respectGitignore !== undefined ? { configured: config.respectGitignore } : {}),\n ...(opts.onNotice !== undefined ? { onNotice: opts.onNotice } : {}),\n }),\n });\n const files = fromCollections ? retainMembers(walked, membersFor) : walked;\n assertNonEmpty({\n files,\n inputs,\n usingStdin: false,\n ...(allowEmpty !== undefined ? { allowEmpty } : {}),\n exclude,\n ...(exts !== undefined ? { exts } : {}),\n gitignoreSkipped,\n action: \"relocated\",\n });\n\n const validator = new Validator(\n schemaLoadOptions({\n root: configDir ?? cwd,\n fileBase: cwd,\n ttlHours: config?.schemaCache?.ttlHours,\n offline: config?.offline,\n pins: collectSchemaPins(config),\n registered: config?.registered,\n }),\n );\n const ctx = relocationContext(run, {\n cwd,\n // A config-fallback run named no targets: its pages are already members.\n targets: fromCollections ? [] : opts.inputs,\n validator,\n ...(opts.cliSchemas !== undefined && opts.cliSchemas.length > 0 ? { cliSchemas: opts.cliSchemas } : {}),\n ...(opts.as !== undefined ? { as: opts.as } : {}),\n ...(opts.respectGitignore !== undefined ? { respectGitignore: opts.respectGitignore } : {}),\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n ...(opts.onNotice !== undefined ? { onNotice: opts.onNotice } : {}),\n });\n const plan = await planRelocation(ctx, {\n files,\n ...(opts.fields !== undefined ? { fields: opts.fields } : {}),\n });\n if (opts.dryRun === true) return plan.result;\n return applyRelocation(ctx, plan);\n}\n","/**\n * Reporter for `get`.\n *\n * `render()` in ./index.ts is keyed to ValidationResult/RunSummary, so `get`\n * gets its own renderer, exactly as `fill` does. It lived inline in\n * `src/cli.ts` until `--quiet` arrived and made the question \"who decides what\n * is printed?\" answerable in two places at once.\n *\n * `--quiet` is a **reporter** concern, not a core one. `GetOptions` /\n * `GetFileResult` are public API, and a programmatic caller handed a silently\n * filtered array cannot tell a filtered run from an empty one — so `runGet`\n * returns every file it read, and the filtering happens here, where it only\n * affects text a person is reading.\n */\nimport type { GetFileResult } from \"../commands/get.js\";\nimport { compareDerived, PROVENANCE_FIELD, type DerivedValue } from \"../core/derive/types.js\";\nimport { provenanceEntries, renderProvenanceValue } from \"../core/derive/provenance.js\";\nimport { palette } from \"../../shared/color.js\";\n\nexport interface GetReportOptions {\n color?: boolean;\n /** In pretty output, omit files where every requested field is unset. */\n quiet?: boolean;\n}\n\n/** `(unset)` for a missing field; JSON for anything that is not a string. */\nexport function stringifyValue(value: unknown): string {\n if (value === undefined) return \"(unset)\";\n if (typeof value === \"string\") return value;\n return JSON.stringify(value);\n}\n\n/**\n * A value as the line prints it. `provenance` (0046) prints its entries in\n * file lines, `lines 12-31 claude-fable-5; lines 44 claude-sonnet-5`, since\n * the record stores body lines and a person reads the file; a value that is\n * not a well-formed record prints as any other.\n */\nfunction valueOf(r: GetFileResult, field: string, value: unknown): string {\n if (field !== PROVENANCE_FIELD || r.provenance === undefined) return stringifyValue(value);\n if (value === undefined || value === null) return \"(unset)\";\n const entries = provenanceEntries(value);\n if (!Array.isArray(value) || entries.length !== value.length || entries.length === 0) {\n return stringifyValue(value);\n }\n return renderProvenanceValue(entries, r.provenance.bodyLine);\n}\n\n/**\n * The evidence as the source wrote it, so the reader can check the claim\n * without re-running — minus a trailing `(<value>)` that repeats the derived\n * value, since the value is already on the line. The git source spells a date\n * fact `body changed in 424f71a (2026-09-07)` so that it stands alone in\n * `query`'s `_sources` column, where nothing else names the date.\n */\nfunction evidenceOf(d: DerivedValue): string {\n const repeated = ` (${stringifyValue(d.value)})`;\n return d.evidence.endsWith(repeated)\n ? d.evidence.slice(0, -repeated.length)\n : d.evidence;\n}\n\n/**\n * The annotation after a resolved value (proposal 0043): which side the value\n * came from, and — when the two sides disagree — what the other one says.\n * Five cases, and only five:\n *\n * 1. asserted, with no derived value or no derivable field → `(asserted)`\n * 2. nothing asserted, a source answered → `(derived, <source>: <evidence>)`\n * 3. both, agreeing as `validate` judges it → `(asserted)`\n * 4. both, disagreeing → `(asserted; <source> says <value>, <evidence>)`\n * 5. neither → nothing at all; the value already prints `(unset)`\n *\n * Case 4 is the drift `validate` files as `derived:stale`. The asserted value\n * is what prints, because that is what the page publishes, and the evidence\n * is named beside it rather than in place of it.\n */\nfunction annotation(r: GetFileResult, field: string): string {\n const origin = r.origin?.[field];\n if (origin === undefined) return \"\";\n const d = r.derived?.[field] ?? null;\n if (origin === \"derived\") {\n // Unreachable with null evidence — `origin` only says `derived` when a\n // source answered — but the record is public API, so a caller that built\n // one by hand gets a plain line rather than a crash.\n return d == null ? \"\" : ` (derived, ${d.source}: ${evidenceOf(d)})`;\n }\n // `provenance` (0046) is judged by the provenance comparator, never as a\n // value: a record git has nothing against is current.\n if (field === PROVENANCE_FIELD && r.provenance !== undefined) {\n if (r.provenance.current !== false) return \" (asserted)\";\n return ` (asserted; ${d?.source ?? \"git\"} says ${valueOf(r, field, d?.value)})`;\n }\n if (d == null) return \" (asserted)\";\n // Judged as `validate` judges it, with lists as multisets, so the two can\n // never disagree about whether a value is drift.\n if (compareDerived(field, r.resolved?.[field], d).status === \"current\") {\n return \" (asserted)\";\n }\n return ` (asserted; ${d.source} says ${stringifyValue(d.value)}, ${evidenceOf(d)})`;\n}\n\n/**\n * One `<file>: <field>=<value>` line per requested field per file. The value\n * is the **resolved** one where the run derived (proposal 0043), followed by\n * the annotation saying which side answered; under `--no-derived` it is what\n * the document stores, with no annotation at all.\n *\n * `quiet` hides a file only when **every** requested field is unset, judged\n * after resolving — so a page whose only `owner` comes from CODEOWNERS is\n * shown, where before the flag hid it. A file where one field resolved and\n * another did not is still printed, `(unset)` included: the flag hides files,\n * never values, so `--quiet` can never be the reason a value the user asked\n * for went missing.\n */\nexport function renderGet(\n results: GetFileResult[],\n fields: string[],\n opts: GetReportOptions = {},\n): string {\n const c = palette(opts.color ?? false);\n const lines: string[] = [];\n for (const r of results) {\n // Checked before `quiet`, deliberately. An unparseable file resolves no\n // values, so the quiet rule below would hide the one file the reader most\n // needs to see — and `--quiet` must never be the reason a missing value\n // goes unexplained, which is the same rule that keeps it hiding files\n // rather than values.\n if (r.error !== undefined) {\n lines.push(`${c.dim(`${r.file}:`)} ${c.red(`(parse) ${r.error}`)}`);\n continue;\n }\n // What the line reports: the resolved value where the run derived, and\n // what the document stores where it did not. `--quiet` reads the same\n // record, so it hides a file only when nothing at all answered for it.\n const effective = r.resolved ?? r.values;\n if (opts.quiet && fields.every((f) => effective[f] === undefined)) continue;\n for (const f of fields) {\n const note = annotation(r, f);\n const suffix = note === \"\" ? \"\" : c.dim(note);\n lines.push(\n `${c.dim(`${r.file}:`)} ${f}=${valueOf(r, f, effective[f])}${suffix}`,\n );\n }\n }\n return lines.join(\"\\n\");\n}\n","/**\n * Reporter for `query`.\n *\n * Same split as `get`: `runQuery` returns every row, and presentation —\n * alignment, the row count, the `--check` verdict — happens here, where it\n * only affects text a person is reading. `json` output never passes through\n * this module; the CLI prints the bare row array, mirroring `get`'s bare\n * array, and the exit code (not the envelope) carries the `--check` verdict.\n */\nimport type { QueryChange, QueryRun } from \"../commands/query.js\";\nimport { palette, type Colors } from \"../../shared/color.js\";\nimport { stringifyValue } from \"./get.js\";\n\nexport interface QueryReportOptions {\n color?: boolean;\n /** `--check`: append a ✓/✗ verdict line instead of the plain count. */\n check?: boolean;\n /** `--dry-run` (or `--check`): the changes were previewed, not applied. */\n dryRun?: boolean;\n}\n\n/**\n * SQL NULL prints as `(null)`; everything else as `get` prints values —\n * except a bigint, which a SQL expression can hand back and which\n * `stringifyValue`'s JSON.stringify would throw on.\n */\nfunction cell(value: unknown): string {\n if (value === null) return \"(null)\";\n return typeof value === \"bigint\" ? String(value) : stringifyValue(value);\n}\n\n/**\n * An aligned table (header + rows) and a trailing count line. The last column\n * is never padded, so no line carries trailing spaces. A metadata edit\n * renders as its per-file diff instead of a row table (0022).\n */\nexport function renderQuery(\n run: QueryRun,\n opts: QueryReportOptions = {},\n): string {\n const c = palette(opts.color ?? false);\n if (run.changes) return renderChanges(run.changes, c, opts);\n const lines: string[] = [];\n if (run.rows.length > 0) {\n const widths = run.columns.map((col) =>\n Math.max(col.length, ...run.rows.map((r) => cell(r[col]).length)),\n );\n const pad = (text: string, i: number): string =>\n i === run.columns.length - 1 ? text : text.padEnd(widths[i] ?? 0);\n lines.push(run.columns.map((col, i) => c.bold(pad(col, i))).join(\" \"));\n for (const row of run.rows) {\n lines.push(run.columns.map((col, i) => pad(cell(row[col]), i)).join(\" \"));\n }\n }\n const n = run.rows.length;\n const count = `${n} row${n === 1 ? \"\" : \"s\"}`;\n lines.push(\n opts.check\n ? n > 0\n ? c.red(`✗ ${count} — check failed`)\n : c.green(`✓ ${count}`)\n : c.dim(count),\n );\n return lines.join(\"\\n\");\n}\n\n/**\n * CSV over result rows (proposal 0029). The dialect, chosen once:\n *\n * - header row always — a zero-row result is the header alone, which a script\n * can tell apart from an error that printed nothing;\n * - LF line endings — a deliberate divergence from RFC 4180's CRLF, named in\n * the reference; quoting itself is RFC 4180 (a field containing a comma,\n * quote, or newline is quoted, and quotes double);\n * - SQL `NULL` → empty field;\n * - arrays and objects stay the JSON text the projection already holds.\n *\n * Rows only, by contract: changes are heterogeneous per-file diffs, not a\n * table, and the CLI refuses them before this is called.\n */\n/** A CSV field needing quoting: it contains a comma, quote, or newline. */\nconst CSV_NEEDS_QUOTING = /[\",\\n\\r]/;\n\nexport function renderQueryCsv(\n run: Pick<QueryRun, \"columns\" | \"rows\">,\n): string {\n const field = (value: unknown): string => {\n if (value === null || value === undefined) return \"\";\n const text =\n typeof value === \"string\"\n ? value\n : typeof value === \"number\" || typeof value === \"bigint\"\n ? String(value)\n : stringifyValue(value); // a BLOB or other oddity, `get`'s way\n return CSV_NEEDS_QUOTING.test(text)\n ? `\"${text.replaceAll('\"', '\"\"')}\"`\n : text;\n };\n return [\n run.columns.map(field).join(\",\"),\n ...run.rows.map((row) => run.columns.map((c) => field(row[c])).join(\",\")),\n ].join(\"\\n\");\n}\n\n/**\n * `<file>: <key>: <from> -> <to>` per changed cell, then the verdict: what\n * was written, what a preview would write, or the ✓/✗ of a `--check` drift\n * gate. `from` is `(unset)` when the file had no value for the key.\n */\nfunction renderChanges(\n changes: QueryChange[],\n c: Colors,\n opts: QueryReportOptions,\n): string {\n const lines = changes.map((ch) => {\n const line = changeLine(ch, c);\n // 0047: a change that lands in a manifest names it.\n return ch.manifest === undefined ? line : `${line} ${c.dim(`[${ch.manifest}]`)}`;\n });\n return finish(lines, changes, c, opts);\n}\n\n/** One change as its report line, before any manifest suffix. */\nfunction changeLine(ch: QueryChange, c: Colors): string {\n if (\"config\" in ch) {\n return `${c.dim(`config ${ch.file}:`)} ${ch.key}: ${cellFrom(ch.from)} -> ${cell(ch.to)}`;\n }\n if (\"schema\" in ch) {\n const fork = ch.forkedFrom ? ` ${c.dim(`(forked from ${ch.forkedFrom})`)}` : \"\";\n if (ch.op === \"rename\") {\n return `${c.dim(`schema ${ch.file}:`)} ${ch.key} -> ${ch.renamedTo ?? ch.key}${fork}`;\n }\n if (ch.op === \"drop\") {\n return `${c.dim(`schema ${ch.file}:`)} - ${ch.key}${fork}`;\n }\n // The whole resulting property, format and enum included, so a\n // near-miss (`DUE-DATE` mapping to nothing) is visible as an\n // unconstrained `+ key` before anything is written (0028).\n const detail = [\n ch.type,\n ch.format !== undefined ? `format ${ch.format}` : undefined,\n // JSON spellings, so the numeric enum [1] and the string enum [\"1\"]\n // read as the distinct properties they are.\n ch.enum !== undefined\n ? `enum [${ch.enum.map((v) => JSON.stringify(v)).join(\", \")}]`\n : undefined,\n ch.required ? \"required\" : undefined,\n ]\n .filter(Boolean)\n .join(\", \");\n return `${c.dim(`schema ${ch.file}:`)} + ${ch.key}${detail ? ` (${detail})` : \"\"}${fork}`;\n }\n if (\"cleared\" in ch) {\n return `${c.dim(`${ch.file}:`)} (frontmatter removed: ${Object.keys(ch.from).join(\", \")})`;\n }\n if (\"created\" in ch) {\n const kv = Object.entries(ch.to)\n .map(([k, v]) => `${k}=${cell(v)}`)\n .join(\", \");\n return `${c.dim(`${ch.file}:`)} (created: ${kv})`;\n }\n if (\"renamed\" in ch) {\n return `${c.dim(`${ch.file} ->`)} ${ch.renamed} ${c.dim(\"(moved)\")}`;\n }\n if (\"renamedFrom\" in ch) {\n return `${c.dim(`${ch.file}:`)} ${ch.renamedFrom} -> ${ch.key} ${c.dim(\"(key renamed)\")}`;\n }\n if (\"deleted\" in ch) {\n return `${c.dim(`${ch.file}:`)} ${ch.key}: ${cellFrom(ch.from)} -> (deleted)`;\n }\n return `${c.dim(`${ch.file}:`)} ${ch.key}: ${cellFrom(ch.from)} -> ${cell(ch.to)}`;\n}\n\n/** The count and verdict line after the changes. */\nfunction finish(\n lines: string[],\n changes: QueryChange[],\n c: Colors,\n opts: QueryReportOptions,\n): string {\n const n = changes.length;\n // Deliberately counts every file the run touches — schema and config\n // included: they are writes the user is approving, and a pure DDL edit\n // reporting \"across 0 files\" would claim less than it does.\n const files = new Set(changes.map((ch) => ch.file)).size;\n const count = `${n} change${n === 1 ? \"\" : \"s\"} across ${files} file${files === 1 ? \"\" : \"s\"}`;\n // `--check` outranks the dry-run hint: it implies the dry run, and its\n // verdict is the line the exit code answers to.\n if (opts.check) {\n lines.push(\n n > 0 ? c.red(`✗ ${count} — check failed`) : c.green(\"✓ 0 changes\"),\n );\n } else if (opts.dryRun) {\n lines.push(\n n > 0\n ? `${count} — ${c.dim(\"dry run; run again without --dry-run to apply\")}`\n : c.dim(\"0 changes\"),\n );\n } else {\n lines.push(n > 0 ? c.green(`✓ ${count} — written`) : c.dim(\"0 changes\"));\n }\n return lines.join(\"\\n\");\n}\n\n/** A preview's `from`: `(unset)` only for a key the file never had. */\nfunction cellFrom(value: unknown): string {\n return value === undefined ? \"(unset)\" : cell(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AE,MAAM,kBAAa;AAAA,IACpE;AAAA,EACF,WAAW,KAAK,QAAQ;AACtB,UAAM;AAAA,MACJ,IAAI,IACA,GAAG,KAAK,WAAM,EAAE,IAAI,+CAA+C,CAAC,KACpE,EAAE,IAAI,WAAW;AAAA,IACvB;AAAA,EACF,OAAO;AACL,UAAM,KAAK,IAAI,IAAI,EAAE,MAAM,UAAK,KAAK,iBAAY,IAAI,EAAE,IAAI,WAAW,CAAC;AAAA,EACzE;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;AAGA,SAAS,SAAS,OAAwB;AACxC,SAAO,UAAU,SAAY,YAAY,KAAK,KAAK;AACrD;","names":["finish","derivableFields","provenanceManifests","readFile","extname","resolve","registered","resolve","readFile","extname","existsSync","mkdir","readFile","dirname","isAbsolute","resolve","extname","sep","parseDocument","resolve","readFile","extname","mkdir","dirname","offered","open","i","cell","isAbsolute","registered","existsSync","parseDocument","keyOf","sep","require","f","readFile","resolve","extname","join","only","typed","single","alternatives","readFile","extname","resolve","valueAt","valueAt","resolve","extname","readFile","readFile","readFile","assertKnownProvider","assertModelHasProvider","resolveIdentity","join","resolve","flags","readFile","extname","finish","readFile","extname","relative","resolve","sep","relative","resolve","sep","loaded","errors","extname","readFile","union","places","derived","marks","errorResult","reported","summarize"]}