gen-module-graph.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. /**
  2. * Generate (and verify) the module dependency graph in docs/module-graph.md.
  3. *
  4. * The architectural shape of the harness lives implicitly in each package's
  5. * `peerDependencies` — the canonical runtime-dependency signal (devDeps mirror
  6. * these as `workspace:^` plus test-only extras, which would add noise). This
  7. * script reads every `packages/* /* /package.json`, keeps only the
  8. * `@deepseek-ai/dsh-*` peer edges (dropping the `cordis` peer), and renders a
  9. * GitHub-viewable Mermaid graph grouped by `packages/<group>/` plus a
  10. * dependency table.
  11. *
  12. * The file is fully generated — never hand-edit it. Output is deterministic
  13. * (packages and edges sorted) so a regenerate-and-diff freshness check is
  14. * stable.
  15. *
  16. * `tsx scripts/gen-module-graph.ts` → write docs/module-graph.md
  17. * `tsx scripts/gen-module-graph.ts --check` → exit 1 if the committed file
  18. * is stale (CI / pre-push gate)
  19. */
  20. import { dirname, resolve } from 'node:path'
  21. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  22. const root = resolve(import.meta.dirname, '..')
  23. const OUT = 'docs/module-graph.md'
  24. const SCOPE = '@deepseek-ai/dsh-'
  25. interface Pkg {
  26. /** Short name, `@deepseek-ai/dsh-` prefix stripped (e.g. `agent-loop`). */
  27. short: string
  28. /** Package group from `packages/<group>/<pkg>`. */
  29. group: string
  30. /** Repo-relative package directory. */
  31. rel: string
  32. /** Short names of this package's in-repo peer dependencies, sorted. */
  33. deps: string[]
  34. }
  35. const GROUP_ORDER = [
  36. 'util',
  37. 'llm',
  38. 'core',
  39. 'bash',
  40. 'fs',
  41. 'compact',
  42. 'subagent',
  43. 'web',
  44. 'timeout',
  45. 'todo',
  46. 'cordis',
  47. 'hooks',
  48. 'session-persistence',
  49. 'support',
  50. 'ui',
  51. ]
  52. /** Read every workspace package and its `@deepseek-ai/dsh-*` peer edges. */
  53. function collect(): Pkg[] {
  54. const pkgs: Pkg[] = []
  55. for (const rel of globSync('packages/*/*/package.json', { cwd: root })) {
  56. const json = JSON.parse(readFileSync(resolve(root, rel), 'utf8')) as {
  57. name: string
  58. peerDependencies?: Record<string, string>
  59. }
  60. if (!json.name.startsWith(SCOPE)) continue
  61. const deps = Object.keys(json.peerDependencies ?? {})
  62. .filter(d => d.startsWith(SCOPE))
  63. .map(d => d.slice(SCOPE.length))
  64. .sort()
  65. const [, group, leaf] = rel.split('/')
  66. if (group === undefined || leaf === undefined) throw new Error(`gen-module-graph: unexpected package path ${rel}`)
  67. pkgs.push({ short: json.name.slice(SCOPE.length), group, rel: dirname(rel), deps })
  68. }
  69. return topoSort(pkgs)
  70. }
  71. /**
  72. * Order packages low-level → high-level: a package appears only after every
  73. * package it depends on. Kahn-style layering with an alphabetical tiebreak
  74. * within each layer, so the output stays deterministic (the freshness check
  75. * compares whole-file). The graph is a DAG, so this always terminates; a cycle
  76. * would leave nodes unplaced and throw.
  77. */
  78. function topoSort(pkgs: Pkg[]): Pkg[] {
  79. const remaining = new Map(pkgs.map(p => [p.short, p]))
  80. const placed = new Set<string>()
  81. const out: Pkg[] = []
  82. while (remaining.size > 0) {
  83. const ready = [...remaining.values()]
  84. .filter(p => p.deps.every(d => placed.has(d)))
  85. .sort(comparePackages)
  86. if (ready.length === 0) throw new Error(`gen-module-graph: dependency cycle among ${[...remaining.keys()].join(', ')}`)
  87. for (const p of ready) {
  88. out.push(p)
  89. placed.add(p.short)
  90. remaining.delete(p.short)
  91. }
  92. }
  93. return out
  94. }
  95. function comparePackages(a: Pkg, b: Pkg): number {
  96. const groupA = GROUP_ORDER.indexOf(a.group)
  97. const groupB = GROUP_ORDER.indexOf(b.group)
  98. const normA = groupA === -1 ? Number.MAX_SAFE_INTEGER : groupA
  99. const normB = groupB === -1 ? Number.MAX_SAFE_INTEGER : groupB
  100. return normA - normB || a.group.localeCompare(b.group) || a.short.localeCompare(b.short)
  101. }
  102. function nodeId(prefix: string, value: string): string {
  103. return `${prefix}_${value.replace(/[^a-zA-Z0-9_]/g, '_')}`
  104. }
  105. function escLabel(value: string): string {
  106. return value.replace(/"/g, '\\"')
  107. }
  108. function packageLink(pkg: Pkg): string {
  109. return `[\`${pkg.short}\`](../${pkg.rel})`
  110. }
  111. /** Render the full docs/module-graph.md content (pure, deterministic). */
  112. function render(pkgs: Pkg[]): string {
  113. const edges: string[] = []
  114. for (const p of pkgs) {
  115. for (const d of p.deps) edges.push(` ${nodeId('pkg', p.short)} --> ${nodeId('pkg', d)}`)
  116. }
  117. const byShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  118. const groups = [...new Set(pkgs.map(pkg => pkg.group))].sort((a, b) => {
  119. const ia = GROUP_ORDER.indexOf(a)
  120. const ib = GROUP_ORDER.indexOf(b)
  121. const na = ia === -1 ? Number.MAX_SAFE_INTEGER : ia
  122. const nb = ib === -1 ? Number.MAX_SAFE_INTEGER : ib
  123. return na - nb || a.localeCompare(b)
  124. })
  125. const groupBlocks: string[] = []
  126. for (const group of groups) {
  127. groupBlocks.push(` subgraph ${nodeId('group', group)}["packages/${escLabel(group)}"]`)
  128. for (const pkg of pkgs.filter(p => p.group === group).sort((a, b) => a.short.localeCompare(b.short))) {
  129. groupBlocks.push(` ${nodeId('pkg', pkg.short)}["${escLabel(pkg.short)}"]`)
  130. }
  131. groupBlocks.push(' end')
  132. }
  133. const rows = pkgs.map((p) => {
  134. const deps = p.deps.length ? p.deps.map((d) => {
  135. const dep = byShort.get(d)
  136. return dep ? packageLink(dep) : `\`${d}\``
  137. }).join(', ') : '—'
  138. return `| ${packageLink(p)} | \`${p.group}\` | ${deps} |`
  139. })
  140. return [
  141. '<!-- Generated by scripts/gen-module-graph.ts — do not edit by hand.',
  142. ' Run `pnpm run gen-module-graph` to regenerate. -->',
  143. '',
  144. '# Module dependency graph',
  145. '',
  146. 'Inter-package dependencies among the `@deepseek-ai/dsh-*` harness packages, derived from each package\'s `peerDependencies` (the canonical runtime-dependency signal) and grouped by the `packages/<group>/<pkg>` hierarchy. An edge `a --> b` means package `a` depends on package `b`. Names have the `@deepseek-ai/dsh-` prefix stripped.',
  147. '',
  148. '```mermaid',
  149. 'flowchart TD',
  150. ...groupBlocks,
  151. ...edges,
  152. '```',
  153. '',
  154. '| Package | Group | Depends on |',
  155. '| --- | --- | --- |',
  156. ...rows,
  157. '',
  158. ].join('\n')
  159. }
  160. const content = render(collect())
  161. if (process.argv.includes('--check')) {
  162. let committed: string | null = null
  163. try {
  164. committed = readFileSync(resolve(root, OUT), 'utf8')
  165. } catch {
  166. // Only an ENOENT (file not yet generated) is expected here; readFileSync of
  167. // a present-but-unreadable file is not a state this repo produces. Either
  168. // way the remedy is the same — regenerate — so we treat a read failure as
  169. // "stale" and fall through to the failure branch below.
  170. committed = null
  171. }
  172. if (committed === content) {
  173. console.log(`gen-module-graph: ${OUT} is up to date.`)
  174. process.exit(0)
  175. }
  176. console.error(`gen-module-graph: ${OUT} is stale. Run \`pnpm run gen-module-graph\` and commit ${OUT}.`)
  177. process.exit(1)
  178. }
  179. writeFileSync(resolve(root, OUT), content)
  180. console.log(`gen-module-graph: wrote ${OUT}.`)