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

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