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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 plus an optional linked long-literal
  5. * appendix; an audited allowlist requires one concise zero-effect or
  6. * indirect-only sentence instead.
  7. *
  8. * Run: `tsx scripts/verify-package-readme-model-experience.ts`.
  9. */
  10. import { existsSync, globSync, readFileSync } from 'node:fs'
  11. import { relative, resolve } from 'node:path'
  12. const root = resolve(import.meta.dirname, '..')
  13. const HEADING = '## Model Experience'
  14. const LIMITATIONS_HEADING = '## Known Limitations and Deferred Work'
  15. const VERBATIM_HEADING = '### Verbatim model-visible text'
  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/fs/fs': { kind: 'indirect', reason: 'The service interface delegates model rendering to dsh-tool-fs.' },
  35. 'packages/fs/fs-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
  36. 'packages/hooks/hook-protocol': { kind: 'indirect', reason: 'Only the hook bridge plugins render decoded hook output to a model.' },
  37. 'packages/sandbox/sandbox': { kind: 'indirect', reason: 'Sandbox consumers render enforcement and availability facts.' },
  38. 'packages/sandbox/sandbox-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-bash-sandbox and dsh-tool-bash.' },
  39. 'packages/skill/skill': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-skill.' },
  40. 'packages/skill/skill-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-skill.' },
  41. 'packages/subagent/subagent': { kind: 'indirect', reason: 'The provider registry delegates parent-model rendering to dsh-tool-subagent.' },
  42. 'packages/subagent/subagent-subprocess': { kind: 'indirect', reason: 'Only process-based subagent backends compose a child model request.' },
  43. 'packages/support/acp-snapshot': { kind: 'none', reason: 'The test harness observes and normalizes transcripts without changing live requests.' },
  44. 'packages/support/invariants': { kind: 'none', reason: 'The observer validates requests but never rewrites their context.' },
  45. 'packages/ui/app-boot': { kind: 'indirect', reason: 'Only the loaded plugin tree contributes model context.' },
  46. 'packages/ui/user-interaction': { kind: 'indirect', reason: 'Model-facing consumers render provider answers and seam errors.' },
  47. 'packages/util/brand': { kind: 'none', reason: 'The type-only primitive is erased at compile time.' },
  48. 'packages/util/timeout': { kind: 'indirect', reason: 'Only timeout consumers render timeout outcomes.' },
  49. 'packages/web/web': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-web.' },
  50. 'packages/web/web-fetch-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  51. 'packages/web/web-search-exa': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  52. 'packages/workflow/workflow': { kind: 'indirect', reason: 'The service delegates parent and child model rendering to its consumer and engine.' },
  53. }
  54. interface Failure {
  55. path: string
  56. message: string
  57. }
  58. interface Line {
  59. index: number
  60. raw: string
  61. }
  62. /** Split Markdown into prose lines, excluding fenced code that may quote the contract. */
  63. function proseLines(text: string): Line[] {
  64. let fence: { marker: '`' | '~'; length: number } | undefined
  65. const kept: Line[] = []
  66. text.split('\n').forEach((raw, i) => {
  67. const token = /^ {0,3}(`{3,}|~{3,})/.exec(raw)?.[1]
  68. if (token !== undefined) {
  69. const marker = token[0] as '`' | '~'
  70. if (fence === undefined) {
  71. fence = { marker, length: token.length }
  72. } else if (marker === fence.marker && token.length >= fence.length) {
  73. fence = undefined
  74. }
  75. return
  76. }
  77. if (fence === undefined) kept.push({ index: i + 1, raw })
  78. })
  79. return kept
  80. }
  81. /** Validate the optional long-form literal appendix after the context blocks. */
  82. function validateVerbatimTail(raw: readonly string[]): { blocks: number; titles: string[]; error?: string } {
  83. let cursor = 0
  84. while (raw[cursor]?.trim().length === 0) cursor += 1
  85. if (cursor === raw.length) return { blocks: 0, titles: [] }
  86. if (raw[cursor] !== VERBATIM_HEADING) {
  87. return { blocks: 0, titles: [], error: `content after the context surfaces must begin with ${VERBATIM_HEADING}` }
  88. }
  89. cursor += 1
  90. let blocks = 0
  91. const titles: string[] = []
  92. while (true) {
  93. while (raw[cursor]?.trim().length === 0) cursor += 1
  94. if (cursor === raw.length) break
  95. if (!/^#### \S/.test(raw[cursor] ?? '')) {
  96. return { blocks, titles, error: `${VERBATIM_HEADING} entries require a non-empty H4 title` }
  97. }
  98. const title = (raw[cursor] as string).slice('#### '.length)
  99. const fragment = headingFragment(title)
  100. if (fragment.length === 0) return { blocks, titles, error: 'verbatim H4 title must produce a non-empty link fragment' }
  101. if (titles.some(existing => headingFragment(existing) === fragment)) {
  102. return { blocks, titles, error: `verbatim H4 link fragment ${JSON.stringify(fragment)} is duplicated` }
  103. }
  104. titles.push(title)
  105. cursor += 1
  106. while (raw[cursor]?.trim().length === 0) cursor += 1
  107. if (raw[cursor] !== '```markdown') {
  108. return { blocks, titles, error: 'each verbatim entry requires an exact ```markdown fence' }
  109. }
  110. cursor += 1
  111. const contentStart = cursor
  112. while (cursor < raw.length && raw[cursor] !== '```') cursor += 1
  113. if (cursor === raw.length) return { blocks, titles, error: 'unterminated verbatim ```markdown fence' }
  114. if (cursor === contentStart) return { blocks, titles, error: 'verbatim ```markdown fence must not be empty' }
  115. cursor += 1
  116. blocks += 1
  117. }
  118. return blocks > 0 ? { blocks, titles } : { blocks, titles, error: `${VERBATIM_HEADING} requires at least one entry` }
  119. }
  120. /** GitHub-style fragment for the simple ASCII H4 titles allowed by this contract. */
  121. function headingFragment(title: string): string {
  122. return title.toLowerCase().replaceAll('`', '').replaceAll(/[^a-z0-9 _-]/g, '').trim().replaceAll(/\s+/g, '-')
  123. }
  124. const failures: Failure[] = []
  125. const packageJsons = globSync('packages/*/*/package.json', { cwd: root }).sort()
  126. const scannedPackages = new Set(packageJsons.map(path => path.slice(0, -'/package.json'.length)))
  127. let structuredCount = 0
  128. let contextSurfaceCount = 0
  129. let noneCount = 0
  130. let indirectCount = 0
  131. let verbatimBlockCount = 0
  132. for (const [pkg, contract] of Object.entries(SENTENCE_MODEL_EXPERIENCE)) {
  133. if (!scannedPackages.has(pkg)) {
  134. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry does not name a scanned package' })
  135. }
  136. if (contract.reason.trim().length === 0) {
  137. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry must justify why structured context surfaces are unnecessary' })
  138. }
  139. }
  140. for (const packageJson of packageJsons) {
  141. const pkg = packageJson.slice(0, -'/package.json'.length)
  142. const readme = packageJson.replace(/package\.json$/, 'README.md')
  143. const abs = resolve(root, readme)
  144. if (!existsSync(abs)) {
  145. failures.push({ path: readme, message: `missing package README; add one with ${HEADING}` })
  146. continue
  147. }
  148. const text = readFileSync(abs, 'utf8')
  149. const rawLines = text.split('\n')
  150. const lines = proseLines(text)
  151. const h2Headings = lines.filter(line => H2_HEADING.test(line.raw))
  152. const modelHeadings = h2Headings.filter(line => line.raw === HEADING)
  153. if (modelHeadings.length !== 1) {
  154. failures.push({
  155. path: readme,
  156. message: modelHeadings.length === 0 ? `missing ${HEADING}` : `contains ${modelHeadings.length} copies of ${HEADING}`,
  157. })
  158. continue
  159. }
  160. const modelHeading = modelHeadings[0] as Line
  161. const modelH2Index = h2Headings.indexOf(modelHeading)
  162. const limitationsH2Index = h2Headings.findIndex(heading => heading.raw === LIMITATIONS_HEADING)
  163. if (limitationsH2Index >= 0) {
  164. if (modelH2Index !== h2Headings.length - 2 || limitationsH2Index !== h2Headings.length - 1) {
  165. failures.push({
  166. path: readme,
  167. message: `${HEADING} and ${LIMITATIONS_HEADING} must be the final two H2 sections, in that order`,
  168. })
  169. continue
  170. }
  171. } else if (modelH2Index !== h2Headings.length - 1) {
  172. failures.push({ path: readme, message: `${HEADING} must be the final H2 when ${LIMITATIONS_HEADING} is absent` })
  173. continue
  174. }
  175. const body = lines.slice(lines.indexOf(modelHeading) + 1)
  176. const nextH2 = body.findIndex(line => H2_HEADING.test(line.raw))
  177. const section = nextH2 < 0 ? body : body.slice(0, nextH2)
  178. const nextH2Line = nextH2 < 0 ? rawLines.length + 1 : (body[nextH2] as Line).index
  179. const rawSection = rawLines.slice(modelHeading.index, nextH2Line - 1)
  180. const content = section.filter(line => line.raw.trim().length > 0)
  181. const sentenceContract = SENTENCE_MODEL_EXPERIENCE[pkg]
  182. if (sentenceContract !== undefined) {
  183. const pattern = sentenceContract.kind === 'none' ? /^None, as .+\.$/ : /^Indirectly, through .+\.$/
  184. const rawContent = rawSection.filter(line => line.trim().length > 0)
  185. if (content.length !== 1 || rawContent.length !== 1 || !pattern.test(content[0]?.raw ?? '')) {
  186. const prefix = sentenceContract.kind === 'none' ? 'None, as ' : 'Indirectly, through '
  187. failures.push({ path: readme, message: `must contain exactly one sentence beginning ${JSON.stringify(prefix)} and ending with a period` })
  188. continue
  189. }
  190. if (sentenceContract.kind === 'none') noneCount += 1
  191. else indirectCount += 1
  192. continue
  193. }
  194. const shortSentence = content.find(line => /^None, as |^Indirectly, through /.test(line.raw))
  195. if (shortSentence !== undefined) {
  196. failures.push({ path: readme, message: `line ${shortSentence.index}: short Model Experience form requires an audited entry in SENTENCE_MODEL_EXPERIENCE` })
  197. continue
  198. }
  199. const appendixIndex = content.findIndex(line => line.raw === VERBATIM_HEADING)
  200. const surfaceContent = appendixIndex < 0 ? content : content.slice(0, appendixIndex)
  201. if (surfaceContent.length === 0 || surfaceContent.length % 3 !== 0) {
  202. failures.push({ path: readme, message: 'must contain one or more complete context-surface blocks' })
  203. continue
  204. }
  205. const surfaces: Array<{ heading: Line; modelView: Line; tokenEffect: Line }> = []
  206. const surfaceFragments = new Set<string>()
  207. let previousTokenEffect: Line | undefined
  208. let surfaceError = false
  209. for (let index = 0; index < surfaceContent.length; index += 3) {
  210. const heading = surfaceContent[index] as Line
  211. const modelView = surfaceContent[index + 1] as Line
  212. const tokenEffect = surfaceContent[index + 2] as Line
  213. const fragment = /^### \S/.test(heading.raw) && heading.raw !== VERBATIM_HEADING
  214. ? headingFragment(heading.raw.slice('### '.length))
  215. : ''
  216. if (fragment.length === 0) {
  217. failures.push({ path: readme, message: `line ${heading.index}: each context surface requires a non-empty H3 heading` })
  218. surfaceError = true
  219. break
  220. }
  221. if (surfaceFragments.has(fragment)) {
  222. failures.push({ path: readme, message: `line ${heading.index}: duplicate context-surface link fragment ${JSON.stringify(fragment)}` })
  223. surfaceError = true
  224. break
  225. }
  226. if (!modelView.raw.startsWith(`${MODEL_VIEW_LABEL}: `) || modelView.raw.slice(`${MODEL_VIEW_LABEL}: `.length).trim().length === 0) {
  227. failures.push({ path: readme, message: `line ${modelView.index}: context surface requires non-empty ${MODEL_VIEW_LABEL}: text` })
  228. surfaceError = true
  229. break
  230. }
  231. if (!tokenEffect.raw.startsWith(`${TOKEN_EFFECT_LABEL}: `) || tokenEffect.raw.slice(`${TOKEN_EFFECT_LABEL}: `.length).trim().length === 0) {
  232. failures.push({ path: readme, message: `line ${tokenEffect.index}: context surface requires non-empty ${TOKEN_EFFECT_LABEL}: text` })
  233. surfaceError = true
  234. break
  235. }
  236. const expectedHeadingLine = previousTokenEffect?.index === undefined ? modelHeading.index + 2 : previousTokenEffect.index + 2
  237. if (heading.index !== expectedHeadingLine || modelView.index !== heading.index + 2 || tokenEffect.index !== modelView.index + 2) {
  238. failures.push({ path: readme, message: `line ${heading.index}: context-surface heading and fields require one blank line between each element` })
  239. surfaceError = true
  240. break
  241. }
  242. surfaceFragments.add(fragment)
  243. surfaces.push({ heading, modelView, tokenEffect })
  244. previousTokenEffect = tokenEffect
  245. }
  246. if (surfaceError) continue
  247. const lastSurface = surfaces.at(-1) as { heading: Line; modelView: Line; tokenEffect: Line }
  248. if (appendixIndex >= 0 && (content[appendixIndex] as Line).index !== lastSurface.tokenEffect.index + 2) {
  249. failures.push({ path: readme, message: `${VERBATIM_HEADING} must follow the final context surface after one blank line` })
  250. continue
  251. }
  252. const rawTail = rawLines.slice(lastSurface.tokenEffect.index, nextH2Line - 1)
  253. const verbatim = validateVerbatimTail(rawTail)
  254. if (verbatim.error !== undefined) {
  255. failures.push({ path: readme, message: verbatim.error })
  256. continue
  257. }
  258. const modelViewText = surfaces.map(surface => surface.modelView.raw).join('\n')
  259. const unlinked = verbatim.titles.find(title => !modelViewText.includes(`](#${headingFragment(title)})`))
  260. if (unlinked !== undefined) {
  261. failures.push({ path: readme, message: `verbatim entry ${JSON.stringify(unlinked)} must be linked from a context surface's ${MODEL_VIEW_LABEL} field` })
  262. continue
  263. }
  264. verbatimBlockCount += verbatim.blocks
  265. contextSurfaceCount += surfaces.length
  266. structuredCount += 1
  267. }
  268. if (failures.length === 0) {
  269. console.log(`verify-package-readme-model-experience: ${packageJsons.length} README(s) checked (${structuredCount} structured, ${contextSurfaceCount} context surfaces, ${noneCount} none, ${indirectCount} indirect, ${verbatimBlockCount} verbatim markdown blocks), all conform.`)
  270. process.exit(0)
  271. }
  272. console.error('verify-package-readme-model-experience failed:')
  273. for (const failure of failures) {
  274. console.error(` ${relative(root, resolve(root, failure.path))}: ${failure.message}`)
  275. }
  276. process.exit(1)