verify-package-readme-model-experience.ts 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /**
  2. * Doc-sync gate for package README Model Experience sections. It validates
  3. * audited package classifications, model/token/KV-cache fields, package-owned
  4. * text blocks, generated-catalog links, and final-section order. See the
  5. * [Model Experience Agent Note](../.agents/notes/implemented/process/2026-07-12-package-model-experience-contract.md).
  6. */
  7. import { existsSync, globSync, readFileSync } from 'node:fs'
  8. import { relative, resolve, sep } from 'node:path'
  9. import { markdownHeadingLines, markdownProseLines, type MarkdownProseLine } from './markdown.ts'
  10. const root = resolve(import.meta.dirname, '..')
  11. const HEADING = '## Model Experience'
  12. const LIMITATIONS_HEADING = '## Known Limitations and Deferred Work'
  13. const MODEL_VIEW_HEADING = '#### What the model sees'
  14. const TOKEN_EFFECT_HEADING = '#### Token effect'
  15. const KV_CACHE_EFFECT_HEADING = '#### KV Cache effect'
  16. const FIELD_HEADINGS = [MODEL_VIEW_HEADING, TOKEN_EFFECT_HEADING, KV_CACHE_EFFECT_HEADING] as const
  17. type SentenceKind = 'none' | 'indirect'
  18. interface SentenceContract {
  19. kind: SentenceKind
  20. reason: string
  21. }
  22. /**
  23. * Generic packages whose public contract is model-agnostic. Their READMEs omit
  24. * Model Experience entirely; the reason stays here as reviewable audit evidence
  25. * so an absent section cannot be mistaken for forgotten documentation.
  26. */
  27. const NO_MODEL_EXPERIENCE_SECTION: Readonly<Record<string, string>> = {
  28. 'packages/core/scope': 'The package is a model-agnostic registration and lifecycle primitive; model-facing consumers own any context selection.',
  29. 'packages/util/brand': 'The package is a type-only primitive erased at compile time.',
  30. 'packages/util/paths': 'The package only resolves harness-owned host paths; model-facing consumers own any rendered use.',
  31. }
  32. /**
  33. * Packages whose Model Experience is simple enough for one gated sentence plus
  34. * a KV-cache field. Every other package must carry canonical context-surface
  35. * blocks. A package moves on or off this list with its context behavior.
  36. */
  37. const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
  38. 'packages/bash/bash': { kind: 'indirect', reason: 'The service interface delegates all model rendering to dsh-tool-bash.' },
  39. 'packages/bash/bash-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-bash.' },
  40. 'packages/code-runtime/code-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to Code Mode in dsh-tools.' },
  41. 'packages/code-runtime/code-runtime-worker': { kind: 'indirect', reason: 'The worker backend delegates model rendering to Code Mode in dsh-tools.' },
  42. 'packages/examples/agent-spine-demo': { kind: 'indirect', reason: 'The bundle only mounts model-facing child plugins.' },
  43. 'packages/fs/fs': { kind: 'indirect', reason: 'The service interface delegates model rendering to dsh-tool-fs.' },
  44. 'packages/fs/fs-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
  45. 'packages/fs/fs-sandbox': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
  46. 'packages/hooks/hook-protocol': { kind: 'indirect', reason: 'Only the hook bridge plugins render decoded hook output to a model.' },
  47. 'packages/llm/llm': { kind: 'none', reason: 'The adapter registry forwards already-assembled requests unchanged.' },
  48. 'packages/llm/token-meter': { kind: 'indirect', reason: 'The measurement service leaves model-visible changes to its consumers.' },
  49. 'packages/sandbox/sandbox-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-bash-sandbox and dsh-tool-bash.' },
  50. 'packages/sandbox/sandbox-policy': { kind: 'indirect', reason: 'The policy service holds the mode dsh-tool-bash and dsh-tool-fs render in their denial markers.' },
  51. 'packages/sdk/create-sdk': { kind: 'indirect', reason: 'The initializer only writes project files; selected runtime plugins provide the generated project model surface.' },
  52. 'packages/sdk/helper': { kind: 'none', reason: 'The project domain edits files and registers no live agent or model surface.' },
  53. 'packages/sdk/scripts': { kind: 'indirect', reason: 'The launcher delegates model context to the loaded project plugin tree.' },
  54. 'packages/sdk/telemetry': { kind: 'none', reason: 'The launcher-side reporter sends developer-cycle telemetry and registers no live agent or model surface.' },
  55. 'packages/session-query/session-query': { kind: 'none', reason: 'The trusted query service exposes cloned records only to callers and registers no model surface.' },
  56. 'packages/skill/skill': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-skill.' },
  57. 'packages/skill/skill-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-skill.' },
  58. 'packages/spill/spill': { kind: 'indirect', reason: 'The storage seam delegates model rendering to spill consumers.' },
  59. 'packages/spill/spill-local': { kind: 'indirect', reason: 'The storage backend delegates model rendering to spill consumers.' },
  60. 'packages/subagent/subagent': { kind: 'indirect', reason: 'The provider registry delegates parent-model rendering to dsh-tool-subagent.' },
  61. 'packages/subagent/subagent-subprocess': { kind: 'indirect', reason: 'Only process-based subagent backends compose a child model request.' },
  62. 'packages/support/acp-snapshot': { kind: 'none', reason: 'The test harness observes and normalizes transcripts without changing live requests.' },
  63. 'packages/support/agent-loop-testkit': { kind: 'none', reason: 'The test helper mounts services but neither drives nor modifies model requests.' },
  64. 'packages/support/invariants': { kind: 'none', reason: 'The observer validates requests but never rewrites their context.' },
  65. 'packages/support/loader-smoke': { kind: 'none', reason: 'The test harness observes child-process streams without changing live requests.' },
  66. 'packages/support/llm-replay': { kind: 'none', reason: 'The keyless adapter invokes no provider model.' },
  67. 'packages/tasks/tasks': { kind: 'indirect', reason: 'Producer and control-surface plugins own all model rendering over the task registry.' },
  68. 'packages/examples/acp-demo': { kind: 'indirect', reason: 'The app bundle delegates request composition to dsh-agent-spine-demo and dsh-acp.' },
  69. 'packages/ui/app-boot': { kind: 'indirect', reason: 'Only the loaded plugin tree contributes model context.' },
  70. 'packages/examples/jsonrpc-demo': { kind: 'indirect', reason: 'Only the externally configured plugin tree contributes model context.' },
  71. 'packages/ui/permission': { kind: 'indirect', reason: 'The service writes mechanism events rendered by dsh-user-approval and dsh-tool-bash.' },
  72. 'packages/ui/user-interaction': { kind: 'indirect', reason: 'Model-facing consumers render provider answers and seam errors.' },
  73. 'packages/util/home': { kind: 'indirect', reason: 'Only dsh-tool-bash exposes the resolved home to model commands.' },
  74. 'packages/util/timeout': { kind: 'indirect', reason: 'Only timeout consumers render timeout outcomes.' },
  75. 'packages/util/retention': { kind: 'indirect', reason: 'Only retention consumers render retained content and omission metadata.' },
  76. 'packages/web/web': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-web.' },
  77. 'packages/web/web-fetch-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  78. 'packages/web/web-search-exa': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  79. 'packages/workflow/workflow': { kind: 'indirect', reason: 'The service delegates parent and child model rendering to its consumer and engine.' },
  80. }
  81. interface Failure {
  82. path: string
  83. message: string
  84. }
  85. type Line = MarkdownProseLine
  86. interface ContextSurface {
  87. heading: Line
  88. modelView: Line
  89. tokenEffect: Line
  90. kvCacheEffect: Line
  91. title: string
  92. modelViewVerbatimBlocks: number
  93. verbatimBlocks: number
  94. }
  95. interface ParsedField {
  96. value: Line
  97. verbatimBlocks: number
  98. }
  99. /** Validate H5-plus-markdown literals nested under one Model Experience field. */
  100. function validateNestedVerbatim(raw: readonly string[], fragments: Set<string>): { blocks: number; error?: string } {
  101. let cursor = 0
  102. while (raw[cursor]?.trim().length === 0) cursor += 1
  103. if (cursor === raw.length) return { blocks: 0 }
  104. let blocks = 0
  105. while (true) {
  106. while (raw[cursor]?.trim().length === 0) cursor += 1
  107. if (cursor === raw.length) break
  108. if (!/^##### \S/.test(raw[cursor] ?? '')) {
  109. return { blocks, error: 'content after a field paragraph must be a titled H5 verbatim block' }
  110. }
  111. const title = (raw[cursor] as string).slice('##### '.length)
  112. const fragment = headingFragment(title)
  113. if (fragment.length === 0) return { blocks, error: 'verbatim H5 title must be non-empty' }
  114. if (fragments.has(fragment)) {
  115. return { blocks, error: `verbatim H5 title ${JSON.stringify(title)} is duplicated within its context surface` }
  116. }
  117. fragments.add(fragment)
  118. cursor += 1
  119. while (raw[cursor]?.trim().length === 0) cursor += 1
  120. if (raw[cursor] !== '```markdown') {
  121. return { blocks, error: 'each nested verbatim H5 requires an exact ```markdown fence' }
  122. }
  123. cursor += 1
  124. const contentStart = cursor
  125. while (cursor < raw.length && raw[cursor] !== '```') cursor += 1
  126. if (cursor === raw.length) return { blocks, error: 'unterminated nested ```markdown fence' }
  127. if (cursor === contentStart) return { blocks, error: 'nested ```markdown fence must not be empty' }
  128. cursor += 1
  129. blocks += 1
  130. }
  131. return { blocks }
  132. }
  133. /** GitHub-style fragment for the simple ASCII nested titles allowed by this contract. */
  134. function headingFragment(title: string): string {
  135. return title.toLowerCase().replaceAll('`', '').replaceAll(/[^a-z0-9 _-]/g, '').trim().replaceAll(/\s+/g, '-')
  136. }
  137. /** A direct stable system-prompt contribution, as named by the README contract. */
  138. function isDirectSystemPromptSurface(title: string): boolean {
  139. return /\bsystem prompt\b/i.test(title)
  140. }
  141. /** Anchored generated-catalog links in one model-view field. */
  142. function toolCatalogLinkFragments(text: string): string[] {
  143. return [...text.matchAll(/\]\(\.\.\/\.\.\/\.\.\/docs\/tool-catalog\.md#([a-z0-9_-]+)\)/g)]
  144. .map(match => match[1] as string)
  145. }
  146. const toolCatalogFragments = new Set<string>()
  147. for (const line of readFileSync(resolve(root, 'docs/tool-catalog.md'), 'utf8').split('\n')) {
  148. const title = /^## (.+)$/.exec(line)?.[1]
  149. if (title !== undefined) toolCatalogFragments.add(headingFragment(title))
  150. }
  151. const failures: Failure[] = []
  152. const packageJsons = globSync('packages/*/*/package.json', { cwd: root }).map(path => path.split(sep).join('/')).sort()
  153. const scannedPackages = new Set(packageJsons.map(path => path.slice(0, -'/package.json'.length)))
  154. let structuredCount = 0
  155. let contextSurfaceCount = 0
  156. let omittedSectionCount = 0
  157. let explainedNoneCount = 0
  158. let indirectCount = 0
  159. let verbatimBlockCount = 0
  160. let systemPromptSurfaceCount = 0
  161. let toolSchemaSurfaceCount = 0
  162. let kvCacheEffectCount = 0
  163. for (const [pkg, reason] of Object.entries(NO_MODEL_EXPERIENCE_SECTION)) {
  164. if (!scannedPackages.has(pkg)) {
  165. failures.push({ path: `${pkg}/README.md`, message: 'no-section allowlist entry does not name a scanned package' })
  166. }
  167. if (reason.trim().length === 0) {
  168. failures.push({ path: `${pkg}/README.md`, message: 'no-section allowlist entry must retain its audit justification' })
  169. }
  170. if (SENTENCE_MODEL_EXPERIENCE[pkg] !== undefined) {
  171. failures.push({ path: `${pkg}/README.md`, message: 'package cannot appear in both Model Experience allowlists' })
  172. }
  173. }
  174. for (const [pkg, contract] of Object.entries(SENTENCE_MODEL_EXPERIENCE)) {
  175. if (!scannedPackages.has(pkg)) {
  176. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry does not name a scanned package' })
  177. }
  178. if (contract.reason.trim().length === 0) {
  179. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry must justify why structured context surfaces are unnecessary' })
  180. }
  181. }
  182. for (const packageJson of packageJsons) {
  183. const pkg = packageJson.slice(0, -'/package.json'.length)
  184. const readme = packageJson.replace(/package\.json$/, 'README.md')
  185. const abs = resolve(root, readme)
  186. if (!existsSync(abs)) {
  187. failures.push({ path: readme, message: 'missing package README' })
  188. continue
  189. }
  190. const text = readFileSync(abs, 'utf8')
  191. const rawLines = text.split('\n')
  192. const lines = markdownProseLines(text)
  193. const headings = markdownHeadingLines(text)
  194. const h2Headings = headings.filter(heading => heading.depth === 2)
  195. const modelExperienceHeadings = headings.filter(heading => heading.text
  196. .trim().replaceAll(/\s+/g, ' ').toLowerCase() === 'model experience')
  197. const modelHeadings = modelExperienceHeadings.filter(heading => heading.depth === 2 && heading.raw === HEADING)
  198. if (NO_MODEL_EXPERIENCE_SECTION[pkg] !== undefined) {
  199. if (modelExperienceHeadings.length !== 0) {
  200. for (const heading of modelExperienceHeadings) {
  201. failures.push({ path: readme, message: `line ${heading.index}: audited model-agnostic package must omit every Model Experience heading; found ${JSON.stringify(heading.raw)}` })
  202. }
  203. } else {
  204. omittedSectionCount += 1
  205. }
  206. continue
  207. }
  208. const nonCanonicalModelHeading = modelExperienceHeadings.find(heading => heading.depth !== 2 || heading.raw !== HEADING)
  209. if (nonCanonicalModelHeading !== undefined) {
  210. failures.push({ path: readme, message: `line ${nonCanonicalModelHeading.index}: non-canonical Model Experience heading ${JSON.stringify(nonCanonicalModelHeading.raw)}; use exactly ${JSON.stringify(HEADING)}` })
  211. continue
  212. }
  213. const modelHeading = modelHeadings.at(0)
  214. if (modelHeading === undefined) {
  215. failures.push({
  216. path: readme,
  217. message: `missing ${HEADING}`,
  218. })
  219. continue
  220. }
  221. if (modelHeadings.length !== 1) {
  222. failures.push({ path: readme, message: `contains ${modelHeadings.length} copies of ${HEADING}` })
  223. continue
  224. }
  225. const modelH2Index = h2Headings.indexOf(modelHeading)
  226. const limitationsH2Index = h2Headings.findIndex(heading => heading.depth === 2 && heading.raw === LIMITATIONS_HEADING)
  227. if (limitationsH2Index >= 0) {
  228. if (modelH2Index !== h2Headings.length - 2 || limitationsH2Index !== h2Headings.length - 1) {
  229. failures.push({
  230. path: readme,
  231. message: `${HEADING} and ${LIMITATIONS_HEADING} must be the final two H2 sections, in that order`,
  232. })
  233. continue
  234. }
  235. } else if (modelH2Index !== h2Headings.length - 1) {
  236. failures.push({ path: readme, message: `${HEADING} must be the final H2 when ${LIMITATIONS_HEADING} is absent` })
  237. continue
  238. }
  239. const modelHeadingAt = lines.findIndex(line => line.index === modelHeading.index)
  240. const body = lines.slice(modelHeadingAt + 1)
  241. const h2Lines = new Set(h2Headings.map(heading => heading.index))
  242. const nextH2 = body.findIndex(line => h2Lines.has(line.index))
  243. const section = nextH2 < 0 ? body : body.slice(0, nextH2)
  244. const nextH2Line = nextH2 < 0 ? rawLines.length + 1 : (body[nextH2] as Line).index
  245. const rawSection = rawLines.slice(modelHeading.index, nextH2Line - 1)
  246. const content = section.filter(line => line.raw.trim().length > 0)
  247. const sentenceContract = SENTENCE_MODEL_EXPERIENCE[pkg]
  248. if (sentenceContract !== undefined) {
  249. const pattern = sentenceContract.kind === 'none' ? /^None, as .+\.$/ : /^Indirectly, through .+\.$/
  250. const rawContent = rawSection.filter(line => line.trim().length > 0)
  251. const sentence = content[0]
  252. const kvCacheHeading = content[1]
  253. const kvCacheEffect = content[2]
  254. if (content.length !== 3 || rawContent.length !== 3 || !pattern.test(sentence?.raw ?? '')) {
  255. const prefix = sentenceContract.kind === 'none' ? 'None, as ' : 'Indirectly, through '
  256. failures.push({ path: readme, message: `must contain exactly one sentence beginning ${JSON.stringify(prefix)} and ending with a period, followed by ${KV_CACHE_EFFECT_HEADING} and one non-empty paragraph` })
  257. continue
  258. }
  259. if (kvCacheHeading?.raw !== KV_CACHE_EFFECT_HEADING
  260. || kvCacheEffect === undefined
  261. || /^#{1,6} /.test(kvCacheEffect.raw)
  262. || kvCacheEffect.raw.trim().length === 0) {
  263. failures.push({ path: readme, message: `line ${kvCacheHeading?.index ?? sentence?.index ?? modelHeading.index}: short Model Experience form requires exact ${KV_CACHE_EFFECT_HEADING} and one non-empty paragraph` })
  264. continue
  265. }
  266. if (sentence === undefined
  267. || sentence.index !== modelHeading.index + 2
  268. || kvCacheHeading.index !== sentence.index + 2
  269. || kvCacheEffect.index !== kvCacheHeading.index + 2) {
  270. failures.push({ path: readme, message: 'short Model Experience sentence, KV-cache H4, and paragraph require one blank line between each element' })
  271. continue
  272. }
  273. if (sentenceContract.kind === 'none') explainedNoneCount += 1
  274. else indirectCount += 1
  275. kvCacheEffectCount += 1
  276. continue
  277. }
  278. const shortSentence = content.find(line => line.raw === 'None.' || /^None, as |^Indirectly, through /.test(line.raw))
  279. if (shortSentence !== undefined) {
  280. failures.push({ path: readme, message: `line ${shortSentence.index}: short Model Experience form requires an audited entry in SENTENCE_MODEL_EXPERIENCE` })
  281. continue
  282. }
  283. const surfaceStarts = content
  284. .map((line, index) => ({ line, index }))
  285. .filter(entry => /^### \S/.test(entry.line.raw))
  286. if (surfaceStarts.length === 0 || surfaceStarts[0]?.index !== 0) {
  287. failures.push({ path: readme, message: 'must contain one or more complete context-surface blocks' })
  288. continue
  289. }
  290. const surfaces: ContextSurface[] = []
  291. const surfaceFragments = new Set<string>()
  292. let surfaceError = false
  293. for (let surfaceIndex = 0; surfaceIndex < surfaceStarts.length; surfaceIndex += 1) {
  294. const start = surfaceStarts[surfaceIndex] as { line: Line; index: number }
  295. const end = surfaceStarts[surfaceIndex + 1]?.index ?? content.length
  296. const entries = content.slice(start.index, end)
  297. const heading = entries[0] as Line
  298. const title = heading.raw.slice('### '.length)
  299. const fragment = headingFragment(title)
  300. if (fragment.length === 0) {
  301. failures.push({ path: readme, message: `line ${heading.index}: each context surface requires a non-empty H3 heading` })
  302. surfaceError = true
  303. break
  304. }
  305. if (surfaceFragments.has(fragment)) {
  306. failures.push({ path: readme, message: `line ${heading.index}: duplicate context-surface link fragment ${JSON.stringify(fragment)}` })
  307. surfaceError = true
  308. break
  309. }
  310. const fieldStarts = entries
  311. .map((line, index) => ({ line, index }))
  312. .filter(entry => /^#### \S/.test(entry.line.raw))
  313. if (fieldStarts.length !== FIELD_HEADINGS.length || fieldStarts[0]?.index !== 1) {
  314. failures.push({ path: readme, message: `line ${heading.index}: context surface requires exactly three ordered H4 fields: ${FIELD_HEADINGS.join(', ')}` })
  315. surfaceError = true
  316. break
  317. }
  318. if ((surfaceIndex === 0 && heading.index !== modelHeading.index + 2)
  319. || rawLines[heading.index - 2]?.trim().length !== 0
  320. || fieldStarts[0].line.index !== heading.index + 2) {
  321. failures.push({ path: readme, message: `line ${heading.index}: context-surface heading and first field require one blank line between them` })
  322. surfaceError = true
  323. break
  324. }
  325. const parsedFields: ParsedField[] = []
  326. const verbatimFragments = new Set<string>()
  327. for (let fieldIndex = 0; fieldIndex < FIELD_HEADINGS.length; fieldIndex += 1) {
  328. const fieldStart = fieldStarts[fieldIndex] as { line: Line; index: number }
  329. const expectedHeading = FIELD_HEADINGS[fieldIndex] as string
  330. if (fieldStart.line.raw !== expectedHeading) {
  331. failures.push({ path: readme, message: `line ${fieldStart.line.index}: expected exact field heading ${JSON.stringify(expectedHeading)}, found ${JSON.stringify(fieldStart.line.raw)}` })
  332. surfaceError = true
  333. break
  334. }
  335. const fieldEnd = fieldStarts[fieldIndex + 1]?.index ?? entries.length
  336. const fieldEntries = entries.slice(fieldStart.index, fieldEnd)
  337. const value = fieldEntries[1]
  338. if (value === undefined || /^#{1,6} /.test(value.raw) || value.raw.trim().length === 0) {
  339. failures.push({ path: readme, message: `line ${fieldStart.line.index}: ${expectedHeading} requires one non-empty paragraph` })
  340. surfaceError = true
  341. break
  342. }
  343. if (value.index !== fieldStart.line.index + 2) {
  344. failures.push({ path: readme, message: `line ${fieldStart.line.index}: ${expectedHeading} and its paragraph require one blank line between them` })
  345. surfaceError = true
  346. break
  347. }
  348. const unexpected = fieldEntries.slice(2).find(line => !/^##### \S/.test(line.raw))
  349. if (unexpected !== undefined) {
  350. failures.push({ path: readme, message: `line ${unexpected.index}: content after ${expectedHeading} paragraph must be a titled H5 plus \`markdown\` fence owned by that field` })
  351. surfaceError = true
  352. break
  353. }
  354. const nextHeadingLine = fieldStarts[fieldIndex + 1]?.line.index
  355. ?? surfaceStarts[surfaceIndex + 1]?.line.index
  356. ?? nextH2Line
  357. if (rawLines[nextHeadingLine - 2]?.trim().length !== 0) {
  358. failures.push({ path: readme, message: `line ${nextHeadingLine}: Model Experience headings require a preceding blank line` })
  359. surfaceError = true
  360. break
  361. }
  362. const verbatim = validateNestedVerbatim(rawLines.slice(value.index, nextHeadingLine - 1), verbatimFragments)
  363. if (verbatim.error !== undefined) {
  364. failures.push({ path: readme, message: `line ${value.index}: ${verbatim.error}` })
  365. surfaceError = true
  366. break
  367. }
  368. if (fieldEntries.length - 2 !== verbatim.blocks) {
  369. failures.push({ path: readme, message: `line ${value.index}: every nested H5 must own exactly one \`markdown\` fence` })
  370. surfaceError = true
  371. break
  372. }
  373. parsedFields.push({ value, verbatimBlocks: verbatim.blocks })
  374. }
  375. if (surfaceError) break
  376. const modelViewField = parsedFields[0] as ParsedField
  377. const tokenEffectField = parsedFields[1] as ParsedField
  378. const kvCacheEffectField = parsedFields[2] as ParsedField
  379. const modelView = modelViewField.value
  380. const tokenEffect = tokenEffectField.value
  381. const kvCacheEffect = kvCacheEffectField.value
  382. if (/\]\(#[^)]+\)/.test(modelView.raw) || /\]\(#[^)]+\)/.test(tokenEffect.raw) || /\]\(#[^)]+\)/.test(kvCacheEffect.raw)) {
  383. failures.push({ path: readme, message: `line ${heading.index}: Model Experience fields must not link between local subsections; nest the H5 in its owning H4 field` })
  384. surfaceError = true
  385. break
  386. }
  387. surfaceFragments.add(fragment)
  388. surfaces.push({
  389. heading,
  390. modelView,
  391. tokenEffect,
  392. kvCacheEffect,
  393. title,
  394. modelViewVerbatimBlocks: modelViewField.verbatimBlocks,
  395. verbatimBlocks: parsedFields.reduce((total, field) => total + field.verbatimBlocks, 0),
  396. })
  397. }
  398. if (surfaceError) continue
  399. const promptWithoutVerbatim = surfaces.find(surface => isDirectSystemPromptSurface(surface.title)
  400. && surface.modelViewVerbatimBlocks === 0)
  401. if (promptWithoutVerbatim !== undefined) {
  402. failures.push({ path: readme, message: `line ${promptWithoutVerbatim.heading.index}: system-prompt surface must contain a titled H5 plus verbatim \`markdown\` block under ${MODEL_VIEW_HEADING}` })
  403. continue
  404. }
  405. const hasConcreteLiteral = surfaces.some(surface => surface.verbatimBlocks > 0
  406. || surface.modelView.raw.includes('`')
  407. || surface.tokenEffect.raw.includes('`')
  408. || toolCatalogLinkFragments(surface.modelView.raw).length > 0)
  409. if (!hasConcreteLiteral) {
  410. failures.push({ path: readme, message: 'structured Model Experience must ground at least one surface with inline code, a nested `markdown` block, or an anchored tool-catalog link' })
  411. continue
  412. }
  413. let catalogError = false
  414. for (const surface of surfaces) {
  415. if (!/\bschemas?\b/i.test(surface.title)) continue
  416. const fragments = toolCatalogLinkFragments(surface.modelView.raw)
  417. if (fragments.length === 0) {
  418. failures.push({ path: readme, message: `line ${surface.heading.index}: tool-schema surface must link an anchored section of ../../../docs/tool-catalog.md` })
  419. catalogError = true
  420. break
  421. }
  422. const invalid = fragments.find(fragment => !toolCatalogFragments.has(fragment))
  423. if (invalid !== undefined) {
  424. failures.push({ path: readme, message: `line ${surface.modelView.index}: tool-catalog link fragment ${JSON.stringify(invalid)} does not name an H2 section` })
  425. catalogError = true
  426. break
  427. }
  428. }
  429. if (catalogError) continue
  430. verbatimBlockCount += surfaces.reduce((total, surface) => total + surface.verbatimBlocks, 0)
  431. contextSurfaceCount += surfaces.length
  432. systemPromptSurfaceCount += surfaces.filter(surface => isDirectSystemPromptSurface(surface.title)).length
  433. toolSchemaSurfaceCount += surfaces.filter(surface => /\bschemas?\b/i.test(surface.title)).length
  434. kvCacheEffectCount += surfaces.length
  435. structuredCount += 1
  436. }
  437. if (failures.length === 0) {
  438. console.log(`verify-package-readme-model-experience: ${packageJsons.length} README(s) checked (${omittedSectionCount} audited omissions, ${structuredCount} structured, ${contextSurfaceCount} context surfaces, ${kvCacheEffectCount} KV-cache fields, ${systemPromptSurfaceCount} fenced system-prompt surfaces, ${toolSchemaSurfaceCount} catalog-linked tool-schema surfaces, ${explainedNoneCount} explained none, ${indirectCount} indirect, ${verbatimBlockCount} verbatim markdown blocks), all conform.`)
  439. process.exit(0)
  440. }
  441. console.error('verify-package-readme-model-experience failed:')
  442. for (const failure of failures) {
  443. console.error(` ${relative(root, resolve(root, failure.path))}: ${failure.message}`)
  444. }
  445. process.exit(1)