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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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 only constructs plain string values and registers nothing model-facing.',
  30. 'packages/util/home-paths': 'The package only resolves harness-owned host paths; model-facing consumers own any rendered use.',
  31. 'packages/util/launch-environment': 'The package only resolves host environment values; model-facing consumers own any rendered use.',
  32. 'packages/util/workspace-path': 'The package only formats Workspace paths for browser UI; it never constructs model input.',
  33. 'packages/util/values': 'The package only validates, snapshots, compares, freezes, or rejects caller-owned values; consumers own every model-facing use.',
  34. }
  35. /**
  36. * Packages whose Model Experience is simple enough for one gated sentence plus
  37. * a KV-cache field. Every other package must carry canonical model-context
  38. * blocks. A package moves on or off this list with its context behavior.
  39. */
  40. const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
  41. 'packages/attachment/attachment': { kind: 'indirect', reason: 'The storage seam delegates model request rendering to provider adapters.' },
  42. 'packages/attachment/attachment-local': { kind: 'indirect', reason: 'The local backend delegates model request rendering to provider adapters.' },
  43. 'packages/shell/shell': { kind: 'indirect', reason: 'The service interface delegates all model rendering to dsh-tool-bash.' },
  44. 'packages/shell/shell-env': { kind: 'indirect', reason: 'The env service exposes managed DSH_* facts through the shell tools (dsh-tool-bash/dsh-tool-pwsh); it registers no prompt or schema of its own.' },
  45. 'packages/shell/bash-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-bash.' },
  46. 'packages/shell/pwsh-local': { kind: 'indirect', reason: 'The executor backend delegates model rendering to dsh-tool-pwsh.' },
  47. 'packages/code-runtime/code-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to PTC mode in dsh-tools.' },
  48. 'packages/core/agent-tool-presentation': { kind: 'indirect', reason: 'The row only selects between the two projections dsh-tools owns; it registers no prompt, schema, or result of its own.' },
  49. 'packages/code-runtime/code-runtime-worker-thread': { kind: 'indirect', reason: 'The worker backend delegates model rendering to PTC mode in dsh-tools.' },
  50. 'packages/experimental/code-runtime-python': { kind: 'indirect', reason: 'Explicit source-checkout compositions delegate model rendering to PTC mode in dsh-tools.' },
  51. 'packages/client/ui-agent-preset': { kind: 'indirect', reason: 'Browser-side settings row; the preset it selects owns every model-facing effect.' },
  52. 'packages/util/crypto': { kind: 'indirect', reason: 'Pure identifier minting; the ids consumers mint with it never enter prompts as semantic content.' },
  53. 'packages/util/deque': { kind: 'none', reason: 'In-process collection primitive; registers nothing model-facing.' },
  54. 'packages/util/chunked-list': { kind: 'none', reason: 'Immutable collection primitive; registers nothing model-facing.' },
  55. 'packages/util/package-manifest': { kind: 'none', reason: 'Type declarations only; registers nothing model-facing.' },
  56. 'packages/util/time': { kind: 'indirect', reason: 'Pure zone validation; the consumer that records a canonical zone owns the model-visible line derived from it.' },
  57. 'packages/core/agent-default-model': { kind: 'indirect', reason: 'The service supplies a ModelSelection; request assembly and adapters own the model-visible request.' },
  58. 'packages/llm/deepseek-llm-api-extensions': { kind: 'indirect', reason: 'The registry contributes model-hidden provider fields; dsh-llm-deepseek owns their wire placement.' },
  59. 'packages/preset/agent-presets': { kind: 'indirect', reason: 'The mount installs a preset\'s own plugins, which own every model-facing registration it makes visible.' },
  60. 'packages/typert/registry': { kind: 'none', reason: 'Runtime type registry; consumers (cordis_inspect, wire faces, gates) own any model-visible projection of registry contents.' },
  61. 'packages/typert/loader': { kind: 'none', reason: 'Loader integration only registers generated artifacts; consumers own any model-visible projection.' },
  62. 'packages/e2b/e2b': { kind: 'none', reason: 'The shared remote-runtime owner registers no model context; provider adapters and consumers own rendered effects.' },
  63. 'packages/util/http-proxy': { kind: 'none', reason: 'Transport policy only: it changes how bytes reach the network and registers no prompt, schema, or result text.' },
  64. 'packages/client/hmr': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  65. 'packages/client/modules': { kind: 'none', reason: 'Browser-side module-loading kernel machinery; registers nothing model-facing.' },
  66. 'packages/test-support/client-runtime': { kind: 'none', reason: 'Browser-side test infrastructure (jsdom bench); registers nothing model-facing.' },
  67. 'packages/experimental/webworker-runtime': { kind: 'none', reason: 'Browser-side host runtime and Node-compatibility layer; the plugins it boots own every model-facing registration.' },
  68. 'packages/experimental/webworker-packer': { kind: 'none', reason: 'Build-time image writer; its output reaches a model only through the tree the worker then boots.' },
  69. 'packages/experimental/inspector': { kind: 'none', reason: 'Developer diagnostics transport; it observes runtime activity without changing model requests.' },
  70. 'packages/client/ui-slots': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  71. 'packages/client/ui-attachment': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  72. 'packages/client/ui-primitives': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  73. 'packages/client/store': { kind: 'none', reason: 'Browser-side state primitives; register nothing model-facing.' },
  74. 'packages/client/ui-renderer': { kind: 'none', reason: 'Browser-side render assembly; registers nothing model-facing.' },
  75. 'packages/client/ui-session': { kind: 'none', reason: 'Browser-side Session adapter; registers nothing model-facing.' },
  76. 'packages/client/connection': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  77. 'packages/client/file-upload': { kind: 'none', reason: 'Browser-side request-body transport; registers nothing model-facing.' },
  78. 'packages/api/remotes': { kind: 'none', reason: 'The Remote BFF selects business methods and forwarded events; selected services own any model-visible effect.' },
  79. 'packages/experimental/agent-team-web-profile': { kind: 'indirect', reason: 'The private Web layer delegates model composition to the Host-side Agent Teams profile.' },
  80. 'packages/experimental/client-ui-agent-team': { kind: 'none', reason: 'The browser projection and task controls register no model-facing input.' },
  81. 'packages/client/ui-layout': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  82. 'packages/client/ui-dockkit': { kind: 'none', reason: 'Browser-side docking layout engine and components; registers nothing model-facing.' },
  83. 'packages/client/ui-sidebar-right': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  84. 'packages/client/ui-sidebar': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  85. 'packages/client/ui-brand-official': { kind: 'none', reason: 'Browser-side presentation occupants; registers nothing model-facing.' },
  86. 'packages/client/ui-conversation': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  87. 'packages/client/ui-approval': { kind: 'none', reason: 'Browser-side approval presentation; registers nothing model-facing.' },
  88. 'packages/client/ui-chat': { kind: 'none', reason: 'Browser-side Chat presentation; registers nothing model-facing.' },
  89. 'packages/client/ui-message-feedback': { kind: 'none', reason: 'Browser-side controls over log-only message feedback; ratings and notes never enter model context or change model-input tokens.' },
  90. 'packages/client/ui-tool': { kind: 'none', reason: 'Browser-side Tool presentation layer; renders logged calls without changing model context.' },
  91. 'packages/client/ui-jobs': { kind: 'none', reason: 'Browser-side read-only projection of ctx.jobs records; dsh-tool-jobs owns the model-facing behavior.' },
  92. 'packages/client/ui-schedule': { kind: 'none', reason: 'Browser-side read-only projection of active Schedule records; dsh-schedule owns the model-facing tools and delivery.' },
  93. 'packages/client/ui-workflow-run': { kind: 'none', reason: 'Browser-side UI plugin layer; renders durable workflow records without changing model context.' },
  94. 'packages/client/ui-input-trigger': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  95. 'packages/client/ui-reference': { kind: 'indirect', reason: 'Browser-side reference selection delegates file guidance and session snapshot preparation to Host-owned providers.' },
  96. 'packages/client/ui-commands': { kind: 'indirect', reason: 'The dispatch paths trigger the host command.execute RPC; each command handler\'s host package owns any model-visible effect.' },
  97. 'packages/client/ui-model-selection': { kind: 'indirect', reason: 'Selection routes session.selectModel; the Host snapshots the selection at the next prompt-assembly boundary and owns the model-visible effect.' },
  98. 'packages/client/ui-goal': { kind: 'indirect', reason: 'The strip verbs route goal.* mutations; the host GoalService owns the model-visible goal/change context message.' },
  99. 'packages/extensions/ui-cordis': { kind: 'indirect', reason: 'The definition card drives the host dynamic run/stop verbs that the model\'s cordis_run/cordis_stop tools also reach; the runner owns any model-visible effect.' },
  100. 'packages/client/ui-permission-presets': { 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.' },
  101. 'packages/client/ui-settings-plugins': { kind: 'none', reason: 'Browser-side settings surface; registers no model surface.' },
  102. '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.' },
  103. 'packages/client/ui-user-questions': { kind: 'indirect', reason: 'The package mounts dsh-tool-ask-user; that tool owns the model-visible schema and answer rendering.' },
  104. 'packages/client/ui-trajectory': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  105. 'packages/client/ui-workspace': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  106. 'packages/client/ui-directory-picker-browse': { kind: 'none', reason: 'Browser-side directory-browsing surface; registers nothing model-facing.' },
  107. 'packages/client/ui-directory-picker-native': { kind: 'none', reason: 'Browser-side surface driving the host OS chooser; registers nothing model-facing.' },
  108. 'packages/client/ui-theme': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  109. 'packages/client/ui-sidebar-documentpreview': { kind: 'none', reason: 'Browser-only text viewer; registers no tool, prompt section, or session event, and what the user reads never enters a model request.' },
  110. 'packages/client/ui-sidebar-files': { kind: 'none', reason: 'Browser-only workspace file tree; registers no tool, prompt section, or session event.' },
  111. 'packages/client/resources': { kind: 'none', reason: 'Browser-side resource model (providers, pinning, useResource); registers nothing model-facing.' },
  112. 'packages/client/ui-settings': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  113. 'packages/client/ui-settings-general': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  114. 'packages/client/ui-settings-models': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  115. 'packages/client/ui-settings-plugin-inventory': { kind: 'none', reason: 'Browser-side inventory projection; registers nothing model-facing.' },
  116. 'packages/client/locale': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  117. 'packages/client/web': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
  118. 'packages/context/file-reference': { kind: 'indirect', reason: 'The discovery seam and grammar delegate model guidance to the composed provider.' },
  119. 'packages/fs/fs': { kind: 'indirect', reason: 'The service interface delegates model rendering to dsh-tool-fs.' },
  120. 'packages/e2b/fs-e2b': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
  121. 'packages/fs/fs-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' },
  122. 'packages/hooks/hook-protocol': { kind: 'indirect', reason: 'Only the hook bridge plugins render decoded hook output to a model.' },
  123. 'packages/host/directory-picker': { kind: 'none', reason: 'The GUI-host picking seam registers nothing model-facing.' },
  124. 'packages/host/directory-picker-auto': { kind: 'none', reason: 'The GUI-host picking chooser only mounts a backend row; it registers nothing model-facing.' },
  125. 'packages/host/directory-picker-browse': { kind: 'none', reason: 'The GUI-host picking backend registers nothing model-facing.' },
  126. 'packages/host/directory-picker-native': { kind: 'none', reason: 'The GUI-host picking backend registers nothing model-facing.' },
  127. 'packages/host/webserver': { kind: 'none', reason: 'The HTTP carrier bridges browser and API handler and registers nothing model-facing.' },
  128. 'packages/webhook/webhook-github': { kind: 'indirect', reason: 'The adapter delegates model-visible text to matching rules and dsh-webhook.' },
  129. 'packages/host/frontend-static': { kind: 'none', reason: 'The SPA dist server answers browser asset requests and registers nothing model-facing.' },
  130. 'packages/host/plugin-inventory': { kind: 'none', reason: 'Host-side read-only Loader projection; registers nothing model-facing.' },
  131. 'packages/host/open-in-app': { kind: 'none', reason: 'Host routes opening desktop applications for a human; registers nothing model-facing.' },
  132. 'packages/client/ui-open-in-app': { kind: 'none', reason: 'Browser-side split button opening the workspace directory for a human; registers nothing model-facing.' },
  133. 'packages/bundle/base': { kind: 'indirect', reason: 'The bundle is a patch-list carrier; each inserted row\'s package owns its model-facing behavior.' },
  134. 'packages/bundle/headless': { kind: 'none', reason: 'The one-shot runner submits the task as an ordinary user message; prompts and tools belong to the composed base and headless bundles.' },
  135. 'packages/llm/llm': { kind: 'none', reason: 'The adapter registry forwards already-assembled requests unchanged.' },
  136. 'packages/llm/token-meter': { kind: 'indirect', reason: 'The measurement service leaves model-visible changes to its consumers.' },
  137. 'packages/lsp/lsp': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-lsp.' },
  138. 'packages/lsp/lsp-stdio': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-lsp.' },
  139. 'packages/subprocess/subprocess': { kind: 'indirect', reason: 'The seam delegates all model rendering to consumer seams such as the bash executor family.' },
  140. 'packages/e2b/subprocess-e2b': { kind: 'indirect', reason: 'The remote spawn backend delegates model rendering to consumer seams such as the bash executor family.' },
  141. 'packages/subprocess/subprocess-local': { kind: 'indirect', reason: 'The spawn backend delegates model rendering to consumer seams such as the bash executor family.' },
  142. 'packages/sandbox/sandbox-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-bash-sandbox and dsh-tool-bash.' },
  143. 'packages/sandbox/sandbox-windows-acl': { kind: 'indirect', reason: 'The provider backend delegates model rendering to the shell/pwsh sandbox executors and their tools.' },
  144. 'packages/sdk/client': { kind: 'none', reason: 'Client-process library; model-facing behavior lives in the spawned runtime\'s composed plugins.' },
  145. 'packages/sdk/protocol': { kind: 'none', reason: 'Client-facing wire library; the runtime plugins behind the serving entry own model-facing behavior.' },
  146. 'packages/session/session-projection': { kind: 'none', reason: 'The projection registry serves client-facing read models of already-logged session state and registers nothing model-facing.' },
  147. 'packages/session/session-projection-cache': { kind: 'none', reason: 'The persisted cache accelerates host-side cold reads of projection state and registers nothing model-facing.' },
  148. 'packages/session/session-stats': { kind: 'none', reason: 'The sessionStats unit folds already-logged step boundaries into a client-facing read model and registers nothing model-facing.' },
  149. 'packages/session/session-turn-outline': { kind: 'none', reason: 'The turnOutline unit folds already-logged turn boundaries into a client-facing read model and registers nothing model-facing.' },
  150. 'packages/session-query/session-query': { kind: 'none', reason: 'The trusted query service exposes cloned records only to callers and registers nothing model-facing.' },
  151. 'packages/session-query/session-query-sqlite': { kind: 'none', reason: 'The search backend returns hits only to callers and registers nothing model-facing.' },
  152. 'packages/settings/settings': { kind: 'indirect', reason: 'The seam stores and resolves user settings; consumer plugins own any model-facing content fed by a value.' },
  153. 'packages/settings/settings-file': { kind: 'indirect', reason: 'The file provider stores and publishes namespace sections; consumers of ctx.settings own any model-facing behavior.' },
  154. 'packages/credentials/credentials': { kind: 'indirect', reason: 'The seam resolves credential references; the consuming adapter owns every model-facing use a value authorizes.' },
  155. 'packages/credentials/credentials-local': { kind: 'indirect', reason: 'The file/environment provider stores credential values; consumers of ctx.credentials own any model-facing behavior.' },
  156. 'packages/credentials/authorization': { kind: 'none', reason: 'A configuration-time conversation with a human; no flow, notice, or prompt reaches a model request.' },
  157. 'packages/util/atomic-write': { kind: 'none', reason: 'Pure filesystem write primitive; registers nothing model-facing.' },
  158. 'packages/session/session-telemetry': { kind: 'none', reason: 'The seam observes the session stream and hands redacted copies outward; it registers nothing model-facing.' },
  159. 'packages/session/session-telemetry-otel': { kind: 'none', reason: 'The backend forwards seam records into the OTel SDK pipeline and registers nothing model-facing.' },
  160. 'packages/identity/anonymous-user-id': { kind: 'none', reason: 'The shared identifier reaches DeepSeek only as model-hidden HTTP metadata; it registers nothing model-facing.' },
  161. 'packages/skill/skill': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-skill.' },
  162. 'packages/skill/skill-badge': { kind: 'indirect', reason: 'The bundled provider delegates model rendering to dsh-tool-skill.' },
  163. 'packages/skill/skill-filesystem': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-skill.' },
  164. 'packages/spill/spill': { kind: 'indirect', reason: 'The storage seam delegates model rendering to spill consumers.' },
  165. 'packages/spill/spill-local': { kind: 'indirect', reason: 'The storage backend delegates model rendering to spill consumers.' },
  166. 'packages/test-support/session-snapshot': { kind: 'none', reason: 'The test harness observes and normalizes transcripts without changing live requests.' },
  167. 'packages/test-support/agent-loop-testkit': { kind: 'none', reason: 'The test helper mounts services but neither drives nor modifies model requests.' },
  168. 'packages/runtime-diagnostics/invariants': { kind: 'none', reason: 'The observer validates requests but never rewrites their context.' },
  169. 'packages/test-support/loader-smoke': { kind: 'none', reason: 'The test harness submits an ordinary user task but delegates prompt and tool composition to the loaded tree.' },
  170. 'packages/test-support/llm-mock-server': { kind: 'none', reason: 'The test server substitutes provider wire behavior without invoking a real model.' },
  171. 'packages/test-support/llm-replay': { kind: 'none', reason: 'The keyless adapter invokes no provider model.' },
  172. 'packages/api/gateway': { kind: 'none', reason: 'Remote dispatch infrastructure; invoked business methods own any model-visible effect.' },
  173. 'packages/api/session-controller': { kind: 'none', reason: 'Session API and transport owner; invoked Agent commands own any model-visible effect.' },
  174. 'packages/api/settings-controller': { kind: 'none', reason: 'Configuration-surface API owner; it registers no prompt, tool, or session event.' },
  175. 'packages/api/workspace-controller': { kind: 'none', reason: 'Workspace API and state projection owner; it registers no prompt, tool, or session event.' },
  176. 'packages/api/workspace-files': { kind: 'none', reason: 'Workspace file read API and its Client resource provider; it registers no prompt, tool, or session event.' },
  177. 'packages/typert/protocol': { kind: 'none', reason: 'Compiler-independent Remote protocol declarations; registers nothing model-facing.' },
  178. 'packages/typert/generator': { kind: 'none', reason: 'The build-time generator runs outside any agent runtime and touches no model request.' },
  179. 'packages/jobs/jobs': { kind: 'indirect', reason: 'Producer and controller plugins own all model rendering over the job registry.' },
  180. 'packages/jobs/jobs-local': { kind: 'indirect', reason: 'The registry backend delegates model rendering to producer plugins and dsh-tool-jobs.' },
  181. 'packages/boot/app-boot': { kind: 'indirect', reason: 'Only the loaded plugin tree contributes model context.' },
  182. 'packages/boot/cmdline': { kind: 'none', reason: 'Resolves the process command line before any session exists; configured rows own every model-visible consequence.' },
  183. 'packages/interaction/permission-presets': { kind: 'indirect', reason: 'The service writes mechanism events rendered by dsh-user-approval and dsh-tool-bash.' },
  184. 'packages/interaction/user-questions': { kind: 'indirect', reason: 'Model-facing consumers render provider answers and seam errors.' },
  185. 'packages/util/timeout': { kind: 'indirect', reason: 'Only timeout consumers render timeout outcomes.' },
  186. 'packages/util/output-retention': { kind: 'indirect', reason: 'Only retention consumers render retained content and omission metadata.' },
  187. 'packages/util/native-command': { kind: 'none', reason: 'The host-side subprocess runner registers nothing model-facing.' },
  188. 'packages/web/web': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-web.' },
  189. 'packages/web/web-fetch-http': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  190. 'packages/web/web-search-exa': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
  191. 'packages/workflow/workflow': { kind: 'indirect', reason: 'The service delegates parent and child model rendering to its consumer and engine.' },
  192. }
  193. interface Failure {
  194. path: string
  195. message: string
  196. }
  197. type Line = MarkdownProseLine
  198. interface ModelExperienceEntry {
  199. heading: Line
  200. modelView: Line
  201. tokenEffect: Line
  202. kvCacheEffect: Line
  203. title: string
  204. modelViewVerbatimBlocks: number
  205. verbatimBlocks: number
  206. }
  207. interface ParsedField {
  208. value: Line
  209. verbatimBlocks: number
  210. }
  211. /** Validate H5-plus-markdown literals nested under one Model Experience field. */
  212. function validateNestedVerbatim(raw: readonly string[], fragments: Set<string>): { blocks: number; error?: string } {
  213. let cursor = 0
  214. while (raw[cursor]?.trim().length === 0) cursor += 1
  215. if (cursor === raw.length) return { blocks: 0 }
  216. let blocks = 0
  217. while (true) {
  218. while (raw[cursor]?.trim().length === 0) cursor += 1
  219. if (cursor === raw.length) break
  220. if (!/^##### \S/.test(raw[cursor] ?? '')) {
  221. return { blocks, error: 'content after a field paragraph must be a titled H5 verbatim block' }
  222. }
  223. const title = (raw[cursor] as string).slice('##### '.length)
  224. const fragment = headingFragment(title)
  225. if (fragment.length === 0) return { blocks, error: 'verbatim H5 title must be non-empty' }
  226. if (fragments.has(fragment)) {
  227. return { blocks, error: `verbatim H5 title ${JSON.stringify(title)} is duplicated within its model-context entry` }
  228. }
  229. fragments.add(fragment)
  230. cursor += 1
  231. while (raw[cursor]?.trim().length === 0) cursor += 1
  232. if (raw[cursor] !== '```markdown') {
  233. return { blocks, error: 'each nested verbatim H5 requires an exact ```markdown fence' }
  234. }
  235. cursor += 1
  236. const contentStart = cursor
  237. while (cursor < raw.length && raw[cursor] !== '```') cursor += 1
  238. if (cursor === raw.length) return { blocks, error: 'unterminated nested ```markdown fence' }
  239. if (cursor === contentStart) return { blocks, error: 'nested ```markdown fence must not be empty' }
  240. cursor += 1
  241. blocks += 1
  242. }
  243. return { blocks }
  244. }
  245. /** GitHub-style fragment for the simple ASCII nested titles allowed by these rules. */
  246. function headingFragment(title: string): string {
  247. return title.toLowerCase().replaceAll('`', '').replaceAll(/[^a-z0-9 _-]/g, '').trim().replaceAll(/\s+/g, '-')
  248. }
  249. /** A direct stable system-prompt contribution, as named by the README rules. */
  250. function isDirectSystemPromptEntry(title: string): boolean {
  251. return /\bsystem prompt\b/i.test(title)
  252. }
  253. /** Anchored generated-catalog links in one model-view field. */
  254. function toolCatalogLinkFragments(text: string): string[] {
  255. return [...text.matchAll(/\]\(\.\.\/\.\.\/\.\.\/docs\/tool-catalog\.md#([a-z0-9_-]+)\)/g)]
  256. .map(match => match[1] as string)
  257. }
  258. const toolCatalogFragments = new Set<string>()
  259. for (const line of readFileSync(resolve(root, 'docs/tool-catalog.md'), 'utf8').split('\n')) {
  260. const title = /^## (.+)$/.exec(line)?.[1]
  261. if (title !== undefined) toolCatalogFragments.add(headingFragment(title))
  262. }
  263. const failures: Failure[] = []
  264. const packageJsons = globSync('packages/*/*/package.json', { cwd: root }).map(path => path.split(sep).join('/')).sort()
  265. const scannedPackages = new Set(packageJsons.map(path => path.slice(0, -'/package.json'.length)))
  266. let structuredCount = 0
  267. let modelContextEntryCount = 0
  268. let omittedSectionCount = 0
  269. let explainedNoneCount = 0
  270. let indirectCount = 0
  271. let verbatimBlockCount = 0
  272. let systemPromptEntryCount = 0
  273. let toolSchemaEntryCount = 0
  274. let kvCacheEffectCount = 0
  275. for (const [pkg, reason] of Object.entries(NO_MODEL_EXPERIENCE_SECTION)) {
  276. if (!scannedPackages.has(pkg)) {
  277. failures.push({ path: `${pkg}/README.md`, message: 'no-section allowlist entry does not name a scanned package' })
  278. }
  279. if (reason.trim().length === 0) {
  280. failures.push({ path: `${pkg}/README.md`, message: 'no-section allowlist entry must retain its audit justification' })
  281. }
  282. if (SENTENCE_MODEL_EXPERIENCE[pkg] !== undefined) {
  283. failures.push({ path: `${pkg}/README.md`, message: 'package cannot appear in both Model Experience allowlists' })
  284. }
  285. }
  286. for (const [pkg, contract] of Object.entries(SENTENCE_MODEL_EXPERIENCE)) {
  287. if (!scannedPackages.has(pkg)) {
  288. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry does not name a scanned package' })
  289. }
  290. if (contract.reason.trim().length === 0) {
  291. failures.push({ path: `${pkg}/README.md`, message: 'sentence allowlist entry must justify why structured model-context entries are unnecessary' })
  292. }
  293. }
  294. for (const packageJson of packageJsons) {
  295. const pkg = packageJson.slice(0, -'/package.json'.length)
  296. const readme = packageJson.replace(/package\.json$/, 'README.md')
  297. const abs = resolve(root, readme)
  298. if (!existsSync(abs)) {
  299. failures.push({ path: readme, message: 'missing package README' })
  300. continue
  301. }
  302. const text = readFileSync(abs, 'utf8')
  303. const rawLines = text.split('\n')
  304. const lines = markdownProseLines(text)
  305. const headings = markdownHeadingLines(text)
  306. const h2Headings = headings.filter(heading => heading.depth === 2)
  307. const modelExperienceHeadings = headings.filter(heading => heading.text
  308. .trim().replaceAll(/\s+/g, ' ').toLowerCase() === 'model experience')
  309. const modelHeadings = modelExperienceHeadings.filter(heading => heading.depth === 2 && heading.raw === HEADING)
  310. if (NO_MODEL_EXPERIENCE_SECTION[pkg] !== undefined) {
  311. if (modelExperienceHeadings.length !== 0) {
  312. for (const heading of modelExperienceHeadings) {
  313. failures.push({ path: readme, message: `line ${heading.index}: audited model-agnostic package must omit every Model Experience heading; found ${JSON.stringify(heading.raw)}` })
  314. }
  315. } else {
  316. omittedSectionCount += 1
  317. }
  318. continue
  319. }
  320. const nonCanonicalModelHeading = modelExperienceHeadings.find(heading => heading.depth !== 2 || heading.raw !== HEADING)
  321. if (nonCanonicalModelHeading !== undefined) {
  322. failures.push({ path: readme, message: `line ${nonCanonicalModelHeading.index}: non-canonical Model Experience heading ${JSON.stringify(nonCanonicalModelHeading.raw)}; use exactly ${JSON.stringify(HEADING)}` })
  323. continue
  324. }
  325. const modelHeading = modelHeadings.at(0)
  326. if (modelHeading === undefined) {
  327. failures.push({
  328. path: readme,
  329. message: `missing ${HEADING}`,
  330. })
  331. continue
  332. }
  333. if (modelHeadings.length !== 1) {
  334. failures.push({ path: readme, message: `contains ${modelHeadings.length} copies of ${HEADING}` })
  335. continue
  336. }
  337. const modelH2Index = h2Headings.indexOf(modelHeading)
  338. const limitationsH2Index = h2Headings.findIndex(heading => heading.depth === 2 && heading.raw === LIMITATIONS_HEADING)
  339. if (limitationsH2Index >= 0) {
  340. if (modelH2Index !== h2Headings.length - 2 || limitationsH2Index !== h2Headings.length - 1) {
  341. failures.push({
  342. path: readme,
  343. message: `${HEADING} and ${LIMITATIONS_HEADING} must be the final two H2 sections, in that order`,
  344. })
  345. continue
  346. }
  347. } else if (modelH2Index !== h2Headings.length - 1) {
  348. failures.push({ path: readme, message: `${HEADING} must be the final H2 when ${LIMITATIONS_HEADING} is absent` })
  349. continue
  350. }
  351. const modelHeadingAt = lines.findIndex(line => line.index === modelHeading.index)
  352. const body = lines.slice(modelHeadingAt + 1)
  353. const h2Lines = new Set(h2Headings.map(heading => heading.index))
  354. const nextH2 = body.findIndex(line => h2Lines.has(line.index))
  355. const section = nextH2 < 0 ? body : body.slice(0, nextH2)
  356. const nextH2Line = nextH2 < 0 ? rawLines.length + 1 : (body[nextH2] as Line).index
  357. const rawSection = rawLines.slice(modelHeading.index, nextH2Line - 1)
  358. const content = section.filter(line => line.raw.trim().length > 0)
  359. const sentenceContract = SENTENCE_MODEL_EXPERIENCE[pkg]
  360. if (sentenceContract !== undefined) {
  361. const pattern = sentenceContract.kind === 'none' ? /^None, as .+\.$/ : /^Indirectly, through .+\.$/
  362. const rawContent = rawSection.filter(line => line.trim().length > 0)
  363. const sentence = content[0]
  364. const kvCacheHeading = content[1]
  365. const kvCacheEffect = content[2]
  366. if (content.length !== 3 || rawContent.length !== 3 || !pattern.test(sentence?.raw ?? '')) {
  367. const prefix = sentenceContract.kind === 'none' ? 'None, as ' : 'Indirectly, through '
  368. 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` })
  369. continue
  370. }
  371. if (kvCacheHeading?.raw !== KV_CACHE_EFFECT_HEADING
  372. || kvCacheEffect === undefined
  373. || /^#{1,6} /.test(kvCacheEffect.raw)
  374. || kvCacheEffect.raw.trim().length === 0) {
  375. 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` })
  376. continue
  377. }
  378. if (sentence === undefined
  379. || sentence.index !== modelHeading.index + 2
  380. || kvCacheHeading.index !== sentence.index + 2
  381. || kvCacheEffect.index !== kvCacheHeading.index + 2) {
  382. failures.push({ path: readme, message: 'short Model Experience sentence, KV-cache H4, and paragraph require one blank line between each element' })
  383. continue
  384. }
  385. if (sentenceContract.kind === 'none') explainedNoneCount += 1
  386. else indirectCount += 1
  387. kvCacheEffectCount += 1
  388. continue
  389. }
  390. const shortSentence = content.find(line => line.raw === 'None.' || /^None, as |^Indirectly, through /.test(line.raw))
  391. if (shortSentence !== undefined) {
  392. failures.push({ path: readme, message: `line ${shortSentence.index}: short Model Experience form requires an audited entry in SENTENCE_MODEL_EXPERIENCE` })
  393. continue
  394. }
  395. const entryStarts = content
  396. .map((line, index) => ({ line, index }))
  397. .filter(entry => /^### \S/.test(entry.line.raw))
  398. if (entryStarts.length === 0 || entryStarts[0]?.index !== 0) {
  399. failures.push({ path: readme, message: 'must contain one or more complete model-context entries' })
  400. continue
  401. }
  402. const modelContextEntries: ModelExperienceEntry[] = []
  403. const entryFragments = new Set<string>()
  404. let entryError = false
  405. for (let entryIndex = 0; entryIndex < entryStarts.length; entryIndex += 1) {
  406. const start = entryStarts[entryIndex] as { line: Line; index: number }
  407. const end = entryStarts[entryIndex + 1]?.index ?? content.length
  408. const entries = content.slice(start.index, end)
  409. const heading = entries[0] as Line
  410. const title = heading.raw.slice('### '.length)
  411. const fragment = headingFragment(title)
  412. if (fragment.length === 0) {
  413. failures.push({ path: readme, message: `line ${heading.index}: each model-context entry requires a non-empty H3 heading` })
  414. entryError = true
  415. break
  416. }
  417. if (entryFragments.has(fragment)) {
  418. failures.push({ path: readme, message: `line ${heading.index}: duplicate model-context entry link fragment ${JSON.stringify(fragment)}` })
  419. entryError = true
  420. break
  421. }
  422. const fieldStarts = entries
  423. .map((line, index) => ({ line, index }))
  424. .filter(entry => /^#### \S/.test(entry.line.raw))
  425. if (fieldStarts.length !== FIELD_HEADINGS.length || fieldStarts[0]?.index !== 1) {
  426. failures.push({ path: readme, message: `line ${heading.index}: model-context entry requires exactly three ordered H4 fields: ${FIELD_HEADINGS.join(', ')}` })
  427. entryError = true
  428. break
  429. }
  430. if ((entryIndex === 0 && heading.index !== modelHeading.index + 2)
  431. || rawLines[heading.index - 2]?.trim().length !== 0
  432. || fieldStarts[0].line.index !== heading.index + 2) {
  433. failures.push({ path: readme, message: `line ${heading.index}: model-context entry heading and first field require one blank line between them` })
  434. entryError = true
  435. break
  436. }
  437. const parsedFields: ParsedField[] = []
  438. const verbatimFragments = new Set<string>()
  439. for (let fieldIndex = 0; fieldIndex < FIELD_HEADINGS.length; fieldIndex += 1) {
  440. const fieldStart = fieldStarts[fieldIndex] as { line: Line; index: number }
  441. const expectedHeading = FIELD_HEADINGS[fieldIndex] as string
  442. if (fieldStart.line.raw !== expectedHeading) {
  443. failures.push({ path: readme, message: `line ${fieldStart.line.index}: expected exact field heading ${JSON.stringify(expectedHeading)}, found ${JSON.stringify(fieldStart.line.raw)}` })
  444. entryError = true
  445. break
  446. }
  447. const fieldEnd = fieldStarts[fieldIndex + 1]?.index ?? entries.length
  448. const fieldEntries = entries.slice(fieldStart.index, fieldEnd)
  449. const value = fieldEntries[1]
  450. if (value === undefined || /^#{1,6} /.test(value.raw) || value.raw.trim().length === 0) {
  451. failures.push({ path: readme, message: `line ${fieldStart.line.index}: ${expectedHeading} requires one non-empty paragraph` })
  452. entryError = true
  453. break
  454. }
  455. if (value.index !== fieldStart.line.index + 2) {
  456. failures.push({ path: readme, message: `line ${fieldStart.line.index}: ${expectedHeading} and its paragraph require one blank line between them` })
  457. entryError = true
  458. break
  459. }
  460. const unexpected = fieldEntries.slice(2).find(line => !/^##### \S/.test(line.raw))
  461. if (unexpected !== undefined) {
  462. failures.push({ path: readme, message: `line ${unexpected.index}: content after ${expectedHeading} paragraph must be a titled H5 plus \`markdown\` fence owned by that field` })
  463. entryError = true
  464. break
  465. }
  466. const nextHeadingLine = fieldStarts[fieldIndex + 1]?.line.index
  467. ?? entryStarts[entryIndex + 1]?.line.index
  468. ?? nextH2Line
  469. if (rawLines[nextHeadingLine - 2]?.trim().length !== 0) {
  470. failures.push({ path: readme, message: `line ${nextHeadingLine}: Model Experience headings require a preceding blank line` })
  471. entryError = true
  472. break
  473. }
  474. const verbatim = validateNestedVerbatim(rawLines.slice(value.index, nextHeadingLine - 1), verbatimFragments)
  475. if (verbatim.error !== undefined) {
  476. failures.push({ path: readme, message: `line ${value.index}: ${verbatim.error}` })
  477. entryError = true
  478. break
  479. }
  480. if (fieldEntries.length - 2 !== verbatim.blocks) {
  481. failures.push({ path: readme, message: `line ${value.index}: every nested H5 must own exactly one \`markdown\` fence` })
  482. entryError = true
  483. break
  484. }
  485. parsedFields.push({ value, verbatimBlocks: verbatim.blocks })
  486. }
  487. if (entryError) break
  488. const modelViewField = parsedFields[0] as ParsedField
  489. const tokenEffectField = parsedFields[1] as ParsedField
  490. const kvCacheEffectField = parsedFields[2] as ParsedField
  491. const modelView = modelViewField.value
  492. const tokenEffect = tokenEffectField.value
  493. const kvCacheEffect = kvCacheEffectField.value
  494. if (/\]\(#[^)]+\)/.test(modelView.raw) || /\]\(#[^)]+\)/.test(tokenEffect.raw) || /\]\(#[^)]+\)/.test(kvCacheEffect.raw)) {
  495. 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` })
  496. entryError = true
  497. break
  498. }
  499. entryFragments.add(fragment)
  500. modelContextEntries.push({
  501. heading,
  502. modelView,
  503. tokenEffect,
  504. kvCacheEffect,
  505. title,
  506. modelViewVerbatimBlocks: modelViewField.verbatimBlocks,
  507. verbatimBlocks: parsedFields.reduce((total, field) => total + field.verbatimBlocks, 0),
  508. })
  509. }
  510. if (entryError) continue
  511. const promptWithoutVerbatim = modelContextEntries.find(entry => isDirectSystemPromptEntry(entry.title)
  512. && entry.modelViewVerbatimBlocks === 0)
  513. if (promptWithoutVerbatim !== undefined) {
  514. failures.push({ path: readme, message: `line ${promptWithoutVerbatim.heading.index}: system-prompt entry must contain a titled H5 plus verbatim \`markdown\` block under ${MODEL_VIEW_HEADING}` })
  515. continue
  516. }
  517. const hasConcreteLiteral = modelContextEntries.some(entry => entry.verbatimBlocks > 0
  518. || entry.modelView.raw.includes('`')
  519. || entry.tokenEffect.raw.includes('`')
  520. || toolCatalogLinkFragments(entry.modelView.raw).length > 0)
  521. if (!hasConcreteLiteral) {
  522. failures.push({ path: readme, message: 'structured Model Experience must ground at least one entry with inline code, a nested `markdown` block, or an anchored tool-catalog link' })
  523. continue
  524. }
  525. let catalogError = false
  526. for (const entry of modelContextEntries) {
  527. if (!/\bschemas?\b/i.test(entry.title)) continue
  528. const fragments = toolCatalogLinkFragments(entry.modelView.raw)
  529. if (fragments.length === 0) {
  530. failures.push({ path: readme, message: `line ${entry.heading.index}: tool-schema entry must link an anchored section of ../../../docs/tool-catalog.md` })
  531. catalogError = true
  532. break
  533. }
  534. const invalid = fragments.find(fragment => !toolCatalogFragments.has(fragment))
  535. if (invalid !== undefined) {
  536. failures.push({ path: readme, message: `line ${entry.modelView.index}: tool-catalog link fragment ${JSON.stringify(invalid)} does not name an H2 section` })
  537. catalogError = true
  538. break
  539. }
  540. }
  541. if (catalogError) continue
  542. verbatimBlockCount += modelContextEntries.reduce((total, entry) => total + entry.verbatimBlocks, 0)
  543. modelContextEntryCount += modelContextEntries.length
  544. systemPromptEntryCount += modelContextEntries.filter(entry => isDirectSystemPromptEntry(entry.title)).length
  545. toolSchemaEntryCount += modelContextEntries.filter(entry => /\bschemas?\b/i.test(entry.title)).length
  546. kvCacheEffectCount += modelContextEntries.length
  547. structuredCount += 1
  548. }
  549. if (failures.length === 0) {
  550. console.log(`verify-package-readme-model-experience: ${packageJsons.length} README(s) checked (${omittedSectionCount} audited omissions, ${structuredCount} structured, ${modelContextEntryCount} model-context entries, ${kvCacheEffectCount} KV-cache fields, ${systemPromptEntryCount} fenced system-prompt entries, ${toolSchemaEntryCount} catalog-linked tool-schema entries, ${explainedNoneCount} explained none, ${indirectCount} indirect, ${verbatimBlockCount} verbatim markdown blocks), all conform.`)
  551. process.exit(0)
  552. }
  553. console.error('verify-package-readme-model-experience failed:')
  554. for (const failure of failures) {
  555. console.error(` ${relative(root, resolve(root, failure.path))}: ${failure.message}`)
  556. }
  557. process.exit(1)