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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /**
  2. * Doc-sync gate: require every workspace package README to explain its exact
  3. * model-visible context surface and token behavior. Most packages require the
  4. * canonical context-surface blocks with optional nested verbatim H4 blocks.
  5. * Direct system-prompt surfaces must contain exact `markdown` blocks,
  6. * tool-schema surfaces must link generated catalog sections, local subsection
  7. * links are rejected, and an audited allowlist uses one concise sentence.
  8. *
  9. * Run: `tsx scripts/verify-package-readme-model-experience.ts`.
  10. */
  11. import { existsSync, globSync, readFileSync } from 'node:fs'
  12. import { relative, resolve } from 'node:path'
  13. const root = resolve(import.meta.dirname, '..')
  14. const HEADING = '## Model Experience'
  15. const LIMITATIONS_HEADING = '## Known Limitations and Deferred Work'
  16. const MODEL_VIEW_LABEL = '**What the model sees**'
  17. const TOKEN_EFFECT_LABEL = '**Token effect**'
  18. const H2_HEADING = /^## .+$/
  19. type SentenceKind = 'none' | 'indirect'
  20. interface SentenceContract {
  21. kind: SentenceKind
  22. reason: string
  23. }
  24. /**
  25. * Packages whose Model Experience is simple enough for one gated sentence.
  26. * Every other package must carry canonical context-surface blocks. A package
  27. * moves on or off this list with the change to its context behavior.
  28. */
  29. const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
  30. 'packages/bash/bash': { kind: 'indirect', reason: 'The service interface delegates all model rendering to dsh-tool-bash.' },
  31. 'packages/bash/bash-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-bash.' },
  32. 'packages/code-runtime/code-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to Code Mode in dsh-tools.' },
  33. 'packages/code-runtime/code-runtime-worker': { kind: 'indirect', reason: 'The worker backend delegates model rendering to Code Mode in dsh-tools.' },
  34. 'packages/core/agent-core': { kind: 'indirect', reason: 'The bundle only mounts model-facing child plugins.' },
  35. 'packages/core/scope': { kind: 'none', reason: 'The routing primitive emits no model-bound content.' },
  36. 'packages/fs/fs': { kind: 'indirect', reason: 'The service interface delegates model rendering to dsh-tool-fs.' },
  37. 'packages/fs/fs-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
  38. 'packages/hooks/hook-protocol': { kind: 'indirect', reason: 'Only the hook bridge plugins render decoded hook output to a model.' },
  39. 'packages/llm/llm': { kind: 'none', reason: 'The adapter registry forwards already-assembled requests unchanged.' },
  40. 'packages/sandbox/sandbox': { kind: 'indirect', reason: 'Sandbox consumers render enforcement and availability facts.' },
  41. 'packages/sandbox/sandbox-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-bash-sandbox and dsh-tool-bash.' },
  42. 'packages/skill/skill': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-skill.' },
  43. 'packages/skill/skill-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-skill.' },
  44. 'packages/subagent/subagent': { kind: 'indirect', reason: 'The provider registry delegates parent-model rendering to dsh-tool-subagent.' },
  45. 'packages/subagent/subagent-subprocess': { kind: 'indirect', reason: 'Only process-based subagent backends compose a child model request.' },
  46. 'packages/support/acp-snapshot': { kind: 'none', reason: 'The test harness observes and normalizes transcripts without changing live requests.' },
  47. 'packages/support/invariants': { kind: 'none', reason: 'The observer validates requests but never rewrites their context.' },
  48. 'packages/support/llm-replay': { kind: 'none', reason: 'The keyless adapter invokes no provider model.' },
  49. 'packages/support/subagent-mock': { kind: 'indirect', reason: 'Only dsh-tool-subagent renders its configured test outcome.' },
  50. 'packages/ui/acp-agent': { kind: 'indirect', reason: 'The app bundle delegates request composition to dsh-agent-core and dsh-acp.' },
  51. 'packages/ui/app-boot': { kind: 'indirect', reason: 'Only the loaded plugin tree contributes model context.' },
  52. 'packages/ui/user-interaction': { kind: 'indirect', reason: 'Model-facing consumers render provider answers and seam errors.' },
  53. 'packages/util/brand': { kind: 'none', reason: 'The type-only primitive is erased at compile time.' },
  54. 'packages/util/timeout': { kind: 'indirect', reason: 'Only timeout consumers render timeout outcomes.' },
  55. 'packages/web/web': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-web.' },
  56. 'packages/web/web-fetch-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  57. 'packages/web/web-search-exa': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  58. 'packages/workflow/workflow': { kind: 'indirect', reason: 'The service delegates parent and child model rendering to its consumer and engine.' },
  59. }
  60. interface Failure {
  61. path: string
  62. message: string
  63. }
  64. interface Line {
  65. index: number
  66. raw: string
  67. }
  68. interface ContextSurface {
  69. heading: Line
  70. modelView: Line
  71. tokenEffect: Line
  72. title: string
  73. verbatimBlocks: number
  74. }
  75. /** Split Markdown into prose lines, excluding fenced code that may quote the contract. */
  76. function proseLines(text: string): Line[] {
  77. let fence: { marker: '`' | '~'; length: number } | undefined
  78. const kept: Line[] = []
  79. text.split('\n').forEach((raw, i) => {
  80. const token = /^ {0,3}(`{3,}|~{3,})/.exec(raw)?.[1]
  81. if (token !== undefined) {
  82. const marker = token[0] as '`' | '~'
  83. if (fence === undefined) {
  84. fence = { marker, length: token.length }
  85. } else if (marker === fence.marker && token.length >= fence.length) {
  86. fence = undefined
  87. }
  88. return
  89. }
  90. if (fence === undefined) kept.push({ index: i + 1, raw })
  91. })
  92. return kept
  93. }
  94. /** Validate H4-plus-markdown literals nested after one context surface's fields. */
  95. function validateNestedVerbatim(raw: readonly string[]): { blocks: number; error?: string } {
  96. let cursor = 0
  97. while (raw[cursor]?.trim().length === 0) cursor += 1
  98. if (cursor === raw.length) return { blocks: 0 }
  99. let blocks = 0
  100. const fragments = new Set<string>()
  101. while (true) {
  102. while (raw[cursor]?.trim().length === 0) cursor += 1
  103. if (cursor === raw.length) break
  104. if (!/^#### \S/.test(raw[cursor] ?? '')) {
  105. return { blocks, error: 'content after Token effect must be a titled H4 verbatim block' }
  106. }
  107. const title = (raw[cursor] as string).slice('#### '.length)
  108. const fragment = headingFragment(title)
  109. if (fragment.length === 0) return { blocks, error: 'verbatim H4 title must be non-empty' }
  110. if (fragments.has(fragment)) {
  111. return { blocks, error: `verbatim H4 title ${JSON.stringify(title)} is duplicated within its context surface` }
  112. }
  113. fragments.add(fragment)
  114. cursor += 1
  115. while (raw[cursor]?.trim().length === 0) cursor += 1
  116. if (raw[cursor] !== '```markdown') {
  117. return { blocks, error: 'each nested verbatim H4 requires an exact ```markdown fence' }
  118. }
  119. cursor += 1
  120. const contentStart = cursor
  121. while (cursor < raw.length && raw[cursor] !== '```') cursor += 1
  122. if (cursor === raw.length) return { blocks, error: 'unterminated nested ```markdown fence' }
  123. if (cursor === contentStart) return { blocks, error: 'nested ```markdown fence must not be empty' }
  124. cursor += 1
  125. blocks += 1
  126. }
  127. return { blocks }
  128. }
  129. /** GitHub-style fragment for the simple ASCII H4 titles allowed by this contract. */
  130. function headingFragment(title: string): string {
  131. return title.toLowerCase().replaceAll('`', '').replaceAll(/[^a-z0-9 _-]/g, '').trim().replaceAll(/\s+/g, '-')
  132. }
  133. /** A direct stable system-prompt contribution, as named by the README contract. */
  134. function isDirectSystemPromptSurface(title: string): boolean {
  135. return /\bsystem prompt\b/i.test(title)
  136. }
  137. /** Anchored generated-catalog links in one model-view field. */
  138. function toolCatalogLinkFragments(text: string): string[] {
  139. return [...text.matchAll(/\]\(\.\.\/\.\.\/\.\.\/docs\/tool-catalog\.md#([a-z0-9_-]+)\)/g)]
  140. .map(match => match[1] as string)
  141. }
  142. const toolCatalogFragments = new Set<string>()
  143. for (const line of readFileSync(resolve(root, 'docs/tool-catalog.md'), 'utf8').split('\n')) {
  144. const title = /^## (.+)$/.exec(line)?.[1]
  145. if (title !== undefined) toolCatalogFragments.add(headingFragment(title))
  146. }
  147. const failures: Failure[] = []
  148. const packageJsons = globSync('packages/*/*/package.json', { cwd: root }).sort()
  149. const scannedPackages = new Set(packageJsons.map(path => path.slice(0, -'/package.json'.length)))
  150. let structuredCount = 0
  151. let contextSurfaceCount = 0
  152. let noneCount = 0
  153. let indirectCount = 0
  154. let verbatimBlockCount = 0
  155. let systemPromptSurfaceCount = 0
  156. let toolSchemaSurfaceCount = 0
  157. for (const [pkg, contract] of Object.entries(SENTENCE_MODEL_EXPERIENCE)) {
  158. if (!scannedPackages.has(pkg)) {
  159. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry does not name a scanned package' })
  160. }
  161. if (contract.reason.trim().length === 0) {
  162. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry must justify why structured context surfaces are unnecessary' })
  163. }
  164. }
  165. for (const packageJson of packageJsons) {
  166. const pkg = packageJson.slice(0, -'/package.json'.length)
  167. const readme = packageJson.replace(/package\.json$/, 'README.md')
  168. const abs = resolve(root, readme)
  169. if (!existsSync(abs)) {
  170. failures.push({ path: readme, message: `missing package README; add one with ${HEADING}` })
  171. continue
  172. }
  173. const text = readFileSync(abs, 'utf8')
  174. const rawLines = text.split('\n')
  175. const lines = proseLines(text)
  176. const h2Headings = lines.filter(line => H2_HEADING.test(line.raw))
  177. const modelHeadings = h2Headings.filter(line => line.raw === HEADING)
  178. if (modelHeadings.length !== 1) {
  179. failures.push({
  180. path: readme,
  181. message: modelHeadings.length === 0 ? `missing ${HEADING}` : `contains ${modelHeadings.length} copies of ${HEADING}`,
  182. })
  183. continue
  184. }
  185. const modelHeading = modelHeadings[0] as Line
  186. const modelH2Index = h2Headings.indexOf(modelHeading)
  187. const limitationsH2Index = h2Headings.findIndex(heading => heading.raw === LIMITATIONS_HEADING)
  188. if (limitationsH2Index >= 0) {
  189. if (modelH2Index !== h2Headings.length - 2 || limitationsH2Index !== h2Headings.length - 1) {
  190. failures.push({
  191. path: readme,
  192. message: `${HEADING} and ${LIMITATIONS_HEADING} must be the final two H2 sections, in that order`,
  193. })
  194. continue
  195. }
  196. } else if (modelH2Index !== h2Headings.length - 1) {
  197. failures.push({ path: readme, message: `${HEADING} must be the final H2 when ${LIMITATIONS_HEADING} is absent` })
  198. continue
  199. }
  200. const body = lines.slice(lines.indexOf(modelHeading) + 1)
  201. const nextH2 = body.findIndex(line => H2_HEADING.test(line.raw))
  202. const section = nextH2 < 0 ? body : body.slice(0, nextH2)
  203. const nextH2Line = nextH2 < 0 ? rawLines.length + 1 : (body[nextH2] as Line).index
  204. const rawSection = rawLines.slice(modelHeading.index, nextH2Line - 1)
  205. const content = section.filter(line => line.raw.trim().length > 0)
  206. const sentenceContract = SENTENCE_MODEL_EXPERIENCE[pkg]
  207. if (sentenceContract !== undefined) {
  208. const pattern = sentenceContract.kind === 'none' ? /^None, as .+\.$/ : /^Indirectly, through .+\.$/
  209. const rawContent = rawSection.filter(line => line.trim().length > 0)
  210. if (content.length !== 1 || rawContent.length !== 1 || !pattern.test(content[0]?.raw ?? '')) {
  211. const prefix = sentenceContract.kind === 'none' ? 'None, as ' : 'Indirectly, through '
  212. failures.push({ path: readme, message: `must contain exactly one sentence beginning ${JSON.stringify(prefix)} and ending with a period` })
  213. continue
  214. }
  215. if (sentenceContract.kind === 'none') noneCount += 1
  216. else indirectCount += 1
  217. continue
  218. }
  219. const shortSentence = content.find(line => /^None, as |^Indirectly, through /.test(line.raw))
  220. if (shortSentence !== undefined) {
  221. failures.push({ path: readme, message: `line ${shortSentence.index}: short Model Experience form requires an audited entry in SENTENCE_MODEL_EXPERIENCE` })
  222. continue
  223. }
  224. const surfaceStarts = content
  225. .map((line, index) => ({ line, index }))
  226. .filter(entry => /^### \S/.test(entry.line.raw))
  227. if (surfaceStarts.length === 0 || surfaceStarts[0]?.index !== 0) {
  228. failures.push({ path: readme, message: 'must contain one or more complete context-surface blocks' })
  229. continue
  230. }
  231. const surfaces: ContextSurface[] = []
  232. const surfaceFragments = new Set<string>()
  233. let surfaceError = false
  234. for (let surfaceIndex = 0; surfaceIndex < surfaceStarts.length; surfaceIndex += 1) {
  235. const start = surfaceStarts[surfaceIndex] as { line: Line; index: number }
  236. const end = surfaceStarts[surfaceIndex + 1]?.index ?? content.length
  237. const entries = content.slice(start.index, end)
  238. const heading = entries[0] as Line
  239. const modelView = entries[1]
  240. const tokenEffect = entries[2]
  241. const title = heading.raw.slice('### '.length)
  242. const fragment = headingFragment(title)
  243. if (fragment.length === 0) {
  244. failures.push({ path: readme, message: `line ${heading.index}: each context surface requires a non-empty H3 heading` })
  245. surfaceError = true
  246. break
  247. }
  248. if (surfaceFragments.has(fragment)) {
  249. failures.push({ path: readme, message: `line ${heading.index}: duplicate context-surface link fragment ${JSON.stringify(fragment)}` })
  250. surfaceError = true
  251. break
  252. }
  253. if (modelView === undefined || !modelView.raw.startsWith(`${MODEL_VIEW_LABEL}: `) || modelView.raw.slice(`${MODEL_VIEW_LABEL}: `.length).trim().length === 0) {
  254. failures.push({ path: readme, message: `line ${modelView?.index ?? heading.index}: context surface requires non-empty ${MODEL_VIEW_LABEL}: text` })
  255. surfaceError = true
  256. break
  257. }
  258. if (tokenEffect === undefined || !tokenEffect.raw.startsWith(`${TOKEN_EFFECT_LABEL}: `) || tokenEffect.raw.slice(`${TOKEN_EFFECT_LABEL}: `.length).trim().length === 0) {
  259. failures.push({ path: readme, message: `line ${tokenEffect?.index ?? heading.index}: context surface requires non-empty ${TOKEN_EFFECT_LABEL}: text` })
  260. surfaceError = true
  261. break
  262. }
  263. if ((surfaceIndex === 0 && heading.index !== modelHeading.index + 2)
  264. || rawLines[heading.index - 2]?.trim().length !== 0
  265. || modelView.index !== heading.index + 2
  266. || tokenEffect.index !== modelView.index + 2) {
  267. failures.push({ path: readme, message: `line ${heading.index}: context-surface heading and fields require one blank line between each element` })
  268. surfaceError = true
  269. break
  270. }
  271. const unexpected = entries.slice(3).find(line => !/^#### \S/.test(line.raw))
  272. if (unexpected !== undefined) {
  273. failures.push({ path: readme, message: `line ${unexpected.index}: content after ${TOKEN_EFFECT_LABEL} must be a titled H4 plus \`markdown\` fence inside this context surface` })
  274. surfaceError = true
  275. break
  276. }
  277. const nextHeadingLine = surfaceStarts[surfaceIndex + 1]?.line.index ?? nextH2Line
  278. const verbatim = validateNestedVerbatim(rawLines.slice(tokenEffect.index, nextHeadingLine - 1))
  279. if (verbatim.error !== undefined) {
  280. failures.push({ path: readme, message: `line ${tokenEffect.index}: ${verbatim.error}` })
  281. surfaceError = true
  282. break
  283. }
  284. if (entries.length - 3 !== verbatim.blocks) {
  285. failures.push({ path: readme, message: `line ${tokenEffect.index}: every nested H4 must own exactly one \`markdown\` fence` })
  286. surfaceError = true
  287. break
  288. }
  289. if (/\]\(#[^)]+\)/.test(modelView.raw) || /\]\(#[^)]+\)/.test(tokenEffect.raw)) {
  290. failures.push({ path: readme, message: `line ${heading.index}: Model Experience fields must not link between local subsections; nest the H4 in its owning H3` })
  291. surfaceError = true
  292. break
  293. }
  294. surfaceFragments.add(fragment)
  295. surfaces.push({ heading, modelView, tokenEffect, title, verbatimBlocks: verbatim.blocks })
  296. }
  297. if (surfaceError) continue
  298. const promptWithoutVerbatim = surfaces.find(surface => isDirectSystemPromptSurface(surface.title)
  299. && surface.verbatimBlocks === 0)
  300. if (promptWithoutVerbatim !== undefined) {
  301. failures.push({ path: readme, message: `line ${promptWithoutVerbatim.heading.index}: system-prompt surface must contain a titled H4 plus verbatim \`markdown\` block` })
  302. continue
  303. }
  304. const hasConcreteLiteral = surfaces.some(surface => surface.verbatimBlocks > 0
  305. || surface.modelView.raw.includes('`')
  306. || surface.tokenEffect.raw.includes('`')
  307. || toolCatalogLinkFragments(surface.modelView.raw).length > 0)
  308. if (!hasConcreteLiteral) {
  309. 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' })
  310. continue
  311. }
  312. let catalogError = false
  313. for (const surface of surfaces) {
  314. if (!/\bschemas?\b/i.test(surface.title)) continue
  315. const fragments = toolCatalogLinkFragments(surface.modelView.raw)
  316. if (fragments.length === 0) {
  317. failures.push({ path: readme, message: `line ${surface.heading.index}: tool-schema surface must link an anchored section of ../../../docs/tool-catalog.md` })
  318. catalogError = true
  319. break
  320. }
  321. const invalid = fragments.find(fragment => !toolCatalogFragments.has(fragment))
  322. if (invalid !== undefined) {
  323. failures.push({ path: readme, message: `line ${surface.modelView.index}: tool-catalog link fragment ${JSON.stringify(invalid)} does not name an H2 section` })
  324. catalogError = true
  325. break
  326. }
  327. }
  328. if (catalogError) continue
  329. verbatimBlockCount += surfaces.reduce((total, surface) => total + surface.verbatimBlocks, 0)
  330. contextSurfaceCount += surfaces.length
  331. systemPromptSurfaceCount += surfaces.filter(surface => isDirectSystemPromptSurface(surface.title)).length
  332. toolSchemaSurfaceCount += surfaces.filter(surface => /\bschemas?\b/i.test(surface.title)).length
  333. structuredCount += 1
  334. }
  335. if (failures.length === 0) {
  336. console.log(`verify-package-readme-model-experience: ${packageJsons.length} README(s) checked (${structuredCount} structured, ${contextSurfaceCount} context surfaces, ${systemPromptSurfaceCount} fenced system-prompt surfaces, ${toolSchemaSurfaceCount} catalog-linked tool-schema surfaces, ${noneCount} none, ${indirectCount} indirect, ${verbatimBlockCount} verbatim markdown blocks), all conform.`)
  337. process.exit(0)
  338. }
  339. console.error('verify-package-readme-model-experience failed:')
  340. for (const failure of failures) {
  341. console.error(` ${relative(root, resolve(root, failure.path))}: ${failure.message}`)
  342. }
  343. process.exit(1)