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

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