@hawkeyexl/manni 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +1 -1
  2. package/dist/batch-OZOACN4G.js +41 -0
  3. package/dist/build-Z5VOVADH.js +32 -0
  4. package/dist/calibrate-TZYT42DR.js +36 -0
  5. package/dist/capture-SL4MNDDP.js +34 -0
  6. package/dist/check-5OMA42Y6.js +26 -0
  7. package/dist/{check-ESNS7ZBC.js → check-OAJWC3WD.js} +7 -5
  8. package/dist/{check-RQIIIURI.js → check-PKY7KTQE.js} +13 -14
  9. package/dist/check-WB2QDHJQ.js +880 -0
  10. package/dist/check-WB2QDHJQ.js.map +1 -0
  11. package/dist/{chunk-F2OVHJNC.js → chunk-2JFPBZJK.js} +11 -11
  12. package/dist/{chunk-CP4ZM43V.js → chunk-2KRB3EG7.js} +2 -2
  13. package/dist/{chunk-QLUMKWQQ.js → chunk-2M6DVNI5.js} +10 -6
  14. package/dist/{chunk-QLUMKWQQ.js.map → chunk-2M6DVNI5.js.map} +1 -1
  15. package/dist/{chunk-HQFVJDEN.js → chunk-3NWX34ZI.js} +19 -19
  16. package/dist/{chunk-TCC737IS.js → chunk-5G53XATW.js} +4 -4
  17. package/dist/{chunk-B7XUEQF3.js → chunk-6KKZXB2O.js} +7 -5
  18. package/dist/{chunk-B7XUEQF3.js.map → chunk-6KKZXB2O.js.map} +1 -1
  19. package/dist/{chunk-SNEHX4VE.js → chunk-733Y2STG.js} +2 -2
  20. package/dist/{chunk-ELZ2IIOF.js → chunk-73TC4DYH.js} +2 -2
  21. package/dist/{chunk-QY3DOZMS.js → chunk-7WRP5FFP.js} +4 -4
  22. package/dist/{chunk-3R5Y3XOL.js → chunk-APKH2T6E.js} +29 -591
  23. package/dist/chunk-APKH2T6E.js.map +1 -0
  24. package/dist/{chunk-FLF6AECQ.js → chunk-B3TS4WRM.js} +17 -15
  25. package/dist/{chunk-FLF6AECQ.js.map → chunk-B3TS4WRM.js.map} +1 -1
  26. package/dist/chunk-BWCWTHYS.js +146 -0
  27. package/dist/chunk-BWCWTHYS.js.map +1 -0
  28. package/dist/{chunk-C6HZ6C5T.js → chunk-C3B2VJNC.js} +2 -2
  29. package/dist/{chunk-NN4ASVTY.js → chunk-C73RSUIC.js} +4 -4
  30. package/dist/chunk-CU57HT2E.js +116 -0
  31. package/dist/chunk-CU57HT2E.js.map +1 -0
  32. package/dist/chunk-CWXZ2MRT.js +222 -0
  33. package/dist/chunk-CWXZ2MRT.js.map +1 -0
  34. package/dist/{chunk-GAZFKZHM.js → chunk-DC5DDJVE.js} +6 -6
  35. package/dist/{chunk-52PDIZKV.js → chunk-ECVQNGTH.js} +3 -3
  36. package/dist/chunk-FLAO4ZS3.js +502 -0
  37. package/dist/chunk-FLAO4ZS3.js.map +1 -0
  38. package/dist/chunk-FQGLRJGX.js +174 -0
  39. package/dist/chunk-FQGLRJGX.js.map +1 -0
  40. package/dist/{chunk-XWFNO5PO.js → chunk-GAJIJKET.js} +3 -3
  41. package/dist/{chunk-QCBICNKC.js → chunk-GREQKO6M.js} +202 -54
  42. package/dist/chunk-GREQKO6M.js.map +1 -0
  43. package/dist/chunk-HX44GB4Z.js +30 -0
  44. package/dist/chunk-HX44GB4Z.js.map +1 -0
  45. package/dist/{chunk-7ZUCEMCY.js → chunk-IY7NYNPZ.js} +9 -11
  46. package/dist/{chunk-7ZUCEMCY.js.map → chunk-IY7NYNPZ.js.map} +1 -1
  47. package/dist/{chunk-527HHQPS.js → chunk-KCOFEWV5.js} +6 -4
  48. package/dist/{chunk-527HHQPS.js.map → chunk-KCOFEWV5.js.map} +1 -1
  49. package/dist/chunk-M2RLHZ4J.js +849 -0
  50. package/dist/chunk-M2RLHZ4J.js.map +1 -0
  51. package/dist/{chunk-K3U5F2QT.js → chunk-M6GSS72T.js} +12 -12
  52. package/dist/{chunk-UK2I3ACY.js → chunk-MHM4QEBV.js} +4 -4
  53. package/dist/{chunk-EL2BZTDL.js → chunk-MOWMCEOJ.js} +13 -11
  54. package/dist/{chunk-EL2BZTDL.js.map → chunk-MOWMCEOJ.js.map} +1 -1
  55. package/dist/{chunk-OIZ3XMKB.js → chunk-MWBJ3KTF.js} +4 -4
  56. package/dist/chunk-N7JSEDSC.js +233 -0
  57. package/dist/chunk-N7JSEDSC.js.map +1 -0
  58. package/dist/{chunk-MZC62HPZ.js → chunk-NBMPHD4I.js} +2 -2
  59. package/dist/{chunk-YA63PVWI.js → chunk-NHHOPZRA.js} +12 -10
  60. package/dist/{chunk-YA63PVWI.js.map → chunk-NHHOPZRA.js.map} +1 -1
  61. package/dist/{chunk-DX32P2DT.js → chunk-NTWW7J76.js} +2 -2
  62. package/dist/{chunk-6XTQDFGP.js → chunk-PCFG7E6B.js} +3 -3
  63. package/dist/{chunk-6XTQDFGP.js.map → chunk-PCFG7E6B.js.map} +1 -1
  64. package/dist/{chunk-SJO2FTPG.js → chunk-PL4UAF4S.js} +73 -1304
  65. package/dist/chunk-PL4UAF4S.js.map +1 -0
  66. package/dist/chunk-QCHVR4ZM.js +286 -0
  67. package/dist/chunk-QCHVR4ZM.js.map +1 -0
  68. package/dist/{chunk-JQU7FHYH.js → chunk-QW77LCOU.js} +10 -10
  69. package/dist/{chunk-IA7BMIPE.js → chunk-SM6NOMJS.js} +2 -2
  70. package/dist/{chunk-DE7JSWXV.js → chunk-SWSTHZBI.js} +8 -6
  71. package/dist/{chunk-DE7JSWXV.js.map → chunk-SWSTHZBI.js.map} +1 -1
  72. package/dist/{chunk-NGK3N6F2.js → chunk-T6SYGLWR.js} +3 -3
  73. package/dist/chunk-TH4JVQPF.js +133 -0
  74. package/dist/chunk-TH4JVQPF.js.map +1 -0
  75. package/dist/{chunk-TVIX653Q.js → chunk-TLXE7LYK.js} +4 -4
  76. package/dist/{chunk-HVFR66GQ.js → chunk-TUAAR3MM.js} +3280 -283
  77. package/dist/chunk-TUAAR3MM.js.map +1 -0
  78. package/dist/{chunk-TA42STP7.js → chunk-UAKNZVCD.js} +4 -4
  79. package/dist/{chunk-C3KI45RF.js → chunk-UJSGS2Y5.js} +4 -4
  80. package/dist/{chunk-ZX43SRZR.js → chunk-UWQ2UVHE.js} +8 -6
  81. package/dist/{chunk-ZX43SRZR.js.map → chunk-UWQ2UVHE.js.map} +1 -1
  82. package/dist/chunk-WQWKYAAK.js +86 -0
  83. package/dist/chunk-WQWKYAAK.js.map +1 -0
  84. package/dist/{chunk-LJ2RDH3F.js → chunk-XG6PVB5S.js} +1 -23
  85. package/dist/chunk-XG6PVB5S.js.map +1 -0
  86. package/dist/{chunk-Q35YIDBV.js → chunk-XKBEHKWO.js} +29 -264
  87. package/dist/chunk-XKBEHKWO.js.map +1 -0
  88. package/dist/chunk-XPEWUK7J.js +532 -0
  89. package/dist/chunk-XPEWUK7J.js.map +1 -0
  90. package/dist/{chunk-BOIF2XGG.js → chunk-XXDXIIQ4.js} +2 -2
  91. package/dist/chunk-YLK2J5YK.js +610 -0
  92. package/dist/chunk-YLK2J5YK.js.map +1 -0
  93. package/dist/{chunk-7OQAU4EA.js → chunk-Z4IZGEM3.js} +16 -12
  94. package/dist/{chunk-7OQAU4EA.js.map → chunk-Z4IZGEM3.js.map} +1 -1
  95. package/dist/{cli-E3H6ZP4I.js → cli-6EWVMEN6.js} +5 -3
  96. package/dist/{cli-E3H6ZP4I.js.map → cli-6EWVMEN6.js.map} +1 -1
  97. package/dist/{cli-MHTYPVOD.js → cli-6H7HVDMQ.js} +113 -20
  98. package/dist/{cli-MHTYPVOD.js.map → cli-6H7HVDMQ.js.map} +1 -1
  99. package/dist/{cli-HUIMNJT6.js → cli-EPVZHAZS.js} +19 -20
  100. package/dist/{cli-HUIMNJT6.js.map → cli-EPVZHAZS.js.map} +1 -1
  101. package/dist/{cli-6PGVHP7Y.js → cli-LUCSGTVI.js} +17 -19
  102. package/dist/{cli-6PGVHP7Y.js.map → cli-LUCSGTVI.js.map} +1 -1
  103. package/dist/{cli-PRZHQ3QB.js → cli-NIG4N3XM.js} +14 -15
  104. package/dist/{cli-PRZHQ3QB.js.map → cli-NIG4N3XM.js.map} +1 -1
  105. package/dist/{cli-TYGOHJOJ.js → cli-PSKNB66T.js} +225 -58
  106. package/dist/cli-PSKNB66T.js.map +1 -0
  107. package/dist/{cli-QKIJOXGW.js → cli-UO4NHIB3.js} +17 -17
  108. package/dist/{cli-AAG3N4NB.js → cli-UQ7A3YA2.js} +17 -18
  109. package/dist/{cli-AAG3N4NB.js.map → cli-UQ7A3YA2.js.map} +1 -1
  110. package/dist/{cli-YW6VWBHX.js → cli-YHYDLQAF.js} +10 -10
  111. package/dist/cli.js +11 -11
  112. package/dist/config-P4HDNTYD.js +26 -0
  113. package/dist/conformance-ZFCMKM6M.js +18 -0
  114. package/dist/docmeta.js +9 -9
  115. package/dist/github-7ZCH5PSO.js +26 -0
  116. package/dist/github-POT6724K.js +31 -0
  117. package/dist/host-6GURH5HE.js +23 -0
  118. package/dist/index.d.ts +72 -4
  119. package/dist/index.js +176 -166
  120. package/dist/index.js.map +1 -1
  121. package/dist/{json-4DCKDGUV.js → json-KT2K62L5.js} +12 -13
  122. package/dist/lint-5AQ5C2BV.js +29 -0
  123. package/dist/list-5JZKX2NK.js +28 -0
  124. package/dist/list-SWPFXQMU.js +30 -0
  125. package/dist/{page-QEDB7EVU.js → page-UPSXRP75.js} +11 -12
  126. package/dist/prepare-6GNEWCNH.js +155 -0
  127. package/dist/prepare-6GNEWCNH.js.map +1 -0
  128. package/dist/{pretty-SQX33UM2.js → pretty-Q6FQAOK4.js} +13 -14
  129. package/dist/{pretty-5DGEBZSV.js → pretty-SQRPFPSQ.js} +12 -13
  130. package/dist/provider-AMGRDY6V.js +34 -0
  131. package/dist/release-IECYCLTD.js +36 -0
  132. package/dist/release-IECYCLTD.js.map +1 -0
  133. package/dist/{reporters-OHSI3RMV.js → reporters-45MMC2ID.js} +11 -12
  134. package/dist/{reporters-YELDDYJD.js → reporters-XUV4MM64.js} +7 -5
  135. package/dist/reporters-XUV4MM64.js.map +1 -0
  136. package/dist/run-KMWY2IAN.js +32 -0
  137. package/dist/run-KMWY2IAN.js.map +1 -0
  138. package/dist/{term-2WMDZ4PY.js → term-PCJUCWNF.js} +16 -17
  139. package/dist/{term-2WMDZ4PY.js.map → term-PCJUCWNF.js.map} +1 -1
  140. package/dist/validate-IMNCZNWG.js +17 -0
  141. package/dist/validate-IMNCZNWG.js.map +1 -0
  142. package/package.json +2 -2
  143. package/plugin/manni/.claude-plugin/plugin.json +1 -1
  144. package/plugin/manni/hooks/hooks.json +47 -0
  145. package/dist/batch-GOE3UXOD.js +0 -36
  146. package/dist/build-M7BMEHL2.js +0 -33
  147. package/dist/calibrate-6RRAILUY.js +0 -31
  148. package/dist/capture-RJPQ6B4N.js +0 -32
  149. package/dist/check-BQD64X3N.js +0 -27
  150. package/dist/chunk-3R5Y3XOL.js.map +0 -1
  151. package/dist/chunk-3YHAYXBC.js +0 -164
  152. package/dist/chunk-3YHAYXBC.js.map +0 -1
  153. package/dist/chunk-HVFR66GQ.js.map +0 -1
  154. package/dist/chunk-LJ2RDH3F.js.map +0 -1
  155. package/dist/chunk-NAZRLJAK.js +0 -3090
  156. package/dist/chunk-NAZRLJAK.js.map +0 -1
  157. package/dist/chunk-Q35YIDBV.js.map +0 -1
  158. package/dist/chunk-QCBICNKC.js.map +0 -1
  159. package/dist/chunk-SJO2FTPG.js.map +0 -1
  160. package/dist/chunk-TU2WUBVZ.js +0 -2
  161. package/dist/cli-TYGOHJOJ.js.map +0 -1
  162. package/dist/github-3WMSTNTK.js +0 -32
  163. package/dist/github-OXSJQ4PS.js +0 -27
  164. package/dist/lint-YDHVVZHT.js +0 -30
  165. package/dist/list-3ZO2NIYO.js +0 -31
  166. package/dist/list-EJH6VAOW.js +0 -29
  167. package/dist/run-IP6NZHAG.js +0 -33
  168. package/dist/validate-G6HH3YXL.js +0 -16
  169. /package/dist/{batch-GOE3UXOD.js.map → batch-OZOACN4G.js.map} +0 -0
  170. /package/dist/{build-M7BMEHL2.js.map → build-Z5VOVADH.js.map} +0 -0
  171. /package/dist/{calibrate-6RRAILUY.js.map → calibrate-TZYT42DR.js.map} +0 -0
  172. /package/dist/{capture-RJPQ6B4N.js.map → capture-SL4MNDDP.js.map} +0 -0
  173. /package/dist/{check-BQD64X3N.js.map → check-5OMA42Y6.js.map} +0 -0
  174. /package/dist/{check-ESNS7ZBC.js.map → check-OAJWC3WD.js.map} +0 -0
  175. /package/dist/{check-RQIIIURI.js.map → check-PKY7KTQE.js.map} +0 -0
  176. /package/dist/{chunk-F2OVHJNC.js.map → chunk-2JFPBZJK.js.map} +0 -0
  177. /package/dist/{chunk-CP4ZM43V.js.map → chunk-2KRB3EG7.js.map} +0 -0
  178. /package/dist/{chunk-HQFVJDEN.js.map → chunk-3NWX34ZI.js.map} +0 -0
  179. /package/dist/{chunk-TCC737IS.js.map → chunk-5G53XATW.js.map} +0 -0
  180. /package/dist/{chunk-SNEHX4VE.js.map → chunk-733Y2STG.js.map} +0 -0
  181. /package/dist/{chunk-ELZ2IIOF.js.map → chunk-73TC4DYH.js.map} +0 -0
  182. /package/dist/{chunk-QY3DOZMS.js.map → chunk-7WRP5FFP.js.map} +0 -0
  183. /package/dist/{chunk-C6HZ6C5T.js.map → chunk-C3B2VJNC.js.map} +0 -0
  184. /package/dist/{chunk-NN4ASVTY.js.map → chunk-C73RSUIC.js.map} +0 -0
  185. /package/dist/{chunk-GAZFKZHM.js.map → chunk-DC5DDJVE.js.map} +0 -0
  186. /package/dist/{chunk-52PDIZKV.js.map → chunk-ECVQNGTH.js.map} +0 -0
  187. /package/dist/{chunk-XWFNO5PO.js.map → chunk-GAJIJKET.js.map} +0 -0
  188. /package/dist/{chunk-K3U5F2QT.js.map → chunk-M6GSS72T.js.map} +0 -0
  189. /package/dist/{chunk-UK2I3ACY.js.map → chunk-MHM4QEBV.js.map} +0 -0
  190. /package/dist/{chunk-OIZ3XMKB.js.map → chunk-MWBJ3KTF.js.map} +0 -0
  191. /package/dist/{chunk-MZC62HPZ.js.map → chunk-NBMPHD4I.js.map} +0 -0
  192. /package/dist/{chunk-DX32P2DT.js.map → chunk-NTWW7J76.js.map} +0 -0
  193. /package/dist/{chunk-JQU7FHYH.js.map → chunk-QW77LCOU.js.map} +0 -0
  194. /package/dist/{chunk-IA7BMIPE.js.map → chunk-SM6NOMJS.js.map} +0 -0
  195. /package/dist/{chunk-NGK3N6F2.js.map → chunk-T6SYGLWR.js.map} +0 -0
  196. /package/dist/{chunk-TVIX653Q.js.map → chunk-TLXE7LYK.js.map} +0 -0
  197. /package/dist/{chunk-TA42STP7.js.map → chunk-UAKNZVCD.js.map} +0 -0
  198. /package/dist/{chunk-C3KI45RF.js.map → chunk-UJSGS2Y5.js.map} +0 -0
  199. /package/dist/{chunk-BOIF2XGG.js.map → chunk-XXDXIIQ4.js.map} +0 -0
  200. /package/dist/{cli-QKIJOXGW.js.map → cli-UO4NHIB3.js.map} +0 -0
  201. /package/dist/{chunk-TU2WUBVZ.js.map → cli-YHYDLQAF.js.map} +0 -0
  202. /package/dist/{cli-YW6VWBHX.js.map → config-P4HDNTYD.js.map} +0 -0
  203. /package/dist/{github-3WMSTNTK.js.map → conformance-ZFCMKM6M.js.map} +0 -0
  204. /package/dist/{github-OXSJQ4PS.js.map → github-7ZCH5PSO.js.map} +0 -0
  205. /package/dist/{json-4DCKDGUV.js.map → github-POT6724K.js.map} +0 -0
  206. /package/dist/{lint-YDHVVZHT.js.map → host-6GURH5HE.js.map} +0 -0
  207. /package/dist/{list-3ZO2NIYO.js.map → json-KT2K62L5.js.map} +0 -0
  208. /package/dist/{list-EJH6VAOW.js.map → lint-5AQ5C2BV.js.map} +0 -0
  209. /package/dist/{page-QEDB7EVU.js.map → list-5JZKX2NK.js.map} +0 -0
  210. /package/dist/{pretty-5DGEBZSV.js.map → list-SWPFXQMU.js.map} +0 -0
  211. /package/dist/{pretty-SQX33UM2.js.map → page-UPSXRP75.js.map} +0 -0
  212. /package/dist/{reporters-OHSI3RMV.js.map → pretty-Q6FQAOK4.js.map} +0 -0
  213. /package/dist/{reporters-YELDDYJD.js.map → pretty-SQRPFPSQ.js.map} +0 -0
  214. /package/dist/{run-IP6NZHAG.js.map → provider-AMGRDY6V.js.map} +0 -0
  215. /package/dist/{validate-G6HH3YXL.js.map → reporters-45MMC2ID.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/tracevals/commands/list.ts","../src/tracevals/commands/fill.ts","../src/tracevals/evals/write.ts","../src/tracevals/evals/write-location.ts","../src/tracevals/fill/cache.ts","../src/tracevals/fill/prompt.ts","../src/tracevals/fill/gate.ts","../src/tracevals/fill/facts.ts","../src/tracevals/fill/mock.ts","../src/tracevals/fill/vocabulary.ts"],"sourcesContent":["/** `manni tracevals list` — enumerate discoverable traces. */\nimport {\n discoverTraces,\n type DiscoverOptions,\n type TraceListing,\n} from \"../trace/discover.js\";\nimport { palette } from \"../../shared/color.js\";\nimport { keepNewerThan, parseNewerThan } from \"./batch.js\";\n\nexport interface ListOptions extends DiscoverOptions {\n /** `--newer-than`: keep only traces modified within this duration, e.g. `7d`. */\n newerThan?: string;\n}\n\nexport interface ListRun {\n traces: TraceListing[];\n}\n\nexport async function runList(options: ListOptions = {}): Promise<ListRun> {\n // Parsed before the store is read, so a bad duration costs no scan.\n if (options.newerThan !== undefined) parseNewerThan(options.newerThan);\n const { newerThan, ...discover } = options;\n return { traces: keepNewerThan(await discoverTraces(discover), newerThan) };\n}\n\nexport function renderList(\n run: ListRun,\n opts: { color?: boolean } = {},\n): string {\n const pc = palette(opts.color === true);\n const dim = pc.dim;\n const bold = pc.bold;\n\n if (run.traces.length === 0) {\n return \"No traces found. Pass --all-projects to scan every project, or --project <dir> to scope to one.\";\n }\n\n const lines: string[] = [];\n run.traces.forEach((t, i) => {\n const when = new Date(t.mtimeMs).toISOString().slice(0, 16).replace(\"T\", \" \");\n const size = `${Math.max(1, Math.round(t.sizeBytes / 1024))}KB`;\n lines.push(\n `${bold(String(i + 1).padStart(3))}. ${dim(when)} ${t.firstPrompt ?? dim(\"(no prompt)\")}`,\n );\n lines.push(\n ` ${dim(`${t.project ?? \"unknown project\"} · ${t.sessionId ?? \"?\"} · ${size}`)}`,\n );\n lines.push(` ${dim(t.file)}`);\n });\n return lines.join(\"\\n\");\n}\n","/**\n * `manni tracevals fill [paths...]` — propose evals for a project's\n * instruction artifacts and append the survivors to their frontmatter.\n *\n * Authoring, not evaluation: `run` never calls this, and everything written is\n * the same declared-evals contract a human would type by hand. Project\n * rules are proposed but never written — evals inside a file the agent\n * reads before acting would be teaching to the test (ADR 01005).\n */\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\nimport { palette } from \"../../shared/color.js\";\nimport { extractFrontmatter } from \"../../meta/index.js\";\nimport {\n externalWriteWarnings,\n type ExternalWrite,\n type RelocateResult,\n} from \"../../meta/internal.js\";\nimport type { Confirm } from \"../../shared/prompt.js\";\nimport { discoverArtifacts, type DiscoveredArtifact } from \"../artifacts/discover.js\";\nimport {\n appendArtifactEvals,\n appendMetadataEvals,\n type NewEvalEntry,\n} from \"../evals/write.js\";\nimport {\n METADATA_KEY,\n loadExternalEvals,\n urlManifestRefusal,\n} from \"../evals/external.js\";\nimport {\n MetadataWriter,\n noEntryRefusal,\n type MetadataHome,\n} from \"../evals/write-location.js\";\nimport { discoverConfig } from \"../core/config.js\";\nimport { loadGraderPlugins } from \"../graders/plugins.js\";\nimport { TracevalsError } from \"../types.js\";\nimport {\n assertProviderSelection,\n constructProvider,\n resolveProviderIdentity,\n selectProvider,\n} from \"../judge/provider.js\";\nimport { TURN_BUDGET_SKIP } from \"../../docevals/judge/budget.js\";\nimport { FillCache, fillCacheKey } from \"../fill/cache.js\";\nimport { artifactFacts } from \"../fill/facts.js\";\nimport {\n gateProposals,\n type ProposedEval,\n type Rejection,\n} from \"../fill/gate.js\";\nimport {\n PROPOSAL_SCHEMA,\n buildFillUser,\n isValidProposal,\n systemPromptFor,\n} from \"../fill/prompt.js\";\nimport { mockFillProposal } from \"../fill/mock.js\";\nimport { buildVocabulary } from \"../fill/vocabulary.js\";\nimport type { InferenceProvider } from \"@hawkeyexl/inference\";\n\nexport interface FillOptions {\n /** Colour the pretty report. Off unless the caller turns it on. */\n color?: boolean;\n /** Files or directories to scan; defaults to the whole project. */\n paths?: string[];\n /** Project root; defaults to cwd. */\n project?: string;\n configDir?: string;\n /** `-c/--config`: read this file instead of discovering one. */\n config?: string;\n /** `--no-config`: skip discovery and run on the built-in defaults. */\n noConfig?: boolean;\n /**\n * `--offline`: never fetch a remote external-metadata manifest; read the\n * local ones only. A relocated artifact's evals live in one (0047).\n */\n offline?: boolean;\n /**\n * `--exclude <glob>`, repeatable. Removes matching artifacts from whatever\n * the scan would otherwise have found, positional paths included.\n */\n exclude?: string[];\n cwd?: string;\n /** Report proposals without writing. */\n dryRun?: boolean;\n confidence?: number;\n /** Ceiling on an artifact's total evals, existing ones included. */\n maxEvals?: number;\n /** `--max-turns`: inference calls for the whole invocation, one per artifact. */\n maxTurns?: number;\n noCache?: boolean;\n provider?: string;\n model?: string;\n /** `--local`: run inference on this machine, over every configured choice. */\n local?: boolean;\n /** `--require`: grader plugins to load *in addition to* `config.plugins`. */\n require?: string[];\n /** Test seam: bypasses provider construction entirely. */\n providerInstance?: InferenceProvider;\n /**\n * P1 (proposal 0047): asked once per collection when a `metadata` block\n * would land on an artifact because no manifest owns it. The CLI passes\n * `terminalConfirm()`, so off a terminal there is no question and the\n * warning is the only output.\n */\n confirm?: Confirm;\n /** A stderr diagnostic; the caller adds the `manni tracevals: ` prefix. */\n onNotice?: (message: string) => void;\n /** What an accepted relocation moved, for the caller to report. */\n onRelocated?: (result: RelocateResult) => void;\n}\n\nexport type FillStatus =\n | \"filled\"\n | \"proposed\"\n | \"nothing-proposed\"\n | \"propose-only\"\n | \"skipped\"\n | \"unreadable\"\n | \"error\";\n\nexport interface SharpeningNote {\n instruction: string;\n reason: string;\n suggestion?: string;\n}\n\nexport interface FillArtifactResult {\n artifact: string;\n type: string;\n status: FillStatus;\n /** Evals written, or that would be written in a dry run. */\n written: ProposedEval[];\n /**\n * The external-metadata manifest the evals were written to, when this\n * artifact's `metadata` block lives in one (0047). Absent when they went to\n * the artifact's own front matter.\n */\n manifest?: string;\n rejected: Rejection[];\n capped: ProposedEval[];\n /** Instructions the model judged untestable as written. */\n needsSharpening: SharpeningNote[];\n cached: boolean;\n error?: string;\n}\n\nexport interface FillReport {\n results: FillArtifactResult[];\n threshold: number;\n /** True when nothing was written because this was a dry run. */\n dryRun: boolean;\n warnings: string[];\n exitCode: 0 | 1;\n}\n\nexport interface FillRun {\n report: FillReport;\n rendered: string;\n}\n\n/** The artifact's own front matter, which names its entry in a joined manifest. */\nfunction ownData(content: string): Record<string, unknown> {\n return extractFrontmatter(content, \"markdown\").data;\n}\n\n/** Proposals become inline evals; confidence and rationale stay report-only. */\nfunction toEvalEntry(proposed: ProposedEval): NewEvalEntry {\n const entry: NewEvalEntry = {\n id: proposed.name,\n assertion: proposed.assertion,\n // New evals start as regression: they describe behavior the artifact\n // already asks for, not a boundary being probed.\n type: \"regression\",\n grader: proposed.grader,\n // The vocabulary takes one anchor or a list; the model proposes one of each.\n examples: { pass: [proposed.examples.pass], fail: [proposed.examples.fail] },\n };\n if (proposed.options !== undefined) entry.options = proposed.options;\n if (proposed.evidence !== undefined) entry.evidence = proposed.evidence;\n if (proposed.severity !== undefined) entry.severity = proposed.severity;\n return entry;\n}\n\nexport async function runFill(options: FillOptions = {}): Promise<FillRun> {\n const cwd = options.cwd ?? process.cwd();\n const root = resolve(options.project ?? cwd);\n const lookup = {\n ...(options.config === undefined ? {} : { configPath: options.config }),\n ...(options.noConfig === undefined ? {} : { noConfig: options.noConfig }),\n };\n const {\n config: loaded,\n dir: configDir,\n path: configPath,\n } = await discoverConfig(options.configDir ?? cwd, lookup);\n // `--require` is folded into the resolved config, the same way `run` does it,\n // rather than merged inline at the load call. Downstream code reads one\n // fully-resolved `config.plugins`; two commands disagreeing about whether it\n // includes the flag is how a knob starts behaving differently depending on\n // which command reached it.\n const config = {\n ...loaded,\n plugins: [...loaded.plugins, ...(options.require ?? [])],\n };\n\n // The same list `run` loads, appended to the same way, for the same reason:\n // a repo whose config names its house graders must not behave differently\n // depending on which command reached the registry. What it changes here is\n // narrower — `ALLOWED_GRADERS` still refuses to propose a custom kind, but a\n // plugin that *replaces* a built-in replaces the `validateOptions` the gate\n // ground-checks proposals with (ADR 01017).\n const plugins = await loadGraderPlugins({\n plugins: config.plugins,\n configDir,\n });\n\n // The command line's say over every configured level, checked up front and\n // regardless of an injected provider: it costs nothing, and a typo must fail\n // on a run where no artifact needs a model too.\n const flags = {\n ...(options.provider !== undefined ? { provider: options.provider } : {}),\n ...(options.model !== undefined ? { model: options.model } : {}),\n ...(options.local !== undefined ? { local: options.local } : {}),\n };\n assertProviderSelection(selectProvider(config, flags));\n\n const threshold = options.confidence ?? config.fill.confidenceThreshold;\n const maxEvals = options.maxEvals ?? config.fill.maxEvalsPerArtifact;\n const temperature = config.fill.temperature;\n const maxTurns = options.maxTurns ?? config.fill.maxTurns;\n const cache = new FillCache(\n resolve(configDir, config.fill.cacheDir),\n options.noCache !== true,\n );\n\n // Where each artifact's `metadata` block lives. Collections do not choose\n // what `fill` scans — that is still `--project` plus `[paths...]`, and there\n // is no `--collection` (0049 §1). What they say is where a relocated block\n // lives, both for reading what an artifact already declares and for writing\n // what this run proposes.\n const load = async () => {\n // Read fresh each time: an accepted offer edits the config file.\n const { collections } = await discoverConfig(options.configDir ?? cwd, lookup);\n const external = await loadExternalEvals({\n collections,\n configDir,\n ...(configPath === undefined ? {} : { configPath }),\n ...(options.offline === undefined ? {} : { offline: options.offline }),\n });\n const discovery = await discoverArtifacts({\n root,\n cwd,\n ...(options.paths !== undefined ? { paths: options.paths } : {}),\n ...(options.exclude !== undefined ? { exclude: options.exclude } : {}),\n ...(external === null\n ? {}\n : {\n metadataFor: async (artifact) =>\n (await external.forArtifact(artifact)).extracted,\n }),\n });\n const writer = await MetadataWriter.for({\n collections,\n configDir,\n configPath,\n cwd,\n targets: options.paths ?? [],\n });\n return { collections, discovery, writer };\n };\n let { collections, discovery, writer } = await load();\n\n // P1 (proposal 0047): asked before the first model request, so an accepted\n // relocation is applied while nothing has been proposed yet. Only where a\n // collection is declared, the same condition the W1 and W2 lines keep.\n if (\n options.confirm !== undefined &&\n options.dryRun !== true &&\n collections.length > 0\n ) {\n const flagged: ExternalWrite[] = [];\n for (const { artifact, status, skip } of discovery.artifacts) {\n if (status !== \"ok\" || skip || artifact.type === \"project-rules\") continue;\n const home = await writer.homeFor(artifact.path, ownData(artifact.content));\n if (home.kind === \"page\") {\n flagged.push({ label: artifact.path, key: METADATA_KEY, home: home.proposed });\n }\n }\n const applied = await writer.offer(flagged, {\n confirm: options.confirm,\n ...(options.onNotice === undefined ? {} : { onNotice: options.onNotice }),\n ...(options.onRelocated === undefined ? {} : { onRelocated: options.onRelocated }),\n });\n // The config now declares a manifest, the artifacts no longer carry what\n // it owns, and this writer's context predates both.\n if (applied) ({ collections, discovery, writer } = await load());\n }\n const vocabulary = buildVocabulary(discovery.artifacts);\n const knownSkills = [...vocabulary.skills].sort();\n\n // Identity is resolved without constructing the provider, so a fully cached\n // run needs no API key, and on first use, so an all-skipped run never detects\n // a provider under `auto`. Resolved once, and shared by every artifact.\n //\n // Going through the shared resolver rather than reading config by hand\n // matters: it applies the same per-provider model default construction would,\n // so the model in the cache key is the model that actually produced the\n // proposal.\n const injected = options.providerInstance;\n let resolving: ReturnType<typeof resolveProviderIdentity> | undefined;\n const resolveOnce = (): ReturnType<typeof resolveProviderIdentity> =>\n (resolving ??= resolveProviderIdentity(config, flags));\n const getIdentity = async (): Promise<{ provider: string; model: string }> =>\n injected !== undefined\n ? { provider: injected.provider(), model: injected.modelName() }\n : resolveOnce();\n let provider = injected;\n const getProvider = async (): Promise<InferenceProvider> =>\n (provider ??= constructProvider(config, await resolveOnce(), {\n // The default mock response is judge-shaped and would fail this\n // command's schema, so seed the mock seam with a proposal instead.\n mockResponses: [mockFillProposal()],\n }));\n\n let turns = 0;\n const results: FillArtifactResult[] = [];\n /** Blocks that landed on a page whose schema would rather they did not. */\n const homeless: ExternalWrite[] = [];\n\n for (const discovered of discovery.artifacts) {\n results.push(await fillOne(discovered));\n }\n\n const report: FillReport = {\n results,\n threshold,\n dryRun: options.dryRun === true,\n warnings: [\n ...plugins.warnings,\n ...discovery.warnings,\n ...externalWriteWarnings(homeless, options.dryRun === true),\n ],\n exitCode: results.some((r) => r.status === \"error\") ? 1 : 0,\n };\n return {\n report,\n rendered: renderFill(report, {\n cwd,\n ...(options.color === undefined ? {} : { color: options.color }),\n }),\n };\n\n async function fillOne(\n discovered: DiscoveredArtifact,\n ): Promise<FillArtifactResult> {\n const { artifact } = discovered;\n const base: FillArtifactResult = {\n artifact: artifact.path,\n type: artifact.type,\n status: \"nothing-proposed\",\n written: [],\n rejected: [],\n capped: [],\n needsSharpening: [],\n cached: false,\n };\n\n if (discovered.status !== \"ok\") {\n return {\n ...base,\n status: discovered.status === \"unreadable\" ? \"unreadable\" : \"error\",\n ...(discovered.error !== undefined ? { error: discovered.error } : {}),\n };\n }\n if (discovered.skip) return { ...base, status: \"skipped\" };\n\n const facts = artifactFacts(artifact);\n const identity = await getIdentity();\n const key = fillCacheKey({\n provider: identity.provider,\n model: identity.model,\n temperature,\n maxEvals,\n artifactType: artifact.type,\n path: artifact.path,\n body: artifact.content,\n existingNames: discovered.existingNames,\n knownSkills,\n });\n\n let raw = cache.get(key);\n const cached = raw !== undefined;\n if (raw === undefined) {\n // Claimed before the call, not tallied after it (docevals ADR 01019). A\n // cache hit never reaches here, so replaying a cached corpus spends no\n // turns.\n if (maxTurns !== null && turns >= maxTurns) {\n return { ...base, status: \"skipped\", error: `${TURN_BUDGET_SKIP} exhausted` };\n }\n turns += 1;\n try {\n const response = await (await getProvider()).completeJSON({\n system: systemPromptFor(artifact.type),\n user: buildFillUser({\n artifact,\n existingNames: discovered.existingNames,\n maxEvals,\n facts,\n knownSkills,\n }),\n schema: PROPOSAL_SCHEMA,\n temperature,\n });\n if (!isValidProposal(response.json)) {\n return {\n ...base,\n status: \"error\",\n error: \"provider returned a proposal that does not match the schema\",\n };\n }\n raw = response.json as Record<string, unknown>;\n cache.set(key, raw);\n } catch (err) {\n // An operational failure (no API key, unknown provider) is not this\n // artifact's fault and would repeat for every one: let it out so the\n // CLI reports it once and exits 2.\n if (err instanceof TracevalsError) throw err;\n return {\n ...base,\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const gated = gateProposals(raw.evals as ProposedEval[], {\n artifactType: artifact.type,\n threshold,\n existingNames: discovered.existingNames,\n // The cap is a ceiling on the artifact's total, not on one run's\n // additions, so repeated fills cannot grow it without bound.\n maxEvals: Math.max(0, maxEvals - discovered.existingNames.length),\n vocabulary,\n });\n const result: FillArtifactResult = {\n ...base,\n written: gated.accepted,\n rejected: gated.rejected,\n capped: gated.capped,\n needsSharpening: (raw.needsSharpening as SharpeningNote[] | undefined) ?? [],\n cached,\n };\n\n if (gated.accepted.length === 0) return result;\n // Project rules are read by the agent under test before it acts, so\n // writing evals there would leak the rubric into the system prompt.\n if (artifact.type === \"project-rules\") {\n return { ...result, status: \"propose-only\" };\n }\n\n // Where the block lives decides where it is written. A URL manifest is\n // readable and not writable, and a dry run still reports against a hosted\n // trail rather than refusing a run that writes nothing.\n const home = await writer.homeFor(artifact.path, ownData(artifact.content));\n if (options.dryRun !== true) {\n if (home.kind === \"url\") {\n throw new TracevalsError(urlManifestRefusal(artifact.path, home.file));\n }\n if (home.kind === \"no-entry\") {\n throw new TracevalsError(noEntryRefusal(artifact.path, home.join, home.file));\n }\n }\n const landed: FillArtifactResult =\n home.kind === \"page\" ? result : { ...result, manifest: home.file };\n\n if (options.dryRun === true) return { ...landed, status: \"proposed\" };\n\n // Machines propose; humans retire the trail. Recording which model proposed\n // what, at what confidence, is what lets a reviewer tell an unreviewed\n // suggestion from an eval someone actually signed off on.\n //\n // The model's own name, not `provider:model`. The judge's self-preference\n // check compares this against `modelName()`, so a composed spelling would\n // read as a different model every time. The provider name is the fallback\n // only when there is no model to name.\n const provenance = {\n generatedBy: identity.model || identity.provider,\n confidence: Object.fromEntries(\n gated.accepted.map((c) => [c.name, c.confidence]),\n ),\n };\n\n try {\n if (home.kind === \"manifest\") {\n // Through meta's own splice writer: one value of one entry is replaced\n // and no other byte of the manifest moves, comments included.\n await writer.write(home, (current) =>\n appendMetadataEvals(\n current,\n artifact.path,\n gated.accepted.map(toEvalEntry),\n provenance,\n ),\n );\n } else {\n const updated = appendArtifactEvals(\n artifact.content,\n artifact.path,\n gated.accepted.map(toEvalEntry),\n provenance,\n );\n await writeFile(artifact.path, updated);\n if (home.kind === \"page\") noteHomeless(artifact.path, home);\n }\n } catch (err) {\n return {\n ...landed,\n status: \"error\",\n written: [],\n error: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...landed, status: \"filled\" };\n }\n\n /**\n * One W1/W2 line's worth of evidence: the schema marks `metadata`\n * `x-manni-location: external` (0047), and this block went to the page\n * anyway because no manifest owns it.\n *\n * Only when a collection is declared. With none there is nothing to relocate\n * into and no 0047 story to tell, and a repository that has never heard of\n * collections would otherwise be warned on every fill.\n */\n function noteHomeless(\n label: string,\n home: Extract<MetadataHome, { kind: \"page\" }>,\n ): void {\n if (collections.length === 0) return;\n // The home relocation would give it, from every declared collection: an\n // artifact in a collection with no manifest is the W1 case, and one in no\n // collection at all is W2.\n homeless.push({ label, key: METADATA_KEY, home: home.proposed });\n }\n}\n\nconst STATUS_LABEL: Record<FillStatus, string> = {\n filled: \"filled\",\n proposed: \"proposed\",\n \"propose-only\": \"proposed\",\n \"nothing-proposed\": \"no-op\",\n skipped: \"skipped\",\n unreadable: \"skipped\",\n error: \"error\",\n};\n\nfunction names(entries: ProposedEval[]): string {\n return entries\n .map((c) => `${c.name} ${c.confidence.toFixed(2)}`)\n .join(\", \");\n}\n\nexport function renderFill(\n report: FillReport,\n opts: { color?: boolean; cwd?: string } = {},\n): string {\n const pc = palette(opts.color === true);\n const from = opts.cwd ?? process.cwd();\n /** Absolute paths stay in the report; the human view is relative. */\n const show = (path: string): string => {\n const rel = relative(from, path);\n return rel === \"\" || rel.startsWith(\"..\") ? path : rel;\n };\n const { green, cyan, dim, red } = pc;\n\n const lines: string[] = [];\n for (const result of report.results) {\n const label = STATUS_LABEL[result.status].padEnd(9);\n const tag = result.cached ? dim(\" [cached]\") : \"\";\n // Where it landed, when that is not the artifact: a relocated block is\n // written to the manifest that owns it, and a report that did not say so\n // would send the reviewer to a file this run never touched.\n const where =\n result.manifest === undefined ? \"\" : dim(` in ${result.manifest}`);\n switch (result.status) {\n case \"filled\":\n lines.push(`${green(label)} ${show(result.artifact)} +${result.written.length} (${names(result.written)})${where}${tag}`);\n break;\n case \"proposed\":\n lines.push(`${cyan(label)} ${show(result.artifact)} +${result.written.length} (${names(result.written)})${where}${tag} — dry run, not written`);\n break;\n case \"propose-only\":\n lines.push(`${cyan(label)} ${show(result.artifact)} +${result.written.length} (${names(result.written)})${tag} — project rules are never written; copy what you want`);\n break;\n case \"nothing-proposed\":\n lines.push(`${dim(label)} ${show(result.artifact)} (nothing new proposed)${tag}`);\n break;\n case \"skipped\":\n lines.push(`${dim(label)} ${show(result.artifact)} (${result.error ?? \"metadata.evals.skip\"})`);\n break;\n case \"unreadable\":\n lines.push(`${dim(label)} ${show(result.artifact)} (${result.error ?? \"unreadable frontmatter\"})`);\n break;\n case \"error\":\n lines.push(`${red(label)} ${show(result.artifact)}: ${result.error ?? \"unknown error\"}`);\n break;\n }\n const belowThreshold = result.rejected.filter((r) => r.reason === \"low-confidence\");\n if (belowThreshold.length > 0) {\n lines.push(dim(` below ${report.threshold}: ${names(belowThreshold.map((r) => r.proposal))}`));\n }\n for (const rejection of result.rejected) {\n if (rejection.reason === \"low-confidence\") continue;\n lines.push(dim(` ${rejection.reason}: ${rejection.proposal.name}${rejection.detail ? ` — ${rejection.detail}` : \"\"}`));\n }\n if (result.capped.length > 0) {\n lines.push(dim(` over per-artifact cap: ${names(result.capped)}`));\n }\n for (const note of result.needsSharpening) {\n lines.push(dim(` needs sharpening: \"${note.instruction}\" — ${note.reason}`));\n }\n }\n\n if (report.results.length === 0) {\n lines.push(\"No skills, agent definitions, or project rules found.\");\n }\n for (const warning of report.warnings) lines.push(dim(`warning: ${warning}`));\n\n lines.push(\"\");\n const total = report.results.reduce((n, r) => n + r.written.length, 0);\n lines.push(\n report.dryRun\n ? `Threshold ${report.threshold} · ${total} evals proposed, none written (dry run)`\n : `Threshold ${report.threshold} · ${total} evals written`,\n );\n return lines.join(\"\\n\");\n}\n","/**\n * Surgical eval append. Only the YAML frontmatter block is re-serialized\n * via the `yaml` Document API — everything from the closing fence onward is\n * carried over byte-for-byte, and untouched YAML keeps its comments, ordering,\n * and style. Artifacts with no frontmatter get a block synthesized above the\n * untouched body, which is the common case for CLAUDE.md / AGENTS.md.\n *\n * Writing is an authoring-time operation, never part of evaluation (ADR 01005).\n */\nimport {\n Document,\n isMap,\n isNode,\n isScalar,\n isSeq,\n parseDocument,\n type YAMLSeq,\n} from \"yaml\";\nimport { mergeMetaProvenance } from \"../../meta/internal.js\";\nimport { TracevalsError } from \"../types.js\";\nimport { METADATA_KEY } from \"./external.js\";\nimport type { Severity } from \"./extract.js\";\n\n/** An eval to add. Mirrors the artifact-evals object entry form. */\nexport interface NewEvalEntry {\n id: string;\n assertion?: string;\n type?: \"capability\" | \"regression\";\n grader?: string;\n options?: Record<string, unknown>;\n severity?: Severity;\n evidence?: string;\n examples?: { pass?: string[]; fail?: string[] };\n}\n\n/** U+FEFF. A file that opens with it keeps it, byte for byte. */\nconst BOM = \"\\uFEFF\";\n\ninterface Split {\n /** BOM plus the opening fence line, including its newline. */\n open: string;\n /** Raw YAML between the fences. */\n block: string;\n /** Closing fence to EOF, byte-identical. */\n suffix: string;\n eol: \"\\n\" | \"\\r\\n\";\n}\n\n/** Frontmatter dialect an artifact opens with, or undefined when it has none. */\nfunction leadingFormat(content: string): \"yaml\" | \"toml\" | \"json\" | undefined {\n const body = content.startsWith(BOM) ? content.slice(1) : content;\n if (/^---\\r?\\n/.test(body)) return \"yaml\";\n if (/^\\+\\+\\+\\r?\\n/.test(body)) return \"toml\";\n if (/^;;;\\r?\\n/.test(body)) return \"json\";\n return undefined;\n}\n\nfunction splitYamlFrontmatter(content: string, path: string): Split {\n const bom = content.startsWith(BOM) ? BOM : \"\";\n const body = bom ? content.slice(1) : content;\n const openMatch = /^---(\\r?\\n)/.exec(body);\n if (!openMatch) {\n throw new TracevalsError(`${path}: no YAML frontmatter block to edit`);\n }\n const eol: \"\\n\" | \"\\r\\n\" = openMatch[1] === \"\\r\\n\" ? \"\\r\\n\" : \"\\n\";\n // Split but keep line endings. `body` opens with the `---` fence, so the\n // first element is that line; the destructuring default only satisfies the\n // type, which `noUncheckedIndexedAccess` widens to `string | undefined`.\n const [fence = body, ...rest] = body.split(/(?<=\\n)/);\n let offset = fence.length;\n for (const line of rest) {\n const stripped = line.replace(/\\r?\\n$/, \"\");\n if (stripped === \"---\" || stripped === \"...\") {\n return {\n open: bom + fence,\n block: body.slice(fence.length, offset),\n suffix: body.slice(offset),\n eol,\n };\n }\n offset += line.length;\n }\n throw new TracevalsError(`${path}: unterminated frontmatter block`);\n}\n\n/** Ordered plain object for one eval entry, with absent fields dropped. */\nfunction entryObject(entry: NewEvalEntry): Record<string, unknown> {\n const obj: Record<string, unknown> = { id: entry.id };\n // Optional since proposal.2. Emitting the key unconditionally would write\n // `assertion: null` for a deterministic grader, which the schema rejects —\n // the opposite of the point of letting it be omitted.\n if (entry.assertion !== undefined) obj.assertion = entry.assertion;\n if (entry.type !== undefined) obj.type = entry.type;\n if (entry.grader !== undefined) obj.grader = entry.grader;\n if (entry.options !== undefined) obj.options = entry.options;\n if (entry.severity !== undefined) obj.severity = entry.severity;\n if (entry.evidence !== undefined) obj.evidence = entry.evidence;\n if (entry.examples !== undefined) obj.examples = entry.examples;\n return obj;\n}\n\n/**\n * Existing eval ids. String-shorthand entries are id-less — their identity is\n * positional — so they never collide with an id'd append.\n */\nfunction existingIds(seq: YAMLSeq): Set<string> {\n const ids = new Set<string>();\n for (const item of seq.items) {\n if (isMap(item)) {\n const id = item.get(\"id\");\n if (typeof id === \"string\") ids.add(id);\n }\n }\n return ids;\n}\n\n/**\n * A key present with an empty value parses to a null node, not `undefined`.\n * `metadata:` with nothing under it is ordinary in the wild, so treat it as\n * the absent case and fill it in rather than refusing to write.\n */\nfunction isEmptyNode(node: unknown): boolean {\n return node === undefined || node === null || isNullScalar(node);\n}\n\nfunction isNullScalar(node: unknown): boolean {\n return isScalar(node) && node.value === null;\n}\n\n/**\n * Locate the `metadata.evals` list, creating each missing level.\n *\n * The single-string block (`evals: <assertion>`) is a legal authored shape that\n * is not a list. Rewriting it into one would move a human's assertion and\n * silently give it a new positional id, so refuse instead and say what to do.\n */\nfunction evalsSeq(doc: Document, path: string): YAMLSeq {\n const existing = doc.getIn([\"metadata\", \"evals\"], true);\n if (!isEmptyNode(existing)) {\n if (isScalar(existing) && typeof existing.value === \"string\") {\n throw new TracevalsError(\n `${path}: metadata.evals is a single assertion string; expand it to a list before appending`,\n );\n }\n if (!isSeq(existing)) {\n throw new TracevalsError(`${path}: metadata.evals is not a list`);\n }\n return existing;\n }\n const node = doc.getIn([\"metadata\"], true);\n if (isEmptyNode(node)) {\n doc.setIn([\"metadata\"], doc.createNode({}));\n } else if (!isMap(node)) {\n throw new TracevalsError(`${path}: metadata is not a mapping`);\n }\n const seq = doc.createNode([]) as YAMLSeq;\n doc.setIn([\"metadata\", \"evals\"], seq);\n return seq;\n}\n\n/**\n * Attribution for machine-proposed evals. A human deletes the entry once those\n * evals are reviewed, which is what makes the trail useful rather than noise.\n */\nexport interface EvalProvenance {\n /**\n * Model that proposed the evals, by the name its provider reports. A bare\n * model name, never `provider:model`: the criterion axis of the\n * self-preference check compares this against the judge's `modelName()`, and\n * a composed spelling made that comparison one it could never win.\n */\n generatedBy: string;\n /** Per-eval confidence, 0..1, keyed by eval id. */\n confidence: Record<string, number>;\n}\n\n/** The key `fill` records machine-proposed evals under (proposal 0046). */\nconst META_PROVENANCE_KEY = \"meta-provenance\";\n\n/**\n * Merge one run's attribution into `metadata.meta-provenance`, keyed by\n * `generated-by`. A repeat fill by the same model extends its existing entry\n * rather than adding a second one the consumer would have to reconcile.\n *\n * The merge itself is `mergeMetaProvenance`, the one `manni meta fill` and\n * `manni docevals fill` use, so all three tools record attribution one way and\n * the shape has a single owner. What stays here is the splice: reading the\n * held value out of the document and writing the merged list back.\n */\nfunction mergeProvenance(\n doc: Document,\n provenance: EvalProvenance,\n ids: string[],\n): void {\n if (ids.length === 0) return;\n // `getIn` hands back a node for a collection, and the family merge reads a\n // plain value, so the held block is converted before it crosses over.\n const node: unknown = doc.getIn([\"metadata\", META_PROVENANCE_KEY], true);\n const held = isEmptyNode(node)\n ? undefined\n : isNode(node)\n ? (node.toJSON() as unknown)\n : node;\n const merged = mergeMetaProvenance(\n held,\n provenance.generatedBy,\n \"evals\",\n ids.map((id) => ({ name: id, confidence: provenance.confidence[id] ?? 0 })),\n );\n if (!merged) {\n throw new TracevalsError(`metadata.${META_PROVENANCE_KEY} is not a list`);\n }\n doc.setIn(\n [\"metadata\", META_PROVENANCE_KEY],\n doc.createNode(merged.list),\n );\n}\n\n/**\n * The same append over a `metadata` block that is not in the page: the value an\n * external-metadata manifest holds for this artifact (proposal 0047). Returns\n * the new block, for `spliceManifestValue` to write.\n *\n * A plain value in and a plain value out, because a manifest entry is rewritten\n * by meta's splice writer rather than re-serialized here — the comment and key\n * order preservation `appendArtifactEvals` gets from editing YAML nodes is that\n * writer's job on this path. The refusals are the page path's, for the page\n * path's reasons: an id that already exists means the caller's dedupe missed\n * something, and a single-assertion block is a human's sentence that must not\n * be silently given a positional id.\n */\nexport function appendMetadataEvals(\n held: unknown,\n label: string,\n entries: NewEvalEntry[],\n provenance?: EvalProvenance,\n): Record<string, unknown> {\n const block: Record<string, unknown> =\n held === undefined || held === null\n ? {}\n : typeof held === \"object\" && !Array.isArray(held)\n ? { ...(held as Record<string, unknown>) }\n : (() => {\n throw new TracevalsError(`${label}: metadata is not a mapping`);\n })();\n\n const existing = block.evals;\n if (typeof existing === \"string\") {\n throw new TracevalsError(\n `${label}: metadata.evals is a single assertion string; expand it to a list before appending`,\n );\n }\n if (existing !== undefined && existing !== null && !Array.isArray(existing)) {\n throw new TracevalsError(`${label}: metadata.evals is not a list`);\n }\n\n const list: unknown[] = Array.isArray(existing)\n ? [...(existing as unknown[])]\n : [];\n const taken = new Set<string>();\n for (const item of list) {\n if (item !== null && typeof item === \"object\" && !Array.isArray(item)) {\n const id = (item as Record<string, unknown>).id;\n if (typeof id === \"string\") taken.add(id);\n }\n }\n for (const entry of entries) {\n if (taken.has(entry.id)) {\n throw new TracevalsError(\n `${label}: eval \"${entry.id}\" already exists in ${METADATA_KEY}`,\n );\n }\n taken.add(entry.id);\n list.push(entryObject(entry));\n }\n block.evals = list;\n\n if (provenance !== undefined && entries.length > 0) {\n const merged = mergeMetaProvenance(\n block[META_PROVENANCE_KEY],\n provenance.generatedBy,\n \"evals\",\n entries.map((e) => ({\n name: e.id,\n confidence: provenance.confidence[e.id] ?? 0,\n })),\n );\n if (!merged) {\n throw new TracevalsError(`${label}: metadata.${META_PROVENANCE_KEY} is not a list`);\n }\n block[META_PROVENANCE_KEY] = merged.list;\n }\n return block;\n}\n\n/**\n * Append evals to an artifact's `metadata.evals`, returning the new file\n * content. Throws when the frontmatter is not YAML or when an id already\n * exists — a collision means the caller's dedupe missed something, and\n * silently overwriting a human-authored eval is never right.\n *\n * When `provenance` is given, the same splice also records the machine\n * attribution under `metadata.meta-provenance`.\n */\nexport function appendArtifactEvals(\n content: string,\n path: string,\n entries: NewEvalEntry[],\n provenance?: EvalProvenance,\n): string {\n if (entries.length === 0) return content;\n\n const format = leadingFormat(content);\n if (format === \"toml\" || format === \"json\") {\n // Synthesizing a YAML block would leave the artifact with two\n // frontmatter blocks; only YAML can be edited in place.\n throw new TracevalsError(\n `${path}: only YAML frontmatter can be edited (found ${format} frontmatter)`,\n );\n }\n\n const bom = content.startsWith(BOM) ? BOM : \"\";\n const stripped = bom ? content.slice(1) : content;\n\n if (format === undefined) {\n const eol: \"\\n\" | \"\\r\\n\" = stripped.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const doc = new Document({\n metadata: { evals: entries.map(entryObject) },\n });\n if (provenance) {\n mergeProvenance(\n doc,\n provenance,\n entries.map((e) => e.id),\n );\n }\n let block = doc.toString({ lineWidth: 0 });\n if (eol === \"\\r\\n\") block = block.replace(/(?<!\\r)\\n/g, \"\\r\\n\");\n return `${bom}---${eol}${block}---${eol}${stripped}`;\n }\n\n const { open, block, suffix, eol } = splitYamlFrontmatter(content, path);\n const doc = parseDocument(block);\n if (doc.errors.length > 0) {\n throw new TracevalsError(\n `${path}: cannot edit frontmatter — ${doc.errors[0]?.message ?? \"parse error\"}`,\n );\n }\n\n let seq: YAMLSeq;\n try {\n seq = evalsSeq(doc, path);\n } catch (err) {\n // A block that is valid YAML but not a mapping (a sequence, a bare\n // scalar, a `---` that was really a thematic break) makes the yaml\n // library throw its own error type. Callers are promised TracevalsError.\n if (err instanceof TracevalsError) throw err;\n throw new TracevalsError(\n `${path}: cannot edit frontmatter — ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n const taken = existingIds(seq);\n for (const entry of entries) {\n if (taken.has(entry.id)) {\n throw new TracevalsError(\n `${path}: eval \"${entry.id}\" already exists in frontmatter`,\n );\n }\n taken.add(entry.id);\n seq.add(doc.createNode(entryObject(entry)));\n }\n\n if (provenance) {\n try {\n mergeProvenance(\n doc,\n provenance,\n entries.map((e) => e.id),\n );\n } catch (err) {\n if (err instanceof TracevalsError) {\n throw new TracevalsError(`${path}: ${err.message}`);\n }\n throw err;\n }\n }\n\n // lineWidth 0 disables folding: skill descriptions routinely run past 80\n // columns, and reflowing one the user did not touch is gratuitous churn.\n let updated = doc.toString({ lineWidth: 0 });\n if (eol === \"\\r\\n\") updated = updated.replace(/(?<!\\r)\\n/g, \"\\r\\n\");\n return open + updated + suffix;\n}\n","/**\n * Where `manni tracevals fill` writes an artifact's `metadata` block\n * (proposal 0047, §3 and §4).\n *\n * Every write goes through the rule `manni meta fill` and `manni docevals\n * fill` already follow, decided by meta's `keyHome`:\n *\n * - a **local manifest** of one of the artifact's collections owns the\n * block: the value is spliced into the artifact's entry there. A `{page}`\n * manifest (proposal 0058) resolves to the artifact's own file, which the\n * first write creates. A keyless manifest (proposal 0068) owns the block\n * when the artifact's schemas mark it external;\n * - the manifest **joins on a field the artifact lacks**: there is no entry\n * to hold the block, and the write is refused for that artifact;\n * - a **URL manifest** owns it: nothing fetched can be written;\n * - **no manifest owns it**: the artifact keeps it, with the offer (P1) and\n * the warnings (W1, W2) meta's writers use.\n *\n * The marks a keyless manifest owns by are read from meta's section of the\n * same family file the reader (`external.ts`) reads them from, so reading and\n * writing agree on where the block lives.\n */\nimport { relative, resolve } from \"node:path\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport { readManifestOrEmpty } from \"../../shared/manifest-cas.js\";\nimport type { Confirm } from \"../../shared/prompt.js\";\nimport {\n keyHome,\n marksValidator,\n metaSection,\n offerExternalHomes,\n readManifestValue,\n spliceManifestValue,\n type ExternalWrite,\n type ProposedHome,\n type RelocateResult,\n type RelocationContext,\n} from \"../../meta/internal.js\";\nimport {\n DocmetaError,\n writeFileAtomic,\n type CollectionConfig,\n type DocmetaConfig,\n} from \"../../meta/index.js\";\nimport { TracevalsError } from \"../types.js\";\nimport { METADATA_KEY } from \"./external.js\";\n\n/** Where one artifact's `metadata` block goes. */\nexport type MetadataHome =\n /** The artifact's own front matter. `proposed` is the home relocation would give it. */\n | { kind: \"page\"; proposed: ProposedHome }\n /** The artifact's entry in a local manifest. */\n | {\n kind: \"manifest\";\n /** As the run reports it. */\n file: string;\n absPath: string;\n /** `path`, or the artifact field the manifest joins on. */\n join: string;\n entry: string;\n /** A `{page}` manifest, which may not exist yet. */\n perPage: boolean;\n }\n /** A manifest joins on a field this artifact does not carry. */\n | { kind: \"no-entry\"; file: string; join: string }\n /** A URL manifest owns the block. */\n | { kind: \"url\"; file: string };\n\n/** What `offer` reports back while it asks. */\nexport interface OfferHooks {\n confirm: Confirm;\n onNotice?: (message: string) => void;\n onRelocated?: (result: RelocateResult) => void;\n}\n\nexport interface MetadataWriterOptions {\n /** Every collection the config declares. An accepted offer edits these in place. */\n collections: CollectionConfig[];\n /** The config file's directory; artifact entries resolve from it. */\n configDir: string;\n /** The config file; absent when there is none, and then nothing has a home. */\n configPath: string | undefined;\n /** The working directory the positional paths were typed in. */\n cwd: string;\n /** The positional paths as typed, where a created collection's `paths:` come from. */\n targets: readonly string[];\n}\n\n/** `<artifact> carries no <join>, which <file> joins on, so its metadata has no entry there.` */\nexport function noEntryRefusal(label: string, join: string, file: string): string {\n return `${label}: ${METADATA_KEY} is owned by ${file}, which joins on \"${join}\", and this artifact carries no ${join}.`;\n}\n\n/**\n * The run's writer. One per run, because the relocation context it reads is\n * the config as the run found it, and an accepted offer changes that config.\n */\nexport class MetadataWriter {\n private constructor(private readonly ctx: RelocationContext) {}\n\n static async for(opts: MetadataWriterOptions): Promise<MetadataWriter> {\n const { configDir, configPath } = opts;\n const config = configPath === undefined ? null : await metaConfig(configPath, configDir);\n return new MetadataWriter({\n // Artifact labels are absolute, and a manifest is reported relative to\n // the config directory, the way `external.ts` reports one it read.\n cwd: configDir,\n base: configDir,\n noConfig: configPath === undefined,\n config,\n ...(configPath === undefined ? {} : { configDir, configPath }),\n collections: opts.collections,\n declaredCollections: opts.collections,\n targets: opts.targets.map((t) => relative(configDir, resolve(opts.cwd, t)) || \".\"),\n validator: marksValidator({ config, cwd: configDir, configDir })(),\n });\n }\n\n /** Where the `metadata` block of the artifact `label` goes. `data` is its own front matter. */\n async homeFor(label: string, data: Readonly<Record<string, unknown>>): Promise<MetadataHome> {\n const home = await keyHome(this.ctx, label, data, METADATA_KEY);\n if (home.kind === \"url\") return { kind: \"url\", file: home.file };\n if (home.kind === \"manifest\") {\n if (home.entry === undefined) {\n return { kind: \"no-entry\", file: home.file, join: home.join };\n }\n return {\n kind: \"manifest\",\n file: home.file,\n absPath: home.absPath,\n join: home.join,\n entry: home.entry,\n perPage: home.perPage,\n };\n }\n return { kind: \"page\", proposed: home.home };\n }\n\n /**\n * Ask P1 once per collection the flagged writes would be homed in. Returns\n * true when a relocation was applied, which leaves the caller's config,\n * artifacts and this writer stale: rebuild all three before writing.\n */\n async offer(writes: readonly ExternalWrite[], hooks: OfferHooks): Promise<boolean> {\n if (writes.length === 0) return false;\n const applied = await offerExternalHomes(this.ctx, writes, hooks);\n return applied.size > 0;\n }\n\n /**\n * Replace this artifact's `metadata` block in its manifest entry with what\n * `update` makes of the block the file holds now. The file is read just\n * before the write, so a block another run wrote meanwhile is extended\n * rather than lost, and no other byte of the file changes.\n */\n async write(\n home: Extract<MetadataHome, { kind: \"manifest\" }>,\n update: (current: unknown) => unknown,\n ): Promise<void> {\n let text: string;\n try {\n text = await readManifestOrEmpty(home.absPath, home.perPage);\n } catch (e) {\n throw new TracevalsError(`${home.file} could not be read: ${errorMessage(e)}`);\n }\n const at = { entry: home.entry, key: METADATA_KEY, join: home.join };\n let spliced: string;\n try {\n spliced = spliceManifestValue(text, {\n ...at,\n value: update(readManifestValue(text, at)),\n file: home.file,\n }).text;\n } catch (e) {\n // meta's refusal, in this tool's error class.\n throw new TracevalsError(errorMessage(e));\n }\n // A per-page manifest may be the first file in its directory.\n if (spliced !== text) {\n await writeFileAtomic(home.absPath, spliced, { createParents: true });\n }\n }\n}\n\n/**\n * Meta's section of the family file. A file meta cannot read as its own is\n * still tracevals' file, and meta's default set decides the marks then.\n */\nasync function metaConfig(configPath: string, configDir: string): Promise<DocmetaConfig | null> {\n try {\n return await metaSection(configPath, configDir);\n } catch (err) {\n if (err instanceof DocmetaError) return null;\n throw err;\n }\n}\n","/**\n * Fill proposal cache: content-addressed JSON holding the raw, *pre-gating*\n * proposal. Two consequences are the point of the design:\n *\n * - Re-running with a different `--confidence` re-gates from cache, so tuning\n * the threshold costs no tokens.\n * - The existing eval-id set is part of the key, so a re-run after a\n * fill misses and asks the model for *additional* coverage rather than\n * replaying a proposal that has already been applied.\n *\n * Kept in its own directory: the judge cache has a different key scheme and\n * value shape, and the two must never be read into each other.\n *\n * Storage is the inference library's `JsonCache`; the schema re-check on read\n * stays here, because the library's cache deliberately does not know what\n * shape any given consumer stores.\n */\nimport { JsonCache, buildCacheKey, sha256 } from \"@hawkeyexl/inference\";\nimport type { ArtifactType } from \"../artifacts/types.js\";\nimport { FILL_PROMPT_VERSION, isValidProposal } from \"./prompt.js\";\n\nexport interface FillCacheKeyParts {\n provider: string;\n model: string;\n temperature: number;\n maxEvals: number;\n artifactType: ArtifactType;\n /** Artifact path — it appears in the prompt, so it belongs in the key. */\n path: string;\n /** Full artifact content, hashed. */\n body: string;\n existingNames: string[];\n /**\n * Project-wide skill names. They are the grounding vocabulary in the\n * prompt, so adding or renaming a skill must invalidate every artifact's\n * cached proposal, not just that skill's own.\n */\n knownSkills: string[];\n}\n\n/** JSON-encoded so a name containing a separator cannot forge a boundary. */\nfunction listPart(values: string[]): string {\n return JSON.stringify([...values].sort());\n}\n\nexport function fillCacheKey(parts: FillCacheKeyParts): string {\n return buildCacheKey([\n parts.provider,\n parts.model,\n `fill-v${FILL_PROMPT_VERSION}`,\n `t${parts.temperature}`,\n `n${parts.maxEvals}`,\n parts.artifactType,\n parts.path,\n sha256(parts.body),\n listPart(parts.existingNames),\n listPart(parts.knownSkills),\n ]);\n}\n\n/**\n * A proposal cache over `JsonCache`, adding the one thing the generic cache\n * cannot do: reject an entry written by an older proposal schema. Such an\n * entry parses fine, so only a schema check turns it into a miss.\n */\nexport class FillCache {\n private readonly store: JsonCache<unknown>;\n\n constructor(dir: string, enabled: boolean = true) {\n this.store = new JsonCache<unknown>(dir, enabled, \"manni-tracevals\");\n }\n\n get(key: string): Record<string, unknown> | undefined {\n const proposal = this.store.get(key);\n if (!isValidProposal(proposal)) return undefined;\n return proposal as Record<string, unknown>;\n }\n\n set(key: string, proposal: Record<string, unknown>): void {\n this.store.set(key, proposal);\n }\n}\n","/**\n * Fill prompt: asks the provider to extract evals that an artifact's\n * own instructions already imply, each with a self-reported 0-1 confidence.\n * Gating happens downstream; the prompt only demands honesty and restraint.\n *\n * Instructions too vague to test are reported under `needsSharpening` rather\n * than turned into a soft assertion — an untestable instruction is a defect in\n * the artifact, and naming it is more useful than papering over it.\n */\nimport { Ajv2020 } from \"ajv/dist/2020.js\";\nimport { SEVERITIES } from \"../../shared/severity.js\";\nimport type { ArtifactType, ResolvedArtifact } from \"../artifacts/types.js\";\nimport { ALLOWED_GRADERS } from \"./gate.js\";\nimport type { ArtifactFacts } from \"./facts.js\";\n\n/**\n * Part of the cache key: bump whenever the prompt or schema changes.\n *\n * A prompt edit that leaves this alone makes every cached proposal replay the\n * *old* prompt output, silently, for as long as the cache lives.\n * `test/unit/fill-prompt.test.ts` pins this to a digest of the prompt surface\n * so the pair has to move together.\n *\n * 3 — added the `slash-command` type guidance (ADR 01023).\n * 4 — the family severity scale: the quietest level is `notice`, not `info`.\n */\nexport const FILL_PROMPT_VERSION = 4;\n\nexport const MAX_BODY_CHARS = 6000;\n\n/** What each artifact type's instructions look like, in its own vocabulary. */\nconst TYPE_GUIDANCE: Record<ArtifactType, string> = {\n skill: [\n \"This artifact is a skill: a procedure an agent follows on demand.\",\n \"Its testable claims are entry criteria (what must be true before starting),\",\n \"process steps (what must actually happen), and output specifications (what\",\n \"the result must contain or must never contain).\",\n ].join(\"\\n\"),\n \"slash-command\": [\n \"This artifact is a slash command: a procedure whose body is injected as a\",\n \"prompt when a person types its name. Its testable claims are the steps it\",\n \"mandates, the tools it permits or forbids, and the artifact it must leave\",\n \"behind. Its `argument-hint` and `description` are harness metadata, not\",\n \"assertions — do not test them.\",\n ].join(\"\\n\"),\n agent: [\n \"This artifact is an agent definition: a role with boundaries.\",\n \"Its testable claims are constraints (what the agent must never do),\",\n \"quality criteria (measurable standards its output must meet), and\",\n \"escalation rules (conditions under which it must stop and hand off).\",\n \"Its identity and persona are framing, not assertions — do not test them.\",\n ].join(\"\\n\"),\n \"project-rules\": [\n \"This artifact is a project rules file: standing rules for all work in the\",\n \"repository. Its testable claims are process gates, quality gates, approval\",\n \"requirements, and hard limits. These files are assertion-dense; prefer the\",\n \"rules stated plainly over anything you would have to infer.\",\n ].join(\"\\n\"),\n};\n\nconst GRADER_GUIDANCE: Record<string, string> = {\n ai: \"judgment a human would have to read the session to make\",\n \"tool-usage\": \"a named tool was or was not used (options: tool, expect, min, max)\",\n \"skill-invoked\": \"a named skill was or was not invoked (options: skill, expect)\",\n \"file-access\":\n \"a file was or was not read/written/edited (options: path, op, expect)\",\n regex:\n \"a pattern does or does not appear in session text (options: pattern, flags, on, expect)\",\n};\n\nexport function systemPromptFor(artifactType: ArtifactType): string {\n const allowed = ALLOWED_GRADERS[artifactType];\n return [\n \"You extract evals from an AI agent instruction artifact.\",\n \"\",\n TYPE_GUIDANCE[artifactType],\n \"\",\n \"An eval is a durable claim about how a session behaved, graded against\",\n \"a recorded session trace on every future run. You are extracting claims the\",\n \"artifact already makes — not inventing new policy for it.\",\n \"\",\n \"Rules for every eval you propose:\",\n \"- It must be decidable as a binary pass or fail against session evidence.\",\n \" If you cannot say precisely what would make it fail, it does not qualify.\",\n \"- Quote the artifact's own intent. Never assert incidental phrasing,\",\n \" formatting, or wording that is expected to change.\",\n \"- Prefer a deterministic grader whenever the claim can be checked\",\n \" mechanically; fall back to `ai` only for genuine judgment.\",\n \"- Ids are short kebab-case identifiers, unique within the artifact.\",\n \"- Provide examples.pass and examples.fail: one sentence each describing a\",\n \" session that satisfies or violates the eval.\",\n \"- Report an honest confidence between 0 and 1 that the criterion is\",\n \" correct, checkable, and worth guarding. Do not inflate it.\",\n \"- Do not restate evals the artifact already declares.\",\n \"- Propose at most the requested number, fewer when the artifact offers\",\n \" little worth guarding, and none at all when nothing qualifies.\",\n \"\",\n \"Graders available for this artifact type:\",\n ...allowed.map((kind) => `- ${kind}: ${GRADER_GUIDANCE[kind] ?? \"\"}`),\n \"\",\n \"Deterministic graders only work against targets that really exist. Use tool\",\n \"and skill names exactly as given below; if the name you want is not listed,\",\n \"use the `ai` grader instead of guessing.\",\n \"\",\n \"Finally, list under `needsSharpening` any instruction in the artifact that\",\n \"sounds like a requirement but cannot be tested as written — an undefined\",\n \"quality bar, an unmeasurable adjective, a rule with no observable outcome.\",\n \"Say what makes it untestable. Do not invent a criterion to cover it.\",\n ].join(\"\\n\");\n}\n\nexport const PROPOSAL_SCHEMA = {\n type: \"object\",\n required: [\"evals\"],\n additionalProperties: false,\n properties: {\n evals: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"name\", \"assertion\", \"grader\", \"examples\", \"confidence\"],\n additionalProperties: false,\n properties: {\n name: { type: \"string\", pattern: \"^[a-z0-9][a-z0-9-]*$\" },\n assertion: { type: \"string\", minLength: 1 },\n grader: { type: \"string\" },\n options: { type: \"object\" },\n evidence: { type: \"string\" },\n examples: {\n type: \"object\",\n required: [\"pass\", \"fail\"],\n additionalProperties: false,\n properties: {\n pass: { type: \"string\" },\n fail: { type: \"string\" },\n },\n },\n severity: { enum: [...SEVERITIES] },\n confidence: { type: \"number\", minimum: 0, maximum: 1 },\n rationale: { type: \"string\" },\n },\n },\n },\n needsSharpening: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"instruction\", \"reason\"],\n additionalProperties: false,\n properties: {\n instruction: { type: \"string\" },\n reason: { type: \"string\" },\n suggestion: { type: \"string\" },\n },\n },\n },\n },\n} as const;\n\nconst ajv = new Ajv2020({ allErrors: true });\nconst validateProposal = ajv.compile(\n PROPOSAL_SCHEMA as unknown as Record<string, unknown>,\n);\n\nexport function isValidProposal(value: unknown): boolean {\n return validateProposal(value);\n}\n\nexport interface FillUserOptions {\n artifact: ResolvedArtifact;\n existingNames: string[];\n maxEvals: number;\n facts: ArtifactFacts;\n /** Skill names discovered in the same scan — the vocabulary for skill-invoked. */\n knownSkills: string[];\n}\n\nexport function buildFillUser(options: FillUserOptions): string {\n const { artifact, existingNames, maxEvals, facts, knownSkills } = options;\n const body =\n artifact.content.length > MAX_BODY_CHARS\n ? `${artifact.content.slice(0, MAX_BODY_CHARS)}\\n…(truncated)`\n : artifact.content;\n\n const lines = [\n \"# Artifact\",\n `path: ${artifact.path}`,\n `type: ${artifact.type}`,\n `name: ${facts.name ?? artifact.name}`,\n ];\n if (facts.description !== undefined) {\n lines.push(`description: ${facts.description}`);\n }\n lines.push(\n \"\",\n \"# Existing evals (do not restate these)\",\n existingNames.length > 0 ? existingNames.join(\", \") : \"(none)\",\n \"\",\n \"# Tools this artifact grants itself\",\n facts.declaredTools.length > 0 ? facts.declaredTools.join(\", \") : \"(none declared)\",\n \"\",\n \"# Skills that exist in this project\",\n knownSkills.length > 0 ? knownSkills.join(\", \") : \"(none)\",\n \"\",\n \"# Maximum evals to propose\",\n String(maxEvals),\n \"\",\n \"# Artifact content\",\n \"\",\n body,\n );\n return lines.join(\"\\n\");\n}\n","/**\n * Proposal gate: everything between \"the model said so\" and \"this is written\n * to a file the user maintains\".\n *\n * Self-reported confidence is a weak signal on its own, so it is the *last*\n * filter, not the only one. Mechanical checks run first — grader scope, the\n * grader's own option validation (ADR 01004), and whether the target the\n * eval targets actually exist in the project.\n */\nimport { graderFor } from \"../graders/registry.js\";\nimport type { ArtifactType } from \"../artifacts/types.js\";\nimport type { Severity } from \"../evals/extract.js\";\n\nexport interface ProposedEval {\n name: string;\n assertion: string;\n grader: string;\n options?: Record<string, unknown>;\n evidence?: string;\n examples: { pass: string; fail: string };\n severity?: Severity;\n confidence: number;\n rationale?: string;\n}\n\nexport type RejectionReason =\n | \"low-confidence\"\n | \"invalid-options\"\n | \"grader-not-allowed\"\n | \"ungrounded-target\"\n | \"duplicate-name\";\n\nexport interface Rejection {\n proposal: ProposedEval;\n reason: RejectionReason;\n detail?: string;\n}\n\nexport interface Vocabulary {\n /** Tool names the project can actually produce in a trace. */\n tools: Set<string>;\n /** Skill names discovered in the same scan. */\n skills: Set<string>;\n}\n\nexport interface GateOptions {\n artifactType: ArtifactType;\n threshold: number;\n existingNames: string[];\n maxEvals: number;\n vocabulary: Vocabulary;\n}\n\nexport interface GateResult {\n accepted: ProposedEval[];\n rejected: Rejection[];\n /** Survivors dropped for exceeding the per-artifact cap, most confident first. */\n capped: ProposedEval[];\n}\n\n/**\n * Which graders may be proposed for each artifact type.\n *\n * `cost`, `turn-count`, and `json-output` are whole-session graders: a budget\n * declared inside one skill silently constrains the entire session and\n * double-counts when several artifacts declare it. `skill-invoked` is excluded\n * from skills, slash commands, and agents because an eval asserting its own\n * artifact was used can only be graded in sessions that used it — permanently\n * green.\n *\n * A slash command carries the skill list unchanged: both are an injected\n * procedure graded over the span they governed (ADR 01023), so the same\n * graders make sense and the same whole-session ones do not.\n *\n * `tool-order` is never proposed. An order is the instruction's intent, not\n * something a tool list shows, and grounding below checks one named tool,\n * not a pair. It is written by hand.\n */\nexport const ALLOWED_GRADERS: Record<ArtifactType, readonly string[]> = {\n skill: [\"ai\", \"tool-usage\", \"file-access\", \"regex\"],\n \"slash-command\": [\"ai\", \"tool-usage\", \"file-access\", \"regex\"],\n agent: [\"ai\", \"tool-usage\", \"file-access\"],\n \"project-rules\": [\"ai\", \"skill-invoked\", \"tool-usage\"],\n};\n\n/** Absolute paths are machine-specific; file-access matches on a suffix. */\nfunction isAbsoluteish(path: string): boolean {\n return path.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\n\n/**\n * Does the eval name something that can exist in a trace? Rejects\n * hallucinated tool names and skills, however confident the model claims to be.\n */\nfunction groundingError(\n proposal: ProposedEval,\n vocabulary: Vocabulary,\n): string | undefined {\n const options = proposal.options ?? {};\n if (proposal.grader === \"tool-usage\") {\n const tool = options.tool;\n // MCP tools are named at connect time, so they cannot be enumerated ahead\n // of a session; the prefix is the only available signal.\n if (\n typeof tool === \"string\" &&\n !tool.startsWith(\"mcp__\") &&\n !vocabulary.tools.has(tool)\n ) {\n return `no tool named \"${tool}\" is available in this project`;\n }\n }\n if (proposal.grader === \"skill-invoked\") {\n const skill = options.skill;\n if (typeof skill === \"string\" && !vocabulary.skills.has(skill)) {\n return `no skill named \"${skill}\" was found in this project`;\n }\n }\n if (proposal.grader === \"file-access\") {\n const path = options.path;\n if (typeof path === \"string\" && isAbsoluteish(path)) {\n return `options.path must be a repository-relative suffix, not \"${path}\"`;\n }\n }\n return undefined;\n}\n\n/**\n * An eval in an agent definition describes what the *subagent* did, and\n * subagent tool calls are recorded as sidechain calls — which tool-usage\n * excludes by default. Left alone, such an eval silently measures the\n * main thread instead.\n */\nfunction normalize(\n proposal: ProposedEval,\n artifactType: ArtifactType,\n): ProposedEval {\n if (artifactType !== \"agent\" || proposal.grader !== \"tool-usage\") {\n return proposal;\n }\n return {\n ...proposal,\n options: { ...(proposal.options ?? {}), includeSidechains: true },\n };\n}\n\nexport function gateProposals(\n proposals: ProposedEval[],\n options: GateOptions,\n): GateResult {\n const { artifactType, threshold, maxEvals, vocabulary } = options;\n const allowed = new Set(ALLOWED_GRADERS[artifactType]);\n const taken = new Set(options.existingNames);\n const rejected: Rejection[] = [];\n const survivors: ProposedEval[] = [];\n\n for (const raw of proposals) {\n // Names first: a duplicate is rejected on its own terms rather than\n // competing for a slot under the cap.\n if (taken.has(raw.name)) {\n rejected.push({ proposal: raw, reason: \"duplicate-name\" });\n continue;\n }\n if (!allowed.has(raw.grader)) {\n rejected.push({\n proposal: raw,\n reason: \"grader-not-allowed\",\n detail: `${raw.grader} may not be declared on a ${artifactType} artifact`,\n });\n continue;\n }\n\n const proposal = normalize(raw, artifactType);\n\n if (proposal.grader !== \"ai\") {\n const grader = graderFor(proposal.grader);\n const validate = grader?.validateOptions;\n if (validate === undefined) {\n // Without a ground-check there is no way to know the options are\n // usable, and an unusable eval errors on every future run.\n rejected.push({\n proposal,\n reason: \"invalid-options\",\n detail: `grader ${proposal.grader} cannot validate its options`,\n });\n continue;\n }\n const invalid = validate(proposal.options ?? {});\n if (invalid !== undefined) {\n rejected.push({ proposal, reason: \"invalid-options\", detail: invalid });\n continue;\n }\n const ungrounded = groundingError(proposal, vocabulary);\n if (ungrounded !== undefined) {\n rejected.push({\n proposal,\n reason: \"ungrounded-target\",\n detail: ungrounded,\n });\n continue;\n }\n }\n\n taken.add(proposal.name);\n survivors.push(proposal);\n }\n\n // Confidence last, then the cap — so the cap drops the least confident of\n // the evals that were otherwise acceptable, and the two reasons stay\n // distinguishable in the report.\n const confident: ProposedEval[] = [];\n for (const proposal of survivors) {\n if (proposal.confidence >= threshold) confident.push(proposal);\n else rejected.push({ proposal, reason: \"low-confidence\" });\n }\n confident.sort((a, b) => b.confidence - a.confidence);\n\n return {\n accepted: confident.slice(0, maxEvals),\n capped: confident.slice(maxEvals),\n rejected,\n };\n}\n","/**\n * Static facts an artifact states about itself in structured frontmatter the\n * host tool already treats as schema — an agent's `tools:` grant, a skill's\n * `name`/`description`.\n *\n * These are grounding inputs, not evals. Minting an eval directly from\n * them produces evals that cannot fail: a `tools:` list is an allowlist rather\n * than a requirement, and a skill asserting its own invocation is only ever\n * graded in sessions that invoked it (ADR 01005).\n */\nimport { extractFrontmatter } from \"../../meta/index.js\";\nimport type { ResolvedArtifact } from \"../artifacts/types.js\";\n\nexport interface ArtifactFacts {\n name?: string;\n description?: string;\n /** Tools an agent definition grants itself, normalized to a list. */\n declaredTools: string[];\n}\n\n/** `tools: Read, Grep` and `tools: [Read, Grep]` are both in the wild. */\nfunction toolList(value: unknown): string[] {\n if (Array.isArray(value)) {\n return value.filter((v): v is string => typeof v === \"string\");\n }\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((tool) => tool.trim())\n .filter((tool) => tool.length > 0);\n }\n return [];\n}\n\nexport function artifactFacts(artifact: ResolvedArtifact): ArtifactFacts {\n try {\n const { data } = extractFrontmatter(artifact.content, \"markdown\");\n const facts: ArtifactFacts = { declaredTools: toolList(data.tools) };\n if (typeof data.name === \"string\") facts.name = data.name;\n if (typeof data.description === \"string\") {\n facts.description = data.description;\n }\n return facts;\n } catch {\n // Malformed frontmatter yields no facts; discovery already reported it.\n // This runs during vocabulary building, outside any per-artifact handler,\n // so it must not throw.\n return { declaredTools: [] };\n }\n}\n","/**\n * A canned, schema-valid proposal for `--provider mock`.\n *\n * The inference library's `mockVerdict` is judge-shaped, so it cannot drive\n * `fill` — the response would fail the proposal schema. This gives the offline\n * path\n * (CI's dogfood gate, CLI smoke tests) something the gate can actually chew\n * on: one eval that should be accepted and one that should be rejected\n * for low confidence, so a run that rubber-stamps everything is visible.\n */\nexport function mockFillProposal(): { json: Record<string, unknown> } {\n return {\n json: {\n evals: [\n {\n name: \"reads-before-editing\",\n assertion: \"The session read a source file before editing it.\",\n grader: \"tool-usage\",\n options: { tool: \"Read\", expect: \"used\" },\n examples: {\n pass: \"Read is called before the first Edit\",\n fail: \"Edit is called with no prior Read\",\n },\n confidence: 0.9,\n },\n {\n name: \"explains-its-reasoning\",\n assertion: \"The session explained why it made each change.\",\n grader: \"ai\",\n examples: {\n pass: \"Each edit is accompanied by a rationale\",\n fail: \"Edits land with no explanation\",\n },\n confidence: 0.3,\n },\n ],\n needsSharpening: [\n {\n instruction: \"Produce high-quality work.\",\n reason: \"\\\"high-quality\\\" has no measurable bar, so no session could fail it\",\n suggestion: \"Name the specific property that must hold, and how to observe it.\",\n },\n ],\n },\n };\n}\n","/**\n * The set of targets a proposed deterministic criterion may name. Anything\n * outside it is a hallucination that would produce a criterion which can never\n * pass, so the gate rejects it regardless of the model's stated confidence.\n */\nimport type { DiscoveredArtifact } from \"../artifacts/discover.js\";\nimport { artifactFacts } from \"./facts.js\";\nimport type { Vocabulary } from \"./gate.js\";\n\n/**\n * Tools Claude Code exposes by default. Project-specific additions arrive via\n * agent `tools:` grants; MCP tools are recognized by their `mcp__` prefix in\n * the gate rather than enumerated here.\n */\nexport const BUILTIN_TOOLS = [\n \"Agent\",\n \"AskUserQuestion\",\n \"Bash\",\n \"BashOutput\",\n \"Edit\",\n \"ExitPlanMode\",\n \"Glob\",\n \"Grep\",\n \"KillShell\",\n \"NotebookEdit\",\n \"Read\",\n \"Skill\",\n \"SlashCommand\",\n \"Task\",\n \"TodoWrite\",\n \"WebFetch\",\n \"WebSearch\",\n \"Write\",\n] as const;\n\n/** Build the vocabulary from everything the scan found. */\nexport function buildVocabulary(artifacts: DiscoveredArtifact[]): Vocabulary {\n const tools = new Set<string>(BUILTIN_TOOLS);\n const skills = new Set<string>();\n\n for (const discovered of artifacts) {\n if (discovered.artifact.type === \"skill\") {\n skills.add(discovered.artifact.name);\n }\n for (const tool of artifactFacts(discovered.artifact).declaredTools) {\n tools.add(tool);\n }\n }\n return { tools, skills };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,eAAsB,QAAQ,UAAuB,CAAC,GAAqB;AAEzE,MAAI,QAAQ,cAAc,OAAW,gBAAe,QAAQ,SAAS;AACrE,QAAM,EAAE,WAAW,GAAG,SAAS,IAAI;AACnC,SAAO,EAAE,QAAQ,cAAc,MAAM,eAAe,QAAQ,GAAG,SAAS,EAAE;AAC5E;AAEO,SAAS,WACd,KACA,OAA4B,CAAC,GACrB;AACR,QAAM,KAAK,QAAQ,KAAK,UAAU,IAAI;AACtC,QAAM,MAAM,GAAG;AACf,QAAM,OAAO,GAAG;AAEhB,MAAI,IAAI,OAAO,WAAW,GAAG;AAC3B,WAAO;AAAA,EACT;AAEA,QAAM,QAAkB,CAAC;AACzB,MAAI,OAAO,QAAQ,CAAC,GAAG,MAAM;AAC3B,UAAM,OAAO,IAAI,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE,EAAE,QAAQ,KAAK,GAAG;AAC5E,UAAM,OAAO,GAAG,KAAK,IAAI,GAAG,KAAK,MAAM,EAAE,YAAY,IAAI,CAAC,CAAC;AAC3D,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IAAI,aAAa,UAAU,MAAM,KAAK,UAAU,SAAS,IAAI,GAAG,UAAU,SAAS,WAAM,UAAU,MAAM,KAAK,EAAE,EAAE,CAAC;AAAA,IAChI;AACA,QAAI,OAAO,OAAO,SAAS,GAAG;AAC5B,YAAM,KAAK,IAAI,oCAAoC,MAAM,OAAO,MAAM,CAAC,EAAE,CAAC;AAAA,IAC5E;AACA,eAAW,QAAQ,OAAO,iBAAiB;AACzC,YAAM,KAAK,IAAI,gCAAgC,KAAK,WAAW,YAAO,KAAK,MAAM,EAAE,CAAC;AAAA,IACtF;AAAA,EACF;AAEA,MAAI,OAAO,QAAQ,WAAW,GAAG;AAC/B,UAAM,KAAK,uDAAuD;AAAA,EACpE;AACA,aAAW,WAAW,OAAO,SAAU,OAAM,KAAK,IAAI,YAAY,OAAO,EAAE,CAAC;AAE5E,QAAM,KAAK,EAAE;AACb,QAAM,QAAQ,OAAO,QAAQ,OAAO,CAAC,GAAG,MAAM,IAAI,EAAE,QAAQ,QAAQ,CAAC;AACrE,QAAM;AAAA,IACJ,OAAO,SACH,aAAa,OAAO,SAAS,SAAM,KAAK,4CACxC,aAAa,OAAO,SAAS,SAAM,KAAK;AAAA,EAC9C;AACA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["relative","resolve","eol","doc","block","resolve","collections","discovery","writer","relative"]}
1
+ {"version":3,"sources":["../src/tracevals/commands/list.ts","../src/tracevals/commands/fill.ts","../src/tracevals/evals/write.ts","../src/tracevals/evals/write-location.ts","../src/tracevals/fill/cache.ts","../src/tracevals/fill/prompt.ts","../src/tracevals/fill/gate.ts","../src/tracevals/fill/facts.ts","../src/tracevals/fill/mock.ts","../src/tracevals/fill/vocabulary.ts"],"sourcesContent":["/** `manni tracevals list` — enumerate discoverable traces. */\nimport {\n discoverTraces,\n type DiscoverOptions,\n type TraceListing,\n} from \"../trace/discover.js\";\nimport { palette } from \"../../shared/color.js\";\nimport { keepNewerThan, parseNewerThan } from \"./batch.js\";\n\nexport interface ListOptions extends DiscoverOptions {\n /** `--newer-than`: keep only traces modified within this duration, e.g. `7d`. */\n newerThan?: string;\n}\n\nexport interface ListRun {\n traces: TraceListing[];\n}\n\nexport async function runList(options: ListOptions = {}): Promise<ListRun> {\n // Parsed before the store is read, so a bad duration costs no scan.\n if (options.newerThan !== undefined) parseNewerThan(options.newerThan);\n const { newerThan, ...discover } = options;\n return { traces: keepNewerThan(await discoverTraces(discover), newerThan) };\n}\n\nexport function renderList(\n run: ListRun,\n opts: { color?: boolean } = {},\n): string {\n const pc = palette(opts.color === true);\n const dim = pc.dim;\n const bold = pc.bold;\n\n if (run.traces.length === 0) {\n return \"No traces found. Pass --all-projects to scan every project, or --project <dir> to scope to one.\";\n }\n\n const lines: string[] = [];\n run.traces.forEach((t, i) => {\n const when = new Date(t.mtimeMs).toISOString().slice(0, 16).replace(\"T\", \" \");\n const size = `${Math.max(1, Math.round(t.sizeBytes / 1024))}KB`;\n lines.push(\n `${bold(String(i + 1).padStart(3))}. ${dim(when)} ${t.firstPrompt ?? dim(\"(no prompt)\")}`,\n );\n lines.push(\n ` ${dim(`${t.project ?? \"unknown project\"} · ${t.sessionId ?? \"?\"} · ${size}`)}`,\n );\n lines.push(` ${dim(t.file)}`);\n });\n return lines.join(\"\\n\");\n}\n","/**\n * `manni tracevals fill [paths...]` — propose evals for a project's\n * instruction artifacts and append the survivors to their frontmatter.\n *\n * Authoring, not evaluation: `run` never calls this, and everything written is\n * the same declared-evals contract a human would type by hand. Project\n * rules are proposed but never written — evals inside a file the agent\n * reads before acting would be teaching to the test (ADR 01005).\n */\nimport { writeFile } from \"node:fs/promises\";\nimport { relative, resolve } from \"node:path\";\nimport { palette } from \"../../shared/color.js\";\nimport { extractFrontmatter } from \"../../meta/index.js\";\nimport {\n externalWriteWarnings,\n type ExternalWrite,\n type RelocateResult,\n} from \"../../meta/internal.js\";\nimport type { Confirm } from \"../../shared/prompt.js\";\nimport { discoverArtifacts, type DiscoveredArtifact } from \"../artifacts/discover.js\";\nimport {\n appendArtifactEvals,\n appendMetadataEvals,\n type NewEvalEntry,\n} from \"../evals/write.js\";\nimport {\n METADATA_KEY,\n loadExternalEvals,\n urlManifestRefusal,\n} from \"../evals/external.js\";\nimport {\n MetadataWriter,\n noEntryRefusal,\n type MetadataHome,\n} from \"../evals/write-location.js\";\nimport { discoverConfig } from \"../core/config.js\";\nimport { loadGraderPlugins } from \"../graders/plugins.js\";\nimport { TracevalsError } from \"../types.js\";\nimport {\n assertProviderSelection,\n constructProvider,\n resolveProviderIdentity,\n selectProvider,\n} from \"../judge/provider.js\";\nimport { TURN_BUDGET_SKIP } from \"../../docevals/judge/budget.js\";\nimport { FillCache, fillCacheKey } from \"../fill/cache.js\";\nimport { artifactFacts } from \"../fill/facts.js\";\nimport {\n gateProposals,\n type ProposedEval,\n type Rejection,\n} from \"../fill/gate.js\";\nimport {\n PROPOSAL_SCHEMA,\n buildFillUser,\n isValidProposal,\n systemPromptFor,\n} from \"../fill/prompt.js\";\nimport { mockFillProposal } from \"../fill/mock.js\";\nimport { buildVocabulary } from \"../fill/vocabulary.js\";\nimport type { InferenceProvider } from \"@hawkeyexl/inference\";\n\nexport interface FillOptions {\n /** Colour the pretty report. Off unless the caller turns it on. */\n color?: boolean;\n /** Files or directories to scan; defaults to the whole project. */\n paths?: string[];\n /** Project root; defaults to cwd. */\n project?: string;\n configDir?: string;\n /** `-c/--config`: read this file instead of discovering one. */\n config?: string;\n /** `--no-config`: skip discovery and run on the built-in defaults. */\n noConfig?: boolean;\n /**\n * `--offline`: never fetch a remote external-metadata manifest; read the\n * local ones only. A relocated artifact's evals live in one (0047).\n */\n offline?: boolean;\n /**\n * `--exclude <glob>`, repeatable. Removes matching artifacts from whatever\n * the scan would otherwise have found, positional paths included.\n */\n exclude?: string[];\n cwd?: string;\n /** Report proposals without writing. */\n dryRun?: boolean;\n confidence?: number;\n /** Ceiling on an artifact's total evals, existing ones included. */\n maxEvals?: number;\n /** `--max-turns`: inference calls for the whole invocation, one per artifact. */\n maxTurns?: number;\n noCache?: boolean;\n provider?: string;\n model?: string;\n /** `--local`: run inference on this machine, over every configured choice. */\n local?: boolean;\n /** `--require`: grader plugins to load *in addition to* `config.plugins`. */\n require?: string[];\n /** Test seam: bypasses provider construction entirely. */\n providerInstance?: InferenceProvider;\n /**\n * P1 (proposal 0047): asked once per collection when a `metadata` block\n * would land on an artifact because no manifest owns it. The CLI passes\n * `terminalConfirm()`, so off a terminal there is no question and the\n * warning is the only output.\n */\n confirm?: Confirm;\n /** A stderr diagnostic; the caller adds the `manni tracevals: ` prefix. */\n onNotice?: (message: string) => void;\n /** What an accepted relocation moved, for the caller to report. */\n onRelocated?: (result: RelocateResult) => void;\n}\n\nexport type FillStatus =\n | \"filled\"\n | \"proposed\"\n | \"nothing-proposed\"\n | \"propose-only\"\n | \"skipped\"\n | \"unreadable\"\n | \"error\";\n\nexport interface SharpeningNote {\n instruction: string;\n reason: string;\n suggestion?: string;\n}\n\nexport interface FillArtifactResult {\n artifact: string;\n type: string;\n status: FillStatus;\n /** Evals written, or that would be written in a dry run. */\n written: ProposedEval[];\n /**\n * The external-metadata manifest the evals were written to, when this\n * artifact's `metadata` block lives in one (0047). Absent when they went to\n * the artifact's own front matter.\n */\n manifest?: string;\n rejected: Rejection[];\n capped: ProposedEval[];\n /** Instructions the model judged untestable as written. */\n needsSharpening: SharpeningNote[];\n cached: boolean;\n error?: string;\n}\n\nexport interface FillReport {\n results: FillArtifactResult[];\n threshold: number;\n /** True when nothing was written because this was a dry run. */\n dryRun: boolean;\n warnings: string[];\n exitCode: 0 | 1;\n}\n\nexport interface FillRun {\n report: FillReport;\n rendered: string;\n}\n\n/** The artifact's own front matter, which names its entry in a joined manifest. */\nfunction ownData(content: string): Record<string, unknown> {\n return extractFrontmatter(content, \"markdown\").data;\n}\n\n/** Proposals become inline evals; confidence and rationale stay report-only. */\nfunction toEvalEntry(proposed: ProposedEval): NewEvalEntry {\n const entry: NewEvalEntry = {\n id: proposed.name,\n assertion: proposed.assertion,\n // New evals start as regression: they describe behavior the artifact\n // already asks for, not a boundary being probed.\n type: \"regression\",\n grader: proposed.grader,\n // The vocabulary takes one anchor or a list; the model proposes one of each.\n examples: { pass: [proposed.examples.pass], fail: [proposed.examples.fail] },\n };\n if (proposed.options !== undefined) entry.options = proposed.options;\n if (proposed.evidence !== undefined) entry.evidence = proposed.evidence;\n if (proposed.severity !== undefined) entry.severity = proposed.severity;\n return entry;\n}\n\nexport async function runFill(options: FillOptions = {}): Promise<FillRun> {\n const cwd = options.cwd ?? process.cwd();\n const root = resolve(options.project ?? cwd);\n const lookup = {\n ...(options.config === undefined ? {} : { configPath: options.config }),\n ...(options.noConfig === undefined ? {} : { noConfig: options.noConfig }),\n };\n const {\n config: loaded,\n dir: configDir,\n path: configPath,\n } = await discoverConfig(options.configDir ?? cwd, lookup);\n // `--require` is folded into the resolved config, the same way `run` does it,\n // rather than merged inline at the load call. Downstream code reads one\n // fully-resolved `config.plugins`; two commands disagreeing about whether it\n // includes the flag is how a knob starts behaving differently depending on\n // which command reached it.\n const config = {\n ...loaded,\n plugins: [...loaded.plugins, ...(options.require ?? [])],\n };\n\n // The same list `run` loads, appended to the same way, for the same reason:\n // a repo whose config names its house graders must not behave differently\n // depending on which command reached the registry. What it changes here is\n // narrower — `ALLOWED_GRADERS` still refuses to propose a custom kind, but a\n // plugin that *replaces* a built-in replaces the `validateOptions` the gate\n // ground-checks proposals with (ADR 01017).\n const plugins = await loadGraderPlugins({\n plugins: config.plugins,\n configDir,\n });\n\n // The command line's say over every configured level, checked up front and\n // regardless of an injected provider: it costs nothing, and a typo must fail\n // on a run where no artifact needs a model too.\n const flags = {\n ...(options.provider !== undefined ? { provider: options.provider } : {}),\n ...(options.model !== undefined ? { model: options.model } : {}),\n ...(options.local !== undefined ? { local: options.local } : {}),\n };\n assertProviderSelection(selectProvider(config, flags));\n\n const threshold = options.confidence ?? config.fill.confidenceThreshold;\n const maxEvals = options.maxEvals ?? config.fill.maxEvalsPerArtifact;\n const temperature = config.fill.temperature;\n const maxTurns = options.maxTurns ?? config.fill.maxTurns;\n const cache = new FillCache(\n resolve(configDir, config.fill.cacheDir),\n options.noCache !== true,\n );\n\n // Where each artifact's `metadata` block lives. Collections do not choose\n // what `fill` scans — that is still `--project` plus `[paths...]`, and there\n // is no `--collection` (0049 §1). What they say is where a relocated block\n // lives, both for reading what an artifact already declares and for writing\n // what this run proposes.\n const load = async () => {\n // Read fresh each time: an accepted offer edits the config file.\n const { collections } = await discoverConfig(options.configDir ?? cwd, lookup);\n const external = await loadExternalEvals({\n collections,\n configDir,\n ...(configPath === undefined ? {} : { configPath }),\n ...(options.offline === undefined ? {} : { offline: options.offline }),\n });\n const discovery = await discoverArtifacts({\n root,\n cwd,\n ...(options.paths !== undefined ? { paths: options.paths } : {}),\n ...(options.exclude !== undefined ? { exclude: options.exclude } : {}),\n ...(external === null\n ? {}\n : {\n metadataFor: async (artifact) =>\n (await external.forArtifact(artifact)).extracted,\n }),\n });\n const writer = await MetadataWriter.for({\n collections,\n configDir,\n configPath,\n cwd,\n targets: options.paths ?? [],\n });\n return { collections, discovery, writer };\n };\n let { collections, discovery, writer } = await load();\n\n // P1 (proposal 0047): asked before the first model request, so an accepted\n // relocation is applied while nothing has been proposed yet. Only where a\n // collection is declared, the same condition the W1 and W2 lines keep.\n if (\n options.confirm !== undefined &&\n options.dryRun !== true &&\n collections.length > 0\n ) {\n const flagged: ExternalWrite[] = [];\n for (const { artifact, status, skip } of discovery.artifacts) {\n if (status !== \"ok\" || skip || artifact.type === \"project-rules\") continue;\n const home = await writer.homeFor(artifact.path, ownData(artifact.content));\n if (home.kind === \"page\") {\n flagged.push({ label: artifact.path, key: METADATA_KEY, home: home.proposed });\n }\n }\n const applied = await writer.offer(flagged, {\n confirm: options.confirm,\n ...(options.onNotice === undefined ? {} : { onNotice: options.onNotice }),\n ...(options.onRelocated === undefined ? {} : { onRelocated: options.onRelocated }),\n });\n // The config now declares a manifest, the artifacts no longer carry what\n // it owns, and this writer's context predates both.\n if (applied) ({ collections, discovery, writer } = await load());\n }\n const vocabulary = buildVocabulary(discovery.artifacts);\n const knownSkills = [...vocabulary.skills].sort();\n\n // Identity is resolved without constructing the provider, so a fully cached\n // run needs no API key, and on first use, so an all-skipped run never detects\n // a provider under `auto`. Resolved once, and shared by every artifact.\n //\n // Going through the shared resolver rather than reading config by hand\n // matters: it applies the same per-provider model default construction would,\n // so the model in the cache key is the model that actually produced the\n // proposal.\n const injected = options.providerInstance;\n let resolving: ReturnType<typeof resolveProviderIdentity> | undefined;\n const resolveOnce = (): ReturnType<typeof resolveProviderIdentity> =>\n (resolving ??= resolveProviderIdentity(config, flags));\n const getIdentity = async (): Promise<{ provider: string; model: string }> =>\n injected !== undefined\n ? { provider: injected.provider(), model: injected.modelName() }\n : resolveOnce();\n let provider = injected;\n const getProvider = async (): Promise<InferenceProvider> =>\n (provider ??= constructProvider(config, await resolveOnce(), {\n // The default mock response is judge-shaped and would fail this\n // command's schema, so seed the mock seam with a proposal instead.\n mockResponses: [mockFillProposal()],\n }));\n\n let turns = 0;\n const results: FillArtifactResult[] = [];\n /** Blocks that landed on a page whose schema would rather they did not. */\n const homeless: ExternalWrite[] = [];\n\n for (const discovered of discovery.artifacts) {\n results.push(await fillOne(discovered));\n }\n\n const report: FillReport = {\n results,\n threshold,\n dryRun: options.dryRun === true,\n warnings: [\n ...plugins.warnings,\n ...discovery.warnings,\n ...externalWriteWarnings(homeless, options.dryRun === true),\n ],\n exitCode: results.some((r) => r.status === \"error\") ? 1 : 0,\n };\n return {\n report,\n rendered: renderFill(report, {\n cwd,\n ...(options.color === undefined ? {} : { color: options.color }),\n }),\n };\n\n async function fillOne(\n discovered: DiscoveredArtifact,\n ): Promise<FillArtifactResult> {\n const { artifact } = discovered;\n const base: FillArtifactResult = {\n artifact: artifact.path,\n type: artifact.type,\n status: \"nothing-proposed\",\n written: [],\n rejected: [],\n capped: [],\n needsSharpening: [],\n cached: false,\n };\n\n if (discovered.status !== \"ok\") {\n return {\n ...base,\n status: discovered.status === \"unreadable\" ? \"unreadable\" : \"error\",\n ...(discovered.error !== undefined ? { error: discovered.error } : {}),\n };\n }\n if (discovered.skip) return { ...base, status: \"skipped\" };\n\n const facts = artifactFacts(artifact);\n const identity = await getIdentity();\n const key = fillCacheKey({\n provider: identity.provider,\n model: identity.model,\n temperature,\n maxEvals,\n artifactType: artifact.type,\n path: artifact.path,\n body: artifact.content,\n existingNames: discovered.existingNames,\n knownSkills,\n });\n\n let raw = cache.get(key);\n const cached = raw !== undefined;\n if (raw === undefined) {\n // Claimed before the call, not tallied after it (docevals ADR 01019). A\n // cache hit never reaches here, so replaying a cached corpus spends no\n // turns.\n if (maxTurns !== null && turns >= maxTurns) {\n return { ...base, status: \"skipped\", error: `${TURN_BUDGET_SKIP} exhausted` };\n }\n turns += 1;\n try {\n const response = await (await getProvider()).completeJSON({\n system: systemPromptFor(artifact.type),\n user: buildFillUser({\n artifact,\n existingNames: discovered.existingNames,\n maxEvals,\n facts,\n knownSkills,\n }),\n schema: PROPOSAL_SCHEMA,\n temperature,\n });\n if (!isValidProposal(response.json)) {\n return {\n ...base,\n status: \"error\",\n error: \"provider returned a proposal that does not match the schema\",\n };\n }\n raw = response.json as Record<string, unknown>;\n cache.set(key, raw);\n } catch (err) {\n // An operational failure (no API key, unknown provider) is not this\n // artifact's fault and would repeat for every one: let it out so the\n // CLI reports it once and exits 2.\n if (err instanceof TracevalsError) throw err;\n return {\n ...base,\n status: \"error\",\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const gated = gateProposals(raw.evals as ProposedEval[], {\n artifactType: artifact.type,\n threshold,\n existingNames: discovered.existingNames,\n // The cap is a ceiling on the artifact's total, not on one run's\n // additions, so repeated fills cannot grow it without bound.\n maxEvals: Math.max(0, maxEvals - discovered.existingNames.length),\n vocabulary,\n });\n const result: FillArtifactResult = {\n ...base,\n written: gated.accepted,\n rejected: gated.rejected,\n capped: gated.capped,\n needsSharpening: (raw.needsSharpening as SharpeningNote[] | undefined) ?? [],\n cached,\n };\n\n if (gated.accepted.length === 0) return result;\n // Project rules are read by the agent under test before it acts, so\n // writing evals there would leak the rubric into the system prompt.\n if (artifact.type === \"project-rules\") {\n return { ...result, status: \"propose-only\" };\n }\n\n // Where the block lives decides where it is written. A URL manifest is\n // readable and not writable, and a dry run still reports against a hosted\n // trail rather than refusing a run that writes nothing.\n const home = await writer.homeFor(artifact.path, ownData(artifact.content));\n if (options.dryRun !== true) {\n if (home.kind === \"url\") {\n throw new TracevalsError(urlManifestRefusal(artifact.path, home.file));\n }\n if (home.kind === \"no-entry\") {\n throw new TracevalsError(noEntryRefusal(artifact.path, home.join, home.file));\n }\n }\n const landed: FillArtifactResult =\n home.kind === \"page\" ? result : { ...result, manifest: home.file };\n\n if (options.dryRun === true) return { ...landed, status: \"proposed\" };\n\n // Machines propose; humans retire the trail. Recording which model proposed\n // what, at what confidence, is what lets a reviewer tell an unreviewed\n // suggestion from an eval someone actually signed off on.\n //\n // The model's own name, not `provider:model`. The judge's self-preference\n // check compares this against `modelName()`, so a composed spelling would\n // read as a different model every time. The provider name is the fallback\n // only when there is no model to name.\n const provenance = {\n generatedBy: identity.model || identity.provider,\n confidence: Object.fromEntries(\n gated.accepted.map((c) => [c.name, c.confidence]),\n ),\n };\n\n try {\n if (home.kind === \"manifest\") {\n // Through meta's own splice writer: one value of one entry is replaced\n // and no other byte of the manifest moves, comments included.\n await writer.write(home, (current) =>\n appendMetadataEvals(\n current,\n artifact.path,\n gated.accepted.map(toEvalEntry),\n provenance,\n ),\n );\n } else {\n const updated = appendArtifactEvals(\n artifact.content,\n artifact.path,\n gated.accepted.map(toEvalEntry),\n provenance,\n );\n await writeFile(artifact.path, updated);\n if (home.kind === \"page\") noteHomeless(artifact.path, home);\n }\n } catch (err) {\n return {\n ...landed,\n status: \"error\",\n written: [],\n error: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...landed, status: \"filled\" };\n }\n\n /**\n * One W1/W2 line's worth of evidence: the schema marks `metadata`\n * `x-manni-location: external` (0047), and this block went to the page\n * anyway because no manifest owns it.\n *\n * Only when a collection is declared. With none there is nothing to relocate\n * into and no 0047 story to tell, and a repository that has never heard of\n * collections would otherwise be warned on every fill.\n */\n function noteHomeless(\n label: string,\n home: Extract<MetadataHome, { kind: \"page\" }>,\n ): void {\n if (collections.length === 0) return;\n // The home relocation would give it, from every declared collection: an\n // artifact in a collection with no manifest is the W1 case, and one in no\n // collection at all is W2.\n homeless.push({ label, key: METADATA_KEY, home: home.proposed });\n }\n}\n\nconst STATUS_LABEL: Record<FillStatus, string> = {\n filled: \"filled\",\n proposed: \"proposed\",\n \"propose-only\": \"proposed\",\n \"nothing-proposed\": \"no-op\",\n skipped: \"skipped\",\n unreadable: \"skipped\",\n error: \"error\",\n};\n\nfunction names(entries: ProposedEval[]): string {\n return entries\n .map((c) => `${c.name} ${c.confidence.toFixed(2)}`)\n .join(\", \");\n}\n\nexport function renderFill(\n report: FillReport,\n opts: { color?: boolean; cwd?: string } = {},\n): string {\n const pc = palette(opts.color === true);\n const from = opts.cwd ?? process.cwd();\n /** Absolute paths stay in the report; the human view is relative. */\n const show = (path: string): string => {\n const rel = relative(from, path);\n return rel === \"\" || rel.startsWith(\"..\") ? path : rel;\n };\n const { green, cyan, dim, red } = pc;\n\n const lines: string[] = [];\n for (const result of report.results) {\n const label = STATUS_LABEL[result.status].padEnd(9);\n const tag = result.cached ? dim(\" [cached]\") : \"\";\n // Where it landed, when that is not the artifact: a relocated block is\n // written to the manifest that owns it, and a report that did not say so\n // would send the reviewer to a file this run never touched.\n const where =\n result.manifest === undefined ? \"\" : dim(` in ${result.manifest}`);\n switch (result.status) {\n case \"filled\":\n lines.push(`${green(label)} ${show(result.artifact)} +${result.written.length} (${names(result.written)})${where}${tag}`);\n break;\n case \"proposed\":\n lines.push(`${cyan(label)} ${show(result.artifact)} +${result.written.length} (${names(result.written)})${where}${tag} — dry run, not written`);\n break;\n case \"propose-only\":\n lines.push(`${cyan(label)} ${show(result.artifact)} +${result.written.length} (${names(result.written)})${tag} — project rules are never written; copy what you want`);\n break;\n case \"nothing-proposed\":\n lines.push(`${dim(label)} ${show(result.artifact)} (nothing new proposed)${tag}`);\n break;\n case \"skipped\":\n lines.push(`${dim(label)} ${show(result.artifact)} (${result.error ?? \"metadata.evals.skip\"})`);\n break;\n case \"unreadable\":\n lines.push(`${dim(label)} ${show(result.artifact)} (${result.error ?? \"unreadable frontmatter\"})`);\n break;\n case \"error\":\n lines.push(`${red(label)} ${show(result.artifact)}: ${result.error ?? \"unknown error\"}`);\n break;\n }\n const belowThreshold = result.rejected.filter((r) => r.reason === \"low-confidence\");\n if (belowThreshold.length > 0) {\n lines.push(dim(` below ${report.threshold}: ${names(belowThreshold.map((r) => r.proposal))}`));\n }\n for (const rejection of result.rejected) {\n if (rejection.reason === \"low-confidence\") continue;\n lines.push(dim(` ${rejection.reason}: ${rejection.proposal.name}${rejection.detail ? ` — ${rejection.detail}` : \"\"}`));\n }\n if (result.capped.length > 0) {\n lines.push(dim(` over per-artifact cap: ${names(result.capped)}`));\n }\n for (const note of result.needsSharpening) {\n lines.push(dim(` needs sharpening: \"${note.instruction}\" — ${note.reason}`));\n }\n }\n\n if (report.results.length === 0) {\n lines.push(\"No skills, agent definitions, or project rules found.\");\n }\n for (const warning of report.warnings) lines.push(dim(`warning: ${warning}`));\n\n lines.push(\"\");\n const total = report.results.reduce((n, r) => n + r.written.length, 0);\n lines.push(\n report.dryRun\n ? `Threshold ${report.threshold} · ${total} evals proposed, none written (dry run)`\n : `Threshold ${report.threshold} · ${total} evals written`,\n );\n return lines.join(\"\\n\");\n}\n","/**\n * Surgical eval append. Only the YAML frontmatter block is re-serialized\n * via the `yaml` Document API — everything from the closing fence onward is\n * carried over byte-for-byte, and untouched YAML keeps its comments, ordering,\n * and style. Artifacts with no frontmatter get a block synthesized above the\n * untouched body, which is the common case for CLAUDE.md / AGENTS.md.\n *\n * Writing is an authoring-time operation, never part of evaluation (ADR 01005).\n */\nimport {\n Document,\n isMap,\n isNode,\n isScalar,\n isSeq,\n parseDocument,\n type YAMLSeq,\n} from \"yaml\";\nimport { mergeMetaProvenance } from \"../../meta/internal.js\";\nimport { TracevalsError } from \"../types.js\";\nimport { METADATA_KEY } from \"./external.js\";\nimport type { Severity } from \"./extract.js\";\n\n/** An eval to add. Mirrors the artifact-evals object entry form. */\nexport interface NewEvalEntry {\n id: string;\n assertion?: string;\n type?: \"capability\" | \"regression\";\n grader?: string;\n options?: Record<string, unknown>;\n severity?: Severity;\n evidence?: string;\n examples?: { pass?: string[]; fail?: string[] };\n}\n\n/** U+FEFF. A file that opens with it keeps it, byte for byte. */\nconst BOM = \"\\uFEFF\";\n\ninterface Split {\n /** BOM plus the opening fence line, including its newline. */\n open: string;\n /** Raw YAML between the fences. */\n block: string;\n /** Closing fence to EOF, byte-identical. */\n suffix: string;\n eol: \"\\n\" | \"\\r\\n\";\n}\n\n/** Frontmatter dialect an artifact opens with, or undefined when it has none. */\nfunction leadingFormat(content: string): \"yaml\" | \"toml\" | \"json\" | undefined {\n const body = content.startsWith(BOM) ? content.slice(1) : content;\n if (/^---\\r?\\n/.test(body)) return \"yaml\";\n if (/^\\+\\+\\+\\r?\\n/.test(body)) return \"toml\";\n if (/^;;;\\r?\\n/.test(body)) return \"json\";\n return undefined;\n}\n\nfunction splitYamlFrontmatter(content: string, path: string): Split {\n const bom = content.startsWith(BOM) ? BOM : \"\";\n const body = bom ? content.slice(1) : content;\n const openMatch = /^---(\\r?\\n)/.exec(body);\n if (!openMatch) {\n throw new TracevalsError(`${path}: no YAML frontmatter block to edit`);\n }\n const eol: \"\\n\" | \"\\r\\n\" = openMatch[1] === \"\\r\\n\" ? \"\\r\\n\" : \"\\n\";\n // Split but keep line endings. `body` opens with the `---` fence, so the\n // first element is that line; the destructuring default only satisfies the\n // type, which `noUncheckedIndexedAccess` widens to `string | undefined`.\n const [fence = body, ...rest] = body.split(/(?<=\\n)/);\n let offset = fence.length;\n for (const line of rest) {\n const stripped = line.replace(/\\r?\\n$/, \"\");\n if (stripped === \"---\" || stripped === \"...\") {\n return {\n open: bom + fence,\n block: body.slice(fence.length, offset),\n suffix: body.slice(offset),\n eol,\n };\n }\n offset += line.length;\n }\n throw new TracevalsError(`${path}: unterminated frontmatter block`);\n}\n\n/** Ordered plain object for one eval entry, with absent fields dropped. */\nfunction entryObject(entry: NewEvalEntry): Record<string, unknown> {\n const obj: Record<string, unknown> = { id: entry.id };\n // Optional since proposal.2. Emitting the key unconditionally would write\n // `assertion: null` for a deterministic grader, which the schema rejects —\n // the opposite of the point of letting it be omitted.\n if (entry.assertion !== undefined) obj.assertion = entry.assertion;\n if (entry.type !== undefined) obj.type = entry.type;\n if (entry.grader !== undefined) obj.grader = entry.grader;\n if (entry.options !== undefined) obj.options = entry.options;\n if (entry.severity !== undefined) obj.severity = entry.severity;\n if (entry.evidence !== undefined) obj.evidence = entry.evidence;\n if (entry.examples !== undefined) obj.examples = entry.examples;\n return obj;\n}\n\n/**\n * Existing eval ids. String-shorthand entries are id-less — their identity is\n * positional — so they never collide with an id'd append.\n */\nfunction existingIds(seq: YAMLSeq): Set<string> {\n const ids = new Set<string>();\n for (const item of seq.items) {\n if (isMap(item)) {\n const id = item.get(\"id\");\n if (typeof id === \"string\") ids.add(id);\n }\n }\n return ids;\n}\n\n/**\n * A key present with an empty value parses to a null node, not `undefined`.\n * `metadata:` with nothing under it is ordinary in the wild, so treat it as\n * the absent case and fill it in rather than refusing to write.\n */\nfunction isEmptyNode(node: unknown): boolean {\n return node === undefined || node === null || isNullScalar(node);\n}\n\nfunction isNullScalar(node: unknown): boolean {\n return isScalar(node) && node.value === null;\n}\n\n/**\n * Locate the `metadata.evals` list, creating each missing level.\n *\n * The single-string block (`evals: <assertion>`) is a legal authored shape that\n * is not a list. Rewriting it into one would move a human's assertion and\n * silently give it a new positional id, so refuse instead and say what to do.\n */\nfunction evalsSeq(doc: Document, path: string): YAMLSeq {\n const existing = doc.getIn([\"metadata\", \"evals\"], true);\n if (!isEmptyNode(existing)) {\n if (isScalar(existing) && typeof existing.value === \"string\") {\n throw new TracevalsError(\n `${path}: metadata.evals is a single assertion string; expand it to a list before appending`,\n );\n }\n if (!isSeq(existing)) {\n throw new TracevalsError(`${path}: metadata.evals is not a list`);\n }\n return existing;\n }\n const node = doc.getIn([\"metadata\"], true);\n if (isEmptyNode(node)) {\n doc.setIn([\"metadata\"], doc.createNode({}));\n } else if (!isMap(node)) {\n throw new TracevalsError(`${path}: metadata is not a mapping`);\n }\n const seq = doc.createNode([]) as YAMLSeq;\n doc.setIn([\"metadata\", \"evals\"], seq);\n return seq;\n}\n\n/**\n * Attribution for machine-proposed evals. A human deletes the entry once those\n * evals are reviewed, which is what makes the trail useful rather than noise.\n */\nexport interface EvalProvenance {\n /**\n * Model that proposed the evals, by the name its provider reports. A bare\n * model name, never `provider:model`: the criterion axis of the\n * self-preference check compares this against the judge's `modelName()`, and\n * a composed spelling made that comparison one it could never win.\n */\n generatedBy: string;\n /** Per-eval confidence, 0..1, keyed by eval id. */\n confidence: Record<string, number>;\n}\n\n/** The key `fill` records machine-proposed evals under (proposal 0046). */\nconst META_PROVENANCE_KEY = \"meta-provenance\";\n\n/**\n * Merge one run's attribution into `metadata.meta-provenance`, keyed by\n * `generated-by`. A repeat fill by the same model extends its existing entry\n * rather than adding a second one the consumer would have to reconcile.\n *\n * The merge itself is `mergeMetaProvenance`, the one `manni meta fill` and\n * `manni docevals fill` use, so all three tools record attribution one way and\n * the shape has a single owner. What stays here is the splice: reading the\n * held value out of the document and writing the merged list back.\n */\nfunction mergeProvenance(\n doc: Document,\n provenance: EvalProvenance,\n ids: string[],\n): void {\n if (ids.length === 0) return;\n // `getIn` hands back a node for a collection, and the family merge reads a\n // plain value, so the held block is converted before it crosses over.\n const node: unknown = doc.getIn([\"metadata\", META_PROVENANCE_KEY], true);\n const held = isEmptyNode(node)\n ? undefined\n : isNode(node)\n ? (node.toJSON() as unknown)\n : node;\n const merged = mergeMetaProvenance(\n held,\n provenance.generatedBy,\n \"evals\",\n ids.map((id) => ({ name: id, confidence: provenance.confidence[id] ?? 0 })),\n );\n if (!merged) {\n throw new TracevalsError(`metadata.${META_PROVENANCE_KEY} is not a list`);\n }\n doc.setIn(\n [\"metadata\", META_PROVENANCE_KEY],\n doc.createNode(merged.list),\n );\n}\n\n/**\n * The same append over a `metadata` block that is not in the page: the value an\n * external-metadata manifest holds for this artifact (proposal 0047). Returns\n * the new block, for `spliceManifestValue` to write.\n *\n * A plain value in and a plain value out, because a manifest entry is rewritten\n * by meta's splice writer rather than re-serialized here — the comment and key\n * order preservation `appendArtifactEvals` gets from editing YAML nodes is that\n * writer's job on this path. The refusals are the page path's, for the page\n * path's reasons: an id that already exists means the caller's dedupe missed\n * something, and a single-assertion block is a human's sentence that must not\n * be silently given a positional id.\n */\nexport function appendMetadataEvals(\n held: unknown,\n label: string,\n entries: NewEvalEntry[],\n provenance?: EvalProvenance,\n): Record<string, unknown> {\n const block: Record<string, unknown> =\n held === undefined || held === null\n ? {}\n : typeof held === \"object\" && !Array.isArray(held)\n ? { ...(held as Record<string, unknown>) }\n : (() => {\n throw new TracevalsError(`${label}: metadata is not a mapping`);\n })();\n\n const existing = block.evals;\n if (typeof existing === \"string\") {\n throw new TracevalsError(\n `${label}: metadata.evals is a single assertion string; expand it to a list before appending`,\n );\n }\n if (existing !== undefined && existing !== null && !Array.isArray(existing)) {\n throw new TracevalsError(`${label}: metadata.evals is not a list`);\n }\n\n const list: unknown[] = Array.isArray(existing)\n ? [...(existing as unknown[])]\n : [];\n const taken = new Set<string>();\n for (const item of list) {\n if (item !== null && typeof item === \"object\" && !Array.isArray(item)) {\n const id = (item as Record<string, unknown>).id;\n if (typeof id === \"string\") taken.add(id);\n }\n }\n for (const entry of entries) {\n if (taken.has(entry.id)) {\n throw new TracevalsError(\n `${label}: eval \"${entry.id}\" already exists in ${METADATA_KEY}`,\n );\n }\n taken.add(entry.id);\n list.push(entryObject(entry));\n }\n block.evals = list;\n\n if (provenance !== undefined && entries.length > 0) {\n const merged = mergeMetaProvenance(\n block[META_PROVENANCE_KEY],\n provenance.generatedBy,\n \"evals\",\n entries.map((e) => ({\n name: e.id,\n confidence: provenance.confidence[e.id] ?? 0,\n })),\n );\n if (!merged) {\n throw new TracevalsError(`${label}: metadata.${META_PROVENANCE_KEY} is not a list`);\n }\n block[META_PROVENANCE_KEY] = merged.list;\n }\n return block;\n}\n\n/**\n * Append evals to an artifact's `metadata.evals`, returning the new file\n * content. Throws when the frontmatter is not YAML or when an id already\n * exists — a collision means the caller's dedupe missed something, and\n * silently overwriting a human-authored eval is never right.\n *\n * When `provenance` is given, the same splice also records the machine\n * attribution under `metadata.meta-provenance`.\n */\nexport function appendArtifactEvals(\n content: string,\n path: string,\n entries: NewEvalEntry[],\n provenance?: EvalProvenance,\n): string {\n if (entries.length === 0) return content;\n\n const format = leadingFormat(content);\n if (format === \"toml\" || format === \"json\") {\n // Synthesizing a YAML block would leave the artifact with two\n // frontmatter blocks; only YAML can be edited in place.\n throw new TracevalsError(\n `${path}: only YAML frontmatter can be edited (found ${format} frontmatter)`,\n );\n }\n\n const bom = content.startsWith(BOM) ? BOM : \"\";\n const stripped = bom ? content.slice(1) : content;\n\n if (format === undefined) {\n const eol: \"\\n\" | \"\\r\\n\" = stripped.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\";\n const doc = new Document({\n metadata: { evals: entries.map(entryObject) },\n });\n if (provenance) {\n mergeProvenance(\n doc,\n provenance,\n entries.map((e) => e.id),\n );\n }\n let block = doc.toString({ lineWidth: 0 });\n if (eol === \"\\r\\n\") block = block.replace(/(?<!\\r)\\n/g, \"\\r\\n\");\n return `${bom}---${eol}${block}---${eol}${stripped}`;\n }\n\n const { open, block, suffix, eol } = splitYamlFrontmatter(content, path);\n const doc = parseDocument(block);\n if (doc.errors.length > 0) {\n throw new TracevalsError(\n `${path}: cannot edit frontmatter — ${doc.errors[0]?.message ?? \"parse error\"}`,\n );\n }\n\n let seq: YAMLSeq;\n try {\n seq = evalsSeq(doc, path);\n } catch (err) {\n // A block that is valid YAML but not a mapping (a sequence, a bare\n // scalar, a `---` that was really a thematic break) makes the yaml\n // library throw its own error type. Callers are promised TracevalsError.\n if (err instanceof TracevalsError) throw err;\n throw new TracevalsError(\n `${path}: cannot edit frontmatter — ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n const taken = existingIds(seq);\n for (const entry of entries) {\n if (taken.has(entry.id)) {\n throw new TracevalsError(\n `${path}: eval \"${entry.id}\" already exists in frontmatter`,\n );\n }\n taken.add(entry.id);\n seq.add(doc.createNode(entryObject(entry)));\n }\n\n if (provenance) {\n try {\n mergeProvenance(\n doc,\n provenance,\n entries.map((e) => e.id),\n );\n } catch (err) {\n if (err instanceof TracevalsError) {\n throw new TracevalsError(`${path}: ${err.message}`);\n }\n throw err;\n }\n }\n\n // lineWidth 0 disables folding: skill descriptions routinely run past 80\n // columns, and reflowing one the user did not touch is gratuitous churn.\n let updated = doc.toString({ lineWidth: 0 });\n if (eol === \"\\r\\n\") updated = updated.replace(/(?<!\\r)\\n/g, \"\\r\\n\");\n return open + updated + suffix;\n}\n","/**\n * Where `manni tracevals fill` writes an artifact's `metadata` block\n * (proposal 0047, §3 and §4).\n *\n * Every write goes through the rule `manni meta fill` and `manni docevals\n * fill` already follow, decided by meta's `keyHome`:\n *\n * - a **local manifest** of one of the artifact's collections owns the\n * block: the value is spliced into the artifact's entry there. A `{page}`\n * manifest (proposal 0058) resolves to the artifact's own file, which the\n * first write creates. A keyless manifest (proposal 0068) owns the block\n * when the artifact's schemas mark it external;\n * - the manifest **joins on a field the artifact lacks**: there is no entry\n * to hold the block, and the write is refused for that artifact;\n * - a **URL manifest** owns it: nothing fetched can be written;\n * - **no manifest owns it**: the artifact keeps it, with the offer (P1) and\n * the warnings (W1, W2) meta's writers use.\n *\n * The marks a keyless manifest owns by are read from meta's section of the\n * same family file the reader (`external.ts`) reads them from, so reading and\n * writing agree on where the block lives.\n */\nimport { relative, resolve } from \"node:path\";\nimport { errorMessage } from \"../../shared/errors.js\";\nimport { readManifestOrEmpty } from \"../../shared/manifest-cas.js\";\nimport type { Confirm } from \"../../shared/prompt.js\";\nimport {\n keyHome,\n marksValidator,\n metaSection,\n offerExternalHomes,\n readManifestValue,\n spliceManifestValue,\n type ExternalWrite,\n type ProposedHome,\n type RelocateResult,\n type RelocationContext,\n} from \"../../meta/internal.js\";\nimport {\n DocmetaError,\n writeFileAtomic,\n type CollectionConfig,\n type DocmetaConfig,\n} from \"../../meta/index.js\";\nimport { TracevalsError } from \"../types.js\";\nimport { METADATA_KEY } from \"./external.js\";\n\n/** Where one artifact's `metadata` block goes. */\nexport type MetadataHome =\n /** The artifact's own front matter. `proposed` is the home relocation would give it. */\n | { kind: \"page\"; proposed: ProposedHome }\n /** The artifact's entry in a local manifest. */\n | {\n kind: \"manifest\";\n /** As the run reports it. */\n file: string;\n absPath: string;\n /** `path`, or the artifact field the manifest joins on. */\n join: string;\n entry: string;\n /** A `{page}` manifest, which may not exist yet. */\n perPage: boolean;\n }\n /** A manifest joins on a field this artifact does not carry. */\n | { kind: \"no-entry\"; file: string; join: string }\n /** A URL manifest owns the block. */\n | { kind: \"url\"; file: string };\n\n/** What `offer` reports back while it asks. */\nexport interface OfferHooks {\n confirm: Confirm;\n onNotice?: (message: string) => void;\n onRelocated?: (result: RelocateResult) => void;\n}\n\nexport interface MetadataWriterOptions {\n /** Every collection the config declares. An accepted offer edits these in place. */\n collections: CollectionConfig[];\n /** The config file's directory; artifact entries resolve from it. */\n configDir: string;\n /** The config file; absent when there is none, and then nothing has a home. */\n configPath: string | undefined;\n /** The working directory the positional paths were typed in. */\n cwd: string;\n /** The positional paths as typed, where a created collection's `paths:` come from. */\n targets: readonly string[];\n}\n\n/** `<artifact> carries no <join>, which <file> joins on, so its metadata has no entry there.` */\nexport function noEntryRefusal(label: string, join: string, file: string): string {\n return `${label}: ${METADATA_KEY} is owned by ${file}, which joins on \"${join}\", and this artifact carries no ${join}.`;\n}\n\n/**\n * The run's writer. One per run, because the relocation context it reads is\n * the config as the run found it, and an accepted offer changes that config.\n */\nexport class MetadataWriter {\n private constructor(private readonly ctx: RelocationContext) {}\n\n static async for(opts: MetadataWriterOptions): Promise<MetadataWriter> {\n const { configDir, configPath } = opts;\n const config = configPath === undefined ? null : await metaConfig(configPath, configDir);\n return new MetadataWriter({\n // Artifact labels are absolute, and a manifest is reported relative to\n // the config directory, the way `external.ts` reports one it read.\n cwd: configDir,\n base: configDir,\n noConfig: configPath === undefined,\n config,\n ...(configPath === undefined ? {} : { configDir, configPath }),\n collections: opts.collections,\n declaredCollections: opts.collections,\n targets: opts.targets.map((t) => relative(configDir, resolve(opts.cwd, t)) || \".\"),\n validator: marksValidator({ config, cwd: configDir, configDir })(),\n });\n }\n\n /** Where the `metadata` block of the artifact `label` goes. `data` is its own front matter. */\n async homeFor(label: string, data: Readonly<Record<string, unknown>>): Promise<MetadataHome> {\n const home = await keyHome(this.ctx, label, data, METADATA_KEY);\n if (home.kind === \"url\") return { kind: \"url\", file: home.file };\n if (home.kind === \"manifest\") {\n if (home.entry === undefined) {\n return { kind: \"no-entry\", file: home.file, join: home.join };\n }\n return {\n kind: \"manifest\",\n file: home.file,\n absPath: home.absPath,\n join: home.join,\n entry: home.entry,\n perPage: home.perPage,\n };\n }\n return { kind: \"page\", proposed: home.home };\n }\n\n /**\n * Ask P1 once per collection the flagged writes would be homed in. Returns\n * true when a relocation was applied, which leaves the caller's config,\n * artifacts and this writer stale: rebuild all three before writing.\n */\n async offer(writes: readonly ExternalWrite[], hooks: OfferHooks): Promise<boolean> {\n if (writes.length === 0) return false;\n const applied = await offerExternalHomes(this.ctx, writes, hooks);\n return applied.size > 0;\n }\n\n /**\n * Replace this artifact's `metadata` block in its manifest entry with what\n * `update` makes of the block the file holds now. The file is read just\n * before the write, so a block another run wrote meanwhile is extended\n * rather than lost, and no other byte of the file changes.\n */\n async write(\n home: Extract<MetadataHome, { kind: \"manifest\" }>,\n update: (current: unknown) => unknown,\n ): Promise<void> {\n let text: string;\n try {\n text = await readManifestOrEmpty(home.absPath, home.perPage);\n } catch (e) {\n throw new TracevalsError(`${home.file} could not be read: ${errorMessage(e)}`);\n }\n const at = { entry: home.entry, key: METADATA_KEY, join: home.join };\n let spliced: string;\n try {\n spliced = spliceManifestValue(text, {\n ...at,\n value: update(readManifestValue(text, at)),\n file: home.file,\n }).text;\n } catch (e) {\n // meta's refusal, in this tool's error class.\n throw new TracevalsError(errorMessage(e));\n }\n // A per-page manifest may be the first file in its directory.\n if (spliced !== text) {\n await writeFileAtomic(home.absPath, spliced, { createParents: true });\n }\n }\n}\n\n/**\n * Meta's section of the family file. A file meta cannot read as its own is\n * still tracevals' file, and meta's default set decides the marks then.\n */\nasync function metaConfig(configPath: string, configDir: string): Promise<DocmetaConfig | null> {\n try {\n return await metaSection(configPath, configDir);\n } catch (err) {\n if (err instanceof DocmetaError) return null;\n throw err;\n }\n}\n","/**\n * Fill proposal cache: content-addressed JSON holding the raw, *pre-gating*\n * proposal. Two consequences are the point of the design:\n *\n * - Re-running with a different `--confidence` re-gates from cache, so tuning\n * the threshold costs no tokens.\n * - The existing eval-id set is part of the key, so a re-run after a\n * fill misses and asks the model for *additional* coverage rather than\n * replaying a proposal that has already been applied.\n *\n * Kept in its own directory: the judge cache has a different key scheme and\n * value shape, and the two must never be read into each other.\n *\n * Storage is the inference library's `JsonCache`; the schema re-check on read\n * stays here, because the library's cache deliberately does not know what\n * shape any given consumer stores.\n */\nimport { JsonCache, buildCacheKey, sha256 } from \"@hawkeyexl/inference\";\nimport type { ArtifactType } from \"../artifacts/types.js\";\nimport { FILL_PROMPT_VERSION, isValidProposal } from \"./prompt.js\";\n\nexport interface FillCacheKeyParts {\n provider: string;\n model: string;\n temperature: number;\n maxEvals: number;\n artifactType: ArtifactType;\n /** Artifact path — it appears in the prompt, so it belongs in the key. */\n path: string;\n /** Full artifact content, hashed. */\n body: string;\n existingNames: string[];\n /**\n * Project-wide skill names. They are the grounding vocabulary in the\n * prompt, so adding or renaming a skill must invalidate every artifact's\n * cached proposal, not just that skill's own.\n */\n knownSkills: string[];\n}\n\n/** JSON-encoded so a name containing a separator cannot forge a boundary. */\nfunction listPart(values: string[]): string {\n return JSON.stringify([...values].sort());\n}\n\nexport function fillCacheKey(parts: FillCacheKeyParts): string {\n return buildCacheKey([\n parts.provider,\n parts.model,\n `fill-v${FILL_PROMPT_VERSION}`,\n `t${parts.temperature}`,\n `n${parts.maxEvals}`,\n parts.artifactType,\n parts.path,\n sha256(parts.body),\n listPart(parts.existingNames),\n listPart(parts.knownSkills),\n ]);\n}\n\n/**\n * A proposal cache over `JsonCache`, adding the one thing the generic cache\n * cannot do: reject an entry written by an older proposal schema. Such an\n * entry parses fine, so only a schema check turns it into a miss.\n */\nexport class FillCache {\n private readonly store: JsonCache<unknown>;\n\n constructor(dir: string, enabled: boolean = true) {\n this.store = new JsonCache<unknown>(dir, enabled, \"manni-tracevals\");\n }\n\n get(key: string): Record<string, unknown> | undefined {\n const proposal = this.store.get(key);\n if (!isValidProposal(proposal)) return undefined;\n return proposal as Record<string, unknown>;\n }\n\n set(key: string, proposal: Record<string, unknown>): void {\n this.store.set(key, proposal);\n }\n}\n","/**\n * Fill prompt: asks the provider to extract evals that an artifact's\n * own instructions already imply, each with a self-reported 0-1 confidence.\n * Gating happens downstream; the prompt only demands honesty and restraint.\n *\n * Instructions too vague to test are reported under `needsSharpening` rather\n * than turned into a soft assertion — an untestable instruction is a defect in\n * the artifact, and naming it is more useful than papering over it.\n */\nimport { Ajv2020 } from \"ajv/dist/2020.js\";\nimport { SEVERITIES } from \"../../shared/severity.js\";\nimport type { ArtifactType, ResolvedArtifact } from \"../artifacts/types.js\";\nimport { ALLOWED_GRADERS } from \"./gate.js\";\nimport type { ArtifactFacts } from \"./facts.js\";\n\n/**\n * Part of the cache key: bump whenever the prompt or schema changes.\n *\n * A prompt edit that leaves this alone makes every cached proposal replay the\n * *old* prompt output, silently, for as long as the cache lives.\n * `test/unit/fill-prompt.test.ts` pins this to a digest of the prompt surface\n * so the pair has to move together.\n *\n * 3 — added the `slash-command` type guidance (ADR 01023).\n * 4 — the family severity scale: the quietest level is `notice`, not `info`.\n */\nexport const FILL_PROMPT_VERSION = 4;\n\nexport const MAX_BODY_CHARS = 6000;\n\n/** What each artifact type's instructions look like, in its own vocabulary. */\nconst TYPE_GUIDANCE: Record<ArtifactType, string> = {\n skill: [\n \"This artifact is a skill: a procedure an agent follows on demand.\",\n \"Its testable claims are entry criteria (what must be true before starting),\",\n \"process steps (what must actually happen), and output specifications (what\",\n \"the result must contain or must never contain).\",\n ].join(\"\\n\"),\n \"slash-command\": [\n \"This artifact is a slash command: a procedure whose body is injected as a\",\n \"prompt when a person types its name. Its testable claims are the steps it\",\n \"mandates, the tools it permits or forbids, and the artifact it must leave\",\n \"behind. Its `argument-hint` and `description` are harness metadata, not\",\n \"assertions — do not test them.\",\n ].join(\"\\n\"),\n agent: [\n \"This artifact is an agent definition: a role with boundaries.\",\n \"Its testable claims are constraints (what the agent must never do),\",\n \"quality criteria (measurable standards its output must meet), and\",\n \"escalation rules (conditions under which it must stop and hand off).\",\n \"Its identity and persona are framing, not assertions — do not test them.\",\n ].join(\"\\n\"),\n \"project-rules\": [\n \"This artifact is a project rules file: standing rules for all work in the\",\n \"repository. Its testable claims are process gates, quality gates, approval\",\n \"requirements, and hard limits. These files are assertion-dense; prefer the\",\n \"rules stated plainly over anything you would have to infer.\",\n ].join(\"\\n\"),\n};\n\nconst GRADER_GUIDANCE: Record<string, string> = {\n ai: \"judgment a human would have to read the session to make\",\n \"tool-usage\": \"a named tool was or was not used (options: tool, expect, min, max)\",\n \"skill-invoked\": \"a named skill was or was not invoked (options: skill, expect)\",\n \"file-access\":\n \"a file was or was not read/written/edited (options: path, op, expect)\",\n regex:\n \"a pattern does or does not appear in session text (options: pattern, flags, on, expect)\",\n};\n\nexport function systemPromptFor(artifactType: ArtifactType): string {\n const allowed = ALLOWED_GRADERS[artifactType];\n return [\n \"You extract evals from an AI agent instruction artifact.\",\n \"\",\n TYPE_GUIDANCE[artifactType],\n \"\",\n \"An eval is a durable claim about how a session behaved, graded against\",\n \"a recorded session trace on every future run. You are extracting claims the\",\n \"artifact already makes — not inventing new policy for it.\",\n \"\",\n \"Rules for every eval you propose:\",\n \"- It must be decidable as a binary pass or fail against session evidence.\",\n \" If you cannot say precisely what would make it fail, it does not qualify.\",\n \"- Quote the artifact's own intent. Never assert incidental phrasing,\",\n \" formatting, or wording that is expected to change.\",\n \"- Prefer a deterministic grader whenever the claim can be checked\",\n \" mechanically; fall back to `ai` only for genuine judgment.\",\n \"- Ids are short kebab-case identifiers, unique within the artifact.\",\n \"- Provide examples.pass and examples.fail: one sentence each describing a\",\n \" session that satisfies or violates the eval.\",\n \"- Report an honest confidence between 0 and 1 that the criterion is\",\n \" correct, checkable, and worth guarding. Do not inflate it.\",\n \"- Do not restate evals the artifact already declares.\",\n \"- Propose at most the requested number, fewer when the artifact offers\",\n \" little worth guarding, and none at all when nothing qualifies.\",\n \"\",\n \"Graders available for this artifact type:\",\n ...allowed.map((kind) => `- ${kind}: ${GRADER_GUIDANCE[kind] ?? \"\"}`),\n \"\",\n \"Deterministic graders only work against targets that really exist. Use tool\",\n \"and skill names exactly as given below; if the name you want is not listed,\",\n \"use the `ai` grader instead of guessing.\",\n \"\",\n \"Finally, list under `needsSharpening` any instruction in the artifact that\",\n \"sounds like a requirement but cannot be tested as written — an undefined\",\n \"quality bar, an unmeasurable adjective, a rule with no observable outcome.\",\n \"Say what makes it untestable. Do not invent a criterion to cover it.\",\n ].join(\"\\n\");\n}\n\nexport const PROPOSAL_SCHEMA = {\n type: \"object\",\n required: [\"evals\"],\n additionalProperties: false,\n properties: {\n evals: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"name\", \"assertion\", \"grader\", \"examples\", \"confidence\"],\n additionalProperties: false,\n properties: {\n name: { type: \"string\", pattern: \"^[a-z0-9][a-z0-9-]*$\" },\n assertion: { type: \"string\", minLength: 1 },\n grader: { type: \"string\" },\n options: { type: \"object\" },\n evidence: { type: \"string\" },\n examples: {\n type: \"object\",\n required: [\"pass\", \"fail\"],\n additionalProperties: false,\n properties: {\n pass: { type: \"string\" },\n fail: { type: \"string\" },\n },\n },\n severity: { enum: [...SEVERITIES] },\n confidence: { type: \"number\", minimum: 0, maximum: 1 },\n rationale: { type: \"string\" },\n },\n },\n },\n needsSharpening: {\n type: \"array\",\n items: {\n type: \"object\",\n required: [\"instruction\", \"reason\"],\n additionalProperties: false,\n properties: {\n instruction: { type: \"string\" },\n reason: { type: \"string\" },\n suggestion: { type: \"string\" },\n },\n },\n },\n },\n} as const;\n\nconst ajv = new Ajv2020({ allErrors: true });\nconst validateProposal = ajv.compile(\n PROPOSAL_SCHEMA as unknown as Record<string, unknown>,\n);\n\nexport function isValidProposal(value: unknown): boolean {\n return validateProposal(value);\n}\n\nexport interface FillUserOptions {\n artifact: ResolvedArtifact;\n existingNames: string[];\n maxEvals: number;\n facts: ArtifactFacts;\n /** Skill names discovered in the same scan — the vocabulary for skill-invoked. */\n knownSkills: string[];\n}\n\nexport function buildFillUser(options: FillUserOptions): string {\n const { artifact, existingNames, maxEvals, facts, knownSkills } = options;\n const body =\n artifact.content.length > MAX_BODY_CHARS\n ? `${artifact.content.slice(0, MAX_BODY_CHARS)}\\n…(truncated)`\n : artifact.content;\n\n const lines = [\n \"# Artifact\",\n `path: ${artifact.path}`,\n `type: ${artifact.type}`,\n `name: ${facts.name ?? artifact.name}`,\n ];\n if (facts.description !== undefined) {\n lines.push(`description: ${facts.description}`);\n }\n lines.push(\n \"\",\n \"# Existing evals (do not restate these)\",\n existingNames.length > 0 ? existingNames.join(\", \") : \"(none)\",\n \"\",\n \"# Tools this artifact grants itself\",\n facts.declaredTools.length > 0 ? facts.declaredTools.join(\", \") : \"(none declared)\",\n \"\",\n \"# Skills that exist in this project\",\n knownSkills.length > 0 ? knownSkills.join(\", \") : \"(none)\",\n \"\",\n \"# Maximum evals to propose\",\n String(maxEvals),\n \"\",\n \"# Artifact content\",\n \"\",\n body,\n );\n return lines.join(\"\\n\");\n}\n","/**\n * Proposal gate: everything between \"the model said so\" and \"this is written\n * to a file the user maintains\".\n *\n * Self-reported confidence is a weak signal on its own, so it is the *last*\n * filter, not the only one. Mechanical checks run first — grader scope, the\n * grader's own option validation (ADR 01004), and whether the target the\n * eval targets actually exist in the project.\n */\nimport { graderFor } from \"../graders/registry.js\";\nimport type { ArtifactType } from \"../artifacts/types.js\";\nimport type { Severity } from \"../evals/extract.js\";\n\nexport interface ProposedEval {\n name: string;\n assertion: string;\n grader: string;\n options?: Record<string, unknown>;\n evidence?: string;\n examples: { pass: string; fail: string };\n severity?: Severity;\n confidence: number;\n rationale?: string;\n}\n\nexport type RejectionReason =\n | \"low-confidence\"\n | \"invalid-options\"\n | \"grader-not-allowed\"\n | \"ungrounded-target\"\n | \"duplicate-name\";\n\nexport interface Rejection {\n proposal: ProposedEval;\n reason: RejectionReason;\n detail?: string;\n}\n\nexport interface Vocabulary {\n /** Tool names the project can actually produce in a trace. */\n tools: Set<string>;\n /** Skill names discovered in the same scan. */\n skills: Set<string>;\n}\n\nexport interface GateOptions {\n artifactType: ArtifactType;\n threshold: number;\n existingNames: string[];\n maxEvals: number;\n vocabulary: Vocabulary;\n}\n\nexport interface GateResult {\n accepted: ProposedEval[];\n rejected: Rejection[];\n /** Survivors dropped for exceeding the per-artifact cap, most confident first. */\n capped: ProposedEval[];\n}\n\n/**\n * Which graders may be proposed for each artifact type.\n *\n * `cost`, `turn-count`, and `json-output` are whole-session graders: a budget\n * declared inside one skill silently constrains the entire session and\n * double-counts when several artifacts declare it. `skill-invoked` is excluded\n * from skills, slash commands, and agents because an eval asserting its own\n * artifact was used can only be graded in sessions that used it — permanently\n * green.\n *\n * A slash command carries the skill list unchanged: both are an injected\n * procedure graded over the span they governed (ADR 01023), so the same\n * graders make sense and the same whole-session ones do not.\n *\n * `tool-order` is never proposed. An order is the instruction's intent, not\n * something a tool list shows, and grounding below checks one named tool,\n * not a pair. It is written by hand.\n */\nexport const ALLOWED_GRADERS: Record<ArtifactType, readonly string[]> = {\n skill: [\"ai\", \"tool-usage\", \"file-access\", \"regex\"],\n \"slash-command\": [\"ai\", \"tool-usage\", \"file-access\", \"regex\"],\n agent: [\"ai\", \"tool-usage\", \"file-access\"],\n \"project-rules\": [\"ai\", \"skill-invoked\", \"tool-usage\"],\n};\n\n/** Absolute paths are machine-specific; file-access matches on a suffix. */\nfunction isAbsoluteish(path: string): boolean {\n return path.startsWith(\"/\") || /^[A-Za-z]:[\\\\/]/.test(path);\n}\n\n/**\n * Does the eval name something that can exist in a trace? Rejects\n * hallucinated tool names and skills, however confident the model claims to be.\n */\nfunction groundingError(\n proposal: ProposedEval,\n vocabulary: Vocabulary,\n): string | undefined {\n const options = proposal.options ?? {};\n if (proposal.grader === \"tool-usage\") {\n const tool = options.tool;\n // MCP tools are named at connect time, so they cannot be enumerated ahead\n // of a session; the prefix is the only available signal.\n if (\n typeof tool === \"string\" &&\n !tool.startsWith(\"mcp__\") &&\n !vocabulary.tools.has(tool)\n ) {\n return `no tool named \"${tool}\" is available in this project`;\n }\n }\n if (proposal.grader === \"skill-invoked\") {\n const skill = options.skill;\n if (typeof skill === \"string\" && !vocabulary.skills.has(skill)) {\n return `no skill named \"${skill}\" was found in this project`;\n }\n }\n if (proposal.grader === \"file-access\") {\n const path = options.path;\n if (typeof path === \"string\" && isAbsoluteish(path)) {\n return `options.path must be a repository-relative suffix, not \"${path}\"`;\n }\n }\n return undefined;\n}\n\n/**\n * An eval in an agent definition describes what the *subagent* did, and\n * subagent tool calls are recorded as sidechain calls — which tool-usage\n * excludes by default. Left alone, such an eval silently measures the\n * main thread instead.\n */\nfunction normalize(\n proposal: ProposedEval,\n artifactType: ArtifactType,\n): ProposedEval {\n if (artifactType !== \"agent\" || proposal.grader !== \"tool-usage\") {\n return proposal;\n }\n return {\n ...proposal,\n options: { ...(proposal.options ?? {}), includeSidechains: true },\n };\n}\n\nexport function gateProposals(\n proposals: ProposedEval[],\n options: GateOptions,\n): GateResult {\n const { artifactType, threshold, maxEvals, vocabulary } = options;\n const allowed = new Set(ALLOWED_GRADERS[artifactType]);\n const taken = new Set(options.existingNames);\n const rejected: Rejection[] = [];\n const survivors: ProposedEval[] = [];\n\n for (const raw of proposals) {\n // Names first: a duplicate is rejected on its own terms rather than\n // competing for a slot under the cap.\n if (taken.has(raw.name)) {\n rejected.push({ proposal: raw, reason: \"duplicate-name\" });\n continue;\n }\n if (!allowed.has(raw.grader)) {\n rejected.push({\n proposal: raw,\n reason: \"grader-not-allowed\",\n detail: `${raw.grader} may not be declared on a ${artifactType} artifact`,\n });\n continue;\n }\n\n const proposal = normalize(raw, artifactType);\n\n if (proposal.grader !== \"ai\") {\n const grader = graderFor(proposal.grader);\n const validate = grader?.validateOptions;\n if (validate === undefined) {\n // Without a ground-check there is no way to know the options are\n // usable, and an unusable eval errors on every future run.\n rejected.push({\n proposal,\n reason: \"invalid-options\",\n detail: `grader ${proposal.grader} cannot validate its options`,\n });\n continue;\n }\n const invalid = validate(proposal.options ?? {});\n if (invalid !== undefined) {\n rejected.push({ proposal, reason: \"invalid-options\", detail: invalid });\n continue;\n }\n const ungrounded = groundingError(proposal, vocabulary);\n if (ungrounded !== undefined) {\n rejected.push({\n proposal,\n reason: \"ungrounded-target\",\n detail: ungrounded,\n });\n continue;\n }\n }\n\n taken.add(proposal.name);\n survivors.push(proposal);\n }\n\n // Confidence last, then the cap — so the cap drops the least confident of\n // the evals that were otherwise acceptable, and the two reasons stay\n // distinguishable in the report.\n const confident: ProposedEval[] = [];\n for (const proposal of survivors) {\n if (proposal.confidence >= threshold) confident.push(proposal);\n else rejected.push({ proposal, reason: \"low-confidence\" });\n }\n confident.sort((a, b) => b.confidence - a.confidence);\n\n return {\n accepted: confident.slice(0, maxEvals),\n capped: confident.slice(maxEvals),\n rejected,\n };\n}\n","/**\n * Static facts an artifact states about itself in structured frontmatter the\n * host tool already treats as schema — an agent's `tools:` grant, a skill's\n * `name`/`description`.\n *\n * These are grounding inputs, not evals. Minting an eval directly from\n * them produces evals that cannot fail: a `tools:` list is an allowlist rather\n * than a requirement, and a skill asserting its own invocation is only ever\n * graded in sessions that invoked it (ADR 01005).\n */\nimport { extractFrontmatter } from \"../../meta/index.js\";\nimport type { ResolvedArtifact } from \"../artifacts/types.js\";\n\nexport interface ArtifactFacts {\n name?: string;\n description?: string;\n /** Tools an agent definition grants itself, normalized to a list. */\n declaredTools: string[];\n}\n\n/** `tools: Read, Grep` and `tools: [Read, Grep]` are both in the wild. */\nfunction toolList(value: unknown): string[] {\n if (Array.isArray(value)) {\n return value.filter((v): v is string => typeof v === \"string\");\n }\n if (typeof value === \"string\") {\n return value\n .split(\",\")\n .map((tool) => tool.trim())\n .filter((tool) => tool.length > 0);\n }\n return [];\n}\n\nexport function artifactFacts(artifact: ResolvedArtifact): ArtifactFacts {\n try {\n const { data } = extractFrontmatter(artifact.content, \"markdown\");\n const facts: ArtifactFacts = { declaredTools: toolList(data.tools) };\n if (typeof data.name === \"string\") facts.name = data.name;\n if (typeof data.description === \"string\") {\n facts.description = data.description;\n }\n return facts;\n } catch {\n // Malformed frontmatter yields no facts; discovery already reported it.\n // This runs during vocabulary building, outside any per-artifact handler,\n // so it must not throw.\n return { declaredTools: [] };\n }\n}\n","/**\n * A canned, schema-valid proposal for `--provider mock`.\n *\n * The inference library's `mockVerdict` is judge-shaped, so it cannot drive\n * `fill` — the response would fail the proposal schema. This gives the offline\n * path\n * (CI's dogfood gate, CLI smoke tests) something the gate can actually chew\n * on: one eval that should be accepted and one that should be rejected\n * for low confidence, so a run that rubber-stamps everything is visible.\n */\nexport function mockFillProposal(): { json: Record<string, unknown> } {\n return {\n json: {\n evals: [\n {\n name: \"reads-before-editing\",\n assertion: \"The session read a source file before editing it.\",\n grader: \"tool-usage\",\n options: { tool: \"Read\", expect: \"used\" },\n examples: {\n pass: \"Read is called before the first Edit\",\n fail: \"Edit is called with no prior Read\",\n },\n confidence: 0.9,\n },\n {\n name: \"explains-its-reasoning\",\n assertion: \"The session explained why it made each change.\",\n grader: \"ai\",\n examples: {\n pass: \"Each edit is accompanied by a rationale\",\n fail: \"Edits land with no explanation\",\n },\n confidence: 0.3,\n },\n ],\n needsSharpening: [\n {\n instruction: \"Produce high-quality work.\",\n reason: \"\\\"high-quality\\\" has no measurable bar, so no session could fail it\",\n suggestion: \"Name the specific property that must hold, and how to observe it.\",\n },\n ],\n },\n };\n}\n","/**\n * The set of targets a proposed deterministic criterion may name. Anything\n * outside it is a hallucination that would produce a criterion which can never\n * pass, so the gate rejects it regardless of the model's stated confidence.\n */\nimport type { DiscoveredArtifact } from \"../artifacts/discover.js\";\nimport { artifactFacts } from \"./facts.js\";\nimport type { Vocabulary } from \"./gate.js\";\n\n/**\n * Tools Claude Code exposes by default. Project-specific additions arrive via\n * agent `tools:` grants; MCP tools are recognized by their `mcp__` prefix in\n * the gate rather than enumerated here.\n */\nexport const BUILTIN_TOOLS = [\n \"Agent\",\n \"AskUserQuestion\",\n \"Bash\",\n \"BashOutput\",\n \"Edit\",\n \"ExitPlanMode\",\n \"Glob\",\n \"Grep\",\n \"KillShell\",\n \"NotebookEdit\",\n \"Read\",\n \"Skill\",\n \"SlashCommand\",\n \"Task\",\n \"TodoWrite\",\n \"WebFetch\",\n \"WebSearch\",\n \"Write\",\n] as const;\n\n/** Build the vocabulary from everything the scan found. */\nexport function buildVocabulary(artifacts: DiscoveredArtifact[]): Vocabulary {\n const tools = new Set<string>(BUILTIN_TOOLS);\n const skills = new Set<string>();\n\n for (const discovered of artifacts) {\n if (discovered.artifact.type === \"skill\") {\n skills.add(discovered.artifact.name);\n }\n for (const tool of artifactFacts(discovered.artifact).declaredTools) {\n tools.add(tool);\n }\n }\n return { tools, skills };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,eAAsB,QAAQ,UAAuB,CAAC,GAAqB;AAEzE,MAAI,QAAQ,cAA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