gen-third-party-notices.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. /**
  2. * Generate `THIRD_PARTY_NOTICES.md` from the workspace manifests: every
  3. * external dependency named by a workspace `package.json`, the vendored-package
  4. * manifest in `vendor/README.md`, the Python `pyproject.toml` files, and the
  5. * pnpm patch list. License and repository metadata come from the installed
  6. * store, so the tree must be installed. `--check` verifies the committed
  7. * artifact. Tier policy and ownership live in
  8. * `.agents/notes/implemented/process/2026-07-30-generated-third-party-notices.md`.
  9. */
  10. import { existsSync, globSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
  11. import { resolve } from 'node:path'
  12. import * as yaml from 'js-yaml'
  13. import { parse as parseToml, type TomlTableWithoutBigInt, type TomlValueWithoutBigInt } from 'smol-toml'
  14. import parseSpdx from 'spdx-expression-parse'
  15. const root = resolve(import.meta.dirname, '..')
  16. const OUT = 'THIRD_PARTY_NOTICES.md'
  17. /** Dependency-declaration kinds a consumer resolves at runtime. */
  18. const RUNTIME_KINDS = ['dependencies', 'optionalDependencies'] as const
  19. /** All manifest sections that name an external package this file must disclose. */
  20. const ALL_KINDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'] as const
  21. /**
  22. * Workspace areas that never reach a user: repository tooling and gates (the
  23. * root manifest), test infrastructure, the documentation site, the runnable
  24. * demo leaves, and the native launcher's build workspace. A runtime
  25. * declaration by anything outside these areas is a disclosure-relevant
  26. * runtime dependency, because `scripts/install.sh` installs the repository
  27. * itself and any plugin package can be mounted from a user's `cordis.yml`.
  28. */
  29. const DEV_ONLY_AREAS = [
  30. 'package.json',
  31. 'packages/support/',
  32. 'packages/client/test-runtime/',
  33. 'website/',
  34. 'examples/',
  35. 'native/',
  36. ] as const
  37. /**
  38. * First-party packages released from sibling repositories under the project's
  39. * own license: reachable from workspace manifests but not third-party.
  40. */
  41. const FIRST_PARTY = new Set([
  42. 'node-addon-landlock-run',
  43. 'node-addon-landlock-run-linux-arm64',
  44. 'node-addon-landlock-run-linux-x64',
  45. ])
  46. /**
  47. * Metadata overrides where the installed manifest is wrong or unreachable.
  48. * Each entry documents why the store cannot answer.
  49. */
  50. const OVERRIDES: Record<string, { license?: string; repo?: string }> = {
  51. // Rust workspaces publishing npm bins without `license` in package.json.
  52. 'oxlint': { license: 'MIT', repo: 'https://github.com/oxc-project/oxc' },
  53. 'oxlint-tsgolint': { license: 'MIT', repo: 'https://github.com/oxc-project/tsgolint' },
  54. // `license: SEE LICENSE IN LICENSE`: the servers repo is mid MIT→Apache-2.0
  55. // relicensing, so the effective terms are per-contribution.
  56. '@modelcontextprotocol/server-everything': { license: 'MIT / Apache-2.0', repo: 'https://github.com/modelcontextprotocol/servers' },
  57. '@modelcontextprotocol/server-filesystem': { license: 'MIT / Apache-2.0', repo: 'https://github.com/modelcontextprotocol/servers' },
  58. // No repository field in the published manifest.
  59. 'node-addon-require-builtin': { repo: 'https://www.npmjs.com/package/node-addon-require-builtin' },
  60. }
  61. /**
  62. * Python dependencies are few and named directly in `pyproject.toml` files
  63. * without installed metadata to harvest, so license/repo are recorded here and
  64. * the generator fails when a manifest names a package this map misses.
  65. */
  66. const PYTHON_METADATA: Record<string, { license: string; repo: string; role: string }> = {
  67. pydantic: { license: 'MIT', repo: 'https://github.com/pydantic/pydantic', role: 'runtime dependency of `deepseek-harness`' },
  68. hatchling: { license: 'MIT', repo: 'https://github.com/pypa/hatch', role: 'build backend' },
  69. pytest: { license: 'MIT', repo: 'https://github.com/pytest-dev/pytest', role: 'test-only' },
  70. }
  71. type PythonMetadata = typeof PYTHON_METADATA
  72. /** Tools fetched by scripts at build time, keyed by the pin the script owns. */
  73. const BUILD_TIME_TOOLS = [
  74. {
  75. name: '@yao-pkg/pkg',
  76. license: 'MIT',
  77. repo: 'https://github.com/yao-pkg/pkg',
  78. role: 'invoked by `scripts/build-exe-for-python-sdk.ts` to assemble the single-file SDK runtime executable',
  79. pinSource: 'scripts/build-exe-for-python-sdk.ts',
  80. },
  81. ]
  82. /** The `package.json` fields this generator reads. */
  83. export interface Manifest {
  84. name?: string
  85. private?: boolean
  86. license?: string
  87. dependencies?: Record<string, string>
  88. devDependencies?: Record<string, string>
  89. optionalDependencies?: Record<string, string>
  90. peerDependencies?: Record<string, string>
  91. }
  92. /** One disclosed external npm dependency. */
  93. interface ExternalDep {
  94. name: string
  95. license: string
  96. repo: string
  97. /** True when some shipped workspace consumer reaches it through runtime dependency edges. */
  98. runtime: boolean
  99. }
  100. /** Read and parse a workspace-relative `package.json`. */
  101. function readManifest(rel: string): Manifest {
  102. return JSON.parse(readFileSync(resolve(root, rel), 'utf8')) as Manifest
  103. }
  104. /**
  105. * Manifest globs, derived from the workspace declarations rather than listed
  106. * here, so a new member area (`tools/*`) is read the day it is declared.
  107. * @returns one glob per manifest-bearing location, repository-relative.
  108. */
  109. export function manifestPatterns(rootMembers: readonly string[], nativeMembers: readonly string[]): string[] {
  110. return [
  111. 'package.json',
  112. ...rootMembers.map(member => `${member}/package.json`),
  113. // The demo leaves join the workspace through `examples/package.json`, so
  114. // their own manifests are members of nothing and no glob above reaches them.
  115. 'examples/*/package.json',
  116. // `native/landlock-run` is a nested workspace with its own lock file.
  117. 'native/landlock-run/package.json',
  118. ...nativeMembers.map(member => `native/landlock-run/${member}/package.json`),
  119. ]
  120. }
  121. /** The `packages:` member globs declared by one pnpm workspace file. */
  122. function workspaceMembers(rel: string): string[] {
  123. const declared = (yaml.load(readFileSync(resolve(root, rel), 'utf8')) as { packages?: unknown }).packages
  124. if (!Array.isArray(declared) || declared.length === 0) {
  125. throw new Error(`gen-third-party-notices: ${rel} declares no workspace members; the manifest set cannot be derived.`)
  126. }
  127. return declared.map(member => String(member))
  128. }
  129. /**
  130. * Every workspace manifest, keyed by repository-relative path, plus the set of
  131. * workspace package names. Paths are normalized to `/` at ingestion: Node's
  132. * `fs.globSync` returns OS-native separators, and the area matching in
  133. * `tierExternalDeps` compares `/`-suffixed prefixes, so Windows backslashes
  134. * would silently push dev-area manifests into the runtime tier.
  135. */
  136. function loadWorkspaceManifests(): { manifests: Map<string, Manifest>; names: Set<string> } {
  137. const patterns = manifestPatterns(workspaceMembers('pnpm-workspace.yaml'), workspaceMembers('native/landlock-run/pnpm-workspace.yaml'))
  138. const manifests = new Map<string, Manifest>()
  139. const names = new Set<string>()
  140. for (const pattern of patterns) {
  141. for (const path of globSync(pattern, { cwd: root })) {
  142. const normalized = path.replaceAll('\\', '/')
  143. const manifest = readManifest(normalized)
  144. manifests.set(normalized, manifest)
  145. if (manifest.name !== undefined) names.add(manifest.name)
  146. }
  147. }
  148. if (manifests.size < 100) throw new Error(`gen-third-party-notices: only ${manifests.size} workspace manifests found; the glob set is stale.`)
  149. return { manifests, names }
  150. }
  151. type VirtualManifest = Manifest & { license?: string; repository?: string | { url?: string }; homepage?: string }
  152. /**
  153. * Resolve one package's manifest inside a pnpm virtual store. The prefix scan
  154. * matches ordinary `@scope+name@version` directory names; pnpm 11 truncates
  155. * long names (a peer-suffixed name past the length limit becomes
  156. * `<prefix>_<hash>`), so a content scan falls back over the whole store when
  157. * the prefix misses.
  158. *
  159. * @param virtual - the `.pnpm` virtual store directory to scan.
  160. * @param name - the external package name, exactly as `node_modules` spells it.
  161. * @returns the parsed manifest, or `undefined` when neither the prefix match
  162. * nor the content scan finds the package's `package.json`.
  163. */
  164. export function virtualManifest(virtual: string, name: string): VirtualManifest | undefined {
  165. const prefix = `${name.replace('/', '+')}@`
  166. const entry = readdirSync(virtual).find(dir => dir.startsWith(prefix))
  167. if (entry !== undefined) {
  168. return JSON.parse(readFileSync(resolve(virtual, entry, 'node_modules', name, 'package.json'), 'utf8')) as VirtualManifest
  169. }
  170. for (const dir of readdirSync(virtual)) {
  171. const candidate = resolve(virtual, dir, 'node_modules', name, 'package.json')
  172. if (existsSync(candidate)) {
  173. return JSON.parse(readFileSync(candidate, 'utf8')) as VirtualManifest
  174. }
  175. }
  176. return undefined
  177. }
  178. /** License and repository URL for an installed external package, from the pnpm store. */
  179. function installedMetadata(name: string): { license: string; repo: string } {
  180. const override = OVERRIDES[name]
  181. let manifest: (Manifest & { license?: string; repository?: string | { url?: string }; homepage?: string }) | undefined
  182. // The nested Landlock workspace installs into its own store, so a package
  183. // only that workspace depends on is unreachable from the root one.
  184. for (const store of ['node_modules', 'native/landlock-run/node_modules']) {
  185. const direct = resolve(root, store, name, 'package.json')
  186. if (existsSync(direct)) {
  187. manifest = JSON.parse(readFileSync(direct, 'utf8')) as typeof manifest
  188. break
  189. }
  190. const virtual = resolve(root, store, '.pnpm')
  191. if (!existsSync(virtual)) continue
  192. manifest = virtualManifest(virtual, name)
  193. if (manifest !== undefined) break
  194. }
  195. const license = override?.license ?? manifest?.license
  196. const rawRepo = typeof manifest?.repository === 'string' ? manifest.repository : manifest?.repository?.url ?? manifest?.homepage
  197. const repo = override?.repo ?? normalizeRepo(rawRepo)
  198. if (license === undefined || repo === undefined) {
  199. throw new Error(`gen-third-party-notices: cannot resolve ${license === undefined ? 'license' : 'repository'} for ${name}; run \`pnpm install\` (or, for a Landlock-only dependency, \`pnpm --dir native/landlock-run install\`), or add an OVERRIDES entry.`)
  200. }
  201. return { license, repo }
  202. }
  203. /** Normalize a manifest repository/homepage value to a browsable https URL. */
  204. function normalizeRepo(raw: string | undefined): string | undefined {
  205. if (raw === undefined || raw === '') return undefined
  206. let url = raw
  207. .replace(/^git\+ssh:\/\/git@/, 'https://')
  208. .replace(/^git\+/, '')
  209. .replace(/^git:\/\//, 'https://')
  210. .replace(/^github:/, 'https://github.com/')
  211. .replace(/\.git$/, '')
  212. if (!url.startsWith('http')) url = `https://github.com/${url}`
  213. return url
  214. }
  215. /**
  216. * External npm dependencies, tiered by which workspace area declares them at
  217. * runtime: a package is runtime when any manifest outside `DEV_ONLY_AREAS`
  218. * names it in `dependencies`/`optionalDependencies`. A package declared only
  219. * by tooling, test infrastructure, the website, or the demo leaves — whatever
  220. * the declaring section is called — is development-only.
  221. */
  222. function collectNpmDeps(): ExternalDep[] {
  223. const { manifests, names } = loadWorkspaceManifests()
  224. return [...tierExternalDeps(manifests, names)]
  225. .filter(([name]) => !FIRST_PARTY.has(name))
  226. .sort(([a], [b]) => a.localeCompare(b))
  227. .map(([name, runtime]) => ({ name, ...installedMetadata(name), runtime }))
  228. }
  229. /**
  230. * Tier every external dependency the workspace declares.
  231. * @param manifests - workspace manifests keyed by repository-relative path.
  232. * @param names - every workspace package name, which never counts as external.
  233. * @returns each external package mapped to whether it is a runtime dependency.
  234. */
  235. export function tierExternalDeps(manifests: Map<string, Manifest>, names: Set<string>): Map<string, boolean> {
  236. const tiers = new Map<string, boolean>()
  237. // `tsx` is runtime by fiat: `bin/dsh` execs the CLI through its ESM hook.
  238. tiers.set('tsx', true)
  239. for (const [path, manifest] of manifests) {
  240. const devOnly = DEV_ONLY_AREAS.some(area => (area.endsWith('/') ? path.startsWith(area) : path === area))
  241. for (const kind of ALL_KINDS) {
  242. for (const [dep, range] of Object.entries(manifest[kind] ?? {})) {
  243. if (names.has(dep) || range.startsWith('workspace:')) continue
  244. const runtime = !devOnly && (RUNTIME_KINDS as readonly string[]).includes(kind)
  245. tiers.set(dep, (tiers.get(dep) ?? false) || runtime)
  246. }
  247. }
  248. }
  249. return tiers
  250. }
  251. /** A vendored package row parsed out of the `vendor/README.md` manifest table. */
  252. export interface VendoredRow {
  253. npmName: string
  254. upstream: string
  255. }
  256. /**
  257. * Parse the vendored-package manifest table out of `vendor/README.md`.
  258. * @param text - the complete `vendor/README.md` contents.
  259. * @returns one row per manifest-table entry, in table order.
  260. */
  261. export function parseVendoredRows(text: string): VendoredRow[] {
  262. const rows: VendoredRow[] = []
  263. for (const line of text.split('\n')) {
  264. const match = /^\| \x60\S+\/\x60 \| \x60([^\x60]+)\x60 \| \S+ \| (https:\/\/\S+?)(?: \([^)]*\))? \| \x60[0-9a-f]+\x60 \|$/.exec(line)
  265. if (match === null) continue
  266. const [, npmName, upstream] = match
  267. if (npmName === undefined || upstream === undefined) continue
  268. rows.push({ npmName, upstream })
  269. }
  270. return rows
  271. }
  272. /**
  273. * Parse the vendored manifest table and confirm it accounts for every vendored
  274. * directory. The `vendor/` tree — not the table — is the set that must be
  275. * disclosed, so a row that stops matching the table format is a hard error
  276. * rather than a package that quietly vanishes from the notices.
  277. */
  278. function collectVendored(): VendoredRow[] {
  279. const rows = parseVendoredRows(readFileSync(resolve(root, 'vendor/README.md'), 'utf8'))
  280. const onDisk = new Map<string, string>()
  281. for (const entry of readdirSync(resolve(root, 'vendor'), { withFileTypes: true })) {
  282. if (!entry.isDirectory()) continue
  283. const manifest = readManifest(`vendor/${entry.name}/package.json`)
  284. if (manifest.name !== undefined) onDisk.set(manifest.name, entry.name)
  285. }
  286. const parsed = new Set(rows.map(row => row.npmName))
  287. const missing = [...onDisk.keys()].filter(name => !parsed.has(name))
  288. if (missing.length > 0) {
  289. throw new Error(`gen-third-party-notices: vendor/README.md has no manifest-table row for ${missing.join(', ')}; its table format changed or the sync is incomplete.`)
  290. }
  291. for (const row of rows) {
  292. const dir = onDisk.get(row.npmName)
  293. if (dir === undefined) throw new Error(`gen-third-party-notices: vendored package ${row.npmName} from vendor/README.md has no vendor/ directory.`)
  294. const license = readManifest(`vendor/${dir}/package.json`).license
  295. if (license !== 'MIT') {
  296. throw new Error(`gen-third-party-notices: vendored ${row.npmName} declares license ${JSON.stringify(license)}; the vendored section assumes MIT throughout.`)
  297. }
  298. }
  299. return rows
  300. }
  301. /** Whether a parsed TOML value is a table rather than an array or scalar. */
  302. function isTomlTable(value: TomlValueWithoutBigInt | undefined): value is TomlTableWithoutBigInt {
  303. return value !== undefined && typeof value === 'object' && !Array.isArray(value)
  304. }
  305. /** Parse one PEP 508 requirement string into its distribution name. */
  306. function parsePythonRequirement(requirement: string): string {
  307. const name = /^\s*([a-zA-Z][a-zA-Z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(?:[<>=!~;@].*)?$/.exec(requirement)?.[1]
  308. if (name === undefined) {
  309. throw new Error(`gen-third-party-notices: cannot read a distribution name from the requirement ${JSON.stringify(requirement)}.`)
  310. }
  311. return name
  312. }
  313. /** Add the string requirements from one parsed TOML array. */
  314. function collectPythonRequirementArray(
  315. names: string[],
  316. value: TomlValueWithoutBigInt | undefined,
  317. location: string,
  318. allowGroupIncludes = false,
  319. ): void {
  320. if (value === undefined) return
  321. if (!Array.isArray(value)) {
  322. throw new Error(`gen-third-party-notices: ${location} must be an array.`)
  323. }
  324. for (const item of value) {
  325. if (typeof item === 'string') {
  326. names.push(parsePythonRequirement(item))
  327. continue
  328. }
  329. if (allowGroupIncludes && isTomlTable(item) && typeof item['include-group'] === 'string' && Object.keys(item).length === 1) {
  330. continue
  331. }
  332. throw new Error(`gen-third-party-notices: ${location} contains an unsupported requirement entry.`)
  333. }
  334. }
  335. /** Read an optional TOML table and reject a present value of another shape. */
  336. function optionalTomlTable(value: TomlValueWithoutBigInt | undefined, location: string): TomlTableWithoutBigInt | undefined {
  337. if (value === undefined || isTomlTable(value)) return value
  338. throw new Error(`gen-third-party-notices: ${location} must be a table.`)
  339. }
  340. /**
  341. * Parse a `pyproject.toml` project identity and every requirement it declares:
  342. * `requires` under
  343. * `[build-system]`, `dependencies` under `[project]`, and every key under
  344. * `[project.optional-dependencies]` and `[dependency-groups]`. A TOML parser
  345. * owns comments, quoted keys, escapes, and array boundaries; unsupported
  346. * requirement shapes fail instead of disappearing from the notices.
  347. * @param text - the complete `pyproject.toml` contents.
  348. * @returns the local project name and declared requirement names.
  349. */
  350. function parsePyproject(text: string): { projectName?: string; requirements: string[] } {
  351. const names: string[] = []
  352. const document = parseToml(text, { integersAsBigInt: false })
  353. const buildSystem = optionalTomlTable(document['build-system'], '[build-system]')
  354. const project = optionalTomlTable(document.project, '[project]')
  355. const projectName = project?.name
  356. if (projectName !== undefined && typeof projectName !== 'string') {
  357. throw new Error('gen-third-party-notices: [project].name must be a string.')
  358. }
  359. collectPythonRequirementArray(names, buildSystem?.requires, '[build-system].requires')
  360. collectPythonRequirementArray(names, project?.dependencies, '[project].dependencies')
  361. const optional = optionalTomlTable(project?.['optional-dependencies'], '[project.optional-dependencies]')
  362. for (const [group, requirements] of Object.entries(optional ?? {})) {
  363. collectPythonRequirementArray(names, requirements, `[project.optional-dependencies].${group}`)
  364. }
  365. const groups = optionalTomlTable(document['dependency-groups'], '[dependency-groups]')
  366. for (const [group, requirements] of Object.entries(groups ?? {})) {
  367. collectPythonRequirementArray(names, requirements, `[dependency-groups].${group}`, true)
  368. }
  369. return projectName === undefined
  370. ? { requirements: names }
  371. : { projectName, requirements: names }
  372. }
  373. /**
  374. * Read every requirement name declared by one `pyproject.toml`.
  375. * @param text - the complete `pyproject.toml` contents.
  376. * @returns each declared requirement's distribution name, in file order.
  377. */
  378. export function parsePyprojectRequirements(text: string): string[] {
  379. return parsePyproject(text).requirements
  380. }
  381. /** Normalize a Python distribution name according to the packaging name rule. */
  382. function normalizePythonDistributionName(name: string): string {
  383. return name.toLowerCase().replace(/[-_.]+/g, '-')
  384. }
  385. /**
  386. * Resolve external Python dependencies after excluding local project names.
  387. * @param pyprojects - complete local `pyproject.toml` contents.
  388. * @param metadata - disclosure metadata for every external dependency.
  389. * @returns disclosed dependencies in normalized name order.
  390. */
  391. export function collectPythonDependencies(
  392. pyprojects: string[],
  393. metadata: PythonMetadata = PYTHON_METADATA,
  394. ): { name: string; license: string; repo: string; role: string }[] {
  395. const parsed = pyprojects.map(parsePyproject)
  396. const firstParty = new Set(parsed.flatMap(({ projectName }) => (
  397. projectName === undefined ? [] : [normalizePythonDistributionName(projectName)]
  398. )))
  399. const found = new Set(parsed
  400. .flatMap(({ requirements }) => requirements.map(normalizePythonDistributionName))
  401. .filter(name => !firstParty.has(name)))
  402. return [...found].sort((a, b) => a.localeCompare(b)).map((name) => {
  403. const entry = metadata[name]
  404. if (entry === undefined) throw new Error(`gen-third-party-notices: python dependency ${name} is missing from PYTHON_METADATA.`)
  405. return { name, ...entry }
  406. })
  407. }
  408. /** Direct Python dependencies named by the `pyproject.toml` manifests under `python/`. */
  409. function collectPython(): { name: string; license: string; repo: string; role: string }[] {
  410. const manifests = globSync('python/*/pyproject.toml', { cwd: root })
  411. if (manifests.length === 0) throw new Error('gen-third-party-notices: no python/*/pyproject.toml found; the Python tree moved.')
  412. return collectPythonDependencies(manifests.map(path => readFileSync(resolve(root, path), 'utf8')))
  413. }
  414. /** pnpm-patched external packages, from `pnpm-workspace.yaml`. */
  415. function collectPatched(): { spec: string; patch: string }[] {
  416. const workspace = yaml.load(readFileSync(resolve(root, 'pnpm-workspace.yaml'), 'utf8')) as { patchedDependencies?: Record<string, string> }
  417. return Object.entries(workspace.patchedDependencies ?? {}).map(([spec, patch]) => ({ spec, patch }))
  418. }
  419. /** Verify each build-time tool pin still appears in its owning script. */
  420. function verifyBuildTimePins(): void {
  421. for (const tool of BUILD_TIME_TOOLS) {
  422. const text = readFileSync(resolve(root, tool.pinSource), 'utf8')
  423. if (!text.includes(tool.name)) {
  424. throw new Error(`gen-third-party-notices: ${tool.pinSource} no longer references ${tool.name}; update BUILD_TIME_TOOLS.`)
  425. }
  426. }
  427. }
  428. /** SPDX identifiers this project may ship without further review. */
  429. const PERMISSIVE_LICENSES = new Set(['MIT', 'ISC', 'BSD-2-Clause', 'BSD-3-Clause', 'Apache-2.0', '0BSD', 'Unlicense', 'CC0-1.0', 'BlueOak-1.0.0', 'Python-2.0'])
  430. /** Evaluate a parsed SPDX expression under the repository's license policy. */
  431. function isPermissiveSpdx(expression: ReturnType<typeof parseSpdx>): boolean {
  432. if ('conjunction' in expression) {
  433. return expression.conjunction === 'and'
  434. ? isPermissiveSpdx(expression.left) && isPermissiveSpdx(expression.right)
  435. : isPermissiveSpdx(expression.left) || isPermissiveSpdx(expression.right)
  436. }
  437. return expression.plus !== true
  438. && expression.exception === undefined
  439. && PERMISSIVE_LICENSES.has(expression.license)
  440. }
  441. /**
  442. * Whether an SPDX expression grants terms this project may ship under.
  443. * `OR` needs one permissive alternative, because the consumer chooses; `AND`
  444. * needs all of them, because every obligation applies. Anything that is not a
  445. * recognized permissive identifier — copyleft, an exception clause, or a
  446. * license this list has never seen — evaluates to false, so an unfamiliar
  447. * expression fails closed rather than passing on a partial match.
  448. * @param license - the SPDX expression from the package manifest.
  449. * @returns true when the expression's obligations are all permissive.
  450. */
  451. export function isPermissive(license: string): boolean {
  452. // Some npm manifests use a slash for a choice despite SPDX requiring `OR`.
  453. const normalized = license.replace(/\s*\/\s*/g, ' OR ').trim()
  454. try {
  455. return isPermissiveSpdx(parseSpdx(normalized))
  456. } catch {
  457. return false
  458. }
  459. }
  460. /**
  461. * Render the sentence that isolates non-permissive development tooling, or
  462. * nothing at all when every development dependency is permissive.
  463. * @param deps - development dependencies whose license is not permissive.
  464. * @returns the paragraph to place after the development table.
  465. */
  466. function renderNonPermissiveNote(deps: ExternalDep[]): string {
  467. if (deps.length === 0) return ''
  468. const named = deps.map(dep => `\`${dep.name}\` (${dep.license})`)
  469. const subject = named.length === 1 ? named[0] : `${named.slice(0, -1).join(', ')} and ${named.at(-1)}`
  470. return `\n${subject} ${named.length === 1 ? 'runs' : 'run'} only as development tooling; their code is not linked into or distributed with any DeepSeek Harness artifact.\n`
  471. }
  472. /** Render one npm dependency table. */
  473. function renderNpmTable(deps: ExternalDep[]): string {
  474. const lines = ['| Package | License |', '| --- | --- |']
  475. for (const dep of deps) lines.push(`| [\`${dep.name}\`](${dep.repo}) | ${dep.license} |`)
  476. return lines.join('\n')
  477. }
  478. /**
  479. * Render the complete notices document.
  480. * @returns the exact bytes `THIRD_PARTY_NOTICES.md` must hold.
  481. */
  482. export function render(): string {
  483. verifyBuildTimePins()
  484. const npm = collectNpmDeps()
  485. const runtimeDeps = npm.filter(dep => dep.runtime)
  486. const devDeps = npm.filter(dep => !dep.runtime)
  487. const vendored = collectVendored()
  488. const python = collectPython()
  489. const patched = collectPatched()
  490. const nonPermissiveDev = devDeps.filter(dep => !isPermissive(dep.license))
  491. // A copyleft license reaching a shipped surface is a distribution decision,
  492. // not a rendering detail; the notices cannot quietly absorb it.
  493. const nonPermissiveRuntime = runtimeDeps.filter(dep => !isPermissive(dep.license))
  494. if (nonPermissiveRuntime.length > 0) {
  495. throw new Error(`gen-third-party-notices: runtime ${nonPermissiveRuntime.map(dep => `${dep.name} (${dep.license})`).join(', ')} is not a permissive license; review the distribution terms and record the decision before regenerating.`)
  496. }
  497. const patchedLines = patched.map(({ spec, patch }) => `- \`${spec}\` — [\`${patch}\`](${patch})`)
  498. return `<!-- Generated by scripts/gen-third-party-notices.ts — do not edit by hand.
  499. Run \`pnpm run gen-third-party-notices\` to regenerate. -->
  500. # Third-Party Notices
  501. DeepSeek Harness is licensed under [BSD 3-Clause](LICENSE). It depends on the third-party open-source software listed below. Each project remains under its own license; nothing in this file changes those terms.
  502. This file lists **direct** dependencies declared by the workspace. It is generated from the workspace manifests by \`scripts/gen-third-party-notices.ts\`: a pre-commit hook regenerates it whenever a staged file changes one of its inputs, and \`scripts/gen-third-party-notices.spec.ts\` asserts in the test lane that the committed bytes match. Deleting a manifest runs no hook, so that case is caught by the assertion instead. Run \`pnpm run verify-third-party-notices\` for the standalone check.
  503. The complete npm transitive closure, with exact pinned versions, is recorded in [\`pnpm-lock.yaml\`](pnpm-lock.yaml) — inspect it with \`pnpm licenses list\`. The Python closure is recorded in [\`python/sdk/uv.lock\`](python/sdk/uv.lock), and the Landlock launcher workspace keeps its own in [\`native/landlock-run/pnpm-lock.yaml\`](native/landlock-run/pnpm-lock.yaml).
  504. ## Vendored source (\`vendor/\`)
  505. The Cordis framework and its foundation libraries are source-vendored into this repository rather than consumed from npm. All are MIT-licensed; each directory preserves its upstream \`LICENSE\` file. Exact upstream commits and local modifications are recorded in [\`vendor/README.md\`](vendor/README.md).
  506. | Package | Upstream | License |
  507. | --- | --- | --- |
  508. ${vendored.map(row => `| \`${row.npmName}\` | [${row.upstream.replace('https://', '')}](${row.upstream}) | MIT |`).join('\n')}
  509. ## Runtime npm dependencies
  510. External packages that a workspace package resolves at runtime. \`scripts/install.sh\` installs this repository itself, so the tier covers every plugin a user can mount from \`cordis.yml\` — not only what the \`dsh\` CLI, Web UI, and Python SDK runtime load by default.
  511. ${renderNpmTable(runtimeDeps)}
  512. pnpm applies local patches to the following packages at install time, so shipped artifacts carry modified copies; each patch file is the complete record of the modification:
  513. ${patchedLines.join('\n')}
  514. ## Development-only npm dependencies
  515. External packages **directly declared** only by repository tooling, test infrastructure, the documentation site, the demo leaves, or the native launcher's build workspace. No shipped surface names them itself. A package here may still be pulled in transitively by a runtime dependency — \`pnpm-lock.yaml\` is the authority on the full closure — so this tier records who declares a package, not what a build ultimately bundles.
  516. ${renderNpmTable(devDeps)}
  517. ${renderNonPermissiveNote(nonPermissiveDev)}
  518. ## Python SDK dependencies (\`python/\`)
  519. Direct dependencies of the \`pyproject.toml\` manifests, plus \`uv\` as the development workflow tool.
  520. | Package | License | Role |
  521. | --- | --- | --- |
  522. ${python.map(dep => `| [\`${dep.name}\`](${dep.repo}) | ${dep.license} | ${dep.role} |`).join('\n')}
  523. | [\`uv\`](https://github.com/astral-sh/uv) | MIT / Apache-2.0 | development workflow tool |
  524. ## Fetched at build time
  525. | Package | License | Role |
  526. | --- | --- | --- |
  527. ${BUILD_TIME_TOOLS.map(tool => `| [\`${tool.name}\`](${tool.repo}) | ${tool.license} | ${tool.role} |`).join('\n')}
  528. ## First-party sibling releases
  529. \`node-addon-landlock-run\` (and its platform packages) is released from a DeepSeek Harness sibling repository under BSD 3-Clause. It is listed here for completeness; it is first-party, not third-party.
  530. `
  531. }
  532. /** CLI entry: default writes the notices, `--check` fails if the committed copy
  533. * is stale. Guarded behind an entry-point check so importing this module for
  534. * tests neither regenerates the committed file nor calls process.exit. */
  535. function main(): void {
  536. const content = render()
  537. if (process.argv.includes('--check')) {
  538. let committed: string | null = null
  539. try {
  540. committed = readFileSync(resolve(root, OUT), 'utf8')
  541. } catch {
  542. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  543. // file is not a state this repo produces, and the remedy is the same.
  544. committed = null
  545. }
  546. if (committed === content) {
  547. console.log(`gen-third-party-notices: ${OUT} is up to date.`)
  548. process.exit(0)
  549. }
  550. console.error(`gen-third-party-notices: ${OUT} is stale. Run \`pnpm run gen-third-party-notices\` and commit ${OUT}.`)
  551. process.exit(1)
  552. }
  553. writeFileSync(resolve(root, OUT), content)
  554. console.log(`gen-third-party-notices: wrote ${OUT}.`)
  555. }
  556. // Run only when invoked as a script, not when imported by a test.
  557. if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
  558. main()
  559. }