@hawkeyexl/manni 4.9.0 → 4.11.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 (196) hide show
  1. package/README.md +1 -1
  2. package/dist/{batch-W5GXL2P4.js → batch-UAULUMGH.js} +18 -14
  3. package/dist/{build-Q56FEXR6.js → build-QSPNK5AL.js} +14 -11
  4. package/dist/calibrate-KXN4URPM.js +40 -0
  5. package/dist/{capture-GMYH4ATL.js → capture-JHTSUPUC.js} +16 -13
  6. package/dist/{check-OAJWC3WD.js → check-MDGXEUWL.js} +5 -5
  7. package/dist/{check-KUBELO5G.js → check-VELUQAUW.js} +17 -14
  8. package/dist/{check-KUBELO5G.js.map → check-VELUQAUW.js.map} +1 -1
  9. package/dist/check-WOQRKNZK.js +29 -0
  10. package/dist/{check-ZE5HIDOW.js → check-YEOYBFST.js} +14 -11
  11. package/dist/{chunk-FGUXMZXO.js → chunk-2DRHT73U.js} +7 -7
  12. package/dist/{chunk-XHFHXOQQ.js → chunk-2IAZEB45.js} +8 -8
  13. package/dist/{chunk-35WTFPQS.js → chunk-2IR4T5PO.js} +2 -2
  14. package/dist/{chunk-KX5IYIOO.js → chunk-2MJ62AYQ.js} +2 -2
  15. package/dist/chunk-2MJ62AYQ.js.map +1 -0
  16. package/dist/{chunk-OWSNXPPX.js → chunk-4CK6ZSOK.js} +6 -6
  17. package/dist/{chunk-YUZ2ECZY.js → chunk-4D5IZSXM.js} +3 -3
  18. package/dist/{chunk-RFSGKF4O.js → chunk-4VBSTXN6.js} +4 -4
  19. package/dist/{chunk-3XMG4CZY.js → chunk-54F74XR3.js} +15 -13
  20. package/dist/{chunk-3XMG4CZY.js.map → chunk-54F74XR3.js.map} +1 -1
  21. package/dist/{chunk-IN6DWNVE.js → chunk-6HWBRZIN.js} +47 -191
  22. package/dist/chunk-6HWBRZIN.js.map +1 -0
  23. package/dist/{chunk-GEMXGXPR.js → chunk-ADMEPUBT.js} +3 -3
  24. package/dist/{chunk-23UAGEKP.js → chunk-B7XYNRJQ.js} +2 -2
  25. package/dist/{chunk-QKE3XS2L.js → chunk-BBT6AVUG.js} +2 -2
  26. package/dist/{chunk-VKWZCEWB.js → chunk-BKVHX6FU.js} +4 -4
  27. package/dist/{chunk-X6WLCNKC.js → chunk-D4N2V43Z.js} +4 -4
  28. package/dist/{chunk-XXDXIIQ4.js → chunk-EFW7CAG4.js} +2 -2
  29. package/dist/{chunk-UDUHRXJ4.js → chunk-EIFCP6CZ.js} +2 -2
  30. package/dist/{chunk-KPXOJMQ6.js → chunk-FBMZJEB3.js} +2 -2
  31. package/dist/{chunk-HRXDM6H6.js → chunk-FQXWVS6J.js} +8 -8
  32. package/dist/{chunk-76I6I5N2.js → chunk-FUCPZVRY.js} +2 -2
  33. package/dist/{chunk-DTGIUMZV.js → chunk-GDVZ5VII.js} +4 -4
  34. package/dist/{chunk-QCCAHV6A.js → chunk-GV56WGL2.js} +321 -3308
  35. package/dist/chunk-GV56WGL2.js.map +1 -0
  36. package/dist/{chunk-TKTRIZT4.js → chunk-HA6MQMOY.js} +6 -6
  37. package/dist/{chunk-ECVQNGTH.js → chunk-HQR2ZBHW.js} +3 -3
  38. package/dist/{chunk-MHAYLDBK.js → chunk-IGSHYP74.js} +4 -4
  39. package/dist/{chunk-YEUQ7OKT.js → chunk-J6IDQGJL.js} +4 -4
  40. package/dist/{chunk-5LBEQ4ZU.js → chunk-JPQDNYXH.js} +2 -2
  41. package/dist/{chunk-6KKZXB2O.js → chunk-JROBZ7JA.js} +2 -2
  42. package/dist/{chunk-TMI2YF6D.js → chunk-KGEQJ5CC.js} +15 -26
  43. package/dist/{chunk-TMI2YF6D.js.map → chunk-KGEQJ5CC.js.map} +1 -1
  44. package/dist/{chunk-2EHDJ47Y.js → chunk-LBSCW232.js} +4 -4
  45. package/dist/{chunk-M6GH3FGJ.js → chunk-LKP7QDFN.js} +4 -4
  46. package/dist/{chunk-5EB6RIXJ.js → chunk-LPIF5LIE.js} +2 -2
  47. package/dist/chunk-M42DZCOU.js +164 -0
  48. package/dist/chunk-M42DZCOU.js.map +1 -0
  49. package/dist/{chunk-ND2S5BXB.js → chunk-MSRU4D4P.js} +2 -2
  50. package/dist/{chunk-BSTXARMY.js → chunk-NSBXVPZL.js} +11 -11
  51. package/dist/{chunk-Q45PZX2D.js → chunk-ODRPL3WB.js} +2 -2
  52. package/dist/{chunk-FSBIPCWE.js → chunk-OPXWPJDA.js} +10 -10
  53. package/dist/chunk-PCQ7ELJH.js +3081 -0
  54. package/dist/chunk-PCQ7ELJH.js.map +1 -0
  55. package/dist/{chunk-QAKJNPY3.js → chunk-PCS4VJBV.js} +6 -6
  56. package/dist/{chunk-GRILZZGS.js → chunk-PWBH7DCQ.js} +3 -3
  57. package/dist/{chunk-XKBEHKWO.js → chunk-QLWC7MKD.js} +34 -32
  58. package/dist/chunk-QLWC7MKD.js.map +1 -0
  59. package/dist/{chunk-XTAHZTES.js → chunk-R4WXQIOZ.js} +6 -6
  60. package/dist/{chunk-3CDZWY6M.js → chunk-RLT5SEML.js} +5 -5
  61. package/dist/{chunk-XG6PVB5S.js → chunk-SSQZB5SQ.js} +1 -11
  62. package/dist/chunk-SSQZB5SQ.js.map +1 -0
  63. package/dist/chunk-T7JAOYE5.js +393 -0
  64. package/dist/chunk-T7JAOYE5.js.map +1 -0
  65. package/dist/chunk-TU2WUBVZ.js +2 -0
  66. package/dist/{chunk-Q2H7J3FF.js → chunk-U7CTFN2J.js} +12 -10
  67. package/dist/{chunk-Q2H7J3FF.js.map → chunk-U7CTFN2J.js.map} +1 -1
  68. package/dist/{chunk-3XGGF5JW.js → chunk-VSEBFHAY.js} +10 -7
  69. package/dist/{chunk-3XGGF5JW.js.map → chunk-VSEBFHAY.js.map} +1 -1
  70. package/dist/{chunk-OVOYKWCM.js → chunk-WDWXAYVH.js} +4 -4
  71. package/dist/{chunk-5WME4CB6.js → chunk-Y6DOMTQD.js} +10 -8
  72. package/dist/{chunk-5WME4CB6.js.map → chunk-Y6DOMTQD.js.map} +1 -1
  73. package/dist/chunk-ZMECS2IJ.js +27 -0
  74. package/dist/chunk-ZMECS2IJ.js.map +1 -0
  75. package/dist/chunk-ZPLVANY2.js +15 -0
  76. package/dist/chunk-ZPLVANY2.js.map +1 -0
  77. package/dist/{cli-MEPJTS2V.js → cli-3BTCK4AB.js} +18 -15
  78. package/dist/{cli-MEPJTS2V.js.map → cli-3BTCK4AB.js.map} +1 -1
  79. package/dist/{cli-EMQXRN6E.js → cli-4MF37HAQ.js} +16 -12
  80. package/dist/{cli-EMQXRN6E.js.map → cli-4MF37HAQ.js.map} +1 -1
  81. package/dist/{cli-YDMMIL2U.js → cli-6KZTHWGP.js} +17 -14
  82. package/dist/{cli-YDMMIL2U.js.map → cli-6KZTHWGP.js.map} +1 -1
  83. package/dist/{cli-ZJRHU7MO.js → cli-DRMZBZLB.js} +39 -34
  84. package/dist/cli-DRMZBZLB.js.map +1 -0
  85. package/dist/{cli-J35OPSTP.js → cli-I62SRH3R.js} +10 -8
  86. package/dist/cli-JJMOVIKS.js +83 -0
  87. package/dist/cli-JJMOVIKS.js.map +1 -0
  88. package/dist/{cli-TPONWND4.js → cli-O4ABTN4Z.js} +25 -21
  89. package/dist/{cli-TPONWND4.js.map → cli-O4ABTN4Z.js.map} +1 -1
  90. package/dist/{cli-URNPOMOH.js → cli-ONTC5PKT.js} +3 -3
  91. package/dist/{cli-BJ7JXJ2U.js → cli-RORDPAPE.js} +17 -14
  92. package/dist/{cli-BJ7JXJ2U.js.map → cli-RORDPAPE.js.map} +1 -1
  93. package/dist/{cli-B7SFJDZA.js → cli-VID7PJS3.js} +17 -13
  94. package/dist/{cli-B7SFJDZA.js.map → cli-VID7PJS3.js.map} +1 -1
  95. package/dist/cli-VUKMWSSF.js +839 -0
  96. package/dist/cli-VUKMWSSF.js.map +1 -0
  97. package/dist/cli.js +24 -11
  98. package/dist/cli.js.map +1 -1
  99. package/dist/{config-YWSNBFEE.js → config-XDA42RJL.js} +3 -3
  100. package/dist/docmeta.js +9 -7
  101. package/dist/docmeta.js.map +1 -1
  102. package/dist/github-RY3FRA6P.js +29 -0
  103. package/dist/github-YKQSH7FS.js +34 -0
  104. package/dist/index.d.ts +1023 -915
  105. package/dist/index.js +107 -81
  106. package/dist/index.js.map +1 -1
  107. package/dist/{json-JIUPGOUQ.js → json-BXY44ED7.js} +13 -10
  108. package/dist/lint-YJ2L22BW.js +33 -0
  109. package/dist/list-NSG24VVX.js +31 -0
  110. package/dist/list-V6EGCSHX.js +34 -0
  111. package/dist/{page-WQ3GQF76.js → page-EV7OUBAU.js} +12 -9
  112. package/dist/{prepare-ZUTYXTUZ.js → prepare-JHJDJB6I.js} +17 -14
  113. package/dist/{prepare-ZUTYXTUZ.js.map → prepare-JHJDJB6I.js.map} +1 -1
  114. package/dist/{pretty-Q3C433DW.js → pretty-Q5Y2PA64.js} +14 -11
  115. package/dist/{pretty-CBV5XSMZ.js → pretty-SCRK66M5.js} +13 -10
  116. package/dist/{reporters-DH5HPFXJ.js → reporters-A5ADKDYR.js} +12 -9
  117. package/dist/{reporters-TTYGOUAF.js → reporters-RBYTASMI.js} +5 -5
  118. package/dist/run-BUE2DDXN.js +36 -0
  119. package/dist/{term-DL3YFL43.js → term-CQAGNG3Q.js} +17 -14
  120. package/dist/{term-DL3YFL43.js.map → term-CQAGNG3Q.js.map} +1 -1
  121. package/dist/{validate-UVDMC5LT.js → validate-ZBW44RHT.js} +6 -5
  122. package/dist/validate-ZBW44RHT.js.map +1 -0
  123. package/package.json +1 -1
  124. package/plugin/manni/.claude-plugin/plugin.json +1 -1
  125. package/dist/calibrate-XFE56P4M.js +0 -36
  126. package/dist/check-HBRX4FOR.js +0 -26
  127. package/dist/chunk-IN6DWNVE.js.map +0 -1
  128. package/dist/chunk-KX5IYIOO.js.map +0 -1
  129. package/dist/chunk-QCCAHV6A.js.map +0 -1
  130. package/dist/chunk-XG6PVB5S.js.map +0 -1
  131. package/dist/chunk-XKBEHKWO.js.map +0 -1
  132. package/dist/cli-ZJRHU7MO.js.map +0 -1
  133. package/dist/github-63CZJGZS.js +0 -31
  134. package/dist/github-IYOVHWHG.js +0 -26
  135. package/dist/lint-TBE35CCW.js +0 -29
  136. package/dist/list-IZ4RIM72.js +0 -30
  137. package/dist/list-TNEJ3J77.js +0 -28
  138. package/dist/run-LZXKVTM7.js +0 -32
  139. /package/dist/{batch-W5GXL2P4.js.map → batch-UAULUMGH.js.map} +0 -0
  140. /package/dist/{build-Q56FEXR6.js.map → build-QSPNK5AL.js.map} +0 -0
  141. /package/dist/{calibrate-XFE56P4M.js.map → calibrate-KXN4URPM.js.map} +0 -0
  142. /package/dist/{capture-GMYH4ATL.js.map → capture-JHTSUPUC.js.map} +0 -0
  143. /package/dist/{check-HBRX4FOR.js.map → check-MDGXEUWL.js.map} +0 -0
  144. /package/dist/{check-OAJWC3WD.js.map → check-WOQRKNZK.js.map} +0 -0
  145. /package/dist/{check-ZE5HIDOW.js.map → check-YEOYBFST.js.map} +0 -0
  146. /package/dist/{chunk-FGUXMZXO.js.map → chunk-2DRHT73U.js.map} +0 -0
  147. /package/dist/{chunk-XHFHXOQQ.js.map → chunk-2IAZEB45.js.map} +0 -0
  148. /package/dist/{chunk-35WTFPQS.js.map → chunk-2IR4T5PO.js.map} +0 -0
  149. /package/dist/{chunk-OWSNXPPX.js.map → chunk-4CK6ZSOK.js.map} +0 -0
  150. /package/dist/{chunk-YUZ2ECZY.js.map → chunk-4D5IZSXM.js.map} +0 -0
  151. /package/dist/{chunk-RFSGKF4O.js.map → chunk-4VBSTXN6.js.map} +0 -0
  152. /package/dist/{chunk-GEMXGXPR.js.map → chunk-ADMEPUBT.js.map} +0 -0
  153. /package/dist/{chunk-23UAGEKP.js.map → chunk-B7XYNRJQ.js.map} +0 -0
  154. /package/dist/{chunk-QKE3XS2L.js.map → chunk-BBT6AVUG.js.map} +0 -0
  155. /package/dist/{chunk-VKWZCEWB.js.map → chunk-BKVHX6FU.js.map} +0 -0
  156. /package/dist/{chunk-X6WLCNKC.js.map → chunk-D4N2V43Z.js.map} +0 -0
  157. /package/dist/{chunk-XXDXIIQ4.js.map → chunk-EFW7CAG4.js.map} +0 -0
  158. /package/dist/{chunk-UDUHRXJ4.js.map → chunk-EIFCP6CZ.js.map} +0 -0
  159. /package/dist/{chunk-KPXOJMQ6.js.map → chunk-FBMZJEB3.js.map} +0 -0
  160. /package/dist/{chunk-HRXDM6H6.js.map → chunk-FQXWVS6J.js.map} +0 -0
  161. /package/dist/{chunk-76I6I5N2.js.map → chunk-FUCPZVRY.js.map} +0 -0
  162. /package/dist/{chunk-DTGIUMZV.js.map → chunk-GDVZ5VII.js.map} +0 -0
  163. /package/dist/{chunk-TKTRIZT4.js.map → chunk-HA6MQMOY.js.map} +0 -0
  164. /package/dist/{chunk-ECVQNGTH.js.map → chunk-HQR2ZBHW.js.map} +0 -0
  165. /package/dist/{chunk-MHAYLDBK.js.map → chunk-IGSHYP74.js.map} +0 -0
  166. /package/dist/{chunk-YEUQ7OKT.js.map → chunk-J6IDQGJL.js.map} +0 -0
  167. /package/dist/{chunk-5LBEQ4ZU.js.map → chunk-JPQDNYXH.js.map} +0 -0
  168. /package/dist/{chunk-6KKZXB2O.js.map → chunk-JROBZ7JA.js.map} +0 -0
  169. /package/dist/{chunk-2EHDJ47Y.js.map → chunk-LBSCW232.js.map} +0 -0
  170. /package/dist/{chunk-M6GH3FGJ.js.map → chunk-LKP7QDFN.js.map} +0 -0
  171. /package/dist/{chunk-5EB6RIXJ.js.map → chunk-LPIF5LIE.js.map} +0 -0
  172. /package/dist/{chunk-ND2S5BXB.js.map → chunk-MSRU4D4P.js.map} +0 -0
  173. /package/dist/{chunk-BSTXARMY.js.map → chunk-NSBXVPZL.js.map} +0 -0
  174. /package/dist/{chunk-Q45PZX2D.js.map → chunk-ODRPL3WB.js.map} +0 -0
  175. /package/dist/{chunk-FSBIPCWE.js.map → chunk-OPXWPJDA.js.map} +0 -0
  176. /package/dist/{chunk-QAKJNPY3.js.map → chunk-PCS4VJBV.js.map} +0 -0
  177. /package/dist/{chunk-GRILZZGS.js.map → chunk-PWBH7DCQ.js.map} +0 -0
  178. /package/dist/{chunk-XTAHZTES.js.map → chunk-R4WXQIOZ.js.map} +0 -0
  179. /package/dist/{chunk-3CDZWY6M.js.map → chunk-RLT5SEML.js.map} +0 -0
  180. /package/dist/{cli-J35OPSTP.js.map → chunk-TU2WUBVZ.js.map} +0 -0
  181. /package/dist/{chunk-OVOYKWCM.js.map → chunk-WDWXAYVH.js.map} +0 -0
  182. /package/dist/{config-YWSNBFEE.js.map → cli-I62SRH3R.js.map} +0 -0
  183. /package/dist/{cli-URNPOMOH.js.map → cli-ONTC5PKT.js.map} +0 -0
  184. /package/dist/{github-63CZJGZS.js.map → config-XDA42RJL.js.map} +0 -0
  185. /package/dist/{github-IYOVHWHG.js.map → github-RY3FRA6P.js.map} +0 -0
  186. /package/dist/{json-JIUPGOUQ.js.map → github-YKQSH7FS.js.map} +0 -0
  187. /package/dist/{lint-TBE35CCW.js.map → json-BXY44ED7.js.map} +0 -0
  188. /package/dist/{list-IZ4RIM72.js.map → lint-YJ2L22BW.js.map} +0 -0
  189. /package/dist/{list-TNEJ3J77.js.map → list-NSG24VVX.js.map} +0 -0
  190. /package/dist/{page-WQ3GQF76.js.map → list-V6EGCSHX.js.map} +0 -0
  191. /package/dist/{pretty-CBV5XSMZ.js.map → page-EV7OUBAU.js.map} +0 -0
  192. /package/dist/{pretty-Q3C433DW.js.map → pretty-Q5Y2PA64.js.map} +0 -0
  193. /package/dist/{reporters-DH5HPFXJ.js.map → pretty-SCRK66M5.js.map} +0 -0
  194. /package/dist/{reporters-TTYGOUAF.js.map → reporters-A5ADKDYR.js.map} +0 -0
  195. /package/dist/{run-LZXKVTM7.js.map → reporters-RBYTASMI.js.map} +0 -0
  196. /package/dist/{validate-UVDMC5LT.js.map → run-BUE2DDXN.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/meta/commands/validate.ts","../src/meta/core/derive/config.ts","../src/meta/core/derive/index.ts","../src/meta/core/derive/cache.ts","../src/meta/core/derive/codeowners.ts","../src/meta/core/derive/spawn.ts","../src/meta/core/derive/command.ts","../src/meta/core/derive/reviews.ts","../src/meta/core/derive/git.ts","../src/shared/concurrency.ts","../src/meta/core/derive/table.ts","../src/meta/core/checks.ts","../src/meta/core/derive/provenance-place.ts"],"sourcesContent":["/**\n * `validate` command core. Resolves targets, extracts metadata, resolves a\n * schema set per file, validates, and returns structured results. Kept free of\n * CLI/IO plumbing so it can be tested directly.\n */\nimport { readFile } from \"node:fs/promises\";\nimport {\n loadExternalMetadata,\n mergeWithMarks,\n orphanEntries,\n orphanError,\n orphanJoins,\n externalMetadataJoin,\n externalMetadataPointer,\n EXTERNAL_DUPLICATE_SCHEMA,\n EXTERNAL_KEYWORD,\n EXTERNAL_OWNED_SCHEMA,\n PATH_JOIN,\n type MergedMetadata,\n} from \"../core/external-metadata.js\";\nimport {\n LOCATION_EXTERNAL_SCHEMA,\n LOCATION_FINDING_KEYWORD,\n LOCATION_PAGE_SCHEMA,\n} from \"../core/location.js\";\nimport { pageMarks } from \"../core/page-marks.js\";\nimport {\n keyHome,\n relocationContext,\n type RelocationContext,\n} from \"../core/relocation.js\";\nimport { resolve, extname } from \"node:path\";\nimport {\n DocmetaError,\n isErrorSeverity,\n type FieldError,\n type RunSummary,\n type ValidationResult,\n} from \"../types.js\";\nimport {\n canonicalSchemaRef,\n DEFAULT_BASELINE_PATH,\n LEGACY_BASELINE_PATH,\n type FingerprintContext,\n resolveBaselineRequest,\n settleBaseline,\n} from \"../core/baseline.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} from \"../core/config.js\";\nimport { memberOf, retainMembers } from \"../core/collections.js\";\nimport {\n collectSchemaPins,\n resolveSchemaSetWithSource,\n FILE_SCHEMA_KEY,\n type ResolvedSchemaSet,\n resolveElements,\n} from \"../core/resolve-schema.js\";\nimport { Validator } from \"../core/validator.js\";\nimport { schemaLoadOptions } from \"../core/schema-registry.js\";\nimport { runChecks, type CheckEntry } from \"../core/checks.js\";\nimport {\n encryptionFindings,\n encryptionView,\n isAtOrUnder,\n lazyKey,\n pointerOf,\n redactedDerived,\n settleFindings,\n unverifiedWarning,\n} from \"../core/encrypted.js\";\nimport {\n assertSourcesAvailable,\n deriveMetadata,\n type DeriveResult,\n} from \"../core/derive/index.js\";\nimport { commandsOf, machinesOf } from \"../core/derive/config.js\";\nimport {\n compareProvenance,\n provenanceEntries,\n provenanceFindings,\n} from \"../core/derive/provenance.js\";\nimport { readerManifests, readerPlace, stampManifests } from \"../core/derive/provenance-place.js\";\nimport {\n fieldsForSql,\n mentionsDerived,\n mentionsResolved,\n} from \"../core/derive/table.js\";\nimport {\n compareDerived,\n derivableFields,\n DERIVE_SOURCES,\n deriveCovers,\n managedFields,\n PROVENANCE_FIELD,\n STAMPED_DATE_FIELDS,\n staleFindings,\n type DerivedRecord,\n type DeriveInput,\n} from \"../core/derive/types.js\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport { STDIN_REQUIRES_AS } from \"../../shared/cli-options.js\";\n\nexport interface ValidateOptions {\n inputs: string[];\n cliSchemas?: string[];\n exts?: string[];\n exclude?: string[];\n /** `--as` format override (extractor name). */\n as?: 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 /**\n * `--baseline [path]`: compare findings against a recorded baseline and fail\n * only on new ones. A string is a path relative to `cwd`; `true` means the\n * default path; `false` is `--no-baseline`, which suppresses a baseline the\n * config supplied. Absent means \"whatever the config says\".\n */\n baseline?: string | boolean;\n /**\n * `--write-baseline [path]`: record this run's findings as the baseline\n * instead of comparing against one. Wins over `baseline`.\n */\n writeBaseline?: string | boolean;\n /** Called once when a config governs the run, so the CLI can report it. */\n onConfigLoaded?: (info: ConfigNotice) => void;\n /**\n * `--offline`: never fetch a remote schema. Absent leaves config `offline:`\n * in charge, which itself defaults to off.\n */\n offline?: boolean;\n /**\n * `--no-cache` (false): ask GitHub or GitLab again rather than reading the\n * review cache. It reaches the comparison and any check reading the\n * `derived` table; absent leaves the cache on.\n */\n cache?: boolean;\n /**\n * `--no-checks` (false): skip the config's named corpus checks for this\n * run. Absent leaves them on — they still only run when the resolved file\n * set is the config-resolved corpus (proposal 0026).\n */\n checks?: boolean;\n /**\n * The environment `MANNI_ENCRYPTION_KEY` is read from (proposal 0045).\n * Defaults to `process.env`; tests pass their own so a developer's key is\n * never read.\n */\n env?: NodeJS.ProcessEnv;\n /**\n * `--no-derive` (false): skip comparing each managed field (`derive.fields`\n * in the config, proposal 0040) with what the evidence says. Absent leaves\n * the comparison on whenever `derive:` is configured — on scoped runs too,\n * since it is per file rather than a corpus rule.\n */\n derive?: boolean;\n /** The clock an uncommitted body change is dated by. Test seam; default `new Date()`. */\n now?: () => Date;\n /**\n * Leave out a file judged by the built-in default set alone: no `$schema`\n * of its own, and no `schemas:` or `overrides:` entry covering it. Such a\n * file gets no result and is not counted. `manni check` sets this, because\n * a default it would apply is not something the project set up.\n */\n skipDefaultOnly?: boolean;\n}\n\nexport interface ValidateRun {\n results: ValidationResult[];\n summary: RunSummary;\n /**\n * Where the run stood: the working directory, the directory canonical paths\n * are measured from, and the directory `results[].file` labels are relative\n * to.\n *\n * Returned rather than kept private because a `ValidationResult.file` is only\n * meaningful *with* it. A reporter that has to name a file the same way from\n * anywhere — SARIF, whose `artifactLocation.uri` GitHub resolves against the\n * repository root — cannot reconstruct this after the fact, and guessing puts\n * it in the same false-green trap the baseline's canonical keys exist to\n * avoid.\n */\n frame: FingerprintContext;\n}\n\n/**\n * A violation docmeta raises itself rather than one Ajv produced.\n *\n * Two different failures land here and they are not the same thing: the\n * document's metadata block could not be parsed (`parse`), or a schema set\n * could not be resolved for it (`schema`). `keyword` is what tells them apart\n * downstream — the `schema` field stays `\"(parse)\"` for both, because it is the\n * documented literal machine consumers already match on.\n */\nfunction parseErrorResult(\n file: string,\n format: string,\n message: string,\n keyword: \"parse\" | \"schema\",\n): ValidationResult {\n const err: FieldError = {\n schema: \"(parse)\",\n instancePath: \"\",\n message,\n keyword,\n };\n return { file, format, ok: false, schemas: [], errors: [err] };\n}\n\n/**\n * What the derived comparison needs from one file's encryption view\n * (proposals 0040 and 0045), kept from the per-file loop for after it.\n */\ninterface ManagedView {\n /** The metadata with every readable encrypted value decrypted. A copy. */\n data: Record<string, unknown>;\n /** The pointers the schema marks, over the metadata as the page holds it. */\n marked: readonly string[];\n /** Marked pointers holding a ciphertext no key could read. */\n hidden: readonly string[];\n /** The file's schema set, to read the mark of a field the page lacks. */\n refs: string[];\n /** Where a value a manifest supplied lives, so a stale finding names its line (0047). */\n locate: (pointer: string) => { file: string; line?: number } | undefined;\n}\n\n/**\n * Run `fn` at most once and hand every caller the same promise, rejection\n * included: a derivation that failed for the checks has failed for the\n * comparison too, and must not be retried against the same evidence.\n */\nfunction once<T>(fn: () => Promise<T>): () => Promise<T> {\n let pending: Promise<T> | undefined;\n return () => {\n pending ??= fn();\n return pending;\n };\n}\n\nexport async function runValidate(\n opts: ValidateOptions,\n): Promise<ValidateRun> {\n const cwd = opts.cwd ?? process.cwd();\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 run = 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 collections,\n declaredCollections,\n fromCollections,\n configFile,\n } = run;\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 validate. Pass paths/globs, or declare a collection under `collections:` in manni.config.yaml.\",\n );\n }\n\n // Pick an explicit extractor for `--as`, validating it up front.\n const forcedExtractor = opts.as ? extractorByName(opts.as) : undefined;\n if (opts.as && !forcedExtractor) {\n throw new DocmetaError(\n `Unknown format \"${opts.as}\". Supported extensions: ${supportedExtensions().join(\", \")}.`,\n );\n }\n\n const exts =\n opts.exts ?? (forcedExtractor ? forcedExtractor.extensions : undefined);\n\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): the tool has no basis to pick\n // which collection's exclusions to honour once there are several.\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: \"validated\",\n });\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\n // External metadata (0037), read once per run: a manifest the config names\n // that cannot be read is the run's problem, not a document's.\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 const validator = new Validator(\n schemaLoadOptions({\n // The config's directory when a config governs the run, so one project\n // keeps one cache no matter which directory the command was run from.\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 // Built from the rebased config, so a pinned local ref is keyed by the\n // same absolute spelling `resolveSchemaSet` will hand to `loadSchema`.\n pins: collectSchemaPins(config),\n registered: config?.registered,\n }),\n );\n // What each page's schemas mark external, for a keyless manifest (0068).\n const marks = pageMarks({\n validator,\n config,\n cwd,\n trustRoot,\n ...(opts.cliSchemas !== undefined ? { cliSchemas: opts.cliSchemas } : {}),\n });\n // Where a misplaced value could go (proposal 0047), asked only to word a\n // `location:external` finding. Built on first use: most runs mark nothing.\n let relocation: RelocationContext | undefined;\n const relocationCtx = (): RelocationContext =>\n (relocation ??= relocationContext(run, {\n cwd,\n targets: fromCollections ? [] : opts.inputs,\n validator,\n ...(opts.noConfig !== undefined ? { noConfig: opts.noConfig } : {}),\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n }));\n // Schema refs in a location message are named the way a rule id names them,\n // not by the absolute path a rebased config holds.\n const refFrame: FingerprintContext = { cwd, base: configDir ?? cwd, runBase: base };\n\n /**\n * The `location:external` and `location:page` warnings for one document\n * (proposal 0047), judged over `data`, the merged metadata validation saw.\n *\n * - `location:external`: a key the page itself holds, which its schemas\n * prefer in external metadata. Not for a key a manifest of the page's\n * collections owns (`external:owned` already errors there), and not for\n * the join field of a field-joined manifest, which is how the page names\n * its entry and so has to stay in the page.\n * - `location:page`: a key a manifest supplied, which its schemas prefer on\n * the page. Filed at the manifest line, as manifest findings are.\n *\n * In the merged data's key order, the page's own keys first.\n */\n const locationFindings = async (\n label: string,\n own: Readonly<Record<string, unknown>>,\n data: Record<string, unknown>,\n refs: string[],\n members: readonly string[],\n merged: MergedMetadata,\n lineFor: (pointer: string) => number | undefined,\n ): Promise<FieldError[]> => {\n const preferences = await validator.locationPreferences(data, refs);\n if (preferences.size === 0) return [];\n const owned = new Set(merged.collisions.map((c) => c.key));\n // Every declared collection the page is in, as relocate reads them: a\n // `--collection` run that leaves one out still leaves its join in place.\n const declaredMembers =\n declaredCollections === collections\n ? members\n : memberOf(declaredCollections, configDir ?? cwd, base, label);\n const joins = new Set(\n declaredCollections\n .filter((c) => declaredMembers.includes(c.name))\n .flatMap((c) => c.externalMetadata.map(externalMetadataJoin))\n .filter((join) => join !== PATH_JOIN),\n );\n const findings: FieldError[] = [];\n for (const key of Object.keys(data)) {\n const preference = preferences.get(key);\n if (preference === undefined) continue;\n const ref = canonicalSchemaRef(preference.schema, refFrame);\n const pointer = externalMetadataPointer(key);\n const common = {\n keyword: LOCATION_FINDING_KEYWORD,\n subject: key,\n instancePath: pointer,\n severity: \"warning\" as const,\n };\n if (Object.hasOwn(own, key)) {\n if (preference.location !== \"external\" || owned.has(key) || joins.has(key)) continue;\n const line = lineFor(key);\n const none = await homeless(label, own, key);\n findings.push({\n schema: LOCATION_EXTERNAL_SCHEMA,\n ...common,\n // relocate refuses --no-config (U2), so it is no answer there.\n // Nor is it one for stdin, which relocate refuses: no advice there.\n message: opts.noConfig\n ? `\"${key}\" is stored in the page; ${ref} prefers external metadata, and --no-config leaves it no manifest.`\n : label === STDIN_LABEL\n ? `\"${key}\" is stored in the page; ${ref} prefers external metadata.`\n : none > 0\n ? `\"${key}\" is stored in the page; ${ref} prefers external metadata, and this document is in none of the ${String(none)} collections.`\n : `\"${key}\" is stored in the page; ${ref} prefers external metadata. Run manni meta relocate.`,\n ...(line != null ? { line } : {}),\n });\n continue;\n }\n if (preference.location !== \"page\") continue;\n const at = merged.locate(pointer);\n if (at === undefined) continue;\n findings.push({\n schema: LOCATION_PAGE_SCHEMA,\n ...common,\n // A fetched manifest cannot give a value up, so relocate is no\n // answer; the value moves in the repository that serves it.\n message: /^https?:\\/\\//.test(at.file)\n ? `\"${key}\" is stored in manifest ${at.file}; ${ref} prefers the page, and a fetched manifest cannot be written. Move it in that repository.`\n : `\"${key}\" is stored in manifest ${at.file}; ${ref} prefers the page. Run manni meta relocate.`,\n file: at.file,\n ...(at.line != null ? { line: at.line } : {}),\n });\n }\n return findings;\n };\n\n /**\n * How many collections a page is in none of, when that leaves `key` no\n * possible home (several declared, the page in none); otherwise 0. With no\n * collections, or one the page is outside, relocate can still give it one,\n * and `--no-config` is V1 too: the finding says what to run, and relocate's\n * own refusal says why it cannot. Stdin is never homeless.\n */\n const homeless = async (label: string, own: Readonly<Record<string, unknown>>, key: string): Promise<number> => {\n if (label === STDIN_LABEL) return 0;\n const home = await keyHome(relocationCtx(), label, own, key);\n return home.kind === \"unowned\" &&\n home.home.kind === \"none\" &&\n home.home.reason === \"collections\" &&\n home.home.collections > 1\n ? home.home.collections\n : 0;\n };\n\n const results: ValidationResult[] = [];\n /** Files `skipDefaultOnly` left out, so a corpus check's finding on one is dropped with it. */\n const skippedDefaultOnly = new Set<string>();\n /** Whether the config alone gives `label` only the built-in default set. */\n const defaultOnly = (label: string, members: readonly string[]): boolean => {\n try {\n return (\n resolveSchemaSetWithSource({\n filePath: label,\n fileSchema: undefined,\n cliSchemas: opts.cliSchemas,\n config,\n memberOf: members,\n fileBase: cwd,\n trustRoot,\n }).source === \"default\"\n );\n } catch {\n return false;\n }\n };\n // Field-joined entries each document matched (0039), keyed by field then\n // value: the duplicate finding and the post-loop orphan check both need\n // to know which documents claimed which value.\n const joinHits = new Map<\n string,\n Map<string, { label: string; line?: number; file: string; shown: string }[]>\n >();\n // Corpus checks (0026) run only when the resolved file set IS the\n // config-resolved corpus — an invariant, not a flag list: any CLI reshaping\n // of the input set (positional paths, stdin, --as/--ext, --exclude,\n // --no-gitignore) disqualifies the run, because a corpus rule computed over\n // half a corpus reports wrong answers. `--collection` is the same reshaping\n // by name (0041 rule 11): every unselected collection's view holds only what\n // the run happened to load, so a `FROM blog` check would pass by having\n // nothing to fail on. `-s/--schema` disqualifies too even though the file\n // set is unchanged: a CLI schema override reshapes the corpus *contract* —\n // cliSchemas outranks every override, so every file is judged against a set\n // the config never assigned it, and a check written against the configured\n // contract would be reporting on a corpus that does not exist outside this\n // run. Config `exclude:` and `respectGitignore:` do not disqualify — they\n // *define* the corpus; the CLI flags redefine the run.\n const scopedToCollections = (opts.collections?.length ?? 0) > 0;\n const scopedByFlags =\n opts.inputs.length > 0 ||\n // redundant with inputs.length (stdin is an input) — kept as belt-and-suspenders\n usingStdin ||\n opts.as !== undefined ||\n opts.exts !== undefined ||\n (opts.exclude !== undefined && opts.exclude.length > 0) ||\n opts.respectGitignore !== undefined ||\n (opts.cliSchemas?.length ?? 0) > 0;\n // Corpus checks need the whole corpus: a reshaping flag disqualifies, and so\n // does narrowing by name, because every unselected collection's view then\n // holds only what the run happened to load (0041 rule 11).\n const scoped = scopedByFlags || scopedToCollections;\n const configuredChecks = config?.checks ?? [];\n\n // A manifest entry naming a document this run did not load (0037 rule 4):\n // 0014's named-file-that-is-not-there, and 0026 §4's row outside the run.\n // Only when the run is a corpus — a positional path or a reshaping flag means\n // the operator chose to look at part of it, and entries for the rest are\n // expected rather than orphaned.\n //\n // `--collection` is not such a reshaping. It makes each named collection the\n // corpus (0041 rule 6): the run loaded all of every collection it named, so\n // an entry of one of those pointing at a document that is not there is a\n // stale entry, and a CI job narrowed to one collection would otherwise lose\n // the check it relies on. Entries of unselected collections are skipped.\n if (!scopedByFlags) {\n const covered = scopedToCollections ? collections.map((c) => c.name) : undefined;\n const orphans = orphanEntries(externalMetadata, files, base, covered);\n if (orphans.length > 0) throw orphanError(orphans);\n }\n const checksWillRun =\n configuredChecks.length > 0 && opts.checks !== false && !scoped;\n // Every successful extraction, kept for the corpus checks (0026): the\n // projection they run over is these entries, exactly as `query` holds them.\n // 0021 measured that holding a docs corpus in memory is not the cost that\n // matters — but the common no-checks path should not retain every file's\n // extraction, so the list fills only when the checks will actually run.\n const checkEntries: CheckEntry[] = [];\n // The run's encryption key (proposal 0045), resolved the first time a\n // ciphertext needs it, and the encrypted values no key could verify.\n const encryptionKey = lazyKey(configFile, opts.env);\n let unverified = 0;\n\n // The derived channel (0040): with `derive:` configured and the flag\n // absent, every file read is an input to one derivation after the loop,\n // and its managed fields are then compared with what the sources say.\n // Stdin is never an input — there is no history behind it.\n const deriveConfig = config?.derive;\n // A `derive:` with no `fields` manages the merge-safe fields, each only on\n // a page whose schemas claim it (0069), so each page's own set is known\n // once its schemas are resolved. `fields: []` manages nothing.\n const configuredFields = managedFields(deriveConfig);\n const defaultedFields = deriveConfig !== undefined && deriveConfig.fields === undefined;\n const deriveWillRun =\n deriveConfig !== undefined &&\n configuredFields.length > 0 &&\n opts.derive !== false;\n /** Under the merge-safe default, the fields each page's schemas claim. */\n const pageManaged = new Map<string, readonly string[]>();\n // A corpus check naming the `derived` or `resolved` table needs the same\n // inputs, content included (the git source hashes it to spot an uncommitted\n // body), so the one list serves both — and fills only when something will\n // read it. Both names count: a check reading `resolved` alone in a repo\n // with no managed fields would otherwise keep no inputs, derive nothing,\n // and read every column NULL without saying so.\n const derivedChecks = checksWillRun\n ? configuredChecks.filter((c) => mentionsDerived(c.query) || mentionsResolved(c.query))\n : [];\n const checksNeedDerived = derivedChecks.length > 0;\n const deriveInputs: DeriveInput[] = [];\n // Each compared file's encryption view (0045), so a marked managed field is\n // compared by its plaintext and never named in the clear.\n const managedViews = new Map<string, ManagedView>();\n const keepDeriveInputs = deriveWillRun || checksNeedDerived;\n // One derivation for the run, over the union of what either reader needs:\n // the managed fields the comparison judges, and the columns the checks\n // can read. Memoized so a check that names the table and a managed field\n // share the git walk (and the gh or glab round-trip) rather than each paying\n // for one. A source that cannot answer is the run's error either way — a\n // half-derived comparison would read as \"all current\", the false green\n // the channel refuses — and the hint names the reader that asked.\n // The configured commands (0042) are part of both: a command's field is\n // managed like a built-in one, and is a column the checks can read.\n const deriveCommands = commandsOf(deriveConfig);\n // Under the default, each page adds the fields it claims as it is read.\n const deriveFields = new Set<string>(deriveWillRun && !defaultedFields ? configuredFields : []);\n const readable = derivableFields(deriveCommands);\n for (const c of derivedChecks) for (const f of fieldsForSql(c.query, readable)) deriveFields.add(f);\n // The manifests that hold a page's `provenance` record (0046), for evidence rule 2.\n const provenanceManifests =\n keepDeriveInputs &&\n (deriveFields.has(PROVENANCE_FIELD) || (deriveWillRun && configuredFields.includes(PROVENANCE_FIELD)))\n ? readerManifests(declaredCollections, configDir ?? cwd, base)\n : [];\n const derivedOnce = once(async (): Promise<DeriveResult> => {\n const derived = await deriveMetadata(deriveInputs, {\n cwd,\n base,\n ...(configDir !== undefined ? { configDir } : {}),\n sources: deriveConfig?.sources ?? [...DERIVE_SOURCES],\n fields: [...deriveFields],\n ...(deriveConfig?.codeowners !== undefined\n ? { codeowners: deriveConfig.codeowners }\n : {}),\n ...(deriveCommands !== undefined ? { commands: deriveCommands } : {}),\n cache: opts.cache ?? true,\n now: opts.now ?? (() => new Date()),\n machines: machinesOf(deriveConfig),\n });\n assertSourcesAvailable(\n derived.sources,\n deriveWillRun\n ? \"pass --no-derive to skip the comparison, or narrow derive.sources\"\n : \"narrow derive.sources in manni.config.yaml\",\n );\n // A source that answered, with a caveat worth one line: a repository\n // with no CODEOWNERS file derives null owners rather than failing.\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 return derived;\n });\n\n const processOne = async (\n label: string,\n content: string,\n extension: string,\n ): Promise<void> => {\n const extractor =\n forcedExtractor ?? 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\n const members = membersFor(label);\n let extracted;\n try {\n extracted = extractor.extract(content, label, {\n elements: resolveElements(label, config, members),\n });\n } catch (err) {\n // A `DocmetaError` out of an extractor is operational, not a bad\n // document — it aborts the run rather than counting as a file failure.\n if (err instanceof DocmetaError) throw err;\n // A page that does not parse names no `$schema`, so `skipDefaultOnly`\n // judges it by what the config alone would apply to it.\n if (opts.skipDefaultOnly === true && defaultOnly(label, members)) {\n skippedDefaultOnly.add(label);\n return;\n }\n results.push(\n parseErrorResult(label, extractor.name, errorMessage(err), \"parse\"),\n );\n return;\n }\n // The external-metadata merge sits between extraction and everything downstream,\n // so schema resolution, validation, and the corpus checks all see the one\n // object the document and its manifest entry make together.\n // `merged.extracted` keeps the document's own `lineFor`/`colFor`: a\n // manifest key is not in the document, so those answer `undefined` for it\n // and `merged.locate` answers instead. Rebound rather than shadowed, so\n // every read below — resolution, validation, the collision loop — sees\n // the one merged object.\n //\n // The derive sources take the document's OWN extraction, from before the\n // merge, so `lineFor` answers for its own lines. The comparison itself\n // reads the merged view below: a managed key a local manifest owns\n // (0047) is asserted by the manifest, and `merged.locate` points its\n // finding at the manifest's line. `provenance`'s record may live in a\n // manifest too (0046), which the git source then reads at each commit.\n // A manifest with no keys (proposal 0068) owns what this page's schemas\n // mark external, so those marks are read before the merge.\n const merged = await mergeWithMarks(label, extracted, externalMetadata, members, base, {\n encryptionKey,\n marks,\n });\n // A file outside `derive.collections` is derived only when a check\n // reads the derived table (proposal 0070).\n if (\n keepDeriveInputs &&\n label !== STDIN_LABEL &&\n (checksNeedDerived || deriveCovers(deriveConfig, members))\n ) {\n const place = provenanceManifests.length === 0\n ? undefined\n : readerPlace(label, extracted.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, extracted.data, declaredCollections, configDir ?? cwd, base, merged.marked, STAMPED_DATE_FIELDS);\n deriveInputs.push({\n label,\n absPath: resolve(base, label),\n content,\n extracted,\n ...(place !== undefined ? { provenanceManifest: place } : {}),\n ...(Object.keys(owned).length > 0 ? { stampManifests: owned } : {}),\n });\n }\n // The page's own keys, for telling a value the page holds from one a\n // manifest supplied (proposal 0047).\n const own = extracted.data;\n extracted = merged.extracted;\n // The merged data before any schema is known, so a document whose schema\n // set fails still asserts what its manifest supplies. No refs means no\n // marks, which is exactly what the encryption view below would find.\n // Replaced by that view once it is built.\n if (deriveWillRun && label !== STDIN_LABEL) {\n managedViews.set(label, {\n data: extracted.data,\n marked: [],\n hidden: [],\n refs: [],\n locate: merged.locate,\n });\n }\n for (const j of merged.joins) {\n const byValue =\n joinHits.get(j.field) ??\n new Map<string, { label: string; line?: number; file: string; shown: string }[]>();\n const line = extracted.lineFor(j.field);\n const hits = byValue.get(j.value) ?? [];\n // A finding names the join value as the page holds it: the ciphertext\n // of an encrypted field, never its plaintext.\n hits.push({\n label,\n file: j.file,\n shown: j.pageValue ?? j.value,\n ...(line != null ? { line } : {}),\n });\n byValue.set(j.value, hits);\n joinHits.set(j.field, byValue);\n }\n if (checksWillRun) checkEntries.push({ label, extracted });\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 // A document's own `$schema` is measured from the run's directory, the\n // same base `loadSchema` will read it from, and contained to the\n // repository the run is standing in.\n fileBase: cwd,\n trustRoot,\n onNotice: opts.onNotice,\n });\n } catch (err) {\n results.push(\n parseErrorResult(label, extractor.name, errorMessage(err), \"schema\"),\n );\n return;\n }\n\n if (opts.skipDefaultOnly === true && resolved.source === \"default\") {\n skippedDefaultOnly.add(label);\n return;\n }\n const schemaSet = resolved.schemas;\n // The merge-safe default (0069): this page manages what its schemas claim.\n // A set that fails to load claims nothing, and validation says why.\n if (\n deriveWillRun &&\n defaultedFields &&\n label !== STDIN_LABEL &&\n deriveCovers(deriveConfig, members)\n ) {\n let claimed: ReadonlySet<string> = new Set();\n try {\n claimed = await validator.claimedProperties(schemaSet);\n } catch (err) {\n if (!(err instanceof DocmetaError)) throw err;\n }\n const own = configuredFields.filter((f) => claimed.has(f));\n pageManaged.set(label, own);\n for (const f of own) deriveFields.add(f);\n }\n let errors: FieldError[];\n try {\n // Proposal 0045: marked values are validated as their plaintext, on a\n // copy; the page's own object is never mutated, and no finding may say\n // more about an encrypted value than the page did.\n const view = await encryptionView({\n data: extracted.data,\n refs: schemaSet,\n validator,\n key: encryptionKey,\n locate: merged.locate,\n });\n unverified += view.unverified.length;\n if (deriveWillRun && label !== STDIN_LABEL) {\n managedViews.set(label, {\n data: view.data,\n marked: view.marked,\n hidden: [...view.unreadable, ...view.unverified],\n refs: schemaSet,\n locate: merged.locate,\n });\n }\n errors = [\n ...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 ...encryptionFindings(view, extracted, merged.locate),\n // Over the decrypted view, the object validation evaluated: a mark\n // counts where Ajv takes a branch, and a branch may read a value.\n ...(await locationFindings(label, own, view.data, schemaSet, members, merged, extracted.lineFor)),\n ];\n } catch (err) {\n // A schema the *document* chose failing to load — unparseable, missing,\n // integrity mismatch — is that document's failure, and is filed as one.\n // Letting it escape meant a single contributed file naming any non-JSON\n // path in the repo aborted the whole run: exit 2, and nothing reported\n // about any file, including the ones that were fine.\n //\n // Every other source stays operational on purpose. A schema the operator\n // configured is not one document's problem; it invalidates the run, and\n // reporting it per-file would repeat the same error once per document\n // while implying the documents were at fault.\n if (!(err instanceof DocmetaError) || resolved.source !== \"document\") {\n throw err;\n }\n results.push(\n parseErrorResult(label, extractor.name, err.message, \"schema\"),\n );\n return;\n }\n // A document carrying a key a manifest owns (0020 across files: neither\n // channel wins, and the discarded value would be exactly the one nobody\n // checked). Filed against the document at the key's own line.\n for (const { key, file, collection } of merged.collisions) {\n const line = extracted.lineFor(key);\n errors.push({\n schema: EXTERNAL_OWNED_SCHEMA,\n keyword: EXTERNAL_KEYWORD,\n subject: key,\n instancePath: externalMetadataPointer(key),\n message: `\"${key}\" is owned by manifest ${file} (collection ${collection}); remove it from the document`,\n ...(line != null ? { line } : {}),\n });\n }\n results.push({\n file: label,\n format: extractor.name,\n ok: !errors.some(isErrorSeverity),\n schemas: schemaSet,\n errors,\n });\n };\n\n if (usingStdin) {\n const content = opts.stdinContent ?? \"\";\n if (!forcedExtractor) {\n throw new DocmetaError(\n STDIN_REQUIRES_AS,\n );\n }\n await processOne(STDIN_LABEL, content, forcedExtractor.extensions[0] ?? \"\");\n }\n\n for (const file of files) {\n const content = await readFile(resolve(base, file), \"utf8\");\n await processOne(file, content, extname(file));\n }\n\n // Once per run, however many files held them (proposal 0045): the exit code\n // is unaffected, and the count is of values, not of the findings dropped.\n if (unverified > 0) opts.onNotice?.(unverifiedWarning(unverified));\n\n // Two documents carrying one join value (0039): one entry matched both,\n // and the manifest cannot tell them apart. A finding on each, at the\n // field's own line, whether or not the run is scoped — it is about the\n // documents loaded, not the corpus. Then, on a corpus run, a field entry\n // nothing matched is the same orphan a path entry is.\n if (externalMetadata) {\n const byLabel = new Map(results.map((r) => [r.file, r]));\n const matched = new Map<string, Set<string>>();\n for (const [field, byValue] of joinHits) {\n matched.set(field, new Set(byValue.keys()));\n for (const hits of byValue.values()) {\n if (hits.length < 2) continue;\n for (const hit of hits) {\n const others = hits\n .filter((h) => h.label !== hit.label)\n .map((h) => h.label)\n .join(\", \");\n const result = byLabel.get(hit.label);\n if (!result) continue;\n result.errors.push({\n schema: EXTERNAL_DUPLICATE_SCHEMA,\n keyword: EXTERNAL_KEYWORD,\n subject: hit.shown,\n instancePath: externalMetadataPointer(field),\n message: `${hits.length} documents carry ${field} \"${hit.shown}\"; ${hit.file} cannot tell them apart (${others})`,\n ...(hit.line != null ? { line: hit.line } : {}),\n });\n result.ok = false;\n }\n }\n }\n // Same corpus invariant as the path-entry orphans above, and the same\n // reading of `--collection`: a named collection is a corpus of its own.\n if (!scopedByFlags) {\n const covered = scopedToCollections ? collections.map((c) => c.name) : undefined;\n const orphans = orphanJoins(externalMetadata, matched, covered);\n if (orphans.length > 0) throw orphanError(orphans);\n }\n }\n\n // Corpus checks (0026), after the per-file loop and before the baseline so\n // their findings ride the same ratchet the schemas get. The disqualifying\n // conditions live with `scoped`, computed before the loop above.\n if (configuredChecks.length > 0 && opts.checks !== false) {\n if (scoped) {\n // Name the reason when it is `--collection`: \"scoped\" alone reads as a\n // stray positional path, and the operator who narrowed the run by name\n // is the one most likely to expect the checks to have run.\n opts.onNotice?.(\n scopedToCollections\n ? `corpus checks skipped: run is scoped to collections ${collections\n .map((c) => c.name)\n .join(\", \")}`\n : \"corpus checks skipped: run is scoped\",\n );\n } else {\n const findings = await runChecks(configuredChecks, checkEntries, {\n // Every declared collection is a view (0041 rule 7), holding the\n // members this run loaded — decided by the same path arithmetic\n // `membersFor` uses, so a check and a `manni meta query` over the same\n // corpus see the same collections.\n collections: declaredCollections,\n ...(configDir !== undefined ? { configDir } : {}),\n base,\n // A check that names the `derived` table (0040) gets the same view\n // `query` builds, from the run's one derivation — which already\n // covers every field the checks can read, so the list handed back\n // here is not needed. Built only when asked for, because building\n // it spawns git.\n derive: async () => (await derivedOnce()).records,\n // Its columns include the configured commands' keys (0042), which a\n // check's context cannot read from a config since 0041.\n ...(deriveCommands !== undefined ? { commands: deriveCommands } : {}),\n });\n const byFile = new Map(results.map((r) => [r.file, r]));\n for (const [file, errs] of findings) {\n // Unreachable while runChecks vets every path against the loaded set,\n // which is a subset of `results` by construction — but a missed merge\n // must be a loud failure, not findings silently dropped.\n const result = byFile.get(file);\n if (!result && skippedDefaultOnly.has(file)) continue;\n if (!result) {\n throw new DocmetaError(\n `check findings for \"${file}\" have no validation result to attach to.`,\n );\n }\n result.errors.push(...errs);\n result.ok = result.ok && !errs.some(isErrorSeverity);\n }\n }\n }\n\n // The derived comparison (0040): what each document asserts for its\n // managed fields against what the sources say. Per file, so it runs on\n // scoped runs too, and before the baseline so a stale stamp rides the same\n // ratchet every other finding does. Reads only the configured fields from\n // the run's one derivation, which may hold more for the checks' sake.\n if (deriveWillRun && deriveInputs.length > 0) {\n const derived = await derivedOnce();\n const byFile = new Map(results.map((r) => [r.file, r]));\n for (const input of deriveInputs) {\n const record: DerivedRecord | undefined = derived.records.get(input.label);\n const result = byFile.get(input.label);\n if (!record || !result) continue;\n // Proposal 0045: a marked managed field is compared by its plaintext\n // and named as `(encrypted)`. One no key could read is left\n // uncompared: the run already says so once, and a guess either way\n // would be a false finding or a false green.\n const managed = managedViews.get(input.label);\n // A file outside `derive.collections` is not compared (proposal 0070).\n const managedHere = !deriveCovers(deriveConfig, membersFor(input.label))\n ? []\n : defaultedFields\n ? (pageManaged.get(input.label) ?? [])\n : configuredFields;\n const fields = managedHere.filter(\n (field) => !(managed?.hidden.some((p) => isAtOrUnder(p, pointerOf(field))) ?? false),\n );\n let marked: readonly string[] = [];\n if (managed !== undefined) {\n // Read over the page as `derive` would stamp it: an absent property\n // is one Ajv never evaluates, so an unset field's mark only shows\n // once its value is in place.\n const stamped: Record<string, unknown> = { ...managed.data };\n for (const field of fields) {\n const d = record.fields[field];\n if (d != null) stamped[field] = d.value;\n }\n marked = [...managed.marked, ...(await validator.markedPointers(stamped, managed.refs))];\n }\n const asserted = (field: string): unknown =>\n managed !== undefined ? managed.data[field] : input.extracted.data[field];\n const findings = fields.flatMap((field) => {\n // Proposal 0046: `provenance` is judged range by range, against the\n // record wherever it lives, and each finding lands on its range's line.\n if (field === PROVENANCE_FIELD) {\n const derivation = derived.provenance?.get(input.label);\n if (derivation === undefined) return [];\n return provenanceFindings(\n compareProvenance(provenanceEntries(asserted(field)), derivation),\n derivation.page.bodyLine,\n );\n }\n const compared = compareDerived(field, asserted(field), record.fields[field]);\n const at = pointerOf(field);\n return staleFindings(\n [marked.some((p) => isAtOrUnder(p, at)) ? redactedDerived(compared) : compared],\n input.extracted.lineFor,\n managed?.locate,\n );\n });\n if (findings.length === 0) continue;\n result.errors.push(...findings);\n result.ok = false;\n }\n }\n\n // Fingerprints must not depend on where the command was run from, so a\n // local file schema ref is measured against the config's directory.\n const frame: FingerprintContext = { cwd, base: configDir ?? cwd, runBase: base };\n\n const { results: reported, baseline } = await settleBaseline(\n results,\n resolveBaselineRequest(opts, config?.baseline, configDir, cwd, {\n current: DEFAULT_BASELINE_PATH,\n legacy: LEGACY_BASELINE_PATH,\n }),\n frame,\n );\n\n const failed = reported.filter((r) => !r.ok).length;\n const count = (keep: (e: FieldError) => boolean): number =>\n reported.reduce((n, r) => n + r.errors.filter(keep).length, 0);\n const warnings = count((e) => e.severity === \"warning\");\n const notices = count((e) => e.severity === \"notice\");\n const summary: RunSummary = {\n files: reported.length,\n passed: reported.length - failed,\n failed,\n errors: count(isErrorSeverity),\n // Omitted at zero, like `gitignoreSkipped` below: only the location\n // findings (proposal 0047) are warnings, so a run with no\n // `x-manni-location` marks keeps the summary as it was.\n ...(warnings > 0 ? { warnings } : {}),\n ...(notices > 0 ? { notices } : {}),\n // Omitted when nothing was skipped: there is nothing to audit, and the\n // JSON summary stays as it was for every run in a clean repo.\n ...(gitignoreSkipped > 0 ? { gitignoreSkipped } : {}),\n ...(baseline ? { baseline } : {}),\n };\n\n return { results: reported, summary, frame };\n}\n","/**\n * The one adapter between `derive:` as the config file spells it and the\n * derive context as the sources want it.\n *\n * The config is a user-facing document, so it says `timeout: 30`, in whole\n * seconds. Every source downstream measures in milliseconds, because that is\n * what `child_process` takes. Exactly one place should know both, and this is\n * it. It lived in `table.ts` first, which made the SQL projection the owner\n * of a unit conversion four commands need and only one of them is about\n * tables.\n */\nimport type { DeriveConfig } from \"../config.js\";\nimport { DEFAULT_MACHINES } from \"./provenance.js\";\nimport type { DeriveCommand } from \"./types.js\";\n\n/** How long a configured command may run when its entry says nothing: 60 s. */\nexport const DEFAULT_COMMAND_TIMEOUT_MS = 60_000;\n\n/**\n * The `command` source's table as the derive context wants it, from the\n * config's spelling: `timeout` is in seconds there and `timeoutMs` here.\n * Undefined when the config configures no command, so a context built from\n * it consults the source for nothing.\n */\nexport function commandsOf(\n config?: DeriveConfig,\n): Readonly<Record<string, DeriveCommand>> | undefined {\n if (config?.commands === undefined) return undefined;\n const out: Record<string, DeriveCommand> = {};\n for (const [field, c] of Object.entries(config.commands)) {\n out[field] = {\n run: c.run,\n timeoutMs:\n c.timeout === undefined ? DEFAULT_COMMAND_TIMEOUT_MS : Math.round(c.timeout * 1000),\n };\n }\n return out;\n}\n\n/**\n * `derive.machines` as the sources read it (proposal 0046): the configured\n * globs, or `[\"*[bot]\"]` when the config sets none, which is exactly the\n * `[bot]` suffix rule `authors` followed before the key existed.\n */\nexport function machinesOf(config?: DeriveConfig): readonly string[] {\n return config?.machines ?? DEFAULT_MACHINES;\n}\n","/**\n * The derived channel's front door: one call resolves every requested field\n * for every input from the sources the run consults.\n *\n * Three rules live here and nowhere else:\n *\n * 1. **A source is consulted only when a requested field can come from it.**\n * `FIELD_SOURCES` says which for the built-ins, and `derive.commands`\n * which keys the `command` source answers; the run's `sources` list\n * narrows it. A source nobody asked for is never spawned and never\n * reported, and a command for a field the run did not request is never\n * spawned either.\n * 2. **The review sources ride on git, and the origin remote picks one.**\n * `github` and `gitlab` both read the merged change behind a document's\n * newest body-changing commit, which only the git walk can name, so\n * either without `git` is reported unavailable with the fix rather than\n * silently answering null. Per repository root, the origin remote says\n * which host the repository lives on, and only the review source of that\n * name is consulted and reported: a run that allows both on a GitHub\n * repository reports `github` alone. A run that allows only the other\n * one is told which host the origin is, and what to change.\n * 3. **Precedence is per field, first non-null wins.** `reviewed-by` and\n * `last-reviewed` prefer the host's approvals over a `Reviewed-by`\n * trailer; every other field has one source.\n *\n * Availability is reported, not thrown: a caller decides what an\n * unavailable source means for its run through `assertSourcesAvailable`,\n * because the hint differs per command (`--no-derive` on validate,\n * `--sources` on derive).\n */\nimport { dirname, resolve } from \"node:path\";\nimport { findGitRoot } from \"../../../shared/git-root.js\";\nimport { DocmetaError } from \"../../types.js\";\nimport { REVIEW_CACHE_DIR } from \"./cache.js\";\nimport { deriveFromCodeowners } from \"./codeowners.js\";\nimport { deriveFromCommands } from \"./command.js\";\nimport { createReviewClient, deriveFromReviews, type ReviewFacts } from \"./reviews.js\";\nimport { deriveFromGit, type GitFacts } from \"./git.js\";\nimport type { ProvenanceDerivation } from \"./provenance.js\";\nimport { isBuiltinField } from \"./types.js\";\nimport type {\n BuiltinDerivableField,\n DerivableField,\n DeriveCommand,\n DeriveContext,\n DerivedRecord,\n DerivedValue,\n DeriveInput,\n DeriveSource,\n RemoteIdentity,\n ReviewClient,\n SourceStatus,\n} from \"./types.js\";\n\n/** Which sources can state each built-in field, in precedence order. */\nexport const FIELD_SOURCES: Readonly<Record<BuiltinDerivableField, readonly DeriveSource[]>> = {\n created: [\"git\"],\n \"last-updated\": [\"git\"],\n authors: [\"git\"],\n owner: [\"codeowners\"],\n \"reviewed-by\": [\"github\", \"gitlab\", \"git\"],\n \"last-reviewed\": [\"github\", \"gitlab\", \"git\"],\n provenance: [\"git\"],\n};\n\n/** The sources that read a host's review record; one per host, named for it. */\ntype ReviewSource = RemoteIdentity[\"kind\"];\n\nconst REVIEW_SOURCES: readonly ReviewSource[] = [\"github\", \"gitlab\"];\n\n/** How the host is spelled to a person, as opposed to as a source name. */\nconst HOST_NAME: Readonly<Record<ReviewSource, string>> = {\n github: \"GitHub\",\n gitlab: \"GitLab\",\n};\n\nexport interface DeriveResult {\n /** Keyed by `DeriveInput.label`; every input has a record. */\n records: Map<string, DerivedRecord>;\n /**\n * One status per source the run consulted. A source nobody asked for is\n * absent, and so is whichever of `github` and `gitlab` the origin remote does\n * not point at. Absent means not applicable here, never unavailable.\n */\n sources: Partial<Record<DeriveSource, SourceStatus>>;\n /**\n * The provenance derivation per input label (proposal 0046), for the\n * comparison with a page's stamp: present only when `provenance` was\n * requested and the git source answered.\n */\n provenance?: ReadonlyMap<string, ProvenanceDerivation>;\n}\n\n/**\n * Which sources can state a field, in precedence order: the built-in table\n * for one of the six, `command` for a key of `commands`, nothing otherwise.\n * A built-in never reaches the command arm, whatever the table says.\n */\nexport function sourcesFor(\n field: DerivableField,\n commands?: Readonly<Record<string, DeriveCommand>>,\n): readonly DeriveSource[] {\n if (isBuiltinField(field)) return FIELD_SOURCES[field];\n if (commands !== undefined && Object.hasOwn(commands, field)) return [\"command\"];\n return [];\n}\n\n/** The sources a run consults: requested, and able to state a requested field. */\nexport function consultedSources(\n fields: readonly DerivableField[],\n sources: readonly DeriveSource[],\n commands?: Readonly<Record<string, DeriveCommand>>,\n): DeriveSource[] {\n const needed = new Set<DeriveSource>();\n for (const field of fields) {\n for (const s of sourcesFor(field, commands)) needed.add(s);\n }\n return sources.filter((s) => needed.has(s));\n}\n\n/**\n * Throw the exit-2 error for the first consulted source that could not\n * answer. `hint` is the command's own way out, appended after a semicolon.\n */\nexport function assertSourcesAvailable(\n sources: Partial<Record<DeriveSource, SourceStatus>>,\n hint?: string,\n): void {\n for (const name of Object.keys(sources) as DeriveSource[]) {\n const status = sources[name];\n if (status === undefined || status.available) continue;\n const reason = status.reason ?? \"it could not answer\";\n throw new DocmetaError(\n `${name} source unavailable: ${reason}${hint === undefined ? \"\" : `; ${hint}`}`,\n );\n }\n}\n\nexport async function deriveMetadata(\n inputs: readonly DeriveInput[],\n ctx: DeriveContext,\n): Promise<DeriveResult> {\n const consulted = new Set(consultedSources(ctx.fields, ctx.sources, ctx.commands));\n const sources: Partial<Record<DeriveSource, SourceStatus>> = {};\n\n // git: the walk every other source builds on.\n let git: Map<string, GitFacts> = new Map();\n if (consulted.has(\"git\")) {\n const result = await deriveFromGit(inputs, {\n cwd: ctx.cwd,\n now: ctx.now,\n fields: ctx.fields,\n ...(ctx.generatedBy !== undefined ? { generatedBy: ctx.generatedBy } : {}),\n ...(ctx.machines !== undefined ? { machines: ctx.machines } : {}),\n });\n sources.git = result.status;\n git = result.records;\n }\n const provenance = new Map<string, ProvenanceDerivation>();\n for (const [label, facts] of git) {\n if (facts.provenanceDerivation !== undefined) provenance.set(label, facts.provenanceDerivation);\n }\n\n // Repository root per input: git's answer where it gave one, the .git walk otherwise.\n const rootCache = new Map<string, string | null>();\n const rootOf = (absPath: string): string | null => {\n const dir = dirname(absPath);\n let root = rootCache.get(dir);\n if (root === undefined) {\n root = findGitRoot(dir);\n rootCache.set(dir, root);\n }\n return root;\n };\n const rootFor = (input: DeriveInput): string | null =>\n git.get(input.label)?.root ?? rootOf(input.absPath);\n\n // codeowners\n let owners: Map<string, DerivedValue | null> = new Map();\n if (consulted.has(\"codeowners\")) {\n const result = await deriveFromCodeowners(inputs, {\n explicit: ctx.codeowners,\n configDir: ctx.configDir,\n rootOf,\n });\n sources.codeowners = result.status;\n owners = result.records;\n }\n\n // github / gitlab: one client per repository root, or the injected seam\n // for all. Which of the two a root uses is the origin remote's call.\n const requested = REVIEW_SOURCES.filter((s) => consulted.has(s));\n let reviews: Map<string, ReviewFacts> = new Map();\n if (requested.length > 0) {\n if (!consulted.has(\"git\")) {\n for (const s of requested) {\n sources[s] = {\n available: false,\n reason: `the ${s} source needs the git source to find each document's commits; add git to sources`,\n };\n }\n } else if (sources.git?.available === false) {\n // Git already failed the run; every review lookup starts from a commit\n // git names, so spawning gh/glab now would be wasted calls before the\n // same exit 2.\n for (const s of requested) {\n sources[s] = {\n available: false,\n reason: `the git source could not answer, so the ${s} source cannot locate any commit`,\n };\n }\n } else {\n const result = await deriveReviewsByRoot(inputs, git, rootFor, ctx, requested);\n Object.assign(sources, result.status);\n reviews = result.records;\n }\n }\n\n // command: last, and only when nothing has failed yet. A configured\n // command is the one source that runs a program of the operator's own,\n // which may do more than report a value, so it is not spawned for a run\n // already destined for exit 2 — and the source that failed first is the\n // one whose reason `assertSourcesAvailable` reports.\n let commanded: Map<string, Record<string, DerivedValue | null>> = new Map();\n const doomed = Object.values(sources).some((s) => !s.available);\n if (consulted.has(\"command\") && ctx.commands !== undefined && !doomed) {\n // Only the entries for fields this run asked for, so a narrowed\n // `--fields` spawns nothing it does not need.\n const wanted = new Set(ctx.fields);\n const commands = Object.fromEntries(\n Object.entries(ctx.commands).filter(([field]) => wanted.has(field)),\n );\n if (Object.keys(commands).length > 0) {\n const result = await deriveFromCommands(inputs, commands, { cwd: ctx.configDir ?? ctx.cwd });\n sources.command = result.status;\n commanded = result.records;\n }\n }\n\n const records = new Map<string, DerivedRecord>();\n for (const input of inputs) {\n const fields: DerivedRecord[\"fields\"] = {};\n const g = git.get(input.label);\n const r = reviews.get(input.label);\n const c = commanded.get(input.label);\n for (const field of ctx.fields) {\n let value: DerivedValue | null = null;\n for (const source of sourcesFor(field, ctx.commands)) {\n if (!consulted.has(source)) continue;\n const candidate = valueFrom(source, field, g, r, owners.get(input.label), c);\n if (candidate !== null) {\n value = candidate;\n break;\n }\n }\n fields[field] = value;\n }\n records.set(input.label, { file: input.label, fields });\n }\n return { records, sources, ...(provenance.size > 0 ? { provenance } : {}) };\n}\n\nfunction valueFrom(\n source: DeriveSource,\n field: DerivableField,\n git: GitFacts | undefined,\n reviews: ReviewFacts | undefined,\n owner: DerivedValue | null | undefined,\n commanded: Readonly<Record<string, DerivedValue | null>> | undefined,\n): DerivedValue | null {\n switch (source) {\n case \"git\":\n if (git === undefined || !isBuiltinField(field) || field === \"owner\") return null;\n return git[field];\n case \"command\":\n return commanded?.[field] ?? null;\n case \"codeowners\":\n return field === \"owner\" ? (owner ?? null) : null;\n case \"github\":\n case \"gitlab\": {\n if (reviews === undefined) return null;\n if (field !== \"reviewed-by\" && field !== \"last-reviewed\") return null;\n // A fact answers for the source of the host it came from, and no other.\n const fact = reviews[field];\n return fact !== null && fact.source === source ? fact : null;\n }\n }\n}\n\n/**\n * Consult the review record for each repository root that holds an input.\n *\n * The root's origin remote picks the source: a GitHub origin uses `github`,\n * a GitLab origin `gitlab`, and only the one used is reported. When the\n * origin names a host whose source was not requested, that requested source\n * is reported unavailable with the host named and the fix spelled out. With\n * no origin at all, every requested review source is unavailable, because\n * nothing tells the two apart.\n */\nasync function deriveReviewsByRoot(\n inputs: readonly DeriveInput[],\n git: ReadonlyMap<string, GitFacts>,\n rootFor: (input: DeriveInput) => string | null,\n ctx: DeriveContext,\n requested: readonly ReviewSource[],\n): Promise<{ status: Partial<Record<ReviewSource, SourceStatus>>; records: Map<string, ReviewFacts> }> {\n const byRoot = new Map<string, DeriveInput[]>();\n for (const input of inputs) {\n const root = rootFor(input);\n if (root === null) continue;\n const bucket = byRoot.get(root) ?? [];\n bucket.push(input);\n byRoot.set(root, bucket);\n }\n const status: Partial<Record<ReviewSource, SourceStatus>> = {};\n const records = new Map<string, ReviewFacts>();\n const unavailable = (\n which: readonly ReviewSource[],\n reason: string,\n ): { status: Partial<Record<ReviewSource, SourceStatus>>; records: Map<string, ReviewFacts> } => {\n for (const s of which) status[s] = { available: false, reason };\n return { status, records: new Map() };\n };\n if (byRoot.size === 0) {\n return unavailable(requested, \"no git repository contains the documents\");\n }\n const cacheDir = resolve(ctx.configDir ?? ctx.cwd, REVIEW_CACHE_DIR);\n for (const [root, bucket] of byRoot) {\n const client: ReviewClient =\n ctx.reviews ??\n (await createReviewClient(root, { cwd: ctx.cwd, cache: ctx.cache, cacheDir, requested }));\n const identity = await client.detect();\n if (identity === null) {\n // No origin, or a host that names neither platform: the client's own\n // status says which, and names the fix.\n const s = await client.status();\n return unavailable(requested, s.reason ?? \"no origin remote to tell GitHub from GitLab\");\n }\n const source = identity.kind;\n if (!requested.includes(source)) {\n return unavailable(\n requested,\n `the origin remote is ${identity.host}, which is ${HOST_NAME[source]}; add ${source} to sources, or drop reviewed-by and last-reviewed from the managed fields`,\n );\n }\n const result = await deriveFromReviews(\n bucket.map((input) => ({\n label: input.label,\n sha: git.get(input.label)?.lastBodyCommit ?? null,\n })),\n client,\n );\n // One root that cannot answer makes the source unavailable for the run:\n // a half-derived review field would read as \"nobody approved\", which is\n // the false green the whole channel refuses.\n if (!result.status.available) {\n status[source] = result.status;\n return { status, records: new Map() };\n }\n status[source] = result.status;\n for (const [label, facts] of result.records) records.set(label, facts);\n }\n return { status, records };\n}\n\n","/**\n * The GitHub or GitLab review cache: cross-run, for merged-change answers.\n *\n * A merged pull request is history: its approvals cannot change, so the\n * answer for `host/project/sha` is good forever and there is no TTL. An\n * *open* PR's answer is the opposite — the next approval changes it — so a\n * `null` from the host is never written. `--no-cache` disables both\n * directions for one run.\n *\n * Same shape as `schema-cache.ts`: one file per key under\n * `.manni/meta/review-cache/`, named by a digest so the key (which carries\n * `/`) can never decide where a write lands; a malformed entry is a miss;\n * a failed write is swallowed, because a read-only checkout must cost the\n * next run one `gh` call, not this run its result. Synchronous, because a\n * `set()` the caller does not await must still be on disk when the next\n * process starts.\n */\nimport { createHash } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ReviewClient, RemoteIdentity, MergedChange } from \"./types.js\";\n\n/** Where the GitHub or GitLab review cache lives, relative to the project root. `.manni/` is gitignored. */\nexport const REVIEW_CACHE_DIR = \".manni/meta/review-cache\";\n\n/** The only entry format this version understands. */\nexport const REVIEW_CACHE_VERSION = 1;\n\ninterface Entry {\n version: number;\n /** `host/project/sha`; re-checked on read. */\n key: string;\n change: MergedChange;\n}\n\n/** The GitHub or GitLab review cache: one immutable merged change per `host/project/sha`. */\nexport class ReviewCache {\n constructor(\n private readonly dir: string,\n private readonly enabled: boolean,\n ) {}\n\n entryPath(key: string): string {\n const digest = createHash(\"sha256\").update(key).digest(\"hex\");\n return join(this.dir, `${digest}.json`);\n }\n\n /** The cached change, or `undefined` for a miss. Never `null`: nulls are not stored. */\n get(key: string): MergedChange | undefined {\n if (!this.enabled) return undefined;\n let raw: unknown;\n try {\n raw = JSON.parse(readFileSync(this.entryPath(key), \"utf8\"));\n } catch {\n return undefined;\n }\n if (!isRecord(raw)) return undefined;\n if (raw.version !== REVIEW_CACHE_VERSION || raw.key !== key) return undefined;\n const change = readChange(raw.change);\n return change ?? undefined;\n }\n\n set(key: string, value: MergedChange): void {\n if (!this.enabled) return;\n const entry: Entry = { version: REVIEW_CACHE_VERSION, key, change: value };\n const path = this.entryPath(key);\n // Temp file beside the target plus rename, so a reader never sees half an\n // entry. Synchronous: see the module comment.\n const tmp = `${path}.${process.pid}-${Math.random().toString(36).slice(2, 8)}.tmp`;\n try {\n mkdirSync(this.dir, { recursive: true });\n writeFileSync(tmp, `${JSON.stringify(entry, null, 2)}\\n`, \"utf8\");\n renameSync(tmp, path);\n } catch {\n // Intentionally silent: see the module comment.\n try {\n rmSync(tmp, { force: true });\n } catch {\n // The temp file was never created, or cannot be removed either.\n }\n }\n }\n}\n\n/**\n * `client` with `mergedChangeFor` read through the cache. Only a merged\n * answer is stored. With no identity there is no key, and every call goes\n * straight through — which, for a client with no origin, is a `null`.\n */\nexport function cachedClient(\n client: ReviewClient,\n cache: ReviewCache,\n identity: RemoteIdentity | null,\n): ReviewClient {\n return {\n detect: () => client.detect(),\n status: () => client.status(),\n async mergedChangeFor(sha) {\n if (identity === null) return client.mergedChangeFor(sha);\n const key = `${identity.host}/${identity.project}/${sha}`;\n const hit = cache.get(key);\n if (hit !== undefined) return hit;\n const change = await client.mergedChangeFor(sha);\n if (change !== null) cache.set(key, change);\n return change;\n },\n };\n}\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/** A stored change, or `null` when the file does not hold one. */\nfunction readChange(v: unknown): MergedChange | null {\n if (!isRecord(v)) return null;\n const { id, mergedAt, approvals } = v;\n if (typeof id !== \"number\" || typeof mergedAt !== \"string\") return null;\n if (!Array.isArray(approvals)) return null;\n const read: MergedChange[\"approvals\"] = [];\n for (const a of approvals as unknown[]) {\n if (!isRecord(a)) return null;\n if (typeof a.login !== \"string\" || typeof a.submittedAt !== \"string\") return null;\n read.push({ login: a.login, submittedAt: a.submittedAt });\n }\n return { id, mergedAt, approvals: read };\n}\n","/**\n * Derive `owner` from a CODEOWNERS file.\n *\n * Unlike `.gitignore` (see `../gitignore.ts`), CODEOWNERS is matched here\n * rather than by asking a tool. There is no `git check-codeowners`, and the\n * language is the small end of gitignore: GitHub allows no `!` negation and no\n * character ranges, there is one file rather than a stack of nested ones, and\n * the precedence rule is \"last match wins\". That is expressible with\n * picomatch once each pattern is rewritten the way git reads it — a pattern\n * with no slash matches at any depth, a leading `/` anchors it, a trailing\n * `/` names a directory, and any match on a directory covers what is under it.\n *\n * GitLab adds sections. Every section applies, so the owners of a file are the\n * union of the last match in each section; a section may carry default owners\n * for rules that list none, `^[Name]` marks approval optional (the owners are\n * still owners), and `[Name][n]` sets the approvals required. GitHub has no\n * sections, which is the same thing as one unnamed section.\n */\nimport { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, relative, resolve, sep } from \"node:path\";\nimport picomatch from \"picomatch\";\nimport { errorMessage } from \"../../../shared/errors.js\";\nimport type { DerivedValue, SourceStatus } from \"./types.js\";\n\n/** Where a CODEOWNERS file may live, in the order GitHub and GitLab look. */\nexport const CODEOWNERS_LOCATIONS = [\n \".github/CODEOWNERS\",\n \"CODEOWNERS\",\n \"docs/CODEOWNERS\",\n \".gitlab/CODEOWNERS\",\n] as const;\n\nexport interface CodeownersRule {\n pattern: string;\n owners: string[];\n line: number;\n /** The GitLab section the rule sits in; absent in the unnamed default section. */\n section?: string;\n}\n\nexport interface CodeownersSection {\n name: string;\n optional: boolean;\n approvals?: number;\n defaultOwners: string[];\n}\n\nexport interface CodeownersFile {\n path: string;\n /** As the run reports it: forward slashes, relative to the base. */\n label: string;\n rules: CodeownersRule[];\n sections: CodeownersSection[];\n}\n\n/**\n * The first existing location in `CODEOWNERS_LOCATIONS` under `root`, or the\n * explicit path resolved against `root`; null if none exists. An explicit\n * path that is missing is null rather than a fallback to the search, because\n * a config that names a file means that file.\n */\nexport function findCodeowners(root: string, explicit?: string): string | null {\n if (explicit !== undefined) {\n const path = resolve(root, explicit);\n return existsSync(path) ? path : null;\n }\n for (const loc of CODEOWNERS_LOCATIONS) {\n const path = resolve(root, ...loc.split(\"/\"));\n if (existsSync(path)) return path;\n }\n return null;\n}\n\n/** `[Name]`, `^[Name]`, `[Name][2]`, each optionally followed by default owners. */\nconst SECTION_HEADER = /^(\\^?)\\[([^\\]]+)\\](?:\\[(\\d+)\\])?(.*)$/;\n\n/** Tokens split on unescaped whitespace; `\\ ` stays inside its token. */\nconst TOKEN = /(?:\\\\.|[^\\s\\\\])+/g;\n\n/**\n * Parse CODEOWNERS text. Never throws: a line that cannot be read as a rule\n * or a section header (an unclosed `[Name`, say) is skipped, since the host\n * would skip it too and a derived value should not fail the run over it.\n */\nexport function parseCodeowners(\n text: string,\n path: string,\n label: string,\n): CodeownersFile {\n const rules: CodeownersRule[] = [];\n const sections: CodeownersSection[] = [];\n let current: CodeownersSection | undefined;\n\n const lines = text.split(/\\r?\\n/);\n for (let i = 0; i < lines.length; i += 1) {\n const raw = lines[i] ?? \"\";\n const line = raw.trim();\n if (line === \"\" || line.startsWith(\"#\")) continue;\n\n if (line.startsWith(\"[\") || line.startsWith(\"^[\")) {\n const m = SECTION_HEADER.exec(line);\n if (!m) continue;\n const [, caret, rawName, approvals, rest] = m;\n const name = (rawName ?? \"\").trim();\n if (name === \"\") continue;\n const owners = tokens(rest ?? \"\");\n // GitLab merges repeated headers of one section, case-insensitively.\n const existing = sections.find(\n (s) => s.name.toLowerCase() === name.toLowerCase(),\n );\n if (existing) {\n if (owners.length > 0) existing.defaultOwners = owners;\n current = existing;\n continue;\n }\n const section: CodeownersSection = {\n name,\n optional: caret === \"^\",\n ...(approvals !== undefined ? { approvals: Number(approvals) } : {}),\n defaultOwners: owners,\n };\n sections.push(section);\n current = section;\n continue;\n }\n\n const [first, ...owners] = tokens(line);\n if (first === undefined) continue;\n const pattern = unescapePattern(first);\n if (pattern === \"\" || pattern === \"/\") continue;\n rules.push({\n pattern,\n owners,\n line: i + 1,\n ...(current ? { section: current.name } : {}),\n });\n }\n return { path, label, rules, sections };\n}\n\nfunction tokens(s: string): string[] {\n return s.match(TOKEN) ?? [];\n}\n\n/**\n * `\\ ` is a literal space and `\\#` a literal hash at the start; every other\n * escape is left for picomatch, where `\\*` still means a literal star.\n */\nfunction unescapePattern(token: string): string {\n return token.replace(/\\\\ /g, \" \").replace(/^\\\\#/, \"#\");\n}\n\n/**\n * Owners of `relPath` (repository-relative, forward slashes) under `file`,\n * with the line of the last winning rule; null when no rule in any section\n * matches. Within a section the last matching rule wins outright, a winner\n * that lists no owners takes the section's default owners, and a winner with\n * neither means \"no owner\" — a match that clears the field rather than a\n * miss. Across sections the winners' owners are unioned in section order,\n * first appearance kept.\n */\nexport function ownersFor(\n file: CodeownersFile,\n relPath: string,\n): { owners: string[]; line: number } | null {\n const matchers = matchersFor(file);\n const defaults = new Map(file.sections.map((s) => [s.name, s.defaultOwners]));\n\n // Section order is first appearance; the unnamed default section is first.\n const order: (string | undefined)[] = [undefined, ...file.sections.map((s) => s.name)];\n const winners = new Map<string | undefined, CodeownersRule>();\n file.rules.forEach((rule, i) => {\n if (matchers[i]?.(relPath)) winners.set(rule.section, rule);\n });\n if (winners.size === 0) return null;\n\n // The evidence line is the last winner that named an owner, so it points\n // at a rule the reader can see owners on. A winner that names nobody (no\n // owners, no section default) sets the line only when no winner named\n // anyone, which is the \"no owner\" clearing case.\n const owners: string[] = [];\n let line = 0;\n let lineFromOwner = false;\n for (const section of order) {\n const rule = winners.get(section);\n if (!rule) continue;\n const chosen =\n rule.owners.length > 0\n ? rule.owners\n : (section === undefined ? undefined : defaults.get(section)) ?? [];\n if (chosen.length > 0) {\n line = rule.line;\n lineFromOwner = true;\n } else if (!lineFromOwner) {\n line = rule.line;\n }\n for (const o of chosen) if (!owners.includes(o)) owners.push(o);\n }\n return { owners, line };\n}\n\nconst matcherCache = new WeakMap<CodeownersFile, ((p: string) => boolean)[]>();\n\nfunction matchersFor(file: CodeownersFile): ((p: string) => boolean)[] {\n let matchers = matcherCache.get(file);\n if (!matchers) {\n matchers = file.rules.map((r) => picomatch(toGlobs(r.pattern), PICOMATCH));\n matcherCache.set(file, matchers);\n }\n return matchers;\n}\n\n/**\n * `dot` because CODEOWNERS covers `.github/` and friends as a matter of\n * course, and gitignore's `*` never skips dotfiles. `windows: false` pins\n * posix semantics on every platform: the paths handed in are already\n * forward-slashed, and letting picomatch treat `\\` as a separator on Windows\n * would silently change what a `\\*` escape in the file means there.\n */\nconst PICOMATCH = { dot: true, windows: false } as const;\n\n/**\n * Rewrite one CODEOWNERS pattern into the picomatch globs that read it the\n * way git does. A pattern with no slash (or only a trailing one) matches at\n * any depth, so it gets a globstar-and-slash prefix; a leading `/` or a slash\n * in the middle anchors it to the root. A match on a directory covers\n * everything under it, so a second glob with a slash-and-globstar suffix is\n * included when the last segment is a literal name that could be one; a\n * trailing `/` means *only* a directory, so the bare pattern is then left\n * out. A last segment with a wildcard gets no twin: GitHub reads `docs/*`\n * as the files directly in `docs/`, not `docs/build-app/troubleshooting.md`,\n * and `*.md` already reaches any depth through its globstar prefix.\n */\nfunction toGlobs(pattern: string): string[] {\n let p = pattern;\n const dirOnly = p.endsWith(\"/\");\n if (dirOnly) p = p.slice(0, -1);\n let anchored = false;\n if (p.startsWith(\"/\")) {\n anchored = true;\n p = p.slice(1);\n } else if (p.includes(\"/\") && !p.startsWith(\"**/\")) {\n anchored = true;\n }\n const base = anchored || p.startsWith(\"**/\") ? p : `**/${p}`;\n if (dirOnly) return [`${base}/**`];\n const last = p.slice(p.lastIndexOf(\"/\") + 1);\n return /[*?[]/.test(last) ? [base] : [base, `${base}/**`];\n}\n\nexport interface CodeownersSourceOptions {\n /** Explicit path from config `derive.codeowners`, resolved against `configDir`. */\n explicit?: string;\n configDir?: string;\n /** Repository root for an input's absolute path; null when outside a repository. */\n rootOf: (absPath: string) => string | null;\n}\n\nexport interface CodeownersSourceResult {\n status: SourceStatus;\n /** Keyed by label; an input outside any repository is absent. */\n records: Map<string, DerivedValue | null>;\n}\n\nconst NOT_FOUND_REASON = `no CODEOWNERS file found (looked for ${CODEOWNERS_LOCATIONS.join(\", \")})`;\n\n/**\n * Derive owners for every input that sits in a repository. Inputs are grouped\n * by root and each root resolves its own file — the explicit path when the\n * config names one, otherwise the first location found under that root.\n *\n * A root with no file yields null records, and so does a run where no root\n * has one: a repository that declares no owners is a fact, not a broken\n * source, so the status stays available and carries the search as a\n * `reason` for the caller to surface as a notice. Only an explicit\n * `derive.codeowners` path that does not exist is unavailable — a configured\n * file that is missing is the operator's error, and silently answering null\n * there would be the green gate over nothing that the channel refuses.\n */\nexport async function deriveFromCodeowners(\n inputs: readonly { label: string; absPath: string }[],\n opts: CodeownersSourceOptions,\n): Promise<CodeownersSourceResult> {\n const records = new Map<string, DerivedValue | null>();\n\n const explicitPath =\n opts.explicit === undefined\n ? undefined\n : resolve(opts.configDir ?? process.cwd(), opts.explicit);\n if (explicitPath !== undefined && !existsSync(explicitPath)) {\n return {\n status: { available: false, reason: `CODEOWNERS not found at ${explicitPath}` },\n records,\n };\n }\n\n const byRoot = new Map<string, { label: string; absPath: string }[]>();\n const rootCache = new Map<string, string | null>();\n for (const input of inputs) {\n // Keyed by directory: every file in one directory shares its repository.\n const dir = dirname(input.absPath);\n let root = rootCache.get(dir);\n if (root === undefined) {\n root = opts.rootOf(input.absPath);\n rootCache.set(dir, root);\n }\n if (root === null) continue;\n const bucket = byRoot.get(root);\n if (bucket) bucket.push(input);\n else byRoot.set(root, [input]);\n }\n\n let found = 0;\n const parsed = new Map<string, Promise<CodeownersFile>>();\n for (const [root, bucket] of byRoot) {\n const path = explicitPath ?? findCodeowners(root);\n if (path === null) {\n for (const input of bucket) records.set(input.label, null);\n continue;\n }\n found += 1;\n const label = toPosix(relative(opts.configDir ?? root, path));\n const key = `${path}\\0${label}`;\n let file = parsed.get(key);\n if (!file) {\n file = readFile(path, \"utf8\").then((text) =>\n parseCodeowners(text, path, label),\n );\n parsed.set(key, file);\n }\n let owners: CodeownersFile;\n try {\n owners = await file;\n } catch (err) {\n // It was there a moment ago: deleted since, or not a readable file at\n // all. A source that cannot answer says so. It never crashes the run,\n // and it never answers \"nobody owns this\".\n return {\n status: {\n available: false,\n reason: `CODEOWNERS at ${label} could not be read: ${errorMessage(err)}`,\n },\n records,\n };\n }\n for (const input of bucket) {\n const rel = toPosix(relative(root, input.absPath));\n const hit = ownersFor(owners, rel);\n records.set(\n input.label,\n hit === null\n ? null\n : {\n value: hit.owners,\n source: \"codeowners\",\n evidence: `${label}:${hit.line}`,\n },\n );\n }\n }\n\n if (byRoot.size === 0) {\n return {\n status: { available: false, reason: \"no git repository contains the documents\" },\n records,\n };\n }\n if (found === 0 && explicitPath === undefined) {\n return { status: { available: true, reason: NOT_FOUND_REASON }, records };\n }\n return { status: { available: true }, records };\n}\n\nfunction toPosix(p: string): string {\n return p.split(sep).join(\"/\");\n}\n","/**\n * One child process, run to completion: stdout collected, stderr drained and\n * kept for the message, a timer that kills it. The review sources reach `gh`\n * and `glab` through this, and the `command` source reaches whatever the\n * config names; neither holds a token or opens a socket of its own.\n */\nimport { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\n\n/** How a client reaches the binary; tests point `bin` at node and a fake script. */\nexport interface SpawnOptions {\n /** Defaults to `gh` / `glab`, resolved on PATH. */\n bin?: string;\n /** Arguments placed before the command's own, such as a script for `node`. */\n prefixArgs?: string[];\n cwd: string;\n /** Kill the child after this long. Default 30 s. */\n timeoutMs?: number;\n}\n\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * How much of a child's output is kept, per stream. `gh` and `glab` answer\n * in JSON a page at a time, and a configured command reports one field's\n * value, so a stream past this is a program doing something else — `cat` on\n * the wrong file — and reading it to the end would trade the run's memory\n * for output nobody wants. The git walk caps itself the same way.\n */\nexport const MAX_OUTPUT_BYTES = 8 * 1024 * 1024;\n\nexport interface Run {\n /** Exit code; `null` when a signal ended the child. */\n code: number | null;\n stdout: string;\n stderr: string;\n timedOut: boolean;\n /** A stream passed `MAX_OUTPUT_BYTES` and the child was killed. */\n tooLarge: boolean;\n}\n\n/** The binary could not be started at all: nothing on PATH by that name. */\nexport class BinMissing extends Error {}\n\n/** One child, stdout collected, stderr drained and kept for the message. */\nexport function run(bin: string, args: string[], opts: SpawnOptions): Promise<Run> {\n return new Promise((settle, reject) => {\n let done = false;\n const finish = (r: Run): void => {\n if (done) return;\n done = true;\n settle(r);\n };\n const fail = (err: Error): void => {\n if (done) return;\n done = true;\n reject(err);\n };\n\n let child: ChildProcessWithoutNullStreams;\n try {\n child = spawn(bin, [...(opts.prefixArgs ?? []), ...args], {\n cwd: opts.cwd,\n windowsHide: true,\n });\n } catch (err) {\n fail(err instanceof Error ? err : new Error(String(err)));\n return;\n }\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let tooLarge = false;\n\n /**\n * Stop the child for good. `kill()` is SIGTERM, which a program may\n * trap, and `close` waits for the stdio streams as well as the exit —\n * a grandchild holding stdout keeps it pending. So the promise settles\n * here rather than waiting, and SIGKILL follows shortly after.\n *\n * `timer` is cleared here rather than left to `close`, for the same\n * reason: `close` is exactly the event this function refuses to wait\n * for. `clearTimeout` is idempotent, so the `close` handler may still\n * call it. The SIGKILL timer is deliberately not cleared — it is the\n * escalation, and it has to fire.\n *\n * `timer` is declared below this closure, so every caller must reach\n * `stop` from an async handler, as all of them do. Calling it straight\n * from the spawn path would hit the temporal dead zone.\n */\n const stop = (r: Omit<Run, \"code\">): void => {\n clearTimeout(timer);\n child.kill();\n setTimeout(() => child.kill(\"SIGKILL\"), 1_000).unref();\n finish({ code: null, ...r });\n };\n\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdout += chunk;\n if (stdout.length > MAX_OUTPUT_BYTES) {\n tooLarge = true;\n stop({ stdout, stderr, timedOut, tooLarge });\n }\n });\n // Drained *and* kept: a chatty CLI must not stall the pipe, and its last\n // line is what names the failure to the user.\n child.stderr.setEncoding(\"utf8\");\n child.stderr.on(\"data\", (chunk: string) => {\n stderr += chunk;\n if (stderr.length > MAX_OUTPUT_BYTES) {\n tooLarge = true;\n stop({ stdout, stderr, timedOut, tooLarge });\n }\n });\n child.stdin.end();\n\n const timer = setTimeout(() => {\n timedOut = true;\n stop({ stdout, stderr, timedOut, tooLarge });\n }, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n\n // No binary on PATH lands here rather than throwing from spawn().\n child.on(\"error\", (err: NodeJS.ErrnoException) => {\n clearTimeout(timer);\n fail(err.code === \"ENOENT\" ? new BinMissing(err.message) : err);\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n finish({ code, stdout, stderr, timedOut, tooLarge });\n });\n });\n}\n\n/** `gh api --hostname h repos/…`: the command as the user would type it. */\nexport function commandLine(bin: string, args: readonly string[]): string {\n return [bin, ...args].join(\" \");\n}\n\nexport function lastLine(text: string): string {\n const lines = text.split(/\\r?\\n/).filter((l) => l.trim() !== \"\");\n return lines.at(-1) ?? \"\";\n}\n","/**\n * The `command` source: a field derived by running whatever `derive.commands`\n * names for it. The value is the program's stdout — JSON when it parses as\n * JSON, the trimmed text otherwise, `null` when there is none.\n *\n * A command is spawned once per run, and its value copied into every\n * document's record, unless its argv carries `{path}`, in which case it is\n * spawned once per document with the document's label in place. The argv is\n * never handed to a shell: what the config lists is what runs.\n *\n * The first failure ends the source for the whole run, with nothing further\n * spawned: a program that is not on PATH, a timeout, a non-zero exit. A\n * half-derived field would read as \"the command said nothing\" for the\n * documents it never reached, which is the false green the whole channel\n * refuses. Availability is reported, never thrown, as the other sources do.\n */\nimport {\n BinMissing,\n MAX_OUTPUT_BYTES,\n lastLine,\n run,\n type Run,\n type SpawnOptions,\n} from \"./spawn.js\";\nimport { errorMessage } from \"../../../shared/errors.js\";\nimport type { DerivedValue, DeriveCommand, DeriveInput, SourceStatus } from \"./types.js\";\n\n/** The argv token a per-file command carries where the document's label goes. */\nexport const PATH_PLACEHOLDER = \"{path}\";\n\nexport interface CommandSourceOptions {\n /** Where the commands run: the config directory, else the run cwd. */\n cwd: string;\n /** Test seam: `bin` and `prefixArgs` replace the configured program. */\n spawn?: Partial<SpawnOptions>;\n}\n\nexport interface CommandSourceResult {\n status: SourceStatus;\n /** By label; every input present when available, keyed by field within. */\n records: Map<string, Record<string, DerivedValue | null>>;\n}\n\n/** Whether any argv element carries `{path}`, so the command runs once per document. */\nexport function isPerFile(command: DeriveCommand): boolean {\n return command.run.some((arg) => arg.includes(PATH_PLACEHOLDER));\n}\n\n/** The argv with every `{path}` replaced by the label, forward slashes as the run spells it. */\nexport function argvFor(command: DeriveCommand, label: string): string[] {\n return command.run.map((arg) => arg.split(PATH_PLACEHOLDER).join(label));\n}\n\n/**\n * What a command's stdout means: nothing when blank, the parsed value when it\n * is *structured* JSON, the trimmed text otherwise. A date or a version string\n * stays a string; a list or an object arrives as one.\n *\n * Only `{`, `[` and `\"` open a parse, and that boundary is the whole point.\n * A bare scalar is text a person wrote, and reading it as JSON silently\n * rewrites it: `1.10` becomes the number `1.1`, so a command reporting\n * version 1.10 stamps 1.1 into the document. A field wants the characters\n * the command printed. The structured forms are the reason a parse exists at\n * all — `verified-against` takes an object, and a list of anchors is a list —\n * and neither of those can be confused with prose.\n */\nexport function valueOf(stdout: string): unknown {\n const text = stdout.trim();\n if (text === \"\") return null;\n if (!/^[{[\"]/.test(text)) return text;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n}\n\nexport async function deriveFromCommands(\n inputs: readonly DeriveInput[],\n commands: Readonly<Record<string, DeriveCommand>>,\n opts: CommandSourceOptions,\n): Promise<CommandSourceResult> {\n const records = new Map<string, Record<string, DerivedValue | null>>();\n const fields = Object.keys(commands);\n if (fields.length === 0 || inputs.length === 0) {\n return { status: { available: true }, records };\n }\n for (const input of inputs) records.set(input.label, {});\n\n for (const field of fields) {\n const command = commands[field];\n if (command === undefined) continue;\n if (isPerFile(command)) {\n for (const [label, record] of records) {\n const outcome = await runOne(field, argvFor(command, label), command.timeoutMs, opts);\n if (\"reason\" in outcome) return unavailable(outcome.reason);\n record[field] = outcome.value;\n }\n } else {\n const outcome = await runOne(field, command.run, command.timeoutMs, opts);\n if (\"reason\" in outcome) return unavailable(outcome.reason);\n for (const record of records.values()) record[field] = outcome.value;\n }\n }\n return { status: { available: true }, records };\n}\n\nfunction unavailable(reason: string): CommandSourceResult {\n return { status: { available: false, reason }, records: new Map() };\n}\n\ntype Outcome = { value: DerivedValue | null } | { reason: string };\n\n/** One spawn, with every failure turned into the reason the status carries. */\nasync function runOne(\n field: string,\n argv: readonly string[],\n timeoutMs: number,\n opts: CommandSourceOptions,\n): Promise<Outcome> {\n const [program, ...args] = argv;\n const where = `(derive.commands.${field})`;\n if (program === undefined) {\n return { reason: `no program to run ${where}` };\n }\n const line = argv.join(\" \");\n let result: Run;\n try {\n result = await run(opts.spawn?.bin ?? program, args, {\n ...opts.spawn,\n cwd: opts.spawn?.cwd ?? opts.cwd,\n timeoutMs,\n });\n } catch (err) {\n if (err instanceof BinMissing) {\n return { reason: `\\`${program}\\` is not on PATH ${where}` };\n }\n return { reason: `\\`${line}\\` could not be run: ${errorMessage(err)} ${where}` };\n }\n if (result.timedOut) {\n return { reason: `\\`${line}\\` timed out after ${String(timeoutMs / 1000)}s ${where}` };\n }\n if (result.tooLarge) {\n return {\n reason: `\\`${line}\\` wrote more than ${String(MAX_OUTPUT_BYTES / (1024 * 1024))} MiB; a command reports one field's value ${where}`,\n };\n }\n if (result.code !== 0) {\n const last = lastLine(result.stderr);\n const detail = last === \"\" ? \"no output on stderr\" : last;\n const exit = result.code === null ? \"killed by a signal\" : `exit ${String(result.code)}`;\n return { reason: `\\`${line}\\` failed (${exit}): ${detail} ${where}` };\n }\n const value = valueOf(result.stdout);\n return { value: value === null ? null : { value, source: \"command\", evidence: line } };\n}\n","/**\n * The review sources, `github` and `gitlab`: `reviewed-by` and `last-reviewed` from the pull request\n * or merge request that merged a document's newest body-changing commit.\n *\n * Reached through `gh` or `glab`, never an HTTP client. The facts sit behind\n * two vendors' auth stores and two API grammars, and the vendor CLI is the\n * trust boundary: manni never holds a token, never reads one, never prints\n * one. `gh` is on every GitHub-hosted runner and `glab` is one package\n * install on GitLab's (proposal 0040, decision 7).\n *\n * Two answers are deliberately *not* errors. A commit the host has no merged\n * change for (an open PR, a direct push, a commit that came in through\n * another repository) is `null`. A commit the host does not know at all is\n * `null` too. Everything else that goes wrong — a non-zero exit, a timeout,\n * an answer that is not JSON — throws `DocmetaError`, because a half-answer\n * read as \"no approvals\" would file a stale finding against a document that\n * was in fact reviewed.\n */\nimport { resolve as resolvePath } from \"node:path\";\nimport { DocmetaError } from \"../../types.js\";\nimport { ReviewCache, cachedClient } from \"./cache.js\";\nimport {\n BinMissing,\n DEFAULT_TIMEOUT_MS,\n commandLine,\n lastLine,\n run,\n type Run,\n type SpawnOptions,\n} from \"./spawn.js\";\nimport type {\n Approval,\n DerivedValue,\n ReviewClient,\n RemoteIdentity,\n MergedChange,\n SourceStatus,\n} from \"./types.js\";\n\nexport type { Approval, ReviewClient, RemoteIdentity, MergedChange } from \"./types.js\";\nexport type { SpawnOptions } from \"./spawn.js\";\n\n// ---------------------------------------------------------------------------\n// Origin → identity\n\n/**\n * The host and project an origin URL names, for the three spellings git\n * writes: `git@host:owner/repo.git`, `https://[user@]host/owner/repo[.git]`,\n * `ssh://git@host[:port]/owner/repo`. The project keeps every path segment,\n * because a GitLab namespace can nest (`group/sub/repo`). Anything else —\n * a local path, a bare host — is `null`. A local path is recognised before\n * the scp form is tried, because git reads `C:/mirrors/repo.git` as a\n * directory on drive C and the scp regex would read it as host `C`.\n */\nexport function parseOriginUrl(\n url: string,\n): { host: string; project: string } | null {\n const trimmed = url.trim();\n if (trimmed === \"\") return null;\n if (isLocalPath(trimmed)) return null;\n\n const scp = /^(?:[^@/:]+@)?([^/:]+):(?!\\/\\/)(.+)$/.exec(trimmed);\n if (scp) {\n const host = scp[1];\n const path = scp[2];\n if (host === undefined || path === undefined) return null;\n // A one-letter \"host\" is a DOS drive, whichever slash follows it.\n if (/^[A-Za-z]$/.test(host)) return null;\n return project(host, path);\n }\n\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n return null;\n }\n if (!/^(https?|ssh|git):$/.test(parsed.protocol)) return null;\n if (parsed.hostname === \"\") return null;\n return project(parsed.hostname, parsed.pathname);\n}\n\n/** Absolute, relative, or UNC: the spellings of a path that is not a URL. */\nfunction isLocalPath(s: string): boolean {\n return s.startsWith(\"/\") || s.startsWith(\"./\") || s.startsWith(\"../\") || s.startsWith(\"\\\\\\\\\");\n}\n\nfunction project(\n host: string,\n path: string,\n): { host: string; project: string } | null {\n const segments = path\n .replace(/\\.git$/, \"\")\n .split(\"/\")\n .filter((s) => s !== \"\");\n if (segments.length < 2) return null;\n return { host, project: segments.join(\"/\") };\n}\n\n/**\n * Which platform a host is, and so which CLI reaches it. A host whose name\n * says `github` (github.com, github.example.com) is GitHub; one that says\n * `gitlab` is GitLab. A host that says neither, such as `git.example.com`,\n * is decided by the config: when exactly one of the `github` and `gitlab`\n * sources is requested, that is the platform the operator named. Otherwise\n * the answer is null, and the caller reports it as a source that cannot\n * answer. Nothing is ever assumed: the `github` source applies to GitHub\n * and the `gitlab` source to GitLab, and neither stands in for the other.\n */\nexport function identityFromOrigin(\n host: string,\n project: string,\n requested?: readonly RemoteIdentity[\"kind\"][],\n): RemoteIdentity | null {\n const name = host.toLowerCase();\n if (name.includes(\"github\")) return { kind: \"github\", host, project };\n if (name.includes(\"gitlab\")) return { kind: \"gitlab\", host, project };\n const only = requested !== undefined && requested.length === 1 ? requested[0] : undefined;\n return only === undefined ? null : { kind: only, host, project };\n}\n\n/**\n * A client for an origin whose host names neither platform and whose config\n * does not say which it is. It answers nothing, and its status names the fix.\n */\nclass UnknownHostClient implements ReviewClient {\n constructor(private readonly host: string) {}\n detect(): Promise<RemoteIdentity | null> {\n return Promise.resolve(null);\n }\n status(): Promise<SourceStatus> {\n return Promise.resolve({\n available: false,\n reason: `the origin remote is ${this.host}, which names neither GitHub nor GitLab; list exactly one of github, gitlab in derive.sources to say which it is`,\n });\n }\n mergedChangeFor(): Promise<MergedChange | null> {\n return Promise.resolve(null);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Failure reading\n\n/** The HTTP status a `gh`/`glab` failure line carries, when it carries one. */\nfunction httpStatus(stderr: string): number | null {\n const m = /\\b(?:HTTP\\s+(\\d{3})|(\\d{3})\\s+Not\\s+Found)\\b/i.exec(stderr);\n const code = m?.[1] ?? m?.[2];\n return code === undefined ? null : Number(code);\n}\n\n/**\n * Whether a failed call is the host saying \"no such thing\" — a commit it\n * does not know (404, or GitHub's 422 \"No commit found for SHA\") — which is\n * an answer, not an error.\n */\nfunction isNotFound(r: Run): boolean {\n const status = httpStatus(r.stderr);\n return status === 404 || status === 422;\n}\n\n/**\n * The base for both CLIs: the same spawn, the same failure ladder, the same\n * status vocabulary. Subclasses supply the binary name and the lookups.\n */\nabstract class CliClient implements ReviewClient {\n protected abstract readonly tool: \"gh\" | \"glab\";\n\n constructor(\n protected readonly identity: RemoteIdentity | null,\n protected readonly spawnOpts: SpawnOptions,\n ) {}\n\n detect(): Promise<RemoteIdentity | null> {\n return Promise.resolve(this.identity);\n }\n\n async status(): Promise<SourceStatus> {\n if (this.identity === null) {\n return { available: false, reason: \"no origin remote to tell GitHub from GitLab\" };\n }\n const { host } = this.identity;\n let r: Run;\n try {\n r = await this.run([\"auth\", \"status\", \"--hostname\", host]);\n } catch (err) {\n if (err instanceof BinMissing) {\n return {\n available: false,\n reason: `${this.tool} is not on PATH (origin is ${host}); install ${this.tool} and run ${this.tool} auth login`,\n };\n }\n throw err;\n }\n if (r.timedOut) throw this.timeout([\"auth\", \"status\", \"--hostname\", host]);\n if (r.code !== 0) {\n return {\n available: false,\n reason: `${this.tool} is not authenticated for ${host}; run ${this.tool} auth login`,\n };\n }\n return { available: true };\n }\n\n async mergedChangeFor(sha: string): Promise<MergedChange | null> {\n if (this.identity === null) return null;\n return this.lookup(this.identity, sha);\n }\n\n protected abstract lookup(\n identity: RemoteIdentity,\n sha: string,\n ): Promise<MergedChange | null>;\n\n protected get bin(): string {\n return this.spawnOpts.bin ?? this.tool;\n }\n\n protected run(args: string[]): Promise<Run> {\n return run(this.bin, args, this.spawnOpts);\n }\n\n private timeout(args: string[]): DocmetaError {\n const ms = this.spawnOpts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n return new DocmetaError(\n `${commandLine(this.tool, args)} timed out after ${ms}ms`,\n );\n }\n\n /**\n * Run a call whose stdout is JSON. A not-found answer is `null`; any other\n * failure throws, naming the command the user can re-run by hand. The\n * message quotes the tool's own name rather than `bin`, which under test\n * is `node`.\n */\n protected async json(args: string[]): Promise<unknown> {\n let r: Run;\n try {\n r = await this.run(args);\n } catch (err) {\n if (err instanceof BinMissing) {\n throw new DocmetaError(\n `${commandLine(this.tool, args)} failed: ${this.tool} is not on PATH`,\n );\n }\n throw err;\n }\n const cmd = commandLine(this.tool, args);\n if (r.timedOut) throw this.timeout(args);\n // A truncated answer must not be read as the whole one: half a page of\n // reviews would file a stale finding against a document that was\n // reviewed, which is the half-answer this class refuses everywhere.\n if (r.tooLarge) {\n throw new DocmetaError(`${cmd} wrote more output than manni will read`);\n }\n if (r.code !== 0) {\n if (isNotFound(r)) return null;\n const detail = lastLine(r.stderr) || lastLine(r.stdout);\n const exit = r.code === null ? \"signal\" : `exit ${r.code}`;\n throw new DocmetaError(\n `${cmd} failed (${exit})${detail === \"\" ? \"\" : `: ${detail}`}`,\n );\n }\n try {\n return JSON.parse(r.stdout) as unknown;\n } catch {\n throw new DocmetaError(`${cmd} did not return JSON`);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Answer shapes, read defensively\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction items(v: unknown): Record<string, unknown>[] {\n return Array.isArray(v) ? v.filter(isRecord) : [];\n}\n\nfunction numberOf(v: unknown): number | null {\n return typeof v === \"number\" && Number.isInteger(v) ? v : null;\n}\n\nfunction stringOf(v: unknown): string | null {\n return typeof v === \"string\" && v !== \"\" ? v : null;\n}\n\n/** A field that is present and a string, present and null, or absent. */\ntype Tri = string | null | undefined;\n\nfunction timestampOf(v: unknown): Tri {\n if (v === undefined) return undefined;\n return stringOf(v);\n}\n\n/**\n * `claude[bot]` (REST) and `claude` (GraphQL) are one reviewer. The stripped\n * form is the dedupe key; the value keeps whichever spelling the latest\n * approval carried.\n */\nfunction normalizeLogin(login: string): string {\n return login.replace(/\\[bot\\]$/, \"\");\n}\n\n/** `APPROVED` only, the latest per reviewer, oldest approval first. */\nfunction latestApprovals(\n reviews: readonly { login: string; state: string; submittedAt: string }[],\n): Approval[] {\n const latest = new Map<string, Approval>();\n for (const r of reviews) {\n if (r.state !== \"APPROVED\") continue;\n const key = normalizeLogin(r.login);\n const seen = latest.get(key);\n if (seen === undefined || r.submittedAt > seen.submittedAt) {\n latest.set(key, { login: r.login, submittedAt: r.submittedAt });\n }\n }\n return byTime([...latest.values()]);\n}\n\nfunction byTime(approvals: readonly Approval[]): Approval[] {\n return [...approvals].sort((a, b) =>\n a.submittedAt < b.submittedAt ? -1 : a.submittedAt > b.submittedAt ? 1 : 0,\n );\n}\n\n// ---------------------------------------------------------------------------\n// GitHub\n\n/**\n * GitHub through `gh`. Every call carries `--hostname` (or `-R host/project`)\n * so a GHES origin is reached even when `gh`'s default host is github.com.\n *\n * - `gh api --hostname <host> repos/<project>/commits/<sha>/pulls`\n * - if empty: `gh pr list --search <sha> --state merged --json number,mergedAt -R <host>/<project>`\n * (a squash-merged commit's original sha is only findable through search,\n * and a commit that came in through another repository is `[]` here, which\n * is a legitimate non-error)\n * - `gh api --hostname <host> repos/<project>/pulls/<n>` only when the list\n * item does not say whether it merged\n * - `gh api --hostname <host> repos/<project>/pulls/<n>/reviews?per_page=100`\n */\nexport class GitHubClient extends CliClient {\n protected readonly tool = \"gh\";\n\n protected async lookup(\n identity: RemoteIdentity,\n sha: string,\n ): Promise<MergedChange | null> {\n const { host, project } = identity;\n const api = (endpoint: string): Promise<unknown> =>\n this.json([\"api\", \"--hostname\", host, endpoint]);\n\n let candidates = items(await api(`repos/${project}/commits/${sha}/pulls`)).map(\n (p) => ({ number: numberOf(p.number), mergedAt: timestampOf(p.merged_at) }),\n );\n if (candidates.length === 0) {\n const found = await this.json([\n \"pr\", \"list\", \"--search\", sha, \"--state\", \"merged\",\n \"--json\", \"number,mergedAt\", \"-R\", `${host}/${project}`,\n ]);\n candidates = items(found).map((p) => ({\n number: numberOf(p.number),\n mergedAt: timestampOf(p.mergedAt),\n }));\n }\n\n for (const c of candidates) {\n if (c.number === null) continue;\n let mergedAt = c.mergedAt;\n if (mergedAt === undefined) {\n const pr = await api(`repos/${project}/pulls/${c.number}`);\n mergedAt = isRecord(pr) ? (stringOf(pr.merged_at) ?? null) : null;\n }\n if (mergedAt === null) continue;\n\n // The reviews endpoint lists oldest first, 100 per page, with no sort\n // parameter, so a long-lived PR's latest approvals sit past the first\n // page. Walk pages until one comes back short.\n const raw: Record<string, unknown>[] = [];\n for (let page = 1; ; page += 1) {\n const batch = items(\n await api(`repos/${project}/pulls/${c.number}/reviews?per_page=100&page=${page}`),\n );\n raw.push(...batch);\n if (batch.length < 100) break;\n }\n const reviews = raw\n .map((r) => ({\n login: isRecord(r.user) ? stringOf(r.user.login) : null,\n state: stringOf(r.state),\n submittedAt: stringOf(r.submitted_at),\n }))\n .filter(\n (r): r is { login: string; state: string; submittedAt: string } =>\n r.login !== null && r.state !== null && r.submittedAt !== null,\n );\n return { id: c.number, mergedAt, approvals: latestApprovals(reviews) };\n }\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// GitLab\n\n/**\n * GitLab through `glab`. `:fullpath` is substituted by glab from the current\n * repository, which is why the client runs from the checkout.\n *\n * - `glab api --hostname <host> projects/:fullpath/repository/commits/<sha>/merge_requests`\n * - `glab api --hostname <host> projects/:fullpath/merge_requests/<iid>/approvals`\n *\n * GitLab records who approved but not when, so every approval is stamped\n * with the MR's `merged_at`; `deriveFromReviews` says so in the evidence.\n */\nexport class GitLabClient extends CliClient {\n protected readonly tool = \"glab\";\n\n protected async lookup(\n identity: RemoteIdentity,\n sha: string,\n ): Promise<MergedChange | null> {\n const { host } = identity;\n const api = (endpoint: string): Promise<unknown> =>\n this.json([\"api\", \"--hostname\", host, endpoint]);\n\n const merged = items(\n await api(`projects/:fullpath/repository/commits/${sha}/merge_requests`),\n )\n .map((mr) => ({ iid: numberOf(mr.iid), mergedAt: stringOf(mr.merged_at) }))\n .find(\n (mr): mr is { iid: number; mergedAt: string } =>\n mr.iid !== null && mr.mergedAt !== null,\n );\n if (merged === undefined) return null;\n\n const answer = await api(`projects/:fullpath/merge_requests/${merged.iid}/approvals`);\n const approvedBy = isRecord(answer) ? items(answer.approved_by) : [];\n const approvals: Approval[] = [];\n const seen = new Set<string>();\n for (const entry of approvedBy) {\n const login = isRecord(entry.user) ? stringOf(entry.user.username) : null;\n if (login === null) continue;\n const key = normalizeLogin(login);\n if (seen.has(key)) continue;\n seen.add(key);\n approvals.push({ login, submittedAt: merged.mergedAt });\n }\n return { id: merged.iid, mergedAt: merged.mergedAt, approvals };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Assembly\n\n/**\n * The client for the repository at `root`: origin read with\n * `git remote get-url origin`, the CLI chosen by `identityFromOrigin`, the\n * result wrapped in the on-disk cache. No origin (or no git) yields a client\n * whose `status()` says so; nothing throws here, because \"no host\" is a\n * source being unavailable, and that is reported where sources are reported.\n *\n * The CLI is spawned in `root`, not in the caller's `cwd`: `glab` fills in\n * `:fullpath` from the repository it runs in, and `gh` detects the\n * repository the same way, so the child must run from the checkout this\n * client answers for. `spawn.cwd` is the test seam that overrides that.\n */\nexport async function createReviewClient(\n root: string,\n opts: {\n cwd: string;\n cache: boolean;\n cacheDir: string;\n spawn?: Partial<SpawnOptions>;\n /** The review sources the run requested; decides a host that names neither platform. */\n requested?: readonly RemoteIdentity[\"kind\"][];\n },\n): Promise<ReviewClient> {\n const spawnOpts: SpawnOptions = { ...opts.spawn, cwd: opts.spawn?.cwd ?? root };\n const origin = await originUrl(root);\n const parsed = origin === null ? null : parseOriginUrl(origin);\n const identity =\n parsed === null ? null : identityFromOrigin(parsed.host, parsed.project, opts.requested);\n if (parsed !== null && identity === null) return new UnknownHostClient(parsed.host);\n const client =\n identity?.kind === \"gitlab\"\n ? new GitLabClient(identity, spawnOpts)\n : new GitHubClient(identity, spawnOpts);\n const cache = new ReviewCache(resolvePath(root, opts.cacheDir), opts.cache);\n return cachedClient(client, cache, identity);\n}\n\n/** `git remote get-url origin`, or null when there is no origin or no git. */\nasync function originUrl(root: string): Promise<string | null> {\n try {\n const r = await run(\"git\", [\"remote\", \"get-url\", \"origin\"], { cwd: root });\n if (r.code !== 0 || r.timedOut || r.tooLarge) return null;\n return stringOf(r.stdout.trim());\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// The source\n\nexport interface ReviewSourceInput {\n label: string;\n /** The newest body-changing commit; `null` for a working-tree document. */\n sha: string | null;\n}\n\nexport interface ReviewFacts {\n \"reviewed-by\": DerivedValue | null;\n \"last-reviewed\": DerivedValue | null;\n}\n\nexport interface ReviewSourceResult {\n status: SourceStatus;\n /** By label. Empty when the source is unavailable. */\n records: Map<string, ReviewFacts>;\n}\n\nconst NOTHING: ReviewFacts = { \"reviewed-by\": null, \"last-reviewed\": null };\n\n/**\n * `reviewed-by` is every approver of the merged change, in approval order,\n * and every fact names the source of the host it came from, `github` or `gitlab`;\n * `last-reviewed` is the UTC date of the latest approval. A document with no\n * commit, no merged change, or a change nobody approved derives `null` for\n * both. One host lookup per distinct sha, however many documents share it.\n *\n * An unavailable client is reported and never called: `status.reason` names\n * the fix, and the caller decides whether that fails the run.\n */\nexport async function deriveFromReviews(\n inputs: readonly ReviewSourceInput[],\n client: ReviewClient,\n): Promise<ReviewSourceResult> {\n const records = new Map<string, ReviewFacts>();\n const status = await client.status();\n if (!status.available) return { status, records };\n\n const identity = await client.detect();\n // `status()` answering `available` means the client found its host, so both\n // built-in clients return an identity here. The fallback serves only a\n // custom `ReviewClient` that breaks that promise, and it attributes every\n // fact to GitHub. Such a client should return an identity from `detect()`.\n const kind = identity?.kind ?? \"github\";\n const bySha = new Map<string, Promise<MergedChange | null>>();\n const changeFor = (sha: string): Promise<MergedChange | null> => {\n let pending = bySha.get(sha);\n if (pending === undefined) {\n pending = client.mergedChangeFor(sha);\n bySha.set(sha, pending);\n }\n return pending;\n };\n\n for (const input of inputs) {\n if (input.sha === null) {\n records.set(input.label, NOTHING);\n continue;\n }\n const change = await changeFor(input.sha);\n records.set(input.label, factsFrom(change, kind));\n }\n return { status, records };\n}\n\nfunction factsFrom(change: MergedChange | null, kind: RemoteIdentity[\"kind\"]): ReviewFacts {\n if (change === null || change.approvals.length === 0) return NOTHING;\n // Sorted here too: a `ReviewClient` from outside this module makes no\n // ordering promise, and the field order is what the reader sees.\n const ordered = byTime(change.approvals);\n const latest = ordered.at(-1);\n if (latest === undefined) return NOTHING;\n const evidence = kind === \"gitlab\" ? `gitlab MR !${change.id}` : `github PR #${change.id}`;\n const dateEvidence =\n kind === \"gitlab\"\n ? `${evidence} (merge date; GitLab records no approval time)`\n : evidence;\n return {\n \"reviewed-by\": {\n value: ordered.map((a) => a.login),\n source: kind,\n evidence,\n },\n \"last-reviewed\": {\n value: utcDate(latest.submittedAt),\n source: kind,\n evidence: dateEvidence,\n },\n };\n}\n\n/** `YYYY-MM-DD` in UTC; the timestamp's own text when it does not parse. */\nfunction utcDate(iso: string): string {\n const ms = Date.parse(iso);\n if (Number.isNaN(ms)) return iso;\n return new Date(ms).toISOString().slice(0, 10);\n}\n","/**\n * The git source of the derived channel (proposal 0040): what history can\n * state about a document's birth, its last body change, who wrote it and who\n * reviewed it.\n *\n * Documents are grouped by the repository that contains them, as\n * `gitignore.ts` groups candidates, and each root is asked once. A root's\n * history is read in one of two forms that produce the same `FileHistory`:\n * one `git log -- <path>` a lineage for a small run, and one\n * whole-repository `git log --raw -M` walk otherwise. A rename is a path\n * that disappears in the commit that adds the new one, as plain `-M` pairs\n * them, so no two live pages share a lineage. Both forms follow it\n * backwards here, and the judge on top of either is the same.\n *\n * A body change is a change outside the metadata block, so a frontmatter\n * sweep does not move `last-updated`. Blobs are compared by their bodies\n * with line endings normalised, because `core.autocrlf` rewrites a blob on\n * the way in and out of the index and that is not an edit.\n *\n * Availability is a verdict, not an exception (decision 6): git missing, no\n * repository, or a shallow checkout report `available: false` with the fix.\n */\nimport { constants as bufferConstants } from \"node:buffer\";\nimport { spawn, type ChildProcessWithoutNullStreams } from \"node:child_process\";\nimport { availableParallelism } from \"node:os\";\nimport { dirname, extname, isAbsolute, posix, relative, sep } from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport { mapConcurrent } from \"../../../shared/concurrency.js\";\nimport { findGitRoot } from \"../../../shared/git-root.js\";\nimport { locateFrontmatter } from \"../../extractors/frontmatter.js\";\nimport {\n extractorByName,\n extractorForExtension,\n} from \"../../extractors/index.js\";\nimport type { ExtractedMetadata, MetadataExtractor } from \"../../types.js\";\nimport { toJsonText } from \"../json-text.js\";\nimport { parseLines, splitLines, toFileLines } from \"../../../shared/pin.js\";\nimport {\n attributeRange,\n DEFAULT_MACHINES,\n deriveProvenance,\n machineIdentity,\n parseLinePorcelain,\n provenanceEntries,\n readProvenancePage,\n ZERO_SHA,\n type BlameLine,\n type CommitEvidence,\n type ProvenanceDerivation,\n type ProvenanceEntry,\n} from \"./provenance.js\";\nimport {\n PROVENANCE_FIELD,\n STAMPED_DATE_FIELDS,\n type DeriveInput,\n type DerivedValue,\n type ManifestRef,\n type SourceStatus,\n type StampedDateField,\n} from \"./types.js\";\n\n/** Facts git can state about one document. Every field is null when git answered but has no fact. */\nexport interface GitFacts {\n created: DerivedValue | null;\n \"last-updated\": DerivedValue | null;\n authors: DerivedValue | null;\n /** From `Reviewed-by` trailers only. */\n \"reviewed-by\": DerivedValue | null;\n /** From `Reviewed-by` trailers only. */\n \"last-reviewed\": DerivedValue | null;\n /**\n * The machine-written body ranges (proposal 0046), from blame and the\n * commits it names: the entry list as a page would carry it, or null when\n * no line names a machine, and when provenance was not requested.\n */\n provenance: DerivedValue | null;\n /**\n * The derivation behind `provenance`, per body line, which the comparison\n * with a page's stamp reads. Present exactly when provenance was requested.\n */\n provenanceDerivation?: ProvenanceDerivation;\n /** Full sha of the newest body-changing commit, for the review sources; null when uncommitted or none. */\n lastBodyCommit: string | null;\n /** Repository root the document lives in, absolute, native separators. */\n root: string;\n}\n\nexport interface GitSourceOptions {\n cwd: string;\n now: () => Date;\n /** Runs with more inputs per root than this take the bulk walk. Test seam; default 32. */\n bulkThreshold?: number;\n /**\n * Most bytes one git process may write to stdout before the root is\n * reported too large to read. Test seam; default `MAX_GIT_OUTPUT_BYTES`.\n */\n maxOutputBytes?: number;\n /**\n * The fields the run asks for. Blame runs only when it names\n * `provenance`, which is the per-field gating 0040 already has.\n */\n fields?: readonly string[];\n /** `--generated-by` or `MANNI_GENERATED_BY`: the machine uncommitted lines go to (rule 1). */\n generatedBy?: string;\n /** `derive.machines`; `DEFAULT_MACHINES` when absent. */\n machines?: readonly string[];\n}\n\nexport interface GitSourceResult {\n status: SourceStatus;\n /** Keyed by `DeriveInput.label`. A document outside any repository is absent. */\n records: Map<string, GitFacts>;\n}\n\nconst DEFAULT_BULK_THRESHOLD = 32;\nconst NULL_SHA = \"0\".repeat(40);\n\n/**\n * The whole of one git process's stdout is held in memory and decoded in one\n * pass; streaming the log is out of scope for now. A history past this cap\n * is refused rather than decoded: 512 MiB, or V8's string limit where that\n * is lower, so the cap itself is what stops the run and not an\n * `ERR_STRING_TOO_LONG` from inside `Buffer#toString`.\n */\nconst MAX_GIT_OUTPUT_BYTES = Math.min(\n 512 * 1024 * 1024,\n bufferConstants.MAX_STRING_LENGTH,\n);\n\n/** A root whose history cannot be held in memory; caught by `deriveFromGit`. */\nclass HistoryTooLarge extends Error {}\n\n/**\n * `git cat-file --batch` exited non-zero: a corrupt object, a missing pack,\n * lock contention. An empty blob map would read every body as empty and\n * every history entry as unchanged, which is the false green the channel\n * refuses, so it is a failed root like a shallow clone.\n */\nclass BlobsUnreadable extends Error {\n constructor(readonly detail: string) {\n super(detail);\n }\n}\n\n/**\n * `git blame` exited non-zero for a file that HEAD has. A file HEAD lacks\n * (untracked, deleted and recreated, or in a repository with no commits yet)\n * is not this: all of its lines are uncommitted, and blame has nothing to add.\n * `detail` is git's own stderr.\n */\nclass BlameUnreadable extends Error {\n constructor(\n readonly rel: string,\n readonly detail: string,\n ) {\n super(rel);\n }\n}\n\n/** One commit that touched a document, as either walk form reports it. */\ninterface FileHistory {\n sha: string;\n /** `%aI`: ISO 8601 in the author's own offset. */\n authorDate: string;\n authorName: string;\n authorEmail: string;\n /** `Co-authored-by` trailer values, `Name <email>` form. */\n coAuthors: string[];\n /** `Reviewed-by` trailer values, as written. */\n reviewedBy: string[];\n /** `Generated-by` trailer values, as written (proposal 0046). */\n generatedBy: string[];\n oldBlob: string | null;\n newBlob: string | null;\n pathAtCommit: string;\n /** A merge's parents after the first; empty for any other commit. */\n otherParents: string[];\n /**\n * The document's blob at each of `otherParents`, null where that parent\n * did not hold it. Read after the walk, by `readOtherParentBlobs`.\n */\n otherParentBlobs: (string | null)[];\n}\n\n/**\n * Content outside the metadata block: for a fenced document the block\n * `[openStart, closeEnd)` is dropped, so a BOM ahead of it survives; anything\n * else is the whole content. Exported for the orchestrator and tests.\n */\nexport function bodyOf(content: string, fenced: boolean | undefined): string {\n if (fenced !== true) return content;\n const loc = locateFrontmatter(content);\n if (!loc) return content;\n return content.slice(0, loc.openStart) + content.slice(loc.closeEnd);\n}\n\n/**\n * Never throws for availability: git missing, no repository for any input,\n * a shallow clone, or a history too large to read report\n * `status.available: false` with a `reason` that names the fix, and an\n * empty map. One root that cannot answer makes the source unavailable for\n * the whole run, as `deriveReviewsByRoot` rules: a walk that answered for\n * some roots and silently dropped the rest would read as green for\n * documents it never looked at. An input outside any repository is not a\n * failing root; it is simply absent from the records.\n */\nexport async function deriveFromGit(\n inputs: readonly DeriveInput[],\n opts: GitSourceOptions,\n): Promise<GitSourceResult> {\n const records = new Map<string, GitFacts>();\n const byRoot = groupByRoot(inputs);\n if (byRoot.size === 0) {\n return {\n status: {\n available: false,\n reason: \"no git repository contains the documents\",\n },\n records,\n };\n }\n\n const threshold = opts.bulkThreshold ?? DEFAULT_BULK_THRESHOLD;\n const machines = opts.machines ?? DEFAULT_MACHINES;\n const wantsProvenance = opts.fields?.includes(PROVENANCE_FIELD) ?? false;\n const maxBytes = opts.maxOutputBytes ?? MAX_GIT_OUTPUT_BYTES;\n const parse = yamlOnce();\n const reasons: string[] = [];\n for (const [root, bucket] of byRoot) {\n const run: GitRun = (args, stdin) => runGit(args, root, stdin, maxBytes);\n const shallow = await run([\"rev-parse\", \"--is-shallow-repository\"]);\n if (shallow.missing) {\n return {\n status: { available: false, reason: \"git is not on PATH\" },\n records: new Map(),\n };\n }\n if (shallow.code !== 0) {\n reasons.push(`git could not read the repository at ${root}`);\n continue;\n }\n if (text(shallow).trim() === \"true\") {\n reasons.push(\n `this checkout is shallow; use actions/checkout with fetch-depth: 0 (${root})`,\n );\n continue;\n }\n\n try {\n const found = await histories(\n run,\n bucket.map((e) => e.rel),\n threshold,\n );\n if (found === null) {\n reasons.push(`git could not read the history at ${root}`);\n continue;\n }\n await readOtherParentBlobs(run, found);\n const blobs = await fetchBlobs(run, neededBlobs(found));\n if (!(await followTakenBodies(run, bucket, found, blobs, threshold))) {\n reasons.push(`git could not read the history at ${root}`);\n continue;\n }\n const manifestStamps = await stampsInManifests(run, root, bucket, found, blobs, parse);\n\n const facts = bucket.map((entry) =>\n judge(\n entry.input,\n root,\n found.get(entry.rel) ?? [],\n blobs,\n opts.now,\n machines,\n manifestStamps.get(entry.input.label),\n ),\n );\n if (wantsProvenance) {\n // Blame is one git process a page, and no page's depends on another's.\n // Run a few at once: one at a time, process start-up dominates, worst\n // on Windows. What the blames name is then read for the whole root at\n // once. Results keep input order whatever finishes first.\n const pages = await mapConcurrent(bucket, GIT_CONCURRENCY, async (entry) => ({\n entry,\n blame: await blameOf(run, entry.rel, entry.input.content),\n history: found.get(entry.rel) ?? [],\n }));\n const evidence = await commitEvidence(run, root, pages, blobs, parse);\n const provenanceRun: ProvenanceRun = {\n machines,\n ...(opts.generatedBy !== undefined ? { generatedBy: opts.generatedBy } : {}),\n };\n pages.forEach((page, i) => {\n const judged = facts[i];\n const commits = evidence[i];\n if (judged === undefined || commits === undefined) return;\n const derived = provenanceFor(page.entry, page.blame, commits, provenanceRun);\n judged.provenance = derived.value;\n judged.provenanceDerivation = derived.derivation;\n });\n }\n bucket.forEach((entry, i) => {\n const judged = facts[i];\n if (judged !== undefined) records.set(entry.input.label, judged);\n });\n } catch (err) {\n if (err instanceof BlobsUnreadable) {\n reasons.push(`git cat-file could not read the history (${root}): ${err.detail}`);\n continue;\n }\n if (err instanceof BlameUnreadable) {\n const why = err.detail === \"\" ? \"\" : `: ${err.detail}`;\n reasons.push(`git blame could not read ${err.rel} (${root})${why}`);\n continue;\n }\n if (!(err instanceof HistoryTooLarge)) throw err;\n reasons.push(`git history is too large to read in one pass (${root})`);\n continue;\n }\n }\n\n if (reasons.length > 0) {\n return {\n status: { available: false, reason: reasons.join(\"; \") },\n records: new Map(),\n };\n }\n return { status: { available: true }, records };\n}\n\n// ---------------------------------------------------------------------------\n// Grouping\n\ninterface RootEntry {\n input: DeriveInput;\n /** Root-relative, forward slashes: how git names the path. */\n rel: string;\n}\n\nfunction groupByRoot(inputs: readonly DeriveInput[]): Map<string, RootEntry[]> {\n const rootOf = new Map<string, string | null>();\n const byRoot = new Map<string, RootEntry[]>();\n for (const input of inputs) {\n const dir = dirname(input.absPath);\n let root = rootOf.get(dir);\n if (root === undefined) {\n root = findGitRoot(dir);\n rootOf.set(dir, root);\n }\n if (root === null) continue;\n const rel = relative(root, input.absPath).split(sep).join(\"/\");\n const bucket = byRoot.get(root);\n if (bucket) bucket.push({ input, rel });\n else byRoot.set(root, [{ input, rel }]);\n }\n return byRoot;\n}\n\n// ---------------------------------------------------------------------------\n// History walks\n\n/**\n * Record format: one `\\x1e`-led header per commit, its fields `\\0`-separated,\n * trailer values `\\x1f`-separated. `--raw` lines follow each header. `-z` is\n * deliberately absent: it makes the record boundary ambiguous, where `\\x1e`\n * cannot appear in a sha, a date, or a raw line. `--no-abbrev` because\n * `--raw` shortens blob shas by default, and `cat-file` wants the full ones.\n * `unfold` because a trailer may wrap onto an indented continuation line,\n * and the header is read up to its first newline: folded, the rest of the\n * header would be taken for raw lines and the value split in two.\n */\nconst RECORD_FORMAT =\n \"--format=%x1e%H%x00%aI%x00%an%x00%ae%x00\" +\n \"%(trailers:key=Co-authored-by,valueonly,unfold,separator=%x1f)%x00\" +\n \"%(trailers:key=Reviewed-by,valueonly,unfold,separator=%x1f)%x00\" +\n \"%(trailers:key=Generated-by,valueonly,unfold,separator=%x1f)%x00\" +\n \"%P\";\n\n/**\n * `--diff-merges=first-parent` because `--raw` prints nothing for a merge by\n * default. A body two branches both edited exists only in the merge that\n * combined them, so without the merge's own diff no commit in the history\n * holds that blob, and the committed body reads as uncommitted. First parent\n * is also how a commit's prior state is read here (`<sha>^`). A merge whose\n * body another parent already held did not produce it, so the judge passes\n * over it, and the commit that wrote the body on that side dates it. A pull\n * request's merge ref is the common case: the base is its first parent.\n */\nconst LOG_ARGS = [\n \"-c\",\n \"core.quotePath=false\",\n \"log\",\n \"--raw\",\n \"--diff-merges=first-parent\",\n \"-M\",\n \"--no-abbrev\",\n RECORD_FORMAT,\n];\n\n/** Either walk form, by how many paths it reads. */\nfunction histories(\n run: GitRun,\n rels: readonly string[],\n threshold: number,\n rev = \"HEAD\",\n): Promise<Map<string, FileHistory[]> | null> {\n return rels.length <= threshold\n ? perFileHistories(run, rels, rev)\n : bulkHistories(run, rels, rev);\n}\n\n/**\n * The per-file form: one `git log -- <path>` a lineage, attributed the way\n * the bulk form is. A pathspec hides the other side of a rename, so the path\n * reads as added or deleted where the whole commit pairs it. Each such\n * commit is read whole, with the same `-M`, and a rename into the path\n * continues the walk on the old path from the commit's first parent.\n */\nasync function perFileHistories(\n run: GitRun,\n rels: readonly string[],\n rev: string,\n): Promise<Map<string, FileHistory[]> | null> {\n const found = new Map<string, FileHistory[]>();\n for (const rel of rels) {\n const records = await lineage(run, rel, rev);\n if (records === null) {\n if (await isUnbornHead(run)) return found;\n return null;\n }\n found.set(rel, attribute(records, [rel]).get(rel) ?? []);\n }\n return found;\n}\n\n/** The commits that touched `rel`'s lineage from `rev`, newest first; null when git failed. */\nasync function lineage(run: GitRun, rel: string, rev: string): Promise<LogRecord[] | null> {\n const records: LogRecord[] = [];\n let at = rel;\n let from = rev;\n for (;;) {\n const out = await run([...LOG_ARGS, from, \"--\", pathspec(at)]);\n if (out.tooLarge) throw new HistoryTooLarge();\n if (out.code !== 0) return null;\n let renamedFrom: string | undefined;\n for (const record of parseLog(text(out))) {\n const status = record.raw.find((e) => e.newPath === at)?.status;\n if (status === \"A\" || status === \"D\") {\n const whole = await run([...LOG_ARGS, \"-1\", record.sha]);\n if (whole.tooLarge) throw new HistoryTooLarge();\n if (whole.code !== 0) return null;\n record.raw = parseLog(text(whole))[0]?.raw ?? [];\n const entry = record.raw.find((e) => e.newPath === at);\n if (entry !== undefined && entry.oldPath !== at) renamedFrom = entry.oldPath;\n }\n records.push(record);\n if (renamedFrom !== undefined) {\n from = `${record.sha}^`;\n break;\n }\n }\n if (renamedFrom === undefined) return records;\n at = renamedFrom;\n }\n}\n\n/** The bulk form: one walk, every path attributed and followed here. */\nasync function bulkHistories(\n run: GitRun,\n rels: readonly string[],\n rev: string,\n): Promise<Map<string, FileHistory[]> | null> {\n const out = await run([...LOG_ARGS, rev]);\n if (out.tooLarge) throw new HistoryTooLarge();\n if (out.code !== 0) {\n if (await isUnbornHead(run)) return new Map();\n return null;\n }\n return attribute(parseLog(text(out)), [...rels]);\n}\n\n/**\n * A page whose newest body change is a merge that took the body whole from\n * another parent is read as that parent reads it. Its history from that\n * parent replaces the merge and everything older, so the commit that wrote\n * the body dates it, under whatever path it had on that side. The commits\n * newer than the merge are kept: none of them changed the body. Pages that\n * share a parent are walked together, and the walk repeats while the newest\n * body change on the new side is itself such a merge. Each round walks\n * strictly older commits, so it ends.\n */\nasync function followTakenBodies(\n run: GitRun,\n bucket: readonly RootEntry[],\n found: Map<string, FileHistory[]>,\n blobs: Map<string, string>,\n threshold: number,\n): Promise<boolean> {\n for (;;) {\n const byParent = new Map<string, { rel: string; keep: FileHistory[]; path: string }[]>();\n for (const entry of bucket) {\n const history = found.get(entry.rel) ?? [];\n const taken = takenMerge(entry.input.extracted.fenced, history, blobs);\n if (taken === undefined) continue;\n const group = byParent.get(taken.parent) ?? [];\n group.push({ rel: entry.rel, keep: history.slice(0, taken.index), path: taken.path });\n byParent.set(taken.parent, group);\n }\n if (byParent.size === 0) return true;\n\n const walked = new Map<string, FileHistory[]>();\n for (const [parent, group] of byParent) {\n const paths = [...new Set(group.map((g) => g.path))];\n const side = await histories(run, paths, threshold, parent);\n if (side === null) return false;\n for (const g of group) {\n const tail = side.get(g.path) ?? [];\n walked.set(g.rel, tail);\n found.set(g.rel, [...g.keep, ...tail]);\n }\n }\n await readOtherParentBlobs(run, walked);\n const missing = new Set([...neededBlobs(walked)].filter((sha) => !blobs.has(sha)));\n for (const [sha, content] of await fetchBlobs(run, missing)) blobs.set(sha, content);\n }\n}\n\n/**\n * The newest body change in `history`, when it is a merge whose body another\n * parent already held: its position, that parent, and the page's path there.\n */\nfunction takenMerge(\n fenced: boolean | undefined,\n history: readonly FileHistory[],\n blobs: ReadonlyMap<string, string>,\n): { index: number; parent: string; path: string } | undefined {\n const blobBody = (sha: string | null): string | null =>\n sha === null ? null : bodyOf(blobs.get(sha) ?? \"\", fenced);\n const index = history.findIndex((h) => !sameBody(blobBody(h.newBlob), blobBody(h.oldBlob)));\n const newest = history[index];\n if (newest === undefined) return undefined;\n const body = blobBody(newest.newBlob);\n const k = newest.otherParentBlobs.findIndex((b) => b !== null && sameBody(body, blobBody(b)));\n const parent = newest.otherParents[k];\n if (k === -1 || parent === undefined) return undefined;\n return { index, parent, path: newest.pathAtCommit };\n}\n\n/** A path with glob characters is named literally, as `gitignore.ts` does. */\nfunction pathspec(rel: string): string {\n return /[*?[\\]]/.test(rel) ? `:(literal)${rel}` : rel;\n}\n\n/** A repository with no commits yet has no history rather than a broken one. */\nasync function isUnbornHead(run: GitRun): Promise<boolean> {\n const out = await run([\"rev-parse\", \"--verify\", \"--quiet\", \"HEAD^{commit}\"]);\n return !out.missing && out.code !== 0;\n}\n\ninterface RawEntry {\n status: string;\n oldBlob: string;\n newBlob: string;\n oldPath: string;\n newPath: string;\n}\n\ninterface LogRecord {\n sha: string;\n authorDate: string;\n authorName: string;\n authorEmail: string;\n coAuthors: string[];\n reviewedBy: string[];\n generatedBy: string[];\n /** `%P`: the commit's parents, first parent first. */\n parents: string[];\n raw: RawEntry[];\n}\n\nfunction parseLog(text: string): LogRecord[] {\n const records: LogRecord[] = [];\n for (const chunk of text.split(\"\\x1e\")) {\n if (chunk === \"\") continue;\n const nl = chunk.indexOf(\"\\n\");\n const header = nl === -1 ? chunk : chunk.slice(0, nl);\n const fields = header.split(\"\\0\");\n const sha = fields[0];\n if (sha === undefined || sha === \"\") continue;\n const raw: RawEntry[] = [];\n if (nl !== -1) {\n for (const line of chunk.slice(nl + 1).split(\"\\n\")) {\n const entry = parseRawLine(line);\n if (entry) raw.push(entry);\n }\n }\n records.push({\n sha,\n authorDate: fields[1] ?? \"\",\n authorName: fields[2] ?? \"\",\n authorEmail: fields[3] ?? \"\",\n coAuthors: splitTrailers(fields[4]),\n reviewedBy: splitTrailers(fields[5]),\n generatedBy: splitTrailers(fields[6]),\n parents: (fields[7] ?? \"\").trim().split(\" \").filter((p) => p !== \"\"),\n raw,\n });\n }\n return records;\n}\n\nfunction splitTrailers(field: string | undefined): string[] {\n if (field === undefined || field === \"\") return [];\n return field\n .split(\"\\x1f\")\n .map((s) => s.trim())\n .filter((s) => s !== \"\");\n}\n\n/**\n * `:<oldmode> <newmode> <oldsha> <newsha> <status>\\t<path>`, or with two\n * paths after `R`/`C`. A path git still had to quote (a control character\n * or a backslash, even with `core.quotePath=false`) is C-unquoted.\n */\nfunction parseRawLine(line: string): RawEntry | null {\n if (!line.startsWith(\":\")) return null;\n const tab = line.indexOf(\"\\t\");\n if (tab === -1) return null;\n const meta = line.slice(1, tab).split(\" \");\n const oldBlob = meta[2];\n const newBlob = meta[3];\n const status = meta[4];\n if (oldBlob === undefined || newBlob === undefined || status === undefined) {\n return null;\n }\n const paths = line.slice(tab + 1).split(\"\\t\").map(unquotePath);\n const first = paths[0];\n if (first === undefined) return null;\n const second = paths[1];\n const renamed = status.startsWith(\"R\") || status.startsWith(\"C\");\n return {\n status,\n oldBlob,\n newBlob,\n oldPath: first,\n newPath: renamed && second !== undefined ? second : first,\n };\n}\n\nfunction unquotePath(p: string): string {\n if (p.length < 2 || !p.startsWith('\"') || !p.endsWith('\"')) return p;\n const inner = p.slice(1, -1);\n const bytes: number[] = [];\n for (let i = 0; i < inner.length; i += 1) {\n const ch = inner[i];\n if (ch !== \"\\\\\") {\n bytes.push(...Buffer.from(ch ?? \"\", \"utf8\"));\n continue;\n }\n const next = inner[i + 1];\n if (next === undefined) break;\n const octal = /^[0-7]{3}/.exec(inner.slice(i + 1));\n if (octal) {\n bytes.push(parseInt(octal[0], 8));\n i += 3;\n continue;\n }\n const simple: Record<string, number> = {\n a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '\"': 34, \"\\\\\": 92,\n };\n const code = simple[next];\n if (code === undefined) bytes.push(...Buffer.from(next, \"utf8\"));\n else bytes.push(code);\n i += 1;\n }\n return Buffer.from(bytes).toString(\"utf8\");\n}\n\n/**\n * Attribute raw lines to the wanted paths, newest first, following a rename\n * backwards: after the commit that renamed `old` to `new`, the file is\n * looked for under `old`. A path deleted and later re-added is tracked\n * through the deletion, since the re-add is its newest history.\n */\nfunction attribute(\n records: LogRecord[],\n wanted: string[],\n): Map<string, FileHistory[]> {\n const histories = new Map<string, FileHistory[]>();\n // The path each wanted document is currently known by, walking backwards.\n const tracked = new Map<string, string>();\n for (const rel of wanted) {\n histories.set(rel, []);\n tracked.set(rel, rel);\n }\n for (const record of records) {\n if (record.raw.length === 0) continue;\n const byNewPath = new Map<string, RawEntry>();\n for (const entry of record.raw) byNewPath.set(entry.newPath, entry);\n for (const [rel, current] of tracked) {\n const entry = byNewPath.get(current);\n if (!entry) continue;\n histories.get(rel)?.push({\n sha: record.sha,\n authorDate: record.authorDate,\n authorName: record.authorName,\n authorEmail: record.authorEmail,\n coAuthors: record.coAuthors,\n reviewedBy: record.reviewedBy,\n generatedBy: record.generatedBy,\n oldBlob: entry.oldBlob === NULL_SHA ? null : entry.oldBlob,\n newBlob: entry.newBlob === NULL_SHA ? null : entry.newBlob,\n pathAtCommit: entry.newPath,\n otherParents: record.parents.slice(1),\n otherParentBlobs: [],\n });\n if (entry.oldPath !== entry.newPath) tracked.set(rel, entry.oldPath);\n }\n }\n return histories;\n}\n\n// ---------------------------------------------------------------------------\n// Blobs\n\nfunction neededBlobs(histories: Map<string, FileHistory[]>): Set<string> {\n const shas = new Set<string>();\n for (const history of histories.values()) {\n for (const h of history) {\n if (h.oldBlob !== null) shas.add(h.oldBlob);\n if (h.newBlob !== null) shas.add(h.newBlob);\n for (const b of h.otherParentBlobs) if (b !== null) shas.add(b);\n }\n }\n return shas;\n}\n\n/**\n * Fill each merge's `otherParentBlobs`: the document's blob at every parent\n * after the first, by `<parent>:<path>`. One `git cat-file --batch-check`\n * per root, which answers one line per spec in input order:\n * `<sha> <type> <size>`, or `<spec> missing` where the parent lacks the path.\n */\nasync function readOtherParentBlobs(\n run: GitRun,\n histories: ReadonlyMap<string, FileHistory[]>,\n): Promise<void> {\n const merges: FileHistory[] = [];\n const specs: string[] = [];\n for (const history of histories.values()) {\n for (const h of history) {\n if (h.otherParents.length === 0) continue;\n merges.push(h);\n for (const parent of h.otherParents) specs.push(`${parent}:${h.pathAtCommit}`);\n }\n }\n if (specs.length === 0) return;\n const out = await run([\"cat-file\", \"--batch-check\"], `${specs.join(\"\\n\")}\\n`);\n if (out.tooLarge) throw new HistoryTooLarge();\n if (out.code !== 0) throw new BlobsUnreadable(`exit ${String(out.code)}`);\n const lines = text(out).split(\"\\n\");\n let i = 0;\n for (const h of merges) {\n h.otherParentBlobs = h.otherParents.map(() => blobOfCheckLine(lines[i++]));\n }\n}\n\n/** The blob sha a `--batch-check` line names, or null for anything else. */\nfunction blobOfCheckLine(line: string | undefined): string | null {\n const [sha, kind] = (line ?? \"\").split(\" \");\n if (sha === undefined || kind !== \"blob\" || !/^[0-9a-f]{40,64}$/.test(sha)) return null;\n return sha;\n}\n\n/**\n * One `git cat-file --batch` per root, one sha per line on stdin. Output is\n * `<sha> blob <size>\\n<bytes>\\n` per object, correlated by the header's sha\n * rather than by order; a `<sha> missing` line yields nothing.\n */\nasync function fetchBlobs(\n run: GitRun,\n shas: Set<string>,\n): Promise<Map<string, string>> {\n const blobs = new Map<string, string>();\n if (shas.size === 0) return blobs;\n const out = await run([\"cat-file\", \"--batch\"], `${[...shas].join(\"\\n\")}\\n`);\n if (out.tooLarge) throw new HistoryTooLarge();\n if (out.code !== 0) throw new BlobsUnreadable(`exit ${String(out.code)}`);\n const buf = out.raw;\n let cursor = 0;\n while (cursor < buf.length) {\n const nl = buf.indexOf(0x0a, cursor);\n if (nl === -1) break;\n const header = buf.toString(\"utf8\", cursor, nl).split(\" \");\n cursor = nl + 1;\n const sha = header[0];\n const kind = header[1];\n const size = Number(header[2]);\n if (sha === undefined || kind !== \"blob\" || !Number.isFinite(size)) {\n continue;\n }\n blobs.set(sha, buf.toString(\"utf8\", cursor, cursor + size));\n cursor += size + 1; // the trailing newline after the object\n }\n return blobs;\n}\n\n// ---------------------------------------------------------------------------\n// The judge\n\nconst git = (value: unknown, evidence: string): DerivedValue => ({\n value,\n source: \"git\",\n evidence,\n});\n\n/**\n * The commits decision 2 reads a document's facts from: its oldest, for\n * `created`, and its newest body change, for `last-updated`.\n * `bodyChanging` is oldest first, so authors read in order of first appearance.\n */\ninterface FactCommits {\n bodyChanging: FileHistory[];\n oldest: FileHistory | undefined;\n newestBody: FileHistory | undefined;\n}\n\nfunction factCommits(\n input: DeriveInput,\n history: readonly FileHistory[],\n blobs: ReadonlyMap<string, string>,\n): FactCommits {\n const fenced = input.extracted.fenced;\n const blobBody = (sha: string | null): string | null =>\n sha === null ? null : bodyOf(blobs.get(sha) ?? \"\", fenced);\n const bodyChanging = [...history]\n .reverse()\n .filter((h) => {\n const body = blobBody(h.newBlob);\n if (sameBody(body, blobBody(h.oldBlob))) return false;\n // A merge that took the body whole from another parent did not write it.\n return !h.otherParentBlobs.some((b) => b !== null && sameBody(body, blobBody(b)));\n });\n return {\n bodyChanging,\n oldest: history[history.length - 1],\n newestBody: bodyChanging[bodyChanging.length - 1],\n };\n}\n\n/**\n * The value a manifest held for one dated field of a page (proposal 0069,\n * rule 1), at a commit (`sha`) or at its first parent (`sha^`). Undefined\n * when no manifest owns the field, or the manifest held no value there.\n */\ntype ManifestStamp = (field: StampedDateField, rev: string) => unknown;\n\n/**\n * Read, per page, the stamps the manifests that own its dated fields held at\n * the fact commits: the oldest commit for `created`, and the newest body\n * change and its parent for `last-updated`. One `git cat-file --batch` by\n * `<rev>:<path>` for the whole root, as provenance reads its manifest.\n */\nasync function stampsInManifests(\n run: GitRun,\n root: string,\n bucket: readonly RootEntry[],\n histories: ReadonlyMap<string, FileHistory[]>,\n blobs: ReadonlyMap<string, string>,\n parse: ParseYaml,\n): Promise<Map<string, ManifestStamp>> {\n interface Read {\n label: string;\n field: StampedDateField;\n rev: string;\n spec: string;\n key: string;\n join: string;\n }\n const reads: Read[] = [];\n for (const entry of bucket) {\n const refs = entry.input.stampManifests;\n if (refs === undefined) continue;\n const { oldest, newestBody } = factCommits(entry.input, histories.get(entry.rel) ?? [], blobs);\n for (const field of STAMPED_DATE_FIELDS) {\n const ref = refs[field];\n const at = field === \"created\" ? oldest : newestBody;\n if (ref === undefined || at === undefined) continue;\n const rel = insideRoot(root, ref.absPath);\n if (rel === undefined) continue;\n const key = ref.join === \"path\" ? entryAt(ref.entry, entry.rel, at.pathAtCommit) : ref.entry;\n const revs = field === \"created\" ? [at.sha] : [at.sha, `${at.sha}^`];\n for (const rev of revs) {\n reads.push({ label: entry.input.label, field, rev, spec: `${rev}:${rel}`, key, join: ref.join });\n }\n }\n }\n const out = new Map<string, ManifestStamp>();\n if (reads.length === 0) return out;\n const fetched = await fetchSpecs(run, [...new Set(reads.map((r) => r.spec))]);\n const values = new Map<string, unknown>();\n const keyOf = (label: string, field: string, rev: string): string => `${label}\\0${field}\\0${rev}`;\n for (const r of reads) {\n values.set(keyOf(r.label, r.field, r.rev), manifestValue(fetched.get(r.spec), r.key, r.join, r.field, parse));\n }\n for (const label of new Set(reads.map((r) => r.label))) {\n out.set(label, (field, rev) => values.get(keyOf(label, field, rev)));\n }\n return out;\n}\n\nfunction judge(\n input: DeriveInput,\n root: string,\n history: readonly FileHistory[],\n blobs: Map<string, string>,\n now: () => Date,\n machines: readonly string[],\n manifestStamp?: ManifestStamp,\n): GitFacts {\n const fenced = input.extracted.fenced;\n const extractor = extractorFor(input);\n const blobBody = (sha: string | null): string | null =>\n sha === null ? null : bodyOf(blobs.get(sha) ?? \"\", fenced);\n const stampsOf = (sha: string | null): Record<string, unknown> => {\n if (sha === null) return {};\n const content = blobs.get(sha);\n return content === undefined ? {} : extractStamps(extractor, content, input.absPath);\n };\n /**\n * The stamp a commit carries for a dated field (0069 rule 1): the owning\n * manifest's value at the commit, or else the page's. `parent` reads the\n * state before the commit, which tells a changed stamp from a kept one.\n */\n const stampAt = (field: StampedDateField, h: FileHistory, parent: boolean): unknown => {\n const kept = manifestStamp?.(field, parent ? `${h.sha}^` : h.sha);\n if (kept !== undefined && kept !== null) return kept;\n return stampsOf(parent ? h.oldBlob : h.newBlob)[field];\n };\n\n const { bodyChanging, oldest, newestBody } = factCommits(input, history, blobs);\n const head = history[0];\n const headBlob = head === undefined ? null : head.newBlob;\n\n const created = oldest === undefined ? null : createdOf(oldest, stampAt(\"created\", oldest, false));\n\n const workingChanged = !sameBody(\n bodyOf(input.content, fenced),\n headBlob === null ? null : blobBody(headBlob),\n );\n\n let lastUpdated: DerivedValue | null;\n let lastBodyCommit: string | null;\n if (workingChanged) {\n lastBodyCommit = null;\n const working = input.extracted.data[\"last-updated\"];\n const committed = stampsOf(headBlob)[\"last-updated\"];\n lastUpdated =\n working !== undefined && working !== null && !sameValue(working, committed)\n ? git(working, \"stamped in working tree\")\n : git(utcDate(now()), \"uncommitted body change\");\n } else if (newestBody === undefined) {\n lastBodyCommit = null;\n lastUpdated = null;\n } else {\n lastBodyCommit = newestBody.sha;\n lastUpdated = lastUpdatedOf(\n newestBody,\n stampAt(\"last-updated\", newestBody, false),\n stampAt(\"last-updated\", newestBody, true),\n );\n }\n\n const authors = bodyChanging.length === 0 ? null : authorsOf(bodyChanging, machines);\n\n let reviewedBy: DerivedValue | null = null;\n let lastReviewed: DerivedValue | null = null;\n if (!workingChanged && newestBody !== undefined && newestBody.reviewedBy.length > 0) {\n const evidence = `Reviewed-by trailer in ${short(newestBody.sha)}`;\n reviewedBy = git(newestBody.reviewedBy.map(nameOf), evidence);\n lastReviewed = git(datePart(newestBody.authorDate), evidence);\n }\n\n return {\n created,\n \"last-updated\": lastUpdated,\n authors,\n \"reviewed-by\": reviewedBy,\n \"last-reviewed\": lastReviewed,\n provenance: null,\n lastBodyCommit,\n root,\n };\n}\n\nfunction createdOf(oldest: FileHistory, stamp: unknown): DerivedValue {\n if (stamp !== undefined && stamp !== null) {\n return git(stamp, `stamped in ${short(oldest.sha)}`);\n }\n const date = datePart(oldest.authorDate);\n return git(date, `added in ${short(oldest.sha)} (${date})`);\n}\n\n/**\n * `last-updated` from the newest body change (decision 2). A stamp counts\n * only when the commit changed it, on the page or in the manifest that owns\n * the field: a stamp the edit kept was written for an earlier change, so the\n * commit's own date stands.\n */\nfunction lastUpdatedOf(commit: FileHistory, stamp: unknown, before: unknown): DerivedValue {\n if (stamp !== undefined && stamp !== null && !sameValue(stamp, before)) {\n return git(stamp, `stamped in ${short(commit.sha)}`);\n }\n const date = datePart(commit.authorDate);\n return git(date, `body changed in ${short(commit.sha)} (${date})`);\n}\n\n/**\n * Distinct people behind the body-changing commits, oldest first, each\n * commit's author ahead of its co-authors, deduplicated by lowercase email\n * (by lowercase name when a co-author trailer carries none). An identity\n * whose name or email matches `derive.machines` is a machine and is left\n * out (proposal 0046); the default, `*[bot]`, is a name ending `[bot]`.\n */\nfunction authorsOf(bodyChanging: readonly FileHistory[], machines: readonly string[]): DerivedValue {\n const seen = new Set<string>();\n const names: string[] = [];\n const add = (name: string, email: string | null): void => {\n if (name === \"\") return;\n const identity = email === null || email === \"\" ? name : `${name} <${email}>`;\n if (machineIdentity(identity, machines) !== undefined) return;\n const key = email === null || email === \"\" ? `name:${name.toLowerCase()}` : email.toLowerCase();\n if (seen.has(key)) return;\n seen.add(key);\n names.push(name);\n };\n for (const h of bodyChanging) {\n add(h.authorName, h.authorEmail);\n for (const co of h.coAuthors) add(nameOf(co), emailOf(co));\n }\n const n = bodyChanging.length;\n return git(names, `${n} body-changing ${n === 1 ? \"commit\" : \"commits\"}`);\n}\n\n// ---------------------------------------------------------------------------\n// provenance (proposal 0046)\n\n/**\n * Whether a page's metadata is a leading fenced block for provenance's\n * purposes: extracted from one, or a format whose metadata can only ever be\n * one (a Markdown or MDX page with no block yet gets a fenced one when it is\n * stamped). Everywhere else the metadata is part of the body it would pin,\n * so the page cannot carry the stamp itself (stress test 8).\n */\nexport function provenanceFenced(extracted: Pick<ExtractedMetadata, \"fenced\" | \"format\">): boolean {\n return extracted.fenced === true || extracted.format === \"markdown\" || extracted.format === \"mdx\";\n}\n\n/**\n * The sha an out-of-range uncommitted line is given under a ranged\n * attribution: a commit with no trailers and no blob, so it resolves to no\n * evidence. With a range, `--generated-by` names those lines only; the\n * other uncommitted lines are not its to attribute.\n */\nconst OUTSIDE_RANGE = \"outside-the-attributed-range\";\n\n/** The suffix a ranged attribution keys a committed line's commit under; the sha stays its prefix. */\nconst ATTRIBUTED = \":attributed\";\n\ninterface ProvenanceRun {\n machines: readonly string[];\n generatedBy?: string;\n}\n\n/**\n * One page's provenance from its blame and what each blamed commit offers\n * (its trailers and the page or manifest blob at it): the evidence rules.\n */\nfunction provenanceFor(\n entry: RootEntry,\n blame: BlameLine[],\n commits: Map<string, CommitEvidence>,\n opts: ProvenanceRun,\n): { value: DerivedValue | null; derivation: ProvenanceDerivation } {\n const { input } = entry;\n const fenced = provenanceFenced(input.extracted);\n const base = { content: input.content, commits, machines: opts.machines, fenced };\n\n let derivation: ProvenanceDerivation;\n const attribution = input.attribution;\n if (attribution !== undefined) {\n // Refused in 0046's words when a range runs past the end, reaches into\n // the frontmatter, or evidence names another machine for any of its\n // non-blank lines. Each range is the one attributeRange writes, trimmed\n // of blank edge lines (0071), in file lines: a blank line outside it is\n // not the attribution's, and one of only blank lines attributes nothing.\n const page = readProvenancePage(input.content, { fenced });\n const { bodyLine } = page;\n const ranges = attribution.targets.flatMap((target) => {\n const entry = attributeRange({ ...base, blame, target, generatedBy: attribution.generatedBy, page });\n const span = entry === undefined ? undefined : parseLines(entry.lines);\n return span === undefined ? [] : [toFileLines(span, bodyLine)];\n });\n const inRange = (line: BlameLine): boolean =>\n ranges.some((range) => line.finalLine >= range.start && line.finalLine <= range.end);\n // The attribution is evidence of its own, and nothing contradicts it (the\n // refusal above made sure). A committed line in the range is read as its\n // commit naming the machine, under a key that keeps the commit's sha for\n // the evidence text and leaves the commit's other lines as they were; an\n // uncommitted one is rule 1's. An uncommitted line outside the range has\n // no evidence: the range is what --generated-by names.\n const attributed = new Map(commits);\n const trailers = { generatedBy: [attribution.generatedBy], coAuthoredBy: [] };\n attributed.set(OUTSIDE_RANGE, { sha: OUTSIDE_RANGE, trailers: { generatedBy: [], coAuthoredBy: [] } });\n const rekeyed = blame.map((line): BlameLine => {\n if (inRange(line)) {\n if (line.uncommitted) return line;\n const sha = `${line.sha}${ATTRIBUTED}`;\n attributed.set(sha, { sha, trailers });\n return { ...line, sha };\n }\n return line.uncommitted ? { ...line, sha: OUTSIDE_RANGE, uncommitted: false } : line;\n });\n derivation = deriveProvenance({\n ...base,\n commits: attributed,\n generatedBy: attribution.generatedBy,\n blame: rekeyed,\n });\n } else {\n derivation = deriveProvenance({\n ...base,\n blame,\n ...(opts.generatedBy !== undefined ? { generatedBy: opts.generatedBy } : {}),\n });\n }\n\n const entries: ProvenanceEntry[] = derivation.derived.map((d) => d.entry);\n return {\n value: entries.length === 0 ? null : git(entries, provenanceEvidence(derivation)),\n derivation,\n };\n}\n\n/**\n * `blame 9b0e2c1`, `blame 9b0e2c1, 2 commits`, or `uncommitted`: the commits\n * behind the machine-attributed lines, the first in line order named, and\n * `uncommitted` when rule 1 answered for any of them.\n */\nfunction provenanceEvidence(derivation: ProvenanceDerivation): string {\n const shas: string[] = [];\n let uncommitted = false;\n for (const range of derivation.derived) {\n for (let n = range.span.start; n <= range.span.end; n++) {\n const evidence = derivation.evidenceByLine.get(n);\n if (evidence?.machine === undefined) continue;\n if (evidence.rule === 1) uncommitted = true;\n else if (!shas.includes(evidence.sha)) shas.push(evidence.sha);\n }\n }\n const first = shas[0];\n if (first === undefined) return \"uncommitted\";\n const parts = [`blame ${short(first)}`];\n if (shas.length > 1) parts.push(`${String(shas.length)} commits`);\n if (uncommitted) parts.push(\"uncommitted\");\n return parts.join(\", \");\n}\n\n/**\n * `git blame --line-porcelain` over the working file. A path HEAD does not\n * have has nothing to blame, so every line is uncommitted: that covers an\n * untracked file, a repository with no commits, and a file deleted in history\n * and recreated, which has history but no blob in HEAD. Blame failing on a\n * path HEAD has is the root's failure, and git's stderr says why.\n *\n * `--no-ignore-revs-file` because a `blame.ignoreRevsFile` in someone's\n * global config would otherwise move lines onto other commits (or, naming a\n * file the repository lacks, fail blame outright), and attribution must not\n * depend on the machine it runs on. An empty `-c blame.ignoreRevsFile=` does\n * not clear the setting; the flag does.\n */\nasync function blameOf(run: GitRun, rel: string, content: string): Promise<BlameLine[]> {\n const out = await run([\n \"-c\",\n \"core.quotePath=false\",\n \"blame\",\n \"--no-ignore-revs-file\",\n \"--line-porcelain\",\n \"--\",\n rel,\n ]);\n if (out.tooLarge) throw new HistoryTooLarge();\n if (out.code !== 0) {\n // Asked only once blame has failed, so a page that blames cleanly pays nothing.\n const inHead = await run([\"cat-file\", \"-e\", `HEAD:${rel}`]);\n if (inHead.code !== 0) {\n return splitLines(content).map((line, i) => ({\n sha: ZERO_SHA,\n origLine: i + 1,\n finalLine: i + 1,\n author: \"Not Committed Yet\",\n authorMail: \"not.committed.yet\",\n filename: rel,\n boundary: false,\n uncommitted: true,\n content: line,\n }));\n }\n throw new BlameUnreadable(rel, out.stderr.trim());\n }\n return parseLinePorcelain(text(out));\n}\n\n/** One page's blame, with the history already read for it. */\ninterface BlamedPage {\n entry: RootEntry;\n blame: BlameLine[];\n history: readonly FileHistory[];\n}\n\n/**\n * What each blamed commit offers each page: its trailers, from the page's\n * history or else `git log --no-walk` for a commit it lacks, and the page's\n * text at that commit, from the blobs already read or else `git cat-file\n * --batch` by `<sha>:<path>`. When a manifest holds the record, the stamp is\n * read from the manifest's blob at the same commit, under the page's entry as\n * it was keyed then: for a `path` join, the page's path at that commit, so a\n * stamp written before a rename is still found under the old key. Every page\n * of the root is read in one log and one batch, not one of each per page; the\n * answer is one map per page, in input order.\n */\nasync function commitEvidence(\n run: GitRun,\n root: string,\n pages: readonly BlamedPage[],\n blobs: ReadonlyMap<string, string>,\n parse: ParseYaml,\n): Promise<Map<string, CommitEvidence>[]> {\n const plans = pages.map(({ entry, blame, history }) => {\n const pathAt = new Map<string, string>();\n for (const line of blame) {\n if (!line.uncommitted && !pathAt.has(line.sha)) pathAt.set(line.sha, unquotePath(line.filename));\n }\n const trailers = new Map<string, CommitEvidence[\"trailers\"]>();\n const pageBlob = new Map<string, string>();\n for (const h of history) {\n trailers.set(h.sha, { generatedBy: h.generatedBy, coAuthoredBy: h.coAuthors });\n const blob = h.newBlob === null ? undefined : blobs.get(h.newBlob);\n if (blob !== undefined) pageBlob.set(h.sha, blob);\n }\n const manifest = entry.input.provenanceManifest;\n const manifestRel = manifest === undefined ? undefined : insideRoot(root, manifest.absPath);\n return { entry, pathAt, trailers, pageBlob, manifest, manifestRel };\n });\n\n const unlogged = new Set<string>();\n const specs = new Set<string>();\n for (const { pathAt, trailers, pageBlob, manifestRel } of plans) {\n for (const [sha, path] of pathAt) {\n if (!trailers.has(sha)) unlogged.add(sha);\n if (!pageBlob.has(sha)) specs.add(`${sha}:${path}`);\n if (manifestRel !== undefined) specs.add(`${sha}:${manifestRel}`);\n }\n }\n\n const logged = new Map<string, CommitEvidence[\"trailers\"]>();\n if (unlogged.size > 0) {\n // On stdin, so a whole root's shas cannot outgrow the command line.\n const out = await run([\"log\", \"--no-walk=unsorted\", \"--stdin\", RECORD_FORMAT], `${[...unlogged].join(\"\\n\")}\\n`);\n if (out.tooLarge) throw new HistoryTooLarge();\n if (out.code !== 0) throw new BlobsUnreadable(`git log exit ${String(out.code)}`);\n for (const record of parseLog(text(out))) {\n logged.set(record.sha, { generatedBy: record.generatedBy, coAuthoredBy: record.coAuthors });\n }\n }\n const fetched = await fetchSpecs(run, [...specs]);\n\n return plans.map(({ entry, pathAt, trailers, pageBlob, manifest, manifestRel }) => {\n const commits = new Map<string, CommitEvidence>();\n for (const [sha, path] of pathAt) {\n const blob = pageBlob.get(sha) ?? fetched.get(`${sha}:${path}`);\n commits.set(sha, {\n sha,\n trailers: trailers.get(sha) ?? logged.get(sha) ?? { generatedBy: [], coAuthoredBy: [] },\n ...(blob !== undefined ? { blob } : {}),\n ...(manifest !== undefined\n ? {\n stamp:\n manifestRel === undefined\n ? []\n : manifestStamp(\n fetched.get(`${sha}:${manifestRel}`),\n manifest.join === \"path\" ? entryAt(manifest.entry, entry.rel, path) : manifest.entry,\n manifest.join,\n parse,\n ),\n }\n : {}),\n });\n }\n return commits;\n });\n}\n\n/** A path under the root as git names it, or undefined outside the root. */\nfunction insideRoot(root: string, abs: string): string | undefined {\n const rel = relative(root, abs);\n if (rel === \"\" || rel.startsWith(\"..\") || isAbsolute(rel)) return undefined;\n return rel.split(sep).join(\"/\");\n}\n\n/**\n * A `path` join's key for the page as it was named at one commit. `entry` is\n * the current path relative to the config directory and `rel` the current\n * path relative to the root, so the path at the commit (root-relative, as\n * blame names it) is re-expressed from the current file's directory and\n * joined onto the entry's. That holds for an entry that climbs out of the\n * config directory with `..`, and needs no config directory of its own.\n */\nfunction entryAt(entry: string, rel: string, relAtCommit: string): string {\n if (relAtCommit === rel) return entry;\n const fromHere = posix.relative(posix.dirname(rel), relAtCommit);\n return posix.join(posix.dirname(entry), fromHere);\n}\n\n/**\n * The `provenance` entries a manifest's text holds for one page, under `key`\n * (joined on `join`). A manifest that does not parse, or has no entry for the\n * page, holds none.\n */\nfunction manifestStamp(\n text: string | undefined,\n key: string,\n join: ManifestRef[\"join\"],\n parse: ParseYaml,\n): ProvenanceEntry[] {\n return provenanceEntries(manifestValue(text, key, join, PROVENANCE_FIELD, parse));\n}\n\n/** Manifest text to its parsed data, or undefined when it does not parse. */\ntype ParseYaml = (text: string) => unknown;\n\n/**\n * A `ParseYaml` that parses each distinct text once. A manifest's blob is\n * read for every page it holds and at every commit a page's blame names, and\n * it is mostly the same bytes each time. One per run, so nothing outlives it.\n */\nexport function yamlOnce(): ParseYaml {\n const parsed = new Map<string, unknown>();\n return (text) => {\n if (parsed.has(text)) return parsed.get(text);\n let data: unknown;\n try {\n data = parseYaml(text);\n } catch {\n data = undefined;\n }\n parsed.set(text, data);\n return data;\n };\n}\n\n/**\n * One field's value in a manifest's text for one page, under `key` (joined\n * on `join`). Undefined when the manifest does not parse, has no entry for\n * the page, or the entry has no such field.\n */\nfunction manifestValue(\n text: string | undefined,\n key: string,\n join: ManifestRef[\"join\"],\n field: string,\n parse: ParseYaml,\n): unknown {\n if (text === undefined) return undefined;\n const data = parse(text);\n if (!isRecord(data)) return undefined;\n for (const [candidate, value] of Object.entries(data)) {\n const same =\n join === \"path\" ? posix.normalize(candidate) === posix.normalize(key) : candidate === key;\n if (same && isRecord(value)) return value[field];\n }\n return undefined;\n}\n\nfunction isRecord(x: unknown): x is Record<string, unknown> {\n return typeof x === \"object\" && x !== null && !Array.isArray(x);\n}\n\n/**\n * `git cat-file --batch` by `<rev>:<path>`, keyed by the spec. The output\n * header names the object, not the spec, so it is read in input order; a\n * spec that names nothing answers `<spec> missing` and yields nothing. An\n * answer past the read cap is asked for again in halves, since one batch now\n * serves a whole root; only one object past the cap is too large.\n */\nasync function fetchSpecs(run: GitRun, specs: readonly string[]): Promise<Map<string, string>> {\n const found = new Map<string, string>();\n if (specs.length === 0) return found;\n const out = await run([\"cat-file\", \"--batch\"], `${specs.join(\"\\n\")}\\n`);\n if (out.tooLarge && specs.length > 1) {\n const half = Math.ceil(specs.length / 2);\n const first = await fetchSpecs(run, specs.slice(0, half));\n const rest = await fetchSpecs(run, specs.slice(half));\n return new Map([...first, ...rest]);\n }\n if (out.tooLarge) throw new HistoryTooLarge();\n if (out.code !== 0) throw new BlobsUnreadable(`exit ${String(out.code)}`);\n for (const [spec, content] of parseSpecBatch(out.raw, specs)) found.set(spec, content);\n return found;\n}\n\n/**\n * The objects a `git cat-file --batch` answer holds for `specs`, in input\n * order. A header that cannot be read, or output that ends before every spec\n * is answered, leaves no way to find the next object, so the answer is\n * refused rather than cut short: a cut-short answer would read the rest as\n * stamps that are not there, and report them stale.\n */\nexport function parseSpecBatch(buf: Buffer, specs: readonly string[]): Map<string, string> {\n const found = new Map<string, string>();\n let cursor = 0;\n for (const spec of specs) {\n const nl = buf.indexOf(0x0a, cursor);\n if (nl === -1) throw new BlobsUnreadable(`the answer ends before ${spec}`);\n const header = buf.toString(\"utf8\", cursor, nl);\n cursor = nl + 1;\n if (header.endsWith(\" missing\") || header.endsWith(\" ambiguous\")) continue;\n const parts = header.split(\" \");\n const size = Number(parts[2]);\n if (parts.length !== 3 || !Number.isInteger(size) || size < 0) {\n throw new BlobsUnreadable(`unreadable header for ${spec}: ${header}`);\n }\n if (parts[1] === \"blob\") found.set(spec, buf.toString(\"utf8\", cursor, cursor + size));\n cursor += size + 1;\n }\n return found;\n}\n\n// ---------------------------------------------------------------------------\n// Small helpers\n\nfunction extractorFor(input: DeriveInput): MetadataExtractor | undefined {\n return (\n extractorByName(input.extracted.format) ??\n extractorForExtension(extname(input.absPath))\n );\n}\n\n/** The stamps a blob carries; a blob that fails to parse carries none. */\nfunction extractStamps(\n extractor: MetadataExtractor | undefined,\n content: string,\n filePath: string,\n): Record<string, unknown> {\n if (!extractor) return {};\n try {\n return extractor.extract(content, filePath).data;\n } catch {\n return {};\n }\n}\n\n/**\n * Bodies compare with CRLF folded to LF: `core.autocrlf` rewrites line\n * endings between the working tree and the index, and that is not an edit.\n * An absent blob (a file being added, or one with no history) matches only\n * another absent blob.\n */\nfunction sameBody(a: string | null, b: string | null): boolean {\n if (a === null || b === null) return a === b;\n return a.replace(/\\r\\n/g, \"\\n\") === b.replace(/\\r\\n/g, \"\\n\");\n}\n\nfunction sameValue(a: unknown, b: unknown): boolean {\n return toJsonText(a) === toJsonText(b);\n}\n\nconst short = (sha: string): string => sha.slice(0, 7);\n\n/**\n * The UTC `YYYY-MM-DD` of a `%aI` string (proposal 0072). The author's own\n * offset would date one instant differently on two machines, so a page\n * stamped on a branch read stale on main once a squash put another commit's\n * offset in its place.\n */\nconst datePart = (iso: string): string => {\n const d = new Date(iso);\n // A malformed record parses to an empty author date; keep it empty rather\n // than throw, as slicing the string did.\n return Number.isNaN(d.getTime()) ? \"\" : utcDate(d);\n};\n\n/** Today, or any instant, as a UTC day: the same answer on every machine. */\nfunction utcDate(d: Date): string {\n return d.toISOString().slice(0, 10);\n}\n\n/** `Name <email>` → `Name`; a bare name is returned trimmed. */\nfunction nameOf(trailer: string): string {\n const lt = trailer.lastIndexOf(\"<\");\n return (lt === -1 ? trailer : trailer.slice(0, lt)).trim();\n}\n\nfunction emailOf(trailer: string): string | null {\n const m = /<([^>]*)>\\s*$/.exec(trailer);\n return m?.[1]?.trim() ?? null;\n}\n\n// ---------------------------------------------------------------------------\n// Process plumbing\n\ninterface GitOutput {\n /** Exit code; null when git was killed by a signal or never started. */\n code: number | null;\n /**\n * The bytes of stdout, undecoded: `cat-file` sizes are byte counts, and\n * the log is decoded only where it is read, through `text()`.\n */\n raw: Buffer;\n /** True when `git` itself could not be started (not on PATH). */\n missing: boolean;\n /** True when stdout passed the byte cap; `raw` is then empty. */\n tooLarge: boolean;\n /** The start of stderr, decoded, for a failure message; `MAX_STDERR_BYTES` at most. */\n stderr: string;\n}\n\n/** How much of a git process's stderr is kept: enough for its `fatal:` line. */\nconst MAX_STDERR_BYTES = 16 * 1024;\n\n/** One git command in a fixed root, with the run's byte cap bound in. */\ntype GitRun = (args: string[], stdin?: string) => Promise<GitOutput>;\n\n/**\n * How many pages derive reads from git at once. Past eight, a measured run of\n * 239 blames gained little (2.1s at 8, 1.7s at 24, 12s one at a time).\n */\nconst GIT_CONCURRENCY = Math.min(8, availableParallelism());\n\n/**\n * Decode stdout as UTF-8. The cap keeps the byte count under V8's string\n * limit, so a decode that still throws is treated the same way rather than\n * escaping as a crash.\n */\nfunction text(out: GitOutput): string {\n try {\n return out.raw.toString(\"utf8\");\n } catch {\n throw new HistoryTooLarge();\n }\n}\n\n/**\n * One git process from `cwd`, modelled on `checkIgnore` in gitignore.ts.\n * stdout is collected whole and capped at `maxBytes`: past the cap the\n * child is killed and the result says `tooLarge` instead of carrying the\n * bytes. Anything thrown while assembling the result rejects the promise\n * rather than escaping the 'close' handler as an uncaught exception.\n */\nfunction runGit(\n args: string[],\n cwd: string,\n stdin: string | undefined,\n maxBytes: number,\n): Promise<GitOutput> {\n return new Promise((settle, reject) => {\n let done = false;\n const finish = (out: GitOutput): void => {\n if (done) return;\n done = true;\n settle(out);\n };\n const fail = (err: unknown): void => {\n if (done) return;\n done = true;\n reject(err instanceof Error ? err : new Error(String(err)));\n };\n const failed = (missing: boolean): GitOutput => ({\n code: null,\n raw: Buffer.alloc(0),\n missing,\n tooLarge: false,\n stderr: \"\",\n });\n\n let child: ChildProcessWithoutNullStreams;\n try {\n child = spawn(\"git\", args, { cwd, windowsHide: true });\n } catch {\n finish(failed(true));\n return;\n }\n\n let chunks: Buffer[] = [];\n let total = 0;\n let tooLarge = false;\n child.stdout.on(\"data\", (chunk: Buffer) => {\n if (tooLarge) return;\n total += chunk.length;\n if (total > maxBytes) {\n tooLarge = true;\n chunks = [];\n child.kill();\n return;\n }\n chunks.push(chunk);\n });\n // Drain stderr so a chatty git cannot fill the pipe and stall, keeping\n // its start for the message a failure reports.\n const errChunks: Buffer[] = [];\n let errTotal = 0;\n child.stderr.on(\"data\", (chunk: Buffer) => {\n if (errTotal >= MAX_STDERR_BYTES) return;\n const kept = chunk.subarray(0, MAX_STDERR_BYTES - errTotal);\n errTotal += kept.length;\n errChunks.push(kept);\n });\n // No binary on PATH lands here rather than throwing from spawn().\n child.on(\"error\", (err: NodeJS.ErrnoException) => {\n finish(failed(err.code === \"ENOENT\"));\n });\n // A dead child makes the pipe write fail; 'error'/'close' report that.\n child.stdin.on(\"error\", () => {});\n child.on(\"close\", (code) => {\n try {\n const raw = tooLarge ? Buffer.alloc(0) : Buffer.concat(chunks);\n const stderr = Buffer.concat(errChunks).toString(\"utf8\");\n finish({ code, raw, missing: false, tooLarge, stderr });\n } catch (err) {\n fail(err);\n }\n });\n\n if (stdin === undefined) child.stdin.end();\n else child.stdin.end(stdin);\n });\n}\n","/** Bounded worker pool that preserves input order in its output. */\nexport async function mapConcurrent<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T) => Promise<R>,\n): Promise<R[]> {\n const out = new Array<R>(items.length);\n let next = 0;\n const workers = Array.from(\n { length: Math.max(1, Math.min(limit, items.length)) },\n async () => {\n for (;;) {\n const i = next++;\n const item = items[i];\n if (i >= items.length || item === undefined) return;\n out[i] = await fn(item);\n }\n },\n );\n await Promise.all(workers);\n return out;\n}\n","/**\n * The `derived` table (proposal 0040): what the evidence says each derivable\n * field should be, one row per file, as a read-only SQL view beside `docs`.\n *\n * `query` builds it when a statement names it, and a corpus check that names\n * it gets the same view — this module is what keeps the two from drifting.\n * It is a view over a backing table rather than a table, so that SQLite's own\n * `cannot modify derived because it is a view` refuses a write before any\n * effect gate has to: the value it holds is not stored anywhere, and the only\n * way to change it is to change the evidence. Both objects are transient: a\n * `--db` export drops them before the handle closes, so a frozen derived\n * value never outlives the run that computed it.\n *\n * The columns are the run's: the six built-in fields, then one per key of\n * `derive.commands` (proposal 0042), so a command-derived field is read\n * exactly as a built-in one is.\n */\nimport type { DatabaseSync } from \"node:sqlite\";\nimport type { DocmetaConfig } from \"../config.js\";\nimport { bindValue, quoteIdent, RESERVED } from \"../projection.js\";\nimport { commandsOf, machinesOf } from \"./config.js\";\nimport { assertSourcesAvailable, deriveMetadata } from \"./index.js\";\nimport {\n DERIVE_SOURCES,\n PROVENANCE_FIELD,\n derivableFields,\n type DerivableField,\n type DeriveCommand,\n type DerivedRecord,\n type DeriveInput,\n} from \"./types.js\";\n\n/** The view's name, and the backing table the rows actually sit in. */\nexport const DERIVED_VIEW = \"derived\";\nexport const DERIVED_ROWS = \"_derived_rows\";\n\n/** The third table: the effective value per field, over `docs` and the rows. */\nexport const RESOLVED_VIEW = \"resolved\";\n\n/** The two columns `resolved` adds past the fields: which side, and why. */\nconst ORIGIN_COLUMN = \"_origin\";\nconst SOURCES_COLUMN = \"_sources\";\n\n/** The view's columns, in order: the path, every derivable field, the evidence. */\nexport function derivedColumns(commands?: Readonly<Record<string, DeriveCommand>>): string[] {\n return [\"_path\", ...derivableFields(commands), SOURCES_COLUMN];\n}\n\n/**\n * Does the statement name the `derived` table? The search wants `derived`\n * where a table goes — after FROM, JOIN, UPDATE, INTO, TABLE or VIEW, bare\n * or double-quoted — so that the word inside a string literal, a comment or\n * a column alias does not spawn git for nothing. A spelling this misses\n * (`main.derived`, a CTE that shadows it) is caught by the engine's own\n * `no such table: derived`, which `query` rescues with a lazy build.\n */\nexport function mentionsDerived(sql: string): boolean {\n return /\\b(?:from|join|update|into|table|view)\\s+(?:\"derived\"|derived\\b)/i.test(sql);\n}\n\n/**\n * The derivable fields a statement can read, out of `fields` — the run's\n * own list, see `derivableFields`: every one of them when it selects `*`, or\n * reads `_sources` or `_origin` (the evidence and the origin map span them\n * all), otherwise the field names\n * it spells out, quoted or not. `provenance` is the exception to the first\n * half: it costs a blame per page, which proposal 0046 confines to runs that\n * ask for it, so only its name brings it in here (`derive.fields` is the\n * other way, which `deriveForTable` adds). `owner` is not `owners` and `created` is\n * not `recreated`, and the hyphen inside `last-updated` counts as part of\n * the name; a command key is matched as written, whatever it contains.\n * Over-triggering costs one source consulted for nothing; under-triggering\n * would leave a named column NULL, so a field that appears anywhere in the\n * text — a literal, a comment — is derived.\n */\nexport function fieldsForSql(sql: string, fields: readonly DerivableField[]): DerivableField[] {\n const named = (field: string): boolean =>\n new RegExp(`(?<![\\\\w-])${escapeRegExp(field)}(?![\\\\w-])`, \"i\").test(sql);\n if (sql.includes(\"*\") || /\\b_(?:sources|origin)\\b/i.test(sql)) {\n return fields.filter((field) => field !== PROVENANCE_FIELD || named(field));\n }\n return fields.filter(named);\n}\n\nfunction escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Create the backing table, load one row per record, and expose it as the\n * `derived` view. `columns` is the run's list (`derivedColumns`), and the\n * values are placed by it, so the view and the rows agree by construction.\n * Values go through `bindValue`, so a list is JSON text exactly as it is in\n * `docs`; `_sources` is the JSON object `{field: {source, evidence}}` over\n * the non-null fields.\n */\nexport function createDerivedView(\n db: DatabaseSync,\n records: ReadonlyMap<string, DerivedRecord>,\n columns: readonly string[],\n): void {\n const quoted = columns.map(quoteIdent);\n db.exec(\n `CREATE TABLE ${DERIVED_ROWS} (${quoted\n .map((c, i) => (i === 0 ? `${c} TEXT PRIMARY KEY` : `${c} TEXT`))\n .join(\", \")})`,\n );\n const insert = db.prepare(\n `INSERT INTO ${DERIVED_ROWS} VALUES (${quoted.map(() => \"?\").join(\", \")})`,\n );\n const fields = columns.slice(1, -1);\n db.exec(\"BEGIN\");\n // Committed or rolled back, never left open: the caller may keep using the\n // handle after a failed insert, and every later statement would otherwise\n // run inside the half-built transaction.\n let committed = false;\n try {\n for (const [label, record] of records) {\n const sources: Record<string, { source: string; evidence: string }> = {};\n const values = fields.map((field) => {\n const derived = record.fields[field];\n if (derived == null) return null;\n sources[field] = { source: derived.source, evidence: derived.evidence };\n return bindValue(derived.value);\n });\n insert.run(label, ...values, JSON.stringify(sources));\n }\n db.exec(\"COMMIT\");\n committed = true;\n } finally {\n if (!committed) db.exec(\"ROLLBACK\");\n }\n db.exec(`CREATE VIEW ${DERIVED_VIEW} AS SELECT * FROM ${DERIVED_ROWS}`);\n}\n\n/**\n * Every column `resolved` carries, in order: `_path`, the `docs` data columns,\n * then any derivable field `docs` does not already have, then `_origin` and\n * `_sources`. A docs column that is also a derivable field appears once, in\n * the position `docs` gives it, so the field list only ever adds.\n *\n * The system columns are skipped: `_path` is already first, and `_format`,\n * `_present` and `_data` are facts about the document rather than values a\n * source could state. A frontmatter key spelled `_origin` or `_sources` is\n * skipped for the same reason a reserved one is — the column is taken.\n */\nexport function resolvedColumns(\n docsColumns: readonly string[],\n commands?: Readonly<Record<string, DeriveCommand>>,\n): string[] {\n const columns = [\"_path\"];\n const seen = new Set<string>([\"_path\", ORIGIN_COLUMN, SOURCES_COLUMN]);\n for (const column of docsColumns) {\n if (seen.has(column) || RESERVED.has(column)) continue;\n seen.add(column);\n columns.push(column);\n }\n for (const field of derivableFields(commands)) {\n if (seen.has(field)) continue;\n seen.add(field);\n columns.push(field);\n }\n columns.push(ORIGIN_COLUMN, SOURCES_COLUMN);\n return columns;\n}\n\n/**\n * Does the statement name the `resolved` table? The twin of `mentionsDerived`,\n * with the same shape and the same reason: `resolved` where a table goes, so\n * that a column alias or the word inside `unresolved` does not build a view —\n * and, more to the point, does not spawn git behind it.\n */\nexport function mentionsResolved(sql: string): boolean {\n return /\\b(?:from|join|update|into|table|view)\\s+(?:\"resolved\"|resolved\\b)/i.test(sql);\n}\n\n/** One field name as a SQLite JSON path step: `$.\"last-updated\"`. */\nfunction jsonPath(field: string): string {\n // JSON.stringify quotes and escapes exactly the way SQLite's path parser\n // reads a quoted label — `\\\"` for a quote, `\\\\` for a backslash — and the\n // way the label was written into `_data` in the first place.\n return `$.${JSON.stringify(field)}`;\n}\n\n/** Any string as a SQL string literal (doubling internal apostrophes). */\nfunction sqlString(value: string): string {\n return `'${value.replaceAll(\"'\", \"''\")}'`;\n}\n\n/**\n * Create the `resolved` view: one row per `docs` row, holding the effective\n * value of every field — what the document asserts when it carries the key,\n * what the evidence derived otherwise — plus `_origin` saying which of the two\n * answered, and the derived row's `_sources` unchanged. Call after\n * `createDocsTable` and `createDerivedView`.\n *\n * **Presence is decided by `_data`, never by NULL.** A docs column is NULL\n * both when the key is absent and when the document writes `key: null`, and\n * those are opposite answers: an explicit null is an assertion, and the\n * derived value must not overwrite it. So each field asks\n * `json_type(_data, '$.\"field\"') IS NOT NULL`, which is true for a JSON null\n * and false for an absent key.\n *\n * `_origin` is `json_patch('{}', json_object(…))` over a CASE per field that\n * yields `'asserted'`, `'derived'`, or NULL. `json_object` alone would keep\n * the NULL members — a field neither side has would read as present with a\n * null origin — and RFC 7396 merge-patch, which `json_patch` implements, is\n * exactly the \"a null member deletes the key\" rule that drops them. One patch\n * call does the whole object, so the shape stays flat however many fields the\n * run carries.\n *\n * The join is a LEFT JOIN, so a file the derive run has no row for keeps its\n * asserted values with an all-`asserted` `_origin` and a NULL `_sources`.\n *\n * Read-only by construction: SQLite refuses a write to a view with no\n * INSTEAD OF trigger, and there is none. The effective value is not stored\n * anywhere, so the only way to change it is to change the document or the\n * evidence.\n *\n * Call it after `createDocsTable` and `createDerivedView`. SQLite accepts a\n * view over a table that does not exist yet and fails only at the first read,\n * as `no such table: main._derived_rows`, far from the call that got the\n * order wrong.\n */\nexport function createResolvedView(\n db: DatabaseSync,\n docsColumns: readonly string[],\n commands?: Readonly<Record<string, DeriveCommand>>,\n): void {\n const columns = resolvedColumns(docsColumns, commands);\n const fields = columns.slice(1, -2);\n const inDocs = new Set(docsColumns);\n const inDerived = new Set(derivableFields(commands));\n\n const selects = [`d.${quoteIdent(\"_path\")} AS ${quoteIdent(\"_path\")}`];\n const origin: string[] = [];\n for (const field of fields) {\n const path = sqlString(jsonPath(field));\n const asserted = `json_type(d.${quoteIdent(\"_data\")}, ${path}) IS NOT NULL`;\n // A field with no docs column can only be asserted by an inconsistent\n // table, but `_data` answers for it either way and costs nothing here.\n const assertedValue = inDocs.has(field)\n ? `d.${quoteIdent(field)}`\n : `d.${quoteIdent(\"_data\")} ->> ${path}`;\n if (inDerived.has(field)) {\n const derivedValue = `r.${quoteIdent(field)}`;\n selects.push(\n `CASE WHEN ${asserted} THEN ${assertedValue} ELSE ${derivedValue} END AS ${quoteIdent(field)}`,\n );\n origin.push(\n `${sqlString(field)}, CASE WHEN ${asserted} THEN 'asserted' WHEN ${derivedValue} IS NOT NULL THEN 'derived' END`,\n );\n } else {\n // A docs-only column: no source states it, so the document always wins.\n selects.push(`${assertedValue} AS ${quoteIdent(field)}`);\n origin.push(`${sqlString(field)}, CASE WHEN ${asserted} THEN 'asserted' END`);\n }\n }\n selects.push(\n `json_patch('{}', json_object(${origin.join(\", \")})) AS ${quoteIdent(ORIGIN_COLUMN)}`,\n );\n selects.push(`r.${quoteIdent(SOURCES_COLUMN)} AS ${quoteIdent(SOURCES_COLUMN)}`);\n\n db.exec(\n `CREATE VIEW ${RESOLVED_VIEW} AS SELECT ${selects.join(\", \")} FROM docs d LEFT JOIN ${DERIVED_ROWS} r USING (${quoteIdent(\"_path\")})`,\n );\n}\n\n/** Where a table build stands: the run's directories and its config. */\nexport interface DeriveTableContext {\n cwd: string;\n base: string;\n configDir?: string;\n config: DocmetaConfig | null;\n /** Whether the GitHub or GitLab review cache may answer; `--no-cache` clears it. */\n cache: boolean;\n /** The clock an uncommitted body change is dated by; default `new Date()`. */\n now?: () => Date;\n}\n\n/**\n * Derive the table's rows: `fields` — what the caller's statements can read,\n * see `fieldsForSql`, plus `provenance` when `derive.fields` manages it — from the sources the config allows (all five when it\n * says nothing), with the review cache on. The view keeps every column, and\n * a field not derived is NULL in it; only a source some named field needs\n * is consulted, so a statement reading `owner` never spawns `gh`, and a\n * configured command runs only when its field is read. A requested source\n * that cannot answer is the run's error, never an empty column — the same\n * rule `validate` and `derive` follow — and `hint` is the caller's own way\n * out.\n */\nexport async function deriveForTable(\n inputs: readonly DeriveInput[],\n ctx: DeriveTableContext,\n hint: string,\n fields: readonly DerivableField[],\n): Promise<Map<string, DerivedRecord>> {\n const derive = ctx.config?.derive;\n const commands = commandsOf(derive);\n // `*` does not read `provenance` (its blame per page is paid only when\n // asked for), so a run whose `derive.fields` manages it asks here.\n const managesProvenance =\n derive?.fields?.includes(PROVENANCE_FIELD) === true && !fields.includes(PROVENANCE_FIELD);\n const result = await deriveMetadata(inputs, {\n cwd: ctx.cwd,\n base: ctx.base,\n ...(ctx.configDir !== undefined ? { configDir: ctx.configDir } : {}),\n sources: derive?.sources ?? [...DERIVE_SOURCES],\n fields: managesProvenance ? [...fields, PROVENANCE_FIELD] : fields,\n ...(derive?.codeowners !== undefined ? { codeowners: derive.codeowners } : {}),\n ...(commands !== undefined ? { commands } : {}),\n cache: ctx.cache,\n now: ctx.now ?? (() => new Date()),\n machines: machinesOf(derive),\n });\n assertSourcesAvailable(result.sources, hint);\n return result.records;\n}\n","/**\n * Named corpus checks (proposal 0026): SQL from the config's `checks:` list,\n * run over the same `docs` projection `query` builds, whose result rows are\n * **findings** rather than a table.\n *\n * The column convention is the whole mapping: `path` (required) names the file\n * a finding attaches to, `line` its 1-based source line, `key` the metadata\n * field at fault (it becomes the `instancePath`, and with it part of the\n * finding's baseline identity), `message` the prose. A row that follows it\n * becomes an ordinary `FieldError` — `schema: \"check:<name>\"`, `keyword:\n * \"check\"` — and every downstream surface (pretty, github, SARIF, JUnit, the\n * baseline ratchet) works unchanged.\n */\nimport { DocmetaError, type FieldError } from \"../types.js\";\nimport { CHECK_NAME, type CheckConfig } from \"./config.js\";\nimport { escapePointerSegment } from \"../extractors/pointer.js\";\nimport {\n assertSingleStatement,\n collectNamedParameters,\n corpusDataColumns,\n createDocsTable,\n loadSqlite,\n registerLineFor,\n stripLeadingTrivia,\n type ProjectionEntry,\n} from \"./projection.js\";\nimport {\n collectCollections,\n createCollectionViews,\n type CollectionParams,\n} from \"./collections.js\";\nimport {\n createDerivedView,\n createResolvedView,\n derivedColumns,\n fieldsForSql,\n mentionsDerived,\n mentionsResolved,\n} from \"./derive/table.js\";\nimport {\n derivableFields,\n type DerivableField,\n type DeriveCommand,\n type DerivedRecord,\n} from \"./derive/types.js\";\nimport { errorMessage } from \"../../shared/errors.js\";\n\n/** One loaded file a check may attach findings to. */\nexport type CheckEntry = ProjectionEntry;\n\n/** The `keyword` every check finding carries: no Ajv keyword produced it. */\nexport const CHECK_KEYWORD = \"check\";\n\n/**\n * The `schema` ref a check's findings carry — and their baseline identity.\n *\n * The grammar is asserted here as well as in the config parser: a\n * programmatic `CheckConfig` never passes through `parseChecks`, and a\n * path-shaped name (`../evil`, `slugs.json`) would classify as a file ref and\n * fingerprint cwd-relative — the identity bug `CHECK_NAME` exists to prevent.\n */\nexport function checkSchemaRef(name: string): string {\n if (!CHECK_NAME.test(name) || name.toLowerCase().endsWith(\".json\")) {\n throw new DocmetaError(\n `check name \"${name}\" must match [a-z0-9][a-z0-9._-]* and not end in \".json\" — the name is part of each finding's identity (check:<name>).`,\n );\n }\n return `check:${name}`;\n}\n\n/** The columns the convention consumes; everything else feeds the message. */\nconst CONVENTION_COLUMNS = new Set([\"path\", \"line\", \"key\", \"message\"]);\n\n/**\n * Map one check's result rows to findings, keyed by file path.\n *\n * `loaded` is the set of paths this run holds extractions for. A row naming\n * any other path is a broken check, not a finding: fabricating a result for a\n * file the run never read would corrupt the summary, so it refuses (exit 2)\n * with the check named — the same class as SQL that does not prepare. On the\n * `query --check` path no set is passed: the SELECT is the user's own, its\n * `path` column is taken at its word (`<stdin>` included — proposal 0026\n * § stress test 7), and only a non-string path refuses.\n */\nexport function rowsToFindings(\n name: string,\n columns: readonly string[],\n rows: readonly Record<string, unknown>[],\n loaded?: ReadonlySet<string>,\n): Map<string, FieldError[]> {\n if (!columns.includes(\"path\")) {\n throw new DocmetaError(\n `check \"${name}\": the result has no \\`path\\` column. A check's SELECT names its findings through the column convention: \\`path\\` (required), and optionally \\`line\\`, \\`key\\`, and \\`message\\`; any other column is folded into the message.`,\n );\n }\n const findings = new Map<string, FieldError[]>();\n const extras = columns.filter((c) => !CONVENTION_COLUMNS.has(c));\n for (const row of rows) {\n const path = row.path;\n if (typeof path !== \"string\" || (loaded !== undefined && !loaded.has(path))) {\n throw new DocmetaError(\n `check \"${name}\": a result row names ${JSON.stringify(path)}, which this run did not load — a finding must attach to a file of the corpus. Fix the check's \\`path\\` column.`,\n );\n }\n const key = typeof row.key === \"string\" && row.key !== \"\" ? row.key : undefined;\n const line = asLine(row.line);\n const message =\n typeof row.message === \"string\" && row.message !== \"\"\n ? row.message\n : synthesizeMessage(extras, row);\n const err: FieldError = {\n schema: checkSchemaRef(name),\n keyword: CHECK_KEYWORD,\n // RFC 6901 escaping, or a key containing `/` or `~` would build a\n // pointer that parses as a different (nested) location.\n instancePath: key === undefined ? \"\" : `/${escapePointerSegment(key)}`,\n message,\n ...(line === undefined ? {} : { line }),\n };\n const bucket = findings.get(path);\n if (bucket) bucket.push(err);\n else findings.set(path, [err]);\n }\n return findings;\n}\n\n/** A `line` cell, when it is the 1-based positive integer the contract means. */\nfunction asLine(value: unknown): number | undefined {\n const n =\n typeof value === \"bigint\" ? Number(value) : typeof value === \"number\" ? value : undefined;\n return n !== undefined && Number.isInteger(n) && n > 0 ? n : undefined;\n}\n\n/**\n * The fallback prose when a check declares no `message`: `col=value` over the\n * remaining columns, so a lazy `SELECT _path AS path, slug FROM …` is still\n * usable — not so it is a good idea; write a message. A NULL cell says\n * nothing, so it is omitted rather than rendered as a literal `null`; when\n * every remaining cell is NULL the generic fallback stands.\n */\nfunction synthesizeMessage(\n extras: readonly string[],\n row: Record<string, unknown>,\n): string {\n const pairs = extras.flatMap((c) => {\n const value = row[c];\n if (value === null || value === undefined) return [];\n // SQL cells are string | number | bigint (a BLOB cannot arise from the\n // projection's text/numeric columns); the JSON fallback keeps a future\n // surprise printable rather than \"[object Object]\".\n const text =\n typeof value === \"string\"\n ? value\n : typeof value === \"number\" || typeof value === \"bigint\"\n ? String(value)\n : JSON.stringify(value);\n return [`${c}=${text}`];\n });\n return pairs.length > 0 ? pairs.join(\", \") : \"check matched\";\n}\n\n/**\n * Run every configured check over the corpus and merge their findings.\n *\n * The projection is the one `query` builds — same columns, same value\n * conventions — plus `lineFor(path, key)` so a check can carry a source line.\n * A check whose SQL cannot prepare, or whose rows break the column\n * convention, aborts the run with the check named: a broken rule is an\n * operational error, never a finding or a silent skip.\n */\n/**\n * The run context a check projection may need beyond the entries themselves:\n * the declared collections that become views, and the two directories\n * membership is arithmetic between (proposal 0041 rules 7 and 10). No\n * resolution inputs: a check's `FROM authors` means \"the files the authors\n * collection selects\", which is what the config says, and deciding it costs\n * nothing but string arithmetic. The shape IS `CollectionParams`: it is handed\n * to `collectCollections` verbatim, and an intersection is what keeps the two\n * from drifting apart field by field.\n *\n * `derive` is the one addition (proposal 0040): how to get the rows behind\n * the `derived` and `resolved` tables when a check names either. A function\n * rather than the rows,\n * because building them spawns git, and a check that never names the table\n * must not pay for it. It is handed the fields the checks can read, so a\n * caller deriving from scratch consults only the sources those need; a\n * caller that already derived more may hand back what it has. Absent, a\n * check naming the table is refused.\n */\nexport type CheckRunContext = CollectionParams & {\n derive?: (\n fields: readonly DerivableField[],\n ) => Promise<ReadonlyMap<string, DerivedRecord>>;\n /**\n * The configured commands (proposal 0042), whose keys are columns of the\n * `derived` table beside the built-ins. Handed over rather than read from a\n * config, because since proposal 0041 a check's context carries none.\n */\n commands?: Readonly<Record<string, DeriveCommand>>;\n};\n\nexport async function runChecks(\n checks: readonly CheckConfig[],\n entries: readonly CheckEntry[],\n ctx: CheckRunContext = {},\n): Promise<Map<string, FieldError[]>> {\n const merged = new Map<string, FieldError[]>();\n if (checks.length === 0) return merged;\n\n const { DatabaseSync } = await loadSqlite();\n const db = new DatabaseSync(\":memory:\");\n try {\n // The one column list both `docs` and `resolved` are built from: the\n // view's asserted side reads those columns by name, so a second call\n // could not be allowed to disagree with the table's.\n const dataColumns = corpusDataColumns(entries);\n createDocsTable(db, entries, dataColumns);\n registerLineFor(db, entries);\n createCollectionViews(db, collectCollections(entries, ctx));\n // The derived channel's tables (0040), when any check names one: the same\n // views `query` builds, over the union of the fields those checks can\n // read. Either name builds both — `resolved` is `docs` joined to the same\n // rows — so a check reading the effective value costs the same one\n // derivation. Before `query_only`, since building them loads a table.\n const wantsDerived = checks.filter(\n (c) => mentionsDerived(c.query) || mentionsResolved(c.query),\n );\n if (wantsDerived.length > 0) {\n if (ctx.derive === undefined) {\n throw new DocmetaError(\n `check \"${wantsDerived[0]?.name ?? \"\"}\": the SQL names the derived or resolved table, but this run cannot derive. Run it through \\`manni meta validate\\`, or drop the reference.`,\n );\n }\n // The run's columns: the built-ins and the configured command keys\n // (0042), handed over by the caller that read the config.\n const commands = ctx.commands;\n const readable = derivableFields(commands);\n const fields = new Set<DerivableField>();\n for (const c of wantsDerived) for (const f of fieldsForSql(c.query, readable)) fields.add(f);\n createDerivedView(db, await ctx.derive([...fields]), derivedColumns(commands));\n createResolvedView(db, dataColumns, commands);\n }\n // Checks are SELECT-only by design — 0021's original discipline, which\n // 0022 lifted for `query` because writes became query's *feature*, judged\n // by its effect gate. Checks have no such gate: without this, an UPDATE\n // in one check mutates the shared projection every later check computes\n // over, and a DELETE/DROP is misdiagnosed downstream. Set after the\n // table and views are built, before any check's SQL runs.\n db.exec(\"PRAGMA query_only = 1\");\n const loaded = new Set(entries.map((e) => e.label));\n\n for (const check of checks) {\n // ATTACH and VACUUM write files of their own, which `query_only`\n // does not fully prevent (ATTACH creates the attached file; VACUUM\n // INTO creates its target before the engine refuses) — the same two\n // statements `query` refuses by name.\n const head = stripLeadingTrivia(check.query);\n if (/^(attach|vacuum)\\b/i.test(head)) {\n throw new DocmetaError(\n `check \"${check.name}\": ${head.split(/\\s/, 1)[0]?.toUpperCase() ?? \"that statement\"} is refused: it can write outside the docs table.`,\n );\n }\n // Checks bind nothing, so any named parameter would silently bind\n // NULL, match nothing, and green the gate forever — the false-green\n // shape the query-side guard refuses with a bind; here the remedy is\n // to inline the value.\n let tokens: string[];\n try {\n tokens = collectNamedParameters(check.query);\n } catch (err) {\n // The scan's own refusal (one name under two prefixes), check named.\n throw new DocmetaError(\n `check \"${check.name}\": ${errorMessage(err)}`,\n );\n }\n if (tokens.length > 0) {\n throw new DocmetaError(\n `check \"${check.name}\": the SQL references ${tokens.join(\", \")}, but checks bind no parameters — an unbound name binds NULL and matches nothing, so the gate would pass on a typo. Inline the value in the SQL.`,\n );\n }\n let columns: string[];\n let rows: Record<string, unknown>[];\n try {\n assertSingleStatement(check.query);\n const stmt = db.prepare(check.query);\n columns = stmt.columns().map((c) => c.name);\n rows = stmt.all();\n } catch (err) {\n const message = errorMessage(err);\n throw new DocmetaError(\n message.includes(\"attempt to write a readonly database\")\n ? `check \"${check.name}\": ${message} — checks are read-only by design; a check is a SELECT over the projection. Edit the corpus with \\`manni meta query\\` instead.`\n : `check \"${check.name}\": ${message}`,\n );\n }\n for (const [path, errs] of rowsToFindings(\n check.name,\n columns,\n rows,\n loaded,\n )) {\n const bucket = merged.get(path);\n if (bucket) bucket.push(...errs);\n else merged.set(path, errs);\n }\n }\n } finally {\n db.close();\n }\n return merged;\n}\n","/**\n * Where a page's `provenance` record lives (proposal 0046 § In an external\n * manifest): in the page's frontmatter, or in the external-metadata manifest\n * of a collection the page belongs to, when that manifest owns the key.\n *\n * `derive` writes the record there, and every reader that compares it (the\n * derive command, `validate`, `get`) hands the same manifest to the git\n * source, so evidence rule 2 reads the manifest's blob at each commit rather\n * than the page's frontmatter. Membership is decided by every declared\n * collection, as cite decides it for `citations`: a page named by path is\n * still a member of the collection whose manifest holds its record.\n */\nimport { isAbsolute, relative, resolve, sep } from \"node:path\";\nimport {\n ownsKey,\n type CollectionConfig,\n type ExternalMetadataConfig,\n} from \"../../../shared/collections.js\";\nimport { hasPagePlaceholder, pageManifestPath } from \"../../../shared/page-manifest.js\";\nimport { DocmetaError } from \"../../types.js\";\nimport { memberOf } from \"../collections.js\";\nimport { externalMetadataJoin, outsideRefusal, PATH_JOIN, reportedPath } from \"../external-metadata.js\";\nimport { classifyRef } from \"../schema-registry.js\";\nimport {\n PROVENANCE_FIELD,\n STAMPED_DATE_FIELDS,\n type ManifestRef,\n type StampedDateField,\n} from \"./types.js\";\n\n/** A manifest that owns `provenance` for one collection. */\nexport interface ProvenanceManifest {\n collection: string;\n /**\n * The manifest file, absolute. For a `{page}` manifest (proposal 0058) as\n * `provenanceManifests` lists it, the pattern resolved as a path; a place\n * carries the page's own file.\n */\n absPath: string;\n /** The manifest as the run reports it: relative to the run's base, posix. The pattern as written, for a `{page}` manifest before placing. */\n file: string;\n /** `path`, or the page field the manifest joins on. */\n join: string;\n /** `file:` holds `{page}`, so each page keeps its record in a manifest of its own. */\n perPage: boolean;\n /** `file:` as the config writes it, which a `{page}` manifest resolves per page. */\n written: string;\n /**\n * The manifest names no `keys` (proposal 0068), so it holds a page's record\n * only when the page's schemas mark `provenance` external. The declaration,\n * for `ownsKey`.\n */\n implied?: { collection: CollectionConfig; manifest: ExternalMetadataConfig; url: boolean };\n}\n\n/** One page's record in a manifest. */\nexport interface ProvenancePlace extends ManifestRef {\n manifest: ProvenanceManifest;\n}\n\nconst toPosix = (p: string): string => p.split(sep).join(\"/\");\n\n/**\n * Every declared manifest that owns `provenance`, or may: a manifest with no\n * `keys` (proposal 0068) owns it for the pages whose schemas mark it. A URL\n * manifest may not own it: `derive` writes the record, and a URL is not\n * somewhere to write. One that names it is refused here, and a keyless one\n * when a page's marks give it the record.\n */\nexport function provenanceManifests(\n collections: readonly CollectionConfig[],\n configDir: string,\n base: string,\n field: string = PROVENANCE_FIELD,\n): ProvenanceManifest[] {\n const out: ProvenanceManifest[] = [];\n for (const collection of collections) {\n for (const manifest of collection.externalMetadata) {\n const implied = manifest.keys === undefined;\n if (!implied && manifest.keys?.includes(field) !== true) continue;\n const url = classifyRef(manifest.file).kind === \"url\";\n if (url && !implied) throw new DocmetaError(urlRefusal(collection.name, field));\n if (url) {\n out.push({\n collection: collection.name,\n absPath: manifest.file,\n file: manifest.file,\n join: externalMetadataJoin(manifest),\n perPage: false,\n written: manifest.file,\n implied: { collection, manifest, url },\n });\n continue;\n }\n const absPath = isAbsolute(manifest.file) ? manifest.file : resolve(configDir, manifest.file);\n const perPage = hasPagePlaceholder(manifest.file);\n out.push({\n collection: collection.name,\n absPath,\n file: perPage ? manifest.file : reportedPath(absPath, base),\n join: externalMetadataJoin(manifest),\n perPage,\n written: manifest.file,\n ...(implied ? { implied: { collection, manifest, url } } : {}),\n });\n }\n }\n return out;\n}\n\nfunction urlRefusal(collection: string, field: string): string {\n return `collection ${collection}: ${field} cannot come from a URL manifest, because manni meta derive writes it.`;\n}\n\n/**\n * The manifest entry holding one page's record, or undefined when the record\n * is the page's own. A page in two collections whose manifests both own\n * `provenance` is refused: a writer has to know which file to write to.\n * `data` is the page's own metadata, for a manifest joined on a field; a page\n * that does not carry that field has no entry to write to, and is refused.\n * `marked` is what the page's schemas mark external, which decides whether a\n * manifest with no `keys` holds the record (proposal 0068).\n */\nexport function provenancePlace(\n label: string,\n data: Readonly<Record<string, unknown>>,\n manifests: readonly ProvenanceManifest[],\n collections: readonly CollectionConfig[],\n configDir: string,\n base: string,\n marked?: ReadonlySet<string>,\n field: string = PROVENANCE_FIELD,\n): ProvenancePlace | undefined {\n if (manifests.length === 0) return undefined;\n const members = new Set(memberOf(collections, configDir, base, label));\n const owning = manifests.filter(\n (m) =>\n members.has(m.collection) &&\n (m.implied === undefined || ownsKey(m.implied.collection, m.implied.manifest, field, marked)),\n );\n const [declared, second] = owning;\n if (declared === undefined) return undefined;\n if (second !== undefined) {\n throw new DocmetaError(\n `${label} is in collections ${declared.collection} and ${second.collection}, and both keep ${field} in a manifest.`,\n );\n }\n if (declared.implied?.url === true) throw new DocmetaError(urlRefusal(declared.collection, field));\n const manifest = declared.perPage ? ownManifest(declared, label, collections, configDir, base) : declared;\n if (manifest.join === PATH_JOIN) {\n const entry = toPosix(relative(configDir, resolve(base, label)));\n return { manifest, absPath: manifest.absPath, entry, join: manifest.join };\n }\n const value = data[manifest.join];\n if (typeof value !== \"string\" && typeof value !== \"number\") {\n throw new DocmetaError(\n `${label} carries no ${manifest.join}, which ${manifest.file} joins on, so its ${field} has no entry there.`,\n );\n }\n return { manifest, absPath: manifest.absPath, entry: String(value), join: manifest.join };\n}\n\n/**\n * A `{page}` manifest (proposal 0058) as one page keeps its record: the\n * page's own file. A page above the config directory cannot have one, which\n * the loader refuses first whenever the run names the page.\n */\nfunction ownManifest(\n manifest: ProvenanceManifest,\n label: string,\n collections: readonly CollectionConfig[],\n configDir: string,\n base: string,\n): ProvenanceManifest {\n const resolved = pageManifestPath(manifest.written, configDir, resolve(base, label));\n if (\"outside\" in resolved) {\n const declared = collections\n .find((c) => c.name === manifest.collection)\n ?.externalMetadata.find((m) => m.file === manifest.written);\n throw new DocmetaError(\n outsideRefusal(declared ?? { file: manifest.written }, manifest.collection, resolved.pageRel),\n );\n }\n return { ...manifest, absPath: resolved.abs, file: reportedPath(resolved.abs, base) };\n}\n\n/**\n * `provenanceManifests` for a reader (`validate`, `get`): nothing is\n * written, so a URL manifest is not refused here; its record is simply not\n * read at a commit.\n */\nexport function readerManifests(\n collections: readonly CollectionConfig[],\n configDir: string,\n base: string,\n field: string = PROVENANCE_FIELD,\n): ProvenanceManifest[] {\n const local = collections.map((c) => ({\n ...c,\n externalMetadata: c.externalMetadata.filter((m) => classifyRef(m.file).kind !== \"url\"),\n }));\n return provenanceManifests(local, configDir, base, field);\n}\n\n/**\n * `provenancePlace` for a reader: a page the writer would refuse (two\n * owning manifests, a join field it lacks) has no manifest to read at a\n * commit, and the merge already reports what is wrong with it.\n */\nexport function readerPlace(\n label: string,\n data: Readonly<Record<string, unknown>>,\n manifests: readonly ProvenanceManifest[],\n collections: readonly CollectionConfig[],\n configDir: string,\n base: string,\n marked?: ReadonlySet<string>,\n field: string = PROVENANCE_FIELD,\n): ManifestRef | undefined {\n try {\n const place = provenancePlace(label, data, manifests, collections, configDir, base, marked, field);\n return place === undefined ? undefined : { absPath: place.absPath, entry: place.entry, join: place.join };\n } catch (err) {\n if (err instanceof DocmetaError) return undefined;\n throw err;\n }\n}\n\n/**\n * The manifests that own a page's `created` and `last-updated`, for the git\n * source to read the stamp a fact commit carries there (proposal 0069, rule\n * 1). Read as `readerPlace` reads provenance's: nothing is written through\n * these, so a page the writer would refuse simply has no manifest to read.\n * `fields` narrows the reads to the dated fields the run manages.\n */\nexport function stampManifests(\n label: string,\n data: Readonly<Record<string, unknown>>,\n collections: readonly CollectionConfig[],\n configDir: string,\n base: string,\n marked: ReadonlySet<string> | undefined,\n fields: readonly string[],\n): Partial<Record<StampedDateField, ManifestRef>> {\n const out: Partial<Record<StampedDateField, ManifestRef>> = {};\n for (const field of STAMPED_DATE_FIELDS) {\n if (!fields.includes(field)) continue;\n const manifests = readerManifests(collections, configDir, base, field);\n const place = readerPlace(label, data, manifests, collections, configDir, base, marked, field);\n if (place !== undefined) out[field] = place;\n }\n return out;\n}\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C,EAAE,EAAE,EAAE;AAC7C,QAAM,QAAQ,CAAC,SACb,SAAS,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,OAAO,OAAO,IAAI,EAAE,QAAQ,CAAC;AAC/D,QAAM,WAAW,MAAM,CAAC,MAAM,EAAE,aAAa,SAAS;AACtD,QAAM,UAAU,MAAM,CAAC,MAAM,EAAE,aAAa,QAAQ;AACpD,QAAM,UAAsB;AAAA,IAC1B,OAAO,SAAS;AAAA,IAChB,QAAQ,SAAS,SAAS;AAAA,IAC1B;AAAA,IACA,QAAQ,MAAM,eAAe;AAAA;AAAA;AAAA;AAAA,IAI7B,GAAI,WAAW,IAAI,EAAE,SAAS,IAAI,CAAC;AAAA,IACnC,GAAI,UAAU,IAAI,EAAE,QAAQ,IAAI,CAAC;AAAA;AAAA;AAAA,IAGjC,GAAI,mBAAmB,IAAI,EAAE,iBAAiB,IAAI,CAAC;AAAA,IACnD,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,EACjC;AAEA,SAAO,EAAE,SAAS,UAAU,SAAS,MAAM;AAC7C;","names":["readFile","resolve","extname","dirname","resolve","text","owners","text","text","project","isRecord","spawn","dirname","relative","sep","items","run","dirname","relative","sep","text","histories","manifestStamp","utcDate","entry","join","isRecord","spawn","git","dirname","unavailable","resolve","text","tokens","isAbsolute","relative","resolve","sep","toPosix","sep","isAbsolute","resolve","relative","run","resolve","join","provenanceManifests","own","readFile","extname"]}