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

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