gen-module-graph.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. 'skill',
  42. 'compact',
  43. 'subagent',
  44. 'web',
  45. 'timeout',
  46. 'todo',
  47. 'cordis',
  48. 'hooks',
  49. 'session-persistence',
  50. 'support',
  51. 'ui',
  52. ]
  53. /** Read every workspace package and its `@deepseek-ai/dsh-*` peer edges. */
  54. function collect(): Pkg[] {
  55. const pkgs: Pkg[] = []
  56. for (const rel of globSync('packages/*/*/package.json', { cwd: root })) {
  57. const json = JSON.parse(readFileSync(resolve(root, rel), 'utf8')) as {
  58. name: string
  59. peerDependencies?: Record<string, string>
  60. }
  61. if (!json.name.startsWith(SCOPE)) continue
  62. const deps = Object.keys(json.peerDependencies ?? {})
  63. .filter(d => d.startsWith(SCOPE))
  64. .map(d => d.slice(SCOPE.length))
  65. .sort()
  66. const [, group, leaf] = rel.split('/')
  67. if (group === undefined || leaf === undefined) throw new Error(`gen-module-graph: unexpected package path ${rel}`)
  68. pkgs.push({ short: json.name.slice(SCOPE.length), group, rel: dirname(rel), deps })
  69. }
  70. return topoSort(pkgs)
  71. }
  72. /**
  73. * Order packages low-level → high-level: a package appears only after every
  74. * package it depends on. Kahn-style layering with an alphabetical tiebreak
  75. * within each layer, so the output stays deterministic (the freshness check
  76. * compares whole-file). The graph is a DAG, so this always terminates; a cycle
  77. * would leave nodes unplaced and throw.
  78. */
  79. function topoSort(pkgs: Pkg[]): Pkg[] {
  80. const remaining = new Map(pkgs.map(p => [p.short, p]))
  81. const placed = new Set<string>()
  82. const out: Pkg[] = []
  83. while (remaining.size > 0) {
  84. const ready = [...remaining.values()]
  85. .filter(p => p.deps.every(d => placed.has(d)))
  86. .sort(comparePackages)
  87. if (ready.length === 0) throw new Error(`gen-module-graph: dependency cycle among ${[...remaining.keys()].join(', ')}`)
  88. for (const p of ready) {
  89. out.push(p)
  90. placed.add(p.short)
  91. remaining.delete(p.short)
  92. }
  93. }
  94. return out
  95. }
  96. function comparePackages(a: Pkg, b: Pkg): number {
  97. const groupA = GROUP_ORDER.indexOf(a.group)
  98. const groupB = GROUP_ORDER.indexOf(b.group)
  99. const normA = groupA === -1 ? Number.MAX_SAFE_INTEGER : groupA
  100. const normB = groupB === -1 ? Number.MAX_SAFE_INTEGER : groupB
  101. return normA - normB || a.group.localeCompare(b.group) || a.short.localeCompare(b.short)
  102. }
  103. function nodeId(prefix: string, value: string): string {
  104. return `${prefix}_${value.replace(/[^a-zA-Z0-9_]/g, '_')}`
  105. }
  106. function escLabel(value: string): string {
  107. return value.replace(/"/g, '\\"')
  108. }
  109. function packageLink(pkg: Pkg): string {
  110. return `[\`${pkg.short}\`](../${pkg.rel})`
  111. }
  112. /** Render the full docs/module-graph.md content (pure, deterministic). */
  113. function render(pkgs: Pkg[]): string {
  114. const edges: string[] = []
  115. for (const p of pkgs) {
  116. for (const d of p.deps) edges.push(` ${nodeId('pkg', p.short)} --> ${nodeId('pkg', d)}`)
  117. }
  118. const byShort = new Map(pkgs.map(pkg => [pkg.short, pkg]))
  119. const groups = [...new Set(pkgs.map(pkg => pkg.group))].sort((a, b) => {
  120. const ia = GROUP_ORDER.indexOf(a)
  121. const ib = GROUP_ORDER.indexOf(b)
  122. const na = ia === -1 ? Number.MAX_SAFE_INTEGER : ia
  123. const nb = ib === -1 ? Number.MAX_SAFE_INTEGER : ib
  124. return na - nb || a.localeCompare(b)
  125. })
  126. const groupBlocks: string[] = []
  127. for (const group of groups) {
  128. groupBlocks.push(` subgraph ${nodeId('group', group)}["packages/${escLabel(group)}"]`)
  129. for (const pkg of pkgs.filter(p => p.group === group).sort((a, b) => a.short.localeCompare(b.short))) {
  130. groupBlocks.push(` ${nodeId('pkg', pkg.short)}["${escLabel(pkg.short)}"]`)
  131. }
  132. groupBlocks.push(' end')
  133. }
  134. const rows = pkgs.map((p) => {
  135. const deps = p.deps.length ? p.deps.map((d) => {
  136. const dep = byShort.get(d)
  137. return dep ? packageLink(dep) : `\`${d}\``
  138. }).join(', ') : '—'
  139. return `| ${packageLink(p)} | \`${p.group}\` | ${deps} |`
  140. })
  141. return [
  142. '<!-- Generated by scripts/gen-module-graph.ts — do not edit by hand.',
  143. ' Run `pnpm run gen-module-graph` to regenerate. -->',
  144. '',
  145. '# Module dependency graph',
  146. '',
  147. '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.',
  148. '',
  149. '```mermaid',
  150. 'flowchart TD',
  151. ...groupBlocks,
  152. ...edges,
  153. '```',
  154. '',
  155. '| Package | Group | Depends on |',
  156. '| --- | --- | --- |',
  157. ...rows,
  158. '',
  159. ].join('\n')
  160. }
  161. const content = render(collect())
  162. if (process.argv.includes('--check')) {
  163. let committed: string | null = null
  164. try {
  165. committed = readFileSync(resolve(root, OUT), 'utf8')
  166. } catch {
  167. // Only an ENOENT (file not yet generated) is expected here; readFileSync of
  168. // a present-but-unreadable file is not a state this repo produces. Either
  169. // way the remedy is the same — regenerate — so we treat a read failure as
  170. // "stale" and fall through to the failure branch below.
  171. committed = null
  172. }
  173. if (committed === content) {
  174. console.log(`gen-module-graph: ${OUT} is up to date.`)
  175. process.exit(0)
  176. }
  177. console.error(`gen-module-graph: ${OUT} is stale. Run \`pnpm run gen-module-graph\` and commit ${OUT}.`)
  178. process.exit(1)
  179. }
  180. writeFileSync(resolve(root, OUT), content)
  181. console.log(`gen-module-graph: wrote ${OUT}.`)