check-workspace-constraints.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. /**
  2. * Workspace package invariant checks for package-manager-independent quality
  3. * gates.
  4. *
  5. * Run: `tsx scripts/check-workspace-constraints.ts`.
  6. */
  7. import { existsSync, readdirSync, readFileSync } from 'node:fs'
  8. import { join, relative, resolve } from 'node:path'
  9. import { hasTypeRTRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
  10. import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts'
  11. const root = resolve(import.meta.dirname, '..')
  12. // vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
  13. // (the group dirs — core/llm/bash/… — are pure containers with no manifest).
  14. const workspaceGlobs = [
  15. { dir: 'vendor', depth: 1 },
  16. { dir: 'packages', depth: 2 },
  17. { dir: 'native', depth: 1 },
  18. { dir: 'native/landlock-run/packages', depth: 1 },
  19. { dir: 'apps', depth: 1 },
  20. ] as const
  21. const vendoredPackages = new Set([
  22. '@deepseek-ai/cordis',
  23. '@deepseek-ai/cosmokit',
  24. '@deepseek-ai/schemastery',
  25. '@deepseek-ai/cordis-plugin-loader',
  26. '@deepseek-ai/cordis-plugin-include',
  27. '@deepseek-ai/cordis-plugin-group',
  28. '@deepseek-ai/cordis-plugin-timer',
  29. '@deepseek-ai/cordis-plugin-hmr',
  30. '@deepseek-ai/cordis-plugin-logger-console',
  31. ])
  32. const publicLandlockPackages = new Set([
  33. '@deepseek-ai/node-addon-landlock-run',
  34. '@deepseek-ai/node-addon-landlock-run-linux-arm64',
  35. '@deepseek-ai/node-addon-landlock-run-linux-x64',
  36. ])
  37. /** Deliberate source payloads whose exact bytes are part of the package's audit surface. */
  38. const publicationSourceAllowlist: Readonly<Record<string, readonly string[]>> = {
  39. '@deepseek-ai/node-addon-landlock-run': ['src/main.c'],
  40. }
  41. const repositoryUrl = 'git+https://github.com/deepseek-harness/deepseek-harness.git'
  42. const localArtifactDirs = new Set(['node_modules'])
  43. const appPackageFiles: Readonly<Record<string, readonly string[]>> = {
  44. '@deepseek-ai/dsh': ['lib/*.js', 'config'],
  45. '@deepseek-ai/dsh-frontend': ['dist'],
  46. }
  47. /** The subset of package.json fields this constraint check cares about. */
  48. interface PackageManifest {
  49. name?: string
  50. version?: string
  51. private?: boolean
  52. type?: string
  53. main?: string
  54. types?: string
  55. bin?: string | Record<string, string>
  56. exports?: Record<
  57. string,
  58. | string
  59. | {
  60. types?: string
  61. default?: string
  62. }
  63. | null
  64. | undefined
  65. >
  66. files?: string[]
  67. publishConfig?: { access?: string }
  68. repository?: { type?: string; url?: string; directory?: string }
  69. peerDependencies?: Record<string, string>
  70. devDependencies?: Record<string, string>
  71. }
  72. /** One workspace manifest and its repo-relative path. */
  73. interface WorkspaceManifest {
  74. dir: string
  75. manifest: PackageManifest
  76. }
  77. function readJson(path: string): PackageManifest {
  78. return JSON.parse(readFileSync(path, 'utf8')) as PackageManifest
  79. }
  80. const rootManifest = readJson(join(root, 'package.json'))
  81. const repositoryVersion = rootManifest.version
  82. const landlockWorkspaceManifest = readJson(join(root, 'native/landlock-run/package.json'))
  83. const landlockVersion = landlockWorkspaceManifest.version
  84. /** Repo-relative dirs holding a package.json, walked to the configured depth. */
  85. function packageDirs(base: string, depth: number): string[] {
  86. if (depth === 1) {
  87. return readdirSync(join(root, base), { withFileTypes: true })
  88. .filter(entry => entry.isDirectory())
  89. .filter(entry => !localArtifactDirs.has(entry.name))
  90. .filter(entry => existsSync(join(root, base, entry.name, 'package.json')))
  91. .map(entry => `${base}/${entry.name}`)
  92. }
  93. return readdirSync(join(root, base), { withFileTypes: true })
  94. .filter(entry => entry.isDirectory())
  95. .filter(entry => !localArtifactDirs.has(entry.name))
  96. .flatMap(group => packageDirs(`${base}/${group.name}`, depth - 1))
  97. }
  98. function workspaceManifests(): WorkspaceManifest[] {
  99. const manifests: WorkspaceManifest[] = [
  100. { dir: '.', manifest: rootManifest },
  101. ]
  102. for (const { dir: base, depth } of workspaceGlobs) {
  103. for (const dir of packageDirs(base, depth)) {
  104. manifests.push({ dir, manifest: readJson(join(root, dir, 'package.json')) })
  105. }
  106. }
  107. return manifests
  108. }
  109. const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
  110. // Profile bundles publish their dsh.bundle.patch layer beside the lib;
  111. // dsh-base also ships the win32 shell platform layer the launcher reads.
  112. '@deepseek-ai/dsh-base': ['cordis.patch.yml', 'windows.cordis.patch.yml'],
  113. '@deepseek-ai/dsh-web-app': ['cordis.patch.yml'],
  114. '@deepseek-ai/dsh-headless': ['cordis.patch.yml'],
  115. '@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
  116. '@deepseek-ai/dsh-helper': ['lib/assets'],
  117. // The Python runtime uses a distinct closed-resolution bin; the public CLI
  118. // keeps config-owned bare-package resolution through lib/bin.js.
  119. '@deepseek-ai/dsh-jsonrpc-demo': ['lib/packaged-bin.js'],
  120. // The argv-prefix runner entry ships beside the lib as its own bundle;
  121. // sandbox-local resolves it through the package's ./runner export. tsdown
  122. // also shares its generated FFI code through a hashed runtime chunk.
  123. '@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js', 'lib/types-*.js'],
  124. '@deepseek-ai/dsh-skill-badge': ['assets'],
  125. '@deepseek-ai/dsh-subprocess-local': ['scripts/ensure-spawn-helper.mjs'],
  126. '@deepseek-ai/dsh-scripts': [
  127. 'lib/dev/tsdown-config.js',
  128. 'lib/local-plugin-loader-hooks.js',
  129. 'lib/assets',
  130. ],
  131. }
  132. function sameStringList(actual: readonly string[] | undefined, expected: readonly string[]): boolean {
  133. return !!actual && actual.length === expected.length && actual.every((value, index) => value === expected[index])
  134. }
  135. function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
  136. const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
  137. const typeRTRemoteNavigation = hasTypeRTRemoteNavigation(manifest)
  138. return [
  139. 'lib/index.js',
  140. // Every package publishes its invariant ownership companion as a separate
  141. // bundle; the package-invariant gate validates the companion itself.
  142. 'lib/invariant.js',
  143. ...manifest.bin ? ['lib/bin.js'] : [],
  144. ...manifest.exports?.['./worker'] ? ['lib/worker.cjs'] : [],
  145. // UI plugin packages ship their browser bundle beside the node lib
  146. // (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
  147. // Keyed on the artifact path, not the subpath name: apiproxy's ./client is
  148. // a browser-safe source channel, not a bundle.
  149. ...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
  150. // runtime's shell-held loader subpath ships as its own bundle beside the client half.
  151. ...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
  152. // web-react's store subpath ships its own bundle (single-entry builds; no shared chunk).
  153. ...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
  154. ...extras,
  155. // Subpaths whose runtime default is the tsc-emitted tree (lib/types/*.js —
  156. // browser-safe source channels rehomed off src so plain Node can import
  157. // them without type stripping) publish the emitted JS alongside the
  158. // declarations.
  159. ...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
  160. 'lib/types/**/*.d.ts',
  161. ...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
  162. ? ['lib/typert.host.js', 'lib/typert.host.d.ts']
  163. : [],
  164. ...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
  165. ? ['lib/typert.client.js', 'lib/typert.client.d.ts']
  166. : [],
  167. ...typeRTRemoteNavigation
  168. ? [
  169. 'lib/typert.remote-client.js',
  170. 'lib/typert.remote-client.d.ts',
  171. 'lib/typert.remote-client.d.ts.map',
  172. 'src',
  173. ]
  174. : [],
  175. ]
  176. }
  177. /** Whether one conditional export exactly names the generated runtime and declaration pair. */
  178. function hasExportPair(
  179. manifest: PackageManifest,
  180. subpath: string,
  181. types: string,
  182. runtime: string,
  183. ): boolean {
  184. const entry = manifest.exports?.[subpath]
  185. return typeof entry === 'object'
  186. && entry !== null
  187. && entry.types === types
  188. && entry.default === runtime
  189. }
  190. /** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
  191. function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
  192. const entry = manifest.exports?.[subpath]
  193. if (typeof entry === 'string') return entry
  194. if (typeof entry === 'object' && entry !== null) return entry.default
  195. return undefined
  196. }
  197. /** Whether any export's runtime default points into the tsc-emitted lib/types tree. */
  198. function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
  199. return Object.keys(manifest.exports ?? {}).some(subpath =>
  200. exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
  201. }
  202. function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
  203. const errors: string[] = []
  204. const label = manifest.name ?? dir
  205. const isLandlockPackageDir = dir.startsWith('native/landlock-run/packages/')
  206. const isPublicLandlockPackage = isLandlockPackageDir
  207. && manifest.name !== undefined
  208. && publicLandlockPackages.has(manifest.name)
  209. if (isPublicLandlockPackage) {
  210. if (manifest.private === true) {
  211. errors.push(`${label}: published Landlock package must not set "private": true`)
  212. }
  213. if (manifest.publishConfig?.access !== 'public') {
  214. errors.push(`${label}: published Landlock package must set publishConfig.access to "public"`)
  215. }
  216. const expectedDirectory = dir
  217. if (manifest.repository?.type !== 'git'
  218. || manifest.repository.url !== repositoryUrl
  219. || manifest.repository.directory !== expectedDirectory) {
  220. errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
  221. }
  222. } else if (manifest.private !== true) {
  223. errors.push(`${label}: package.json must set "private": true`)
  224. }
  225. if (manifest.name && vendoredPackages.has(manifest.name)) {
  226. return errors
  227. }
  228. if (manifest.name?.startsWith('@deepseek-ai/')) {
  229. const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
  230. const publicationPolicy = { typeRTRemoteNavigation: hasTypeRTRemoteNavigation(manifest) }
  231. for (const file of manifest.files ?? []) {
  232. if (isForbiddenPublicationFile(file, publicationPolicy) && !allowedSources.includes(file)) {
  233. errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
  234. }
  235. }
  236. }
  237. if (dir.startsWith('apps/') && manifest.name?.startsWith('@deepseek-ai/')) {
  238. const expectedFiles = appPackageFiles[manifest.name]
  239. if (expectedFiles === undefined) {
  240. errors.push(`${label}: app package has no publication files policy`)
  241. } else if (!sameStringList(manifest.files, expectedFiles)) {
  242. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  243. }
  244. }
  245. if (isLandlockPackageDir) {
  246. if (!isPublicLandlockPackage) {
  247. errors.push(`${label}: unexpected package in the public Landlock package family`)
  248. }
  249. if (manifest.version !== landlockVersion) {
  250. errors.push(`${label}: package.json version must match Landlock workspace version ${landlockVersion ?? '(missing)'}`)
  251. }
  252. }
  253. if (dir.startsWith('packages/') && manifest.name?.startsWith('@deepseek-ai/dsh-')) {
  254. const peer = manifest.peerDependencies?.['@deepseek-ai/cordis']
  255. const dev = manifest.devDependencies?.['@deepseek-ai/cordis']
  256. if (!peer) errors.push(`${label}: @deepseek-ai/cordis must be a peerDependency`)
  257. if (!dev) errors.push(`${label}: @deepseek-ai/cordis must also be a devDependency`)
  258. if (peer && dev && peer !== dev) {
  259. errors.push(`${label}: @deepseek-ai/cordis peer (${peer}) and dev (${dev}) ranges must match`)
  260. }
  261. if (manifest.version !== repositoryVersion) {
  262. errors.push(`${label}: package.json version must match root version ${repositoryVersion ?? '(missing)'}`)
  263. }
  264. if (manifest.type !== 'module') {
  265. errors.push(`${label}: package.json must set "type": "module"`)
  266. }
  267. if (manifest.main !== 'lib/index.js') {
  268. errors.push(`${label}: package.json must set "main": "lib/index.js"`)
  269. }
  270. if (manifest.types !== 'lib/types/index.d.ts') {
  271. errors.push(`${label}: package.json must set "types": "lib/types/index.d.ts"`)
  272. }
  273. const rootExport = manifest.exports?.['.']
  274. const rootEntry = typeof rootExport === 'object' && rootExport !== null ? rootExport : undefined
  275. if (rootEntry?.types !== './lib/types/index.d.ts') {
  276. errors.push(`${label}: package.json exports["."].types must be "./lib/types/index.d.ts"`)
  277. }
  278. if (rootEntry?.default !== './lib/index.js') {
  279. errors.push(`${label}: package.json exports["."].default must be "./lib/index.js"`)
  280. }
  281. const invariantRaw = manifest.exports?.['./invariant']
  282. const invariantExport = typeof invariantRaw === 'object' && invariantRaw !== null ? invariantRaw : undefined
  283. if (invariantExport?.types !== undefined && invariantExport.types !== './lib/types/invariant.d.ts') {
  284. errors.push(`${label}: package.json exports["./invariant"].types must be "./lib/types/invariant.d.ts"`)
  285. }
  286. if (invariantExport?.default !== undefined && invariantExport.default !== './lib/invariant.js') {
  287. errors.push(`${label}: package.json exports["./invariant"].default must be "./lib/invariant.js"`)
  288. }
  289. if (invariantExport && (invariantExport.types === undefined || invariantExport.default === undefined)) {
  290. errors.push(`${label}: package.json exports["./invariant"] must declare both types and default targets`)
  291. }
  292. const expectedFiles = expectedDshPackageFiles(manifest)
  293. if (!sameStringList(manifest.files, expectedFiles)) {
  294. errors.push(`${label}: package.json files must be ${JSON.stringify(expectedFiles)}`)
  295. }
  296. }
  297. return errors.map(error => `${relative(root, join(root, dir, 'package.json'))}: ${error}`)
  298. }
  299. /**
  300. * Enforce `packages/<group>/<pkg>`: groups are open-named containers without a
  301. * package.json, and packages may be neither flat nor more deeply nested.
  302. */
  303. function checkHierarchyShape(): string[] {
  304. const errors: string[] = []
  305. const packagesRoot = join(root, 'packages')
  306. for (const group of readdirSync(packagesRoot, { withFileTypes: true })) {
  307. if (!group.isDirectory()) continue
  308. const groupRel = join('packages', group.name)
  309. if (existsSync(join(packagesRoot, group.name, 'package.json'))) {
  310. errors.push(`${groupRel}: a group dir must not contain a package.json — packages live at packages/<group>/<pkg>, not directly under packages/`)
  311. continue
  312. }
  313. for (const pkg of readdirSync(join(packagesRoot, group.name), { withFileTypes: true })) {
  314. if (!pkg.isDirectory()) continue
  315. if (localArtifactDirs.has(pkg.name)) continue
  316. const pkgRel = join(groupRel, pkg.name)
  317. if (!existsSync(join(packagesRoot, group.name, pkg.name, 'package.json'))) {
  318. errors.push(`${pkgRel}: expected a package here (no package.json found) — the hierarchy is exactly packages/<group>/<pkg>, no deeper nesting`)
  319. }
  320. }
  321. }
  322. return errors
  323. }
  324. function checkRepositoryVersion(): string[] {
  325. if (repositoryVersion && /^\d+\.\d+\.\d+$/.test(repositoryVersion)) return []
  326. return ['package.json: version must be stable X.Y.Z']
  327. }
  328. const errors = [
  329. ...checkRepositoryVersion(),
  330. ...workspaceManifests().flatMap(checkWorkspace),
  331. ...checkHierarchyShape(),
  332. ...collectProjectReferenceFaceViolations(root),
  333. ]
  334. if (errors.length > 0) {
  335. console.error(errors.join('\n'))
  336. process.exitCode = 1
  337. }