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

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