Merge latest master into test/translation-prompt-snapshot-fixtures
This commit is contained in:
commit
ce2de363dd
4342 files changed
+134795
-98010
No files matched your search
@@ -0,0 +1,49 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { resolveLinuxNodePtyAddon } from './build-exe-for-python-sdk-native-pty.ts'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('resolveLinuxNodePtyAddon', () => {
|
||||
it('prefers the manylinux build produced by the release workflow', () => {
|
||||
const root = temporaryPackage()
|
||||
const built = createAddon(root, 'build', 'Release', 'pty.node')
|
||||
createAddon(root, 'prebuilds', 'linux-x64', 'pty.node')
|
||||
|
||||
expect(resolveLinuxNodePtyAddon(root, 'x64')).toBe(built)
|
||||
})
|
||||
|
||||
it('uses the target prebuild after an ordinary beta install', () => {
|
||||
const root = temporaryPackage()
|
||||
const prebuilt = createAddon(root, 'prebuilds', 'linux-arm64', 'pty.node')
|
||||
|
||||
expect(resolveLinuxNodePtyAddon(root, 'arm64')).toBe(prebuilt)
|
||||
})
|
||||
|
||||
it('reports both expected locations when no addon is installed', () => {
|
||||
const root = temporaryPackage()
|
||||
|
||||
expect(() => resolveLinuxNodePtyAddon(root, 'x64')).toThrow(
|
||||
`node-pty addon is absent from both ${join(root, 'build', 'Release', 'pty.node')} and ${join(root, 'prebuilds', 'linux-x64', 'pty.node')}`,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
function temporaryPackage(): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-node-pty-addon-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
function createAddon(root: string, ...segments: string[]): string {
|
||||
const path = join(root, ...segments)
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, '')
|
||||
return path
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/** Resolve the native node-pty input used by the Python SDK runtime builder. */
|
||||
|
||||
import { existsSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
|
||||
/**
|
||||
* Prefer the workflow's manylinux build and fall back to node-pty's target prebuild.
|
||||
* @param packageDirectory - installed node-pty package directory.
|
||||
* @param arch - Linux target architecture.
|
||||
* @returns the existing addon path.
|
||||
*/
|
||||
export function resolveLinuxNodePtyAddon(
|
||||
packageDirectory: string,
|
||||
arch: 'x64' | 'arm64',
|
||||
): string {
|
||||
const built = join(packageDirectory, 'build', 'Release', 'pty.node')
|
||||
if (existsSync(built)) return built
|
||||
const prebuilt = join(packageDirectory, 'prebuilds', `linux-${arch}`, 'pty.node')
|
||||
if (existsSync(prebuilt)) return prebuilt
|
||||
throw new Error(
|
||||
`build-exe-for-python-sdk: node-pty addon is absent from both ${built} and ${prebuilt}.`,
|
||||
)
|
||||
}
|
||||
@@ -11,13 +11,15 @@ import { existsSync, statSync } from 'node:fs'
|
||||
import { chmod, copyFile, cp, lstat, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises'
|
||||
import { basename, dirname, join, resolve, sep } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { resolveLinuxNodePtyAddon } from './build-exe-for-python-sdk-native-pty.ts'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
|
||||
/** The closure manifest whose dependencies define the executable. */
|
||||
const DEPLOY_ROOT_PACKAGE = 'dsh-jsonrpc-agent-pkg'
|
||||
const DEPLOY_ROOT_PACKAGE = 'dsh-sdk-python-runtime-closure'
|
||||
/** The closed-runtime app entry inside the deployed closure. */
|
||||
const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh-sdk-jsonrpc-demo/lib/packaged-bin.js'
|
||||
const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh-sdk-python-runtime/lib/packaged-bin.js'
|
||||
/** Stable Python-visible executable basename; rename with the later Python runtime migration. */
|
||||
const OUTPUT_BASENAME = 'dsh-jsonrpc-agent-pkg'
|
||||
/** Default Node major; SEA mode requires at least Node 22. */
|
||||
const DEFAULT_NODE_RANGE = 'node24'
|
||||
@@ -377,7 +379,7 @@ class SingleExeBuild {
|
||||
/**
|
||||
* Package one target; SEA mode accepts one target per invocation.
|
||||
* @param target - the pkg target triple to build.
|
||||
* @returns the executable path and, on macOS, its helper path.
|
||||
* @returns the executable and ripgrep sidecar paths, plus the macOS spawn helper path when required.
|
||||
*/
|
||||
async pack(target: Target): Promise<string[]> {
|
||||
const product = join(this.outDir, `${OUTPUT_BASENAME}-${target.platform}-${target.arch}`)
|
||||
@@ -396,7 +398,8 @@ class SingleExeBuild {
|
||||
if (!this.cli.dryRun && !existsSync(product)) {
|
||||
throw new Error(`build-exe-for-python-sdk: product ${product} is missing after the pkg run; inspect ${this.outDir}.`)
|
||||
}
|
||||
if (target.platform !== 'macos') return [product]
|
||||
const ripgrep = await this.copyRipgrepSidecar(target, product)
|
||||
if (target.platform !== 'macos') return [product, ripgrep]
|
||||
const spawnHelper = `${product}-spawn-helper`
|
||||
const source = join(this.staging, 'node_modules', 'node-pty', 'prebuilds', `darwin-${target.arch}`, 'spawn-helper')
|
||||
if (this.cli.dryRun) {
|
||||
@@ -405,12 +408,36 @@ class SingleExeBuild {
|
||||
await copyFile(source, spawnHelper)
|
||||
await chmod(spawnHelper, 0o755)
|
||||
}
|
||||
return [product, spawnHelper]
|
||||
return [product, ripgrep, spawnHelper]
|
||||
}
|
||||
|
||||
/** Copy the target ripgrep binary beside the executable so Node can spawn it outside pkg's virtual filesystem. */
|
||||
private async copyRipgrepSidecar(target: Target, product: string): Promise<string> {
|
||||
const platform = target.platform === 'macos' ? 'darwin' : target.platform
|
||||
const source = join(
|
||||
this.staging,
|
||||
'node_modules',
|
||||
'@vscode',
|
||||
`ripgrep-${platform}-${target.arch}`,
|
||||
'bin',
|
||||
'rg',
|
||||
)
|
||||
const destination = `${product}-rg`
|
||||
if (this.cli.dryRun) {
|
||||
console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`)
|
||||
return destination
|
||||
}
|
||||
if (!existsSync(source)) {
|
||||
throw new Error(`build-exe-for-python-sdk: target ripgrep binary is missing at ${source}.`)
|
||||
}
|
||||
await copyFile(source, destination)
|
||||
await chmod(destination, 0o755)
|
||||
return destination
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the target node-pty addon in the staged closure. Linux npm installs
|
||||
* build it from source, but legacy deploy omits that side-effect directory.
|
||||
* Put the target node-pty addon in the staged closure. The release workflow
|
||||
* provides a manylinux build; ordinary installs use node-pty's target prebuild.
|
||||
* @param target - the pkg target whose native addon is being staged.
|
||||
*/
|
||||
private async prepareNativePty(target: Target): Promise<void> {
|
||||
@@ -418,8 +445,16 @@ class SingleExeBuild {
|
||||
if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${stagedBuild}`)
|
||||
else await rm(stagedBuild, { recursive: true, force: true })
|
||||
if (target.platform !== 'linux') return
|
||||
const source = join(root, 'packages', 'subprocess', 'subprocess-local', 'node_modules', 'node-pty', 'build', 'Release', 'pty.node')
|
||||
const packageDirectory = join(
|
||||
root,
|
||||
'packages',
|
||||
'subprocess',
|
||||
'subprocess-local',
|
||||
'node_modules',
|
||||
'node-pty',
|
||||
)
|
||||
const destination = join(stagedBuild, 'Release', 'pty.node')
|
||||
const source = resolveLinuxNodePtyAddon(packageDirectory, target.arch)
|
||||
if (this.cli.dryRun) {
|
||||
console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`)
|
||||
return
|
||||
|
||||
@@ -48,7 +48,8 @@ PLATFORMS = load_platforms()
|
||||
|
||||
|
||||
def runtime_suffixes(executable_name: str) -> tuple[str, ...]:
|
||||
return ("", "-spawn-helper") if "-macos-" in executable_name else ("",)
|
||||
suffixes = ("", "-rg")
|
||||
return (*suffixes, "-spawn-helper") if "-macos-" in executable_name else suffixes
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/** Run the complete repository build and bind its client artifacts to their public environment. */
|
||||
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { rmSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
import {
|
||||
CLIENT_BUILD_RECORD_PATH,
|
||||
clientBuildProcessEnvironment,
|
||||
repositoryCommitHash,
|
||||
resolveClientBuildEnvironment,
|
||||
writeClientBuildRecord,
|
||||
} from './client-build-environment.ts'
|
||||
import { pnpmInvocation } from './pnpm-invocation.ts'
|
||||
|
||||
/** Run one package script through the package manager that invoked this build. */
|
||||
function runScript(script: string, environment: NodeJS.ProcessEnv): void {
|
||||
const invocation = pnpmInvocation(['run', script], environment)
|
||||
const result = spawnSync(invocation.command, invocation.args, {
|
||||
cwd: resolve(import.meta.dirname, '..'),
|
||||
env: environment,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
if (result.error !== undefined) throw result.error
|
||||
if (result.status !== 0) {
|
||||
throw new Error(`build: ${script} exited with ${String(result.status ?? result.signal)}`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Run the full build selected by `--profile` or `DSH_BUILD_CLIENT_PROFILE`. */
|
||||
function main(): void {
|
||||
const { values } = parseArgs({
|
||||
options: { profile: { type: 'string' } },
|
||||
allowPositionals: false,
|
||||
})
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const parentEnvironment = {
|
||||
...process.env,
|
||||
DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, process.env),
|
||||
}
|
||||
const clientEnvironment = resolveClientBuildEnvironment(parentEnvironment, values.profile)
|
||||
const buildEnvironment = clientBuildProcessEnvironment(parentEnvironment, clientEnvironment)
|
||||
|
||||
rmSync(resolve(root, CLIENT_BUILD_RECORD_PATH), { force: true })
|
||||
runScript('build:lib', buildEnvironment)
|
||||
runScript('build:web', buildEnvironment)
|
||||
const record = writeClientBuildRecord(root, clientEnvironment)
|
||||
console.log(
|
||||
`build: recorded ${String(record.artifacts.fileCount)} client artifact(s) with ${String(Object.keys(record.environment).length)} public value(s)`,
|
||||
)
|
||||
}
|
||||
|
||||
if (import.meta.main) main()
|
||||
@@ -0,0 +1,100 @@
|
||||
/** Experimental-package publication and dependency constraints. */
|
||||
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
checkExperimentalDependencyIsolation,
|
||||
checkExperimentalManifest,
|
||||
checkWorkspaceManifest,
|
||||
type WorkspaceManifest,
|
||||
} from './check-workspace-constraints.ts'
|
||||
|
||||
const experimental: WorkspaceManifest = {
|
||||
dir: 'packages/experimental/prototype',
|
||||
manifest: { name: '@deepseek-ai/dsh-experimental-prototype', private: true },
|
||||
}
|
||||
|
||||
describe('experimental workspace constraints', () => {
|
||||
it('requires the experimental package-name prefix', () => {
|
||||
expect(checkExperimentalManifest({
|
||||
...experimental,
|
||||
manifest: { ...experimental.manifest, name: '@deepseek-ai/dsh-prototype' },
|
||||
})).toEqual([
|
||||
'@deepseek-ai/dsh-prototype: experimental package name must start with "@deepseek-ai/dsh-experimental-"',
|
||||
])
|
||||
})
|
||||
|
||||
it('requires private manifests without publication metadata', () => {
|
||||
expect(checkExperimentalManifest(experimental)).toEqual([])
|
||||
expect(checkExperimentalManifest({
|
||||
...experimental,
|
||||
manifest: { ...experimental.manifest, private: false, publishConfig: { access: 'public' } },
|
||||
})).toEqual([
|
||||
'@deepseek-ai/dsh-experimental-prototype: experimental package must set "private": true',
|
||||
'@deepseek-ai/dsh-experimental-prototype: experimental package must omit publishConfig',
|
||||
])
|
||||
})
|
||||
|
||||
it.each(['dependencies', 'optionalDependencies', 'peerDependencies'] as const)(
|
||||
'rejects release %s on an experimental package',
|
||||
(section) => {
|
||||
expect(checkExperimentalDependencyIsolation([experimental, {
|
||||
dir: 'packages/core/consumer',
|
||||
manifest: {
|
||||
name: '@deepseek-ai/dsh-consumer',
|
||||
[section]: { '@deepseek-ai/dsh-experimental-prototype': 'workspace:^' },
|
||||
},
|
||||
}])).toEqual([
|
||||
`@deepseek-ai/dsh-consumer: ${section}.@deepseek-ai/dsh-experimental-prototype must not reference an experimental package`,
|
||||
])
|
||||
},
|
||||
)
|
||||
|
||||
it('allows development and experimental consumers but rejects the Python release runtime', () => {
|
||||
const manifests: WorkspaceManifest[] = [experimental, {
|
||||
dir: 'packages/core/test-only',
|
||||
manifest: {
|
||||
name: '@deepseek-ai/dsh-test-only',
|
||||
devDependencies: { '@deepseek-ai/dsh-experimental-prototype': 'workspace:^' },
|
||||
},
|
||||
}, {
|
||||
dir: 'packages/experimental/consumer',
|
||||
manifest: {
|
||||
name: '@deepseek-ai/dsh-experimental-consumer',
|
||||
dependencies: { '@deepseek-ai/dsh-experimental-prototype': 'workspace:^' },
|
||||
},
|
||||
}, {
|
||||
dir: 'python/sdk-runtime',
|
||||
manifest: {
|
||||
name: '@deepseek-ai/dsh-python-runtime',
|
||||
dependencies: { '@deepseek-ai/dsh-experimental-prototype': 'workspace:^' },
|
||||
},
|
||||
}]
|
||||
|
||||
expect(checkExperimentalDependencyIsolation(manifests)).toEqual([
|
||||
'@deepseek-ai/dsh-python-runtime: dependencies.@deepseek-ai/dsh-experimental-prototype must not reference an experimental package',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('private Python runtime carrier', () => {
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(new URL('../packages/sdk/python-runtime/package.json', import.meta.url), 'utf8'),
|
||||
) as WorkspaceManifest['manifest']
|
||||
|
||||
it('participates in dsh package checks without becoming an npm release member', () => {
|
||||
expect(checkWorkspaceManifest({ dir: 'packages/sdk/python-runtime', manifest })).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects publication metadata on the private carrier', () => {
|
||||
const path = join('packages', 'sdk', 'python-runtime', 'package.json')
|
||||
expect(checkWorkspaceManifest({
|
||||
dir: 'packages/sdk/python-runtime',
|
||||
manifest: { ...manifest, private: false, publishConfig: { access: 'public' } },
|
||||
})).toEqual([
|
||||
`${path}: @deepseek-ai/dsh-sdk-python-runtime: private carrier must set "private": true`,
|
||||
`${path}: @deepseek-ai/dsh-sdk-python-runtime: private carrier must omit publishConfig`,
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
||||
import { join, relative, resolve } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { hasTypertRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
|
||||
import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts'
|
||||
|
||||
@@ -47,19 +48,26 @@ const repositoryUrl = 'git+https://github.com/deepseek-harness/deepseek-harness.
|
||||
* their trusted publishing against the repository that runs the workflow.
|
||||
*/
|
||||
const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harness.git'
|
||||
/** Private packages that participate in workspace checks but not releases. */
|
||||
const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/
|
||||
/** npm namespace reserved for private experimental packages. */
|
||||
const experimentalPackageNamePrefix = '@deepseek-ai/dsh-experimental-'
|
||||
/** Directories whose packages this repository publishes: one release member each. */
|
||||
const releaseMemberDirectory = /^(?:packages\/[^/]+\/[^/]+|apps\/[^/]+|vendor\/[^/]+)$/
|
||||
const releaseMemberDirectory = /^(?:packages\/(?!experimental\/)[^/]+\/[^/]+|apps\/[^/]+|vendor\/[^/]+)$/
|
||||
/** Named dsh packages that remain private because another distribution embeds them. */
|
||||
const privateCarrierDirectories = new Set(['packages/sdk/python-runtime'])
|
||||
|
||||
const localArtifactDirs = new Set(['node_modules'])
|
||||
const appPackageFiles: Readonly<Record<string, readonly string[]>> = {
|
||||
'@deepseek-ai/dsh': ['lib/*.js', 'config'],
|
||||
// The Web build emits sourcemaps for browser debugging; publishing them is
|
||||
// what the payload policy forbids, so the bundle ships without them.
|
||||
'@deepseek-ai/dsh-web-frontend': ['dist', '!dist/**/*.map'],
|
||||
// Sourcemaps stay out by payload policy; the worker-preview surface
|
||||
// (dist/preview.html and dist/preview/) backs private experimental
|
||||
// packages and is not published.
|
||||
'@deepseek-ai/dsh-web-frontend': ['dist', '!dist/**/*.map', '!dist/preview.html', '!dist/preview'],
|
||||
}
|
||||
|
||||
/** The subset of package.json fields this constraint check cares about. */
|
||||
interface PackageManifest {
|
||||
export interface PackageManifest {
|
||||
name?: string
|
||||
version?: string
|
||||
private?: boolean
|
||||
@@ -84,10 +92,15 @@ interface PackageManifest {
|
||||
devDependencies?: Record<string, string>
|
||||
dependencies?: Record<string, string>
|
||||
optionalDependencies?: Record<string, string>
|
||||
dsh?: {
|
||||
bundle?: {
|
||||
patch?: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One workspace manifest and its repo-relative path. */
|
||||
interface WorkspaceManifest {
|
||||
export interface WorkspaceManifest {
|
||||
dir: string
|
||||
manifest: PackageManifest
|
||||
}
|
||||
@@ -131,19 +144,29 @@ function workspaceManifests(): WorkspaceManifest[] {
|
||||
}
|
||||
|
||||
const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
|
||||
// Profile bundles publish their dsh.bundle.patch layer beside the lib.
|
||||
'@deepseek-ai/dsh-base': ['cordis.patch.yml'],
|
||||
'@deepseek-ai/dsh-web-app': ['cordis.patch.yml'],
|
||||
'@deepseek-ai/dsh-headless': ['cordis.patch.yml'],
|
||||
// Statically linked client libraries keep their stylesheets next to the emitted
|
||||
// JavaScript, which imports them by relative path: the compile shell runs
|
||||
// them through its own CSS pipeline, so the sheets are published artifacts.
|
||||
// The glob covers whichever sheets a package emits; sourcemaps stay
|
||||
// unpublished, as everywhere else in the repository.
|
||||
'@deepseek-ai/dsh-client-ui-primitives': ['lib/**/*.css'],
|
||||
'@deepseek-ai/dsh-client-web': ['lib/**/*.css'],
|
||||
'@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
|
||||
// The Python runtime uses a distinct closed-resolution bin; the public CLI
|
||||
// keeps config-owned bare-package resolution through lib/bin.js.
|
||||
'@deepseek-ai/dsh-sdk-jsonrpc-demo': ['lib/packaged-bin.js'],
|
||||
// The CPython side ships as source .py files, published as-is rather than built.
|
||||
'@deepseek-ai/dsh-code-runtime-python': ['py/**/*.py'],
|
||||
// The private Python carrier ships only its closed-resolution entry.
|
||||
'@deepseek-ai/dsh-sdk-python-runtime': ['lib/packaged-bin.js'],
|
||||
// The argv-prefix runner entry ships beside the lib as its own bundle;
|
||||
// sandbox-local resolves it through the package's ./runner export. tsdown
|
||||
// also shares its generated FFI code through a hashed runtime chunk.
|
||||
'@deepseek-ai/dsh-sandbox-windows-acl': ['lib/runner.js', 'lib/types-*.js'],
|
||||
// SQLite loads every statement from immutable package resources at runtime.
|
||||
'@deepseek-ai/dsh-session-persistence-sqlite': ['resources/sql/**/*.sql'],
|
||||
'@deepseek-ai/dsh-skill-badge': ['assets'],
|
||||
// tsdown shares the repository/pack code between the lib entry and the bin
|
||||
// through a hashed chunk. The committed bin.js is the link target pnpm can
|
||||
// resolve at install time, before the build produces lib/bin.js.
|
||||
'@deepseek-ai/dsh-experimental-webworker-packer': ['bin.js', 'lib/repository-*.js'],
|
||||
'@deepseek-ai/dsh-subprocess-local': ['scripts/ensure-spawn-helper.mjs'],
|
||||
}
|
||||
|
||||
@@ -152,14 +175,23 @@ function sameStringList(actual: readonly string[] | undefined, expected: readonl
|
||||
}
|
||||
|
||||
function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
|
||||
const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
|
||||
const declaredPatch = manifest.dsh?.bundle?.patch
|
||||
const bundleFiles = declaredPatch === undefined ? [] : [declaredPatch.replace(/^\.\//, '')]
|
||||
const extras = [
|
||||
...bundleFiles,
|
||||
...(manifest.name ? packageFileExtras[manifest.name] ?? [] : []),
|
||||
]
|
||||
return [
|
||||
'lib/index.js',
|
||||
// Every package publishes its invariant ownership companion as a separate
|
||||
// bundle; the package-invariant gate validates the companion itself.
|
||||
'lib/invariant.js',
|
||||
...manifest.bin ? ['lib/bin.js'] : [],
|
||||
...manifest.exports?.['./worker'] ? ['lib/worker.cjs'] : [],
|
||||
// Worker-thread packages ship a CJS worker entry; the browser worker
|
||||
// bundle is an ES module a page loads with `new Worker(type: 'module')`.
|
||||
// Keyed on the artifact path, like ./client below.
|
||||
...exportDefault(manifest, './worker') === './lib/worker.cjs' ? ['lib/worker.cjs'] : [],
|
||||
...exportDefault(manifest, './worker') === './lib/worker.js' ? ['lib/worker.js'] : [],
|
||||
// UI plugin packages ship their browser bundle beside the node lib
|
||||
// (single-artifact ruling: dist/ retired, ./client resolves lib/client.js).
|
||||
// Keyed on the artifact path, not the subpath name: apiproxy's ./client is
|
||||
@@ -167,7 +199,7 @@ function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
|
||||
...exportDefault(manifest, './client') === './lib/client.js' ? ['lib/client.js'] : [],
|
||||
// runtime's shell-held loader subpath ships as its own bundle beside the client half.
|
||||
...exportDefault(manifest, './loader') === './lib/loader.js' ? ['lib/loader.js'] : [],
|
||||
// web-react's store subpath ships its own bundle (single-entry builds; no shared chunk).
|
||||
// A store subpath ships its own bundle (single-entry builds; no shared chunk).
|
||||
...exportDefault(manifest, './store') === './lib/store/index.js' ? ['lib/store/index.js'] : [],
|
||||
// A surface bundle's startup row is its own bundle: the Loader imports it
|
||||
// as a row module, so it cannot ride inside the package entry.
|
||||
@@ -219,8 +251,26 @@ function usesEmittedTreeDefaults(manifest: PackageManifest): boolean {
|
||||
exportDefault(manifest, subpath)?.startsWith('./lib/types/') === true)
|
||||
}
|
||||
|
||||
function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
|
||||
/** Experimental manifest requirements enforced independently from release metadata. */
|
||||
export function checkExperimentalManifest({ dir, manifest }: WorkspaceManifest): string[] {
|
||||
if (!experimentalPackageDirectory.test(dir)) return []
|
||||
const label = manifest.name ?? dir
|
||||
const errors: string[] = []
|
||||
if (manifest.name?.startsWith(experimentalPackageNamePrefix) !== true) {
|
||||
errors.push(`${label}: experimental package name must start with ${JSON.stringify(experimentalPackageNamePrefix)}`)
|
||||
}
|
||||
if (manifest.private !== true) errors.push(`${label}: experimental package must set "private": true`)
|
||||
if (manifest.publishConfig !== undefined) errors.push(`${label}: experimental package must omit publishConfig`)
|
||||
return errors
|
||||
}
|
||||
|
||||
/**
|
||||
* Check one workspace manifest against publication and dsh-package policy.
|
||||
* @param workspace - package directory and parsed manifest.
|
||||
* @returns path-qualified policy violations.
|
||||
*/
|
||||
export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): string[] {
|
||||
const errors = checkExperimentalManifest({ dir, manifest })
|
||||
const label = manifest.name ?? dir
|
||||
const isLandlockPackageDir = dir.startsWith('native/landlock-run/packages/')
|
||||
const isPublicLandlockPackage = isLandlockPackageDir
|
||||
@@ -240,6 +290,13 @@ function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
|
||||
|| manifest.repository.directory !== expectedDirectory) {
|
||||
errors.push(`${label}: published Landlock package repository must use ${repositoryUrl} with directory ${expectedDirectory} for trusted publishing`)
|
||||
}
|
||||
} else if (privateCarrierDirectories.has(dir)) {
|
||||
if (manifest.private !== true) {
|
||||
errors.push(`${label}: private carrier must set "private": true`)
|
||||
}
|
||||
if (manifest.publishConfig !== undefined) {
|
||||
errors.push(`${label}: private carrier must omit publishConfig`)
|
||||
}
|
||||
} else if (releaseMemberDirectory.test(dir)) {
|
||||
// Release members state that they are publishable: npm refuses a private
|
||||
// package, and the repository field is how a consumer finds the source of
|
||||
@@ -251,19 +308,18 @@ function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
|
||||
// public. A mixed scope is why no publish path passes `--access` — one flag
|
||||
// cannot serve both, so each packed manifest decides
|
||||
// ([rationale](../.agents/notes/implemented/process/2026-08-13-public-vendor-and-native-sequences.md)).
|
||||
const expectedAccess = dir.startsWith('vendor/') ? 'public' : 'restricted'
|
||||
if (manifest.private === true) {
|
||||
errors.push(`${label}: release member must not set "private": true`)
|
||||
}
|
||||
if (manifest.publishConfig?.access !== expectedAccess) {
|
||||
errors.push(`${label}: release member must set publishConfig.access to "${expectedAccess}"`)
|
||||
if (manifest.publishConfig?.access !== 'public') {
|
||||
errors.push(`${label}: release member must set publishConfig.access to "public"`)
|
||||
}
|
||||
if (manifest.repository?.type !== 'git'
|
||||
|| manifest.repository.url !== publishedRepositoryUrl
|
||||
|| manifest.repository.directory !== dir) {
|
||||
errors.push(`${label}: release member repository must use ${publishedRepositoryUrl} with directory ${dir}`)
|
||||
}
|
||||
} else if (manifest.private !== true) {
|
||||
} else if (!experimentalPackageDirectory.test(dir) && manifest.private !== true) {
|
||||
errors.push(`${label}: package.json must set "private": true`)
|
||||
}
|
||||
|
||||
@@ -382,6 +438,31 @@ function checkRepositoryVersion(): string[] {
|
||||
|
||||
/** Dependency sections whose ranges reach a published tarball or a local install. */
|
||||
const dependencySections = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'] as const
|
||||
/** Dependency sections present in an installed runtime. */
|
||||
const runtimeDependencySections = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const
|
||||
|
||||
/**
|
||||
* Prevent an official runtime from requiring a package its release omits.
|
||||
* @param manifests - release, private experimental, and deployment-root manifests.
|
||||
* @returns One error for each forbidden runtime dependency.
|
||||
*/
|
||||
export function checkExperimentalDependencyIsolation(manifests: readonly WorkspaceManifest[]): string[] {
|
||||
const experimentalNames = new Set(manifests
|
||||
.filter(entry => experimentalPackageDirectory.test(entry.dir))
|
||||
.map(entry => entry.manifest.name)
|
||||
.filter(name => name !== undefined))
|
||||
const errors: string[] = []
|
||||
for (const { dir, manifest } of manifests) {
|
||||
if (!releaseMemberDirectory.test(dir) && dir !== 'python/sdk-runtime') continue
|
||||
for (const section of runtimeDependencySections) {
|
||||
for (const name of Object.keys(manifest[section] ?? {})) {
|
||||
if (!experimentalNames.has(name)) continue
|
||||
errors.push(`${manifest.name ?? dir}: ${section}.${name} must not reference an experimental package`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
/**
|
||||
* Require the `workspace:` protocol for every reference to a workspace member.
|
||||
@@ -407,15 +488,25 @@ function checkWorkspaceProtocol(manifests: readonly WorkspaceManifest[]): string
|
||||
return errors
|
||||
}
|
||||
|
||||
const manifests = workspaceManifests()
|
||||
const errors = [
|
||||
...checkRepositoryVersion(),
|
||||
...manifests.flatMap(checkWorkspace),
|
||||
...checkWorkspaceProtocol(manifests),
|
||||
...checkHierarchyShape(),
|
||||
...collectProjectReferenceFaceViolations(root),
|
||||
]
|
||||
if (errors.length > 0) {
|
||||
console.error(errors.join('\n'))
|
||||
process.exitCode = 1
|
||||
/** Run the repository constraint gate. */
|
||||
export function main(): void {
|
||||
const manifests = workspaceManifests()
|
||||
const dependencyManifests = [
|
||||
...manifests,
|
||||
{ dir: 'python/sdk-runtime', manifest: readJson(join(root, 'python/sdk-runtime/package.json')) },
|
||||
]
|
||||
const errors = [
|
||||
...checkRepositoryVersion(),
|
||||
...manifests.flatMap(checkWorkspaceManifest),
|
||||
...checkWorkspaceProtocol(manifests),
|
||||
...checkExperimentalDependencyIsolation(dependencyManifests),
|
||||
...checkHierarchyShape(),
|
||||
...collectProjectReferenceFaceViolations(root),
|
||||
]
|
||||
if (errors.length > 0) {
|
||||
console.error(errors.join('\n'))
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main()
|
||||
+222
-51
@@ -5,43 +5,60 @@ import { describe, expect, it } from 'vitest'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const runnerPrivatePnpmDestination = '${{ runner.temp }}/setup-pnpm'
|
||||
const nativeWindowsPnpmDestination = '${{ runner.temp }}/setup-pnpm-js'
|
||||
|
||||
describe('CI workflow', () => {
|
||||
it('isolates every pnpm action setup destination per runner', () => {
|
||||
const workflow: unknown = yaml.load(readFileSync(resolve(root, '.github/workflows/ci.yml'), 'utf8'))
|
||||
if (!isRecord(workflow) || !isRecord(workflow.jobs)) throw new TypeError('CI workflow must define jobs')
|
||||
|
||||
const setups = Object.entries(workflow.jobs).flatMap(([jobName, job]) => {
|
||||
if (!isRecord(job) || !Array.isArray(job.steps)) return []
|
||||
return job.steps.flatMap((step) => {
|
||||
if (!isRecord(step) || typeof step.uses !== 'string' || !step.uses.startsWith('pnpm/action-setup@')) return []
|
||||
return [{ jobName, step }]
|
||||
})
|
||||
})
|
||||
const files = ['.github/workflows/ci.yml', '.github/workflows/ci-master.yml']
|
||||
const setups: Array<{ jobName: string; step: unknown }> = []
|
||||
for (const file of files) {
|
||||
const workflow: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'))
|
||||
if (!isRecord(workflow) || !isRecord(workflow.jobs)) throw new TypeError(`${file} must define jobs`)
|
||||
for (const [jobName, job] of Object.entries(workflow.jobs)) {
|
||||
if (!isRecord(job) || !Array.isArray(job.steps)) continue
|
||||
for (const step of job.steps) {
|
||||
if (!isRecord(step) || typeof step.uses !== 'string' || !step.uses.startsWith('pnpm/action-setup@')) continue
|
||||
setups.push({ jobName, step })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(setups.length).toBeGreaterThan(0)
|
||||
for (const { jobName, step } of setups) {
|
||||
expect(step, `${jobName} must not share pnpm/action-setup's default destination`).toMatchObject({
|
||||
with: { dest: runnerPrivatePnpmDestination },
|
||||
with: {
|
||||
dest: jobName === 'windows-native'
|
||||
? nativeWindowsPnpmDestination
|
||||
: runnerPrivatePnpmDestination,
|
||||
},
|
||||
})
|
||||
if (jobName === 'windows-native') expect(step).not.toMatchObject({ with: { standalone: true } })
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a required Wine Windows job, a non-blocking native Windows job with failover, and a master-only standby', () => {
|
||||
it('keeps required Wine and native Windows jobs with failover, plus a master-only standby', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/ci.yml')
|
||||
const masterWorkflow = loadWorkflow('.github/workflows/ci-master.yml')
|
||||
if (!isRecord(workflow.jobs)
|
||||
|| !isRecord(workflow.jobs.windows)
|
||||
|| !isRecord(workflow.jobs['windows-native'])
|
||||
|| !isRecord(workflow.jobs['wine-apt-cache'])
|
||||
|| !isRecord(workflow.jobs['serial-windows'])
|
||||
|| !isRecord(workflow.jobs['all-checks-passed'])) {
|
||||
throw new TypeError('CI workflow must define windows, windows-native, wine-apt-cache, serial-windows, and all-checks-passed jobs')
|
||||
|| !isRecord(workflow.jobs['node-24'])
|
||||
|| !isRecord(workflow.jobs['node-24-coverage'])
|
||||
|| !isRecord(workflow.jobs['node-24-consumers'])
|
||||
|| !isRecord(workflow.jobs['all-checks-passed'])
|
||||
|| !isRecord(masterWorkflow.jobs)
|
||||
|| !isRecord(masterWorkflow.jobs['wine-apt-cache'])
|
||||
|| !isRecord(masterWorkflow.jobs['serial-windows'])) {
|
||||
throw new TypeError('CI workflow must define windows, windows-native, node-24, node-24-coverage, node-24-consumers, and all-checks-passed; ci-master must define wine-apt-cache and serial-windows')
|
||||
}
|
||||
|
||||
const windows = workflow.jobs.windows
|
||||
const windowsNative = workflow.jobs['windows-native']
|
||||
const wineAptCache = workflow.jobs['wine-apt-cache']
|
||||
const serialWindows = workflow.jobs['serial-windows']
|
||||
const wineAptCache = masterWorkflow.jobs['wine-apt-cache']
|
||||
const serialWindows = masterWorkflow.jobs['serial-windows']
|
||||
const node24 = workflow.jobs['node-24']
|
||||
const node24Coverage = workflow.jobs['node-24-coverage']
|
||||
const node24Consumers = workflow.jobs['node-24-consumers']
|
||||
const aggregate = workflow.jobs['all-checks-passed']
|
||||
if (!Array.isArray(windows.steps) || !Array.isArray(aggregate.needs)) {
|
||||
throw new TypeError('Windows job must define steps and the aggregate must define needs')
|
||||
@@ -56,38 +73,72 @@ describe('CI workflow', () => {
|
||||
expect(windows.if).toBe("github.event_name == 'pull_request'")
|
||||
expect(commandSteps.some(step => step.run.includes('wine-windows-gates.sh'))).toBe(true)
|
||||
|
||||
// windows-native: non-blocking native job with failover, runs windows-complete.
|
||||
// windows-native: blocking native job with failover, runs windows-complete.
|
||||
// Its pool is resolved by the Windows-specific switch.
|
||||
expect(typeof windowsNative['runs-on']).toBe('string')
|
||||
expect(windowsNative['runs-on']).toContain('DSH_CI_FAILOVER')
|
||||
expect(windowsNative['runs-on']).toContain('DSH_CI_FAILOVER_WINDOWS')
|
||||
expect(windowsNative['runs-on']).not.toContain('DSH_CI_FAILOVER_LINUX')
|
||||
expect(windowsNative['runs-on']).toContain('self-hosted')
|
||||
expect(windowsNative['runs-on']).toContain('dsh-win-ci')
|
||||
expect(windowsNative['runs-on']).toContain('dsh-windows-2025-16core')
|
||||
expect(windowsNative.name).toBe('windows node 24 / native complete')
|
||||
expect(windowsNative.if).toBe("github.event_name == 'pull_request'")
|
||||
const nativeCommandSteps = (windowsNative.steps as unknown[]).filter((step): step is Record<string, unknown> & { run: string } => (
|
||||
expect(windowsNative.env).toMatchObject({
|
||||
DSH_COVERAGE_MAX_WORKERS: '12',
|
||||
DSH_COVERAGE_PARTITIONS: '16',
|
||||
DSH_COVERAGE_TEST_TIMEOUT_MS: '30000',
|
||||
DSH_GATE_CONCURRENCY: '8',
|
||||
})
|
||||
const nativeSteps = windowsNative.steps as unknown[]
|
||||
const nativeCommandSteps = nativeSteps.filter((step): step is Record<string, unknown> & { run: string } => (
|
||||
isRecord(step) && typeof step.run === 'string'
|
||||
))
|
||||
expect(nativeCommandSteps.map(step => step.run)).toContain('pnpm run check:ci:windows-complete')
|
||||
|
||||
// wine-apt-cache: master-only, seeds the Wine apt cache.
|
||||
// wine-apt-cache: master-only, seeds the Wine apt cache, lives in ci-master.
|
||||
expect(wineAptCache.if).toBe("github.event_name == 'push' && github.ref == 'refs/heads/master'")
|
||||
expect(wineAptCache['runs-on']).toBe('ubuntu-latest')
|
||||
|
||||
// serial-windows: master-only standby, self-hosted, non-blocking.
|
||||
// serial-windows: master-only standby, self-hosted, non-blocking, lives in ci-master.
|
||||
expect(serialWindows.if).toBe("github.event_name == 'push' && github.ref == 'refs/heads/master'")
|
||||
expect(serialWindows['runs-on']).toEqual(['self-hosted', 'dsh-win-ci', 'windows'])
|
||||
expect(serialWindows.name).toBe('serial / windows (self-hosted standby)')
|
||||
|
||||
// Aggregate: Wine `windows` required, native `windows-native` excluded.
|
||||
// Aggregate: both complementary Windows jobs are required.
|
||||
expect(aggregate.needs).toContain('windows')
|
||||
expect(aggregate.needs).not.toContain('windows-native')
|
||||
expect(aggregate.needs).toContain('windows-native')
|
||||
expect(aggregate.needs).not.toContain('serial-windows')
|
||||
|
||||
// Linux failover is a separate switch: the three required Linux workers
|
||||
// and the verdict job resolve their pool through DSH_CI_FAILOVER_LINUX,
|
||||
// never the Windows switch.
|
||||
for (const [jobName, job] of [['node-24', node24], ['node-24-coverage', node24Coverage], ['node-24-consumers', node24Consumers]] as const) {
|
||||
expect(typeof job['runs-on']).toBe('string')
|
||||
expect(job['runs-on'], `${jobName} runs-on must use the Linux failover switch`).toContain('DSH_CI_FAILOVER_LINUX')
|
||||
expect(job['runs-on'], `${jobName} runs-on must not use the Windows failover switch`).not.toContain('DSH_CI_FAILOVER_WINDOWS')
|
||||
expect(job['runs-on']).toContain('vm-backup')
|
||||
}
|
||||
expect(aggregate['runs-on']).toContain('DSH_CI_FAILOVER_LINUX')
|
||||
expect(aggregate['runs-on']).not.toContain('DSH_CI_FAILOVER_WINDOWS')
|
||||
expect(aggregate['runs-on']).toContain('vm-backup')
|
||||
})
|
||||
|
||||
it('exempts push from cancellation, so one master merge does not cancel the running drill', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/ci.yml')
|
||||
it('gives the Wine Host TypeScript compile the repository heap budget', () => {
|
||||
const wineGates = readFileSync(resolve(root, 'scripts/wine-windows-gates.sh'), 'utf8')
|
||||
|
||||
expect(wineGates).toContain(
|
||||
'wine_node "$scratch/logs/host-tsc.log" --max-old-space-size=4096 "$tsc_js" -b tsconfig.host.json --pretty false',
|
||||
)
|
||||
})
|
||||
|
||||
it('exempts push from cancellation in ci-master, so one master merge does not cancel the running drill', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/ci-master.yml')
|
||||
const prWorkflow = loadWorkflow('.github/workflows/ci.yml')
|
||||
if (!isRecord(workflow.jobs) || !isRecord(workflow.concurrency)) {
|
||||
throw new TypeError('CI workflow must define jobs and a workflow-level concurrency block')
|
||||
throw new TypeError('ci-master workflow must define jobs and a workflow-level concurrency block')
|
||||
}
|
||||
if (!isRecord(prWorkflow.jobs)) {
|
||||
throw new TypeError('ci workflow must define jobs')
|
||||
}
|
||||
|
||||
// Cancellation applies to the whole superseded RUN, so this has to be
|
||||
@@ -96,11 +147,26 @@ describe('CI workflow', () => {
|
||||
// a drill takes longer than the interval between master merges. The negated
|
||||
// form is load-bearing: `== 'pull_request'` would also stop cancelling
|
||||
// workflow_dispatch, and a re-dispatched runner benchmark holds up to 12
|
||||
// larger runners for 15 minutes in this same group on master. The
|
||||
// expression is evaluated against the NEWLY TRIGGERED run, so a dispatch on
|
||||
// master still cancels a mid-flight drill; the runbook records that bound.
|
||||
// larger runners for 15 minutes in this same group on master.
|
||||
expect(workflow.concurrency['cancel-in-progress']).toBe("${{ github.event_name != 'push' }}")
|
||||
|
||||
// The PR-only ci.yml still cancels a superseded run on a new push, so a
|
||||
// fresh head does not stack a second full 9-job run behind a stale one.
|
||||
// Unlike ci-master it has no push carve-out: every PR event supersedes.
|
||||
expect(prWorkflow.concurrency).toMatchObject({
|
||||
'cancel-in-progress': true,
|
||||
})
|
||||
|
||||
// The exact event sets are what keep master-only jobs out of the PR check
|
||||
// panel: ci-master triggers only on push(master) + workflow_dispatch and
|
||||
// never on pull_request; ci.yml is exactly pull_request-only. Assert the
|
||||
// full sets so losing the wrong event, or gaining an extra one, fails.
|
||||
if (!isRecord(workflow.on) || !isRecord(prWorkflow.on)) {
|
||||
throw new TypeError('both CI workflows must define on')
|
||||
}
|
||||
expect(Object.keys(workflow.on).sort()).toEqual(['push', 'workflow_dispatch'])
|
||||
expect(Object.keys(prWorkflow.on)).toEqual(['pull_request'])
|
||||
|
||||
// Neither drill may carry a job-level group: it would not exempt the job
|
||||
// from run-scoped cancellation.
|
||||
for (const name of ['serial-linux-selfhosted', 'serial-windows']) {
|
||||
@@ -114,14 +180,7 @@ describe('CI workflow', () => {
|
||||
// What bounds the cost of exempting push: a master push may only carry the
|
||||
// cache seeder and the two drills. Any job reachable on push would start
|
||||
// accumulating uncancelled runs, so the set is pinned here.
|
||||
//
|
||||
// Classification is an exact allowlist of the conditions in use, not a
|
||||
// substring match: `github.event_name != 'pull_request'` mentions
|
||||
// `pull_request` yet IS push-reachable, so matching on the event name alone
|
||||
// would silently misclassify it as gated.
|
||||
const NOT_PUSH_REACHABLE = new Set([
|
||||
"github.event_name == 'pull_request'",
|
||||
"always() && github.event_name == 'pull_request'",
|
||||
"github.event_name == 'workflow_dispatch' && inputs.suite == 'larger-runner-benchmark'",
|
||||
"github.event_name == 'workflow_dispatch' && inputs.suite == 'consolidated-runner-benchmark'",
|
||||
])
|
||||
@@ -187,6 +246,29 @@ describe('CI workflow', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('DeepSeek e2e workflow', () => {
|
||||
it('prepares bubblewrap from the pinned payload without a package transaction', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/e2e.yml')
|
||||
const e2e = workflowJob(workflow, 'e2e')
|
||||
if (!Array.isArray(e2e.steps)) throw new TypeError('DeepSeek e2e workflow must define steps')
|
||||
|
||||
const steps = e2e.steps.filter(isRecord)
|
||||
expect(steps.find(step => step.name === 'Prepare bubblewrap (unrestrict userns)')).toMatchObject({
|
||||
run: 'bash scripts/prepare-ci-bubblewrap.sh',
|
||||
})
|
||||
expect(JSON.stringify(steps)).not.toContain('apt-get')
|
||||
})
|
||||
|
||||
it('bounds profile subprocess fan-out to the tested e2e default', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/e2e.yml')
|
||||
const e2e = workflowJob(workflow, 'e2e')
|
||||
if (!Array.isArray(e2e.steps)) throw new TypeError('DeepSeek e2e workflow must define steps')
|
||||
|
||||
const step = e2e.steps.filter(isRecord).find(candidate => candidate.name === 'E2E tests (real DeepSeek API)')
|
||||
expect(step).toMatchObject({ env: { DSH_E2E_MAX_WORKERS: 4 } })
|
||||
})
|
||||
})
|
||||
|
||||
describe('E2B e2e workflow', () => {
|
||||
it('is manual-only and fails loud before running the focused live suite', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/e2b-e2e.yml')
|
||||
@@ -218,7 +300,6 @@ describe('Python release workflows', () => {
|
||||
it('keeps complete wheel validation separate from protected public publication', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/python-release.yml')
|
||||
const dispatch = workflowEvent(workflow, 'workflow_dispatch')
|
||||
const pullRequest = workflowEvent(workflow, 'pull_request')
|
||||
const build = workflowJob(workflow, 'build')
|
||||
const pythonCompat = workflowJob(workflow, 'python-compat')
|
||||
const validate = workflowJob(workflow, 'validate')
|
||||
@@ -234,9 +315,9 @@ describe('Python release workflows', () => {
|
||||
}
|
||||
|
||||
expect(dispatch.inputs.publish).toMatchObject({ type: 'boolean', default: false })
|
||||
expect(pullRequest).toEqual({ types: ['labeled'] })
|
||||
if (!isRecord(workflow.on)) throw new TypeError('python-release workflow must define on')
|
||||
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
|
||||
expect(build).toMatchObject({
|
||||
if: "github.event_name == 'workflow_dispatch' || github.event.label.name == 'python-release-dry-run'",
|
||||
uses: './.github/workflows/build-exe-for-python-sdk.yml',
|
||||
with: {
|
||||
targets: 'node24-linux-x64,node24-linux-arm64,node24-macos-arm64',
|
||||
@@ -244,7 +325,10 @@ describe('Python release workflows', () => {
|
||||
},
|
||||
})
|
||||
expect(pythonCompat.strategy).toMatchObject({ matrix: { python: ['3.10', '3.14'] } })
|
||||
expect(JSON.stringify(pythonCompat.steps)).toContain('deepseek-harness-sdk==${{ steps.compatibility-version.outputs.version }}')
|
||||
const pythonCompatSteps = JSON.stringify(pythonCompat.steps)
|
||||
expect(pythonCompatSteps).toContain('dist/deepseek_harness_sdk-$VERSION-py3-none-any.whl')
|
||||
expect(pythonCompatSteps).toContain('dist/deepseek_harness_runtime_bin-$VERSION-py3-none-manylinux_2_28_x86_64.whl')
|
||||
expect(pythonCompatSteps).not.toContain('--find-links')
|
||||
const validateSteps = JSON.stringify(validate.steps)
|
||||
const authorize = validate.steps.filter(isRecord).find(step => step.name === 'Authorize publication request')
|
||||
if (!isRecord(authorize) || typeof authorize.run !== 'string') {
|
||||
@@ -317,10 +401,18 @@ describe('Python release workflows', () => {
|
||||
expect(plan.if).toContain('inputs.ci')
|
||||
expect(plan.if).toContain('inputs.release')
|
||||
expect(JSON.stringify(plan.steps)).toContain('pep440_version')
|
||||
expect(JSON.stringify(workflow)).toContain('macosx_14_0_arm64')
|
||||
const workflowJson = JSON.stringify(workflow)
|
||||
expect(workflowJson).toContain('macosx_14_0_arm64')
|
||||
expect(workflowJson).toContain('dist-python/$SDK_WHEEL')
|
||||
expect(workflowJson).toContain('dist-python/$RUNTIME_WHEEL')
|
||||
expect(workflowJson).toContain('/work/dist-python/$SDK_WHEEL')
|
||||
expect(workflowJson).toContain('/work/dist-python/$RUNTIME_WHEEL')
|
||||
expect(workflowJson).not.toContain('--find-links dist-python')
|
||||
expect(workflowJson).not.toContain('--find-links /work/dist-python')
|
||||
expect(manylinuxAddon).toMatchObject({ if: "runner.os == 'Linux'" })
|
||||
expect(JSON.stringify(manylinuxAddon)).toContain('manylinux_2_28_x86_64')
|
||||
expect(JSON.stringify(manylinuxAddon)).toContain('manylinux_2_28_aarch64')
|
||||
expect(JSON.stringify(manylinuxAddon)).toContain('npm_config_build_from_source=true pnpm run install')
|
||||
expect(JSON.stringify(manylinuxAddon)).toContain('$HOME/setup-pnpm:$HOME/setup-pnpm:ro')
|
||||
expect(JSON.stringify(manylinuxAddon)).toContain('node-pty-glibc-versions.txt')
|
||||
expect(JSON.stringify(manylinuxAddon)).toContain('le 2.28')
|
||||
@@ -351,24 +443,103 @@ describe('Python release workflows', () => {
|
||||
})
|
||||
|
||||
describe('Issue lifecycle workflow', () => {
|
||||
it('uses explicit review handoff events without rerunning when a draft becomes ready', () => {
|
||||
it('runs the lifecycle job on every PR/review event but gates token and board steps', () => {
|
||||
const lifecycle = loadWorkflow('.github/workflows/issue-lifecycle.yml')
|
||||
const policy = loadWorkflow('.github/workflows/issue-policy.yml')
|
||||
const lifecycleJob = workflowJob(lifecycle, 'lifecycle')
|
||||
if (!Array.isArray(lifecycleJob.steps)) throw new TypeError('Issue lifecycle job must define steps')
|
||||
|
||||
// The job has no job-level `if`, so it is listed on every pull_request /
|
||||
// pull_request_review event and reports success instead of a gray skip. The
|
||||
// write-capable steps are gated at step level so approved/commented reviews
|
||||
// never mint a Project/Issue App token nor touch the board.
|
||||
expect(lifecycle.on).toHaveProperty('pull_request')
|
||||
expect(lifecycle.on).toHaveProperty('pull_request_review')
|
||||
expect(lifecycleJob.if).toBeUndefined()
|
||||
// Keep the subscription-type gates: issue-lifecycle does not re-subscribe
|
||||
// ready_for_review (issue-policy owns that) and only reacts to submitted
|
||||
// review events.
|
||||
const lifecyclePullRequest = workflowEvent(lifecycle, 'pull_request')
|
||||
const lifecycleReview = workflowEvent(lifecycle, 'pull_request_review')
|
||||
const lifecycleJob = workflowJob(lifecycle, 'lifecycle')
|
||||
const policy = loadWorkflow('.github/workflows/issue-policy.yml')
|
||||
const policyPullRequest = workflowEvent(policy, 'pull_request')
|
||||
|
||||
expect(lifecyclePullRequest.types).not.toContain('ready_for_review')
|
||||
expect(lifecyclePullRequest.types).toContain('review_requested')
|
||||
expect(lifecycleReview.types).toEqual(['submitted'])
|
||||
expect(lifecycleJob.if).toBe(
|
||||
"${{ github.event_name != 'pull_request_review' || (github.event.action == 'submitted' && github.event.review.state == 'changes_requested') }}",
|
||||
)
|
||||
const gated = "${{ github.event_name != 'pull_request_review' || github.event.review.state == 'changes_requested' }}"
|
||||
const steps = lifecycleJob.steps.filter(isRecord)
|
||||
const tokenStep = steps.find(s => s.name === 'Create project token')
|
||||
const handleStep = steps.find(s => s.name === 'Handle repository event')
|
||||
expect(tokenStep).toMatchObject({ if: gated })
|
||||
expect(handleStep).toMatchObject({ if: gated })
|
||||
|
||||
// issue-policy owns PR validation; it is read-only and a real gate.
|
||||
const policyPullRequest = workflowEvent(policy, 'pull_request')
|
||||
expect(policyPullRequest.types).toContain('ready_for_review')
|
||||
})
|
||||
})
|
||||
|
||||
describe('npm release workflows', () => {
|
||||
it('keeps publication dispatch-only and pack in the PR workflow', () => {
|
||||
// pack stays in the PR/master release workflows so a PR proves the set packs.
|
||||
for (const file of ['release.yml', 'release-vendor.yml']) {
|
||||
const workflow = loadWorkflow(`.github/workflows/${file}`)
|
||||
if (!isRecord(workflow.jobs)) throw new TypeError(`${file} must define jobs`)
|
||||
expect(Object.keys(workflow.jobs).sort()).toEqual(['pack'])
|
||||
}
|
||||
|
||||
// publication is workflow_dispatch-only (never a PR check) and keeps the
|
||||
// npm-publish environment plus the shared dist-tag group.
|
||||
for (const file of ['release-publish.yml', 'release-vendor-publish.yml']) {
|
||||
const workflow = loadWorkflow(`.github/workflows/${file}`)
|
||||
if (!isRecord(workflow.on) || !isRecord(workflow.jobs)) throw new TypeError(`${file} must define on and jobs`)
|
||||
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
|
||||
const publish = workflow.jobs.publish
|
||||
if (!isRecord(publish)) throw new TypeError(`${file} must define a publish job`)
|
||||
expect(publish.environment).toBe('npm-publish')
|
||||
expect(publish.concurrency).toMatchObject({ group: 'Release-publish' })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('Documentation site publication', () => {
|
||||
it('keeps Pages deployment dispatch-only from a dsh-v* tag', () => {
|
||||
const workflow = loadWorkflow('.github/workflows/docs-pages.yml')
|
||||
const build = workflowJob(workflow, 'build')
|
||||
const deploy = workflowJob(workflow, 'deploy')
|
||||
if (!isRecord(workflow.on) || !isRecord(workflow.env) || !Array.isArray(build.steps)) {
|
||||
throw new TypeError('Documentation deployment must define on, env, and build steps')
|
||||
}
|
||||
|
||||
// The site presents a released snapshot: a merge must never publish it, and
|
||||
// publication must never appear as a PR check.
|
||||
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
|
||||
|
||||
// RELEASE_PUBLISH makes release:verify reject every ref that is not a dsh-v*
|
||||
// tag naming this tree's version, so the site and the npm sequence share one
|
||||
// definition of a released version.
|
||||
const steps = build.steps.filter(isRecord)
|
||||
const verify = steps.find(step => step.name === 'Verify release version')
|
||||
const checkout = steps.find(
|
||||
step => typeof step.uses === 'string' && step.uses.startsWith('actions/checkout@'),
|
||||
)
|
||||
expect(verify).toMatchObject({
|
||||
env: { RELEASE_PUBLISH: 'true' },
|
||||
run: 'pnpm run release:verify --family dsh',
|
||||
})
|
||||
// Complete history: the release scripts read tags.
|
||||
expect(checkout).toMatchObject({ with: { 'fetch-depth': 0 } })
|
||||
|
||||
// Projected source links stay on the public repository's master. That
|
||||
// repository advances only to each release commit, so its master never
|
||||
// carries unreleased work, while it retains only the most recent tags:
|
||||
// following the dispatched tag would leave every source link on a deploy
|
||||
// from an older tag unresolvable.
|
||||
expect(workflow.env.DOCS_REPOSITORY_REF).toBe('master')
|
||||
|
||||
// The environment owns the deployment tag policy and the required reviewers.
|
||||
expect(deploy.environment).toMatchObject({ name: 'github-pages' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('Git hooks', () => {
|
||||
it('leaves frozen Agent Note sidecars to the archive verifier', () => {
|
||||
const lefthook = loadWorkflow('lefthook.yml')
|
||||
|
||||
@@ -38,6 +38,7 @@ describe('RepositoryCleaner', () => {
|
||||
write(join(root, 'products/shell/lib/types/index.js'))
|
||||
write(join(root, 'products/shell/lib/index.js'))
|
||||
write(join(root, '.typecheck/legacy.tsbuildinfo'))
|
||||
write(join(root, '.dsh-build/client-build-environment.json'))
|
||||
write(join(root, 'root.tsbuildinfo'))
|
||||
write(join(root, 'packages/removed/ghost/node_modules/.bin/tool'))
|
||||
|
||||
@@ -46,6 +47,7 @@ describe('RepositoryCleaner', () => {
|
||||
expect(existsSync(join(root, 'products/shell/lib'))).toBe(false)
|
||||
expect(existsSync(join(root, 'products/shell/src/index.ts'))).toBe(true)
|
||||
expect(existsSync(join(root, '.typecheck'))).toBe(false)
|
||||
expect(existsSync(join(root, '.dsh-build'))).toBe(false)
|
||||
expect(existsSync(join(root, 'root.tsbuildinfo'))).toBe(false)
|
||||
expect(existsSync(join(root, 'packages/removed/ghost'))).toBe(false)
|
||||
})
|
||||
|
||||
@@ -67,6 +67,8 @@ export class RepositoryCleaner {
|
||||
const unsafeOrphans: string[] = []
|
||||
const canonicalRoot = await realpath(this.root)
|
||||
|
||||
await this.addIfPresent(targets, join(this.root, '.dsh-build'), canonicalRoot)
|
||||
|
||||
// These checks cover legacy root-level incremental state emitted by older configs.
|
||||
await this.addIfPresent(targets, join(this.root, '.typecheck'), canonicalRoot)
|
||||
for (const entry of await readdir(this.root, { withFileTypes: true })) {
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import yaml from 'js-yaml'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
assertClientBuildEnvironment,
|
||||
clientBuildEnvironmentDefines,
|
||||
clientBuildProcessEnvironment,
|
||||
readClientBuildRecord,
|
||||
repositoryCommitHash,
|
||||
resolveClientBuildEnvironment,
|
||||
writeClientBuildRecord,
|
||||
} from './client-build-environment.ts'
|
||||
import { clientBundle } from '../packages/client/tsdown.client.ts'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const PROBE_NAME = 'DSH_CLIENT_BUILD_TEST'
|
||||
const COMMIT_HASH = '0123456789abcdef0123456789abcdef01234567'
|
||||
const PROBE_KEY = `process.env.${PROBE_NAME}`
|
||||
const originalProbe = process.env[PROBE_NAME]
|
||||
const roots: string[] = []
|
||||
const dshBuildWorkflows = [
|
||||
'build-exe-for-python-sdk.yml',
|
||||
'ci.yml',
|
||||
'e2b-e2e.yml',
|
||||
'e2e.yml',
|
||||
'release.yml',
|
||||
'release-publish.yml',
|
||||
'sandbox.yml',
|
||||
]
|
||||
|
||||
afterEach(() => {
|
||||
if (originalProbe === undefined) Reflect.deleteProperty(process.env, PROBE_NAME)
|
||||
else process.env[PROBE_NAME] = originalProbe
|
||||
vi.resetModules()
|
||||
for (const fixtureRoot of roots.splice(0)) rmSync(fixtureRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function write(path: string, content: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, content)
|
||||
}
|
||||
|
||||
function buildFixture(environment: Record<string, string>): string {
|
||||
const fixtureRoot = mkdtempSync(join(tmpdir(), 'dsh-client-build-'))
|
||||
roots.push(fixtureRoot)
|
||||
write(join(fixtureRoot, 'apps/web/dist/index.html'), '<main></main>')
|
||||
write(join(fixtureRoot, 'packages/client/example/lib/client.js'), 'module.exports = {}\n')
|
||||
writeClientBuildRecord(fixtureRoot, environment)
|
||||
return fixtureRoot
|
||||
}
|
||||
|
||||
describe('client build environment', () => {
|
||||
it('requires an exact public environment for a named artifact profile', () => {
|
||||
const expected = {
|
||||
DSH_CLIENT_BUILD_PROFILE: 'official',
|
||||
DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7),
|
||||
DSH_CLIENT_TITLE: 'DeepSeek Harness',
|
||||
} as const
|
||||
|
||||
expect(() => { assertClientBuildEnvironment({ PATH: '/bin', ...expected }, expected) }).not.toThrow()
|
||||
expect(() => { assertClientBuildEnvironment({}, expected) }).toThrow(/DSH_CLIENT_TITLE/)
|
||||
expect(() => { assertClientBuildEnvironment({ DSH_CLIENT_TITLE: 'Other' }, expected) }).toThrow(/DSH_CLIENT_TITLE/)
|
||||
expect(() => {
|
||||
assertClientBuildEnvironment({ ...expected, DSH_CLIENT_UNDECLARED: 'value' }, expected)
|
||||
}).toThrow(/DSH_CLIENT_UNDECLARED/)
|
||||
})
|
||||
|
||||
it('inherits public values by default and isolates an explicit official profile', () => {
|
||||
const parent = {
|
||||
PATH: '/bin',
|
||||
DSH_BUILD_CLIENT_PROFILE: 'official',
|
||||
DSH_CLIENT_BUILD_PROFILE: 'local',
|
||||
DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7),
|
||||
DSH_CLIENT_TITLE: 'Local title',
|
||||
DSH_CLIENT_EXTRA: 'local-extra',
|
||||
}
|
||||
|
||||
expect(resolveClientBuildEnvironment({ DSH_CLIENT_TITLE: 'Local title' })).toEqual({
|
||||
DSH_CLIENT_TITLE: 'Local title',
|
||||
})
|
||||
expect(resolveClientBuildEnvironment(parent)).toEqual({
|
||||
DSH_CLIENT_BUILD_PROFILE: 'official',
|
||||
DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7),
|
||||
DSH_CLIENT_TITLE: 'DeepSeek Harness',
|
||||
})
|
||||
expect(() => {
|
||||
resolveClientBuildEnvironment({ DSH_BUILD_CLIENT_PROFILE: 'official' })
|
||||
}).toThrow(/DSH_CLIENT_COMMIT_HASH/)
|
||||
expect(() => { resolveClientBuildEnvironment({}, 'unknown') }).toThrow(/unknown client build profile/)
|
||||
expect(clientBuildProcessEnvironment(parent, {
|
||||
DSH_CLIENT_BUILD_PROFILE: 'official',
|
||||
DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7),
|
||||
DSH_CLIENT_TITLE: 'DeepSeek Harness',
|
||||
})).toEqual({
|
||||
PATH: '/bin',
|
||||
DSH_CLIENT_BUILD_PROFILE: 'official',
|
||||
DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7),
|
||||
DSH_CLIENT_TITLE: 'DeepSeek Harness',
|
||||
})
|
||||
expect(repositoryCommitHash('/unused', { DSH_CLIENT_COMMIT_HASH: COMMIT_HASH })).toBe(COMMIT_HASH.slice(0, 7))
|
||||
})
|
||||
|
||||
it('defines only public client values over a non-enumerable fallback', () => {
|
||||
expect(clientBuildEnvironmentDefines({
|
||||
PATH: '/bin',
|
||||
DSH_TEST_API_KEY: 'secret',
|
||||
DSH_CLIENT_VARIANT: 'quoted "value"',
|
||||
DSH_CLIENT_EMPTY: '',
|
||||
DSH_CLIENT_UNSET: undefined,
|
||||
})).toEqual({
|
||||
'process.env': '{}',
|
||||
'process.env.DSH_CLIENT_EMPTY': '""',
|
||||
'process.env.DSH_CLIENT_VARIANT': '"quoted \\"value\\""',
|
||||
})
|
||||
})
|
||||
|
||||
it('feeds the same build-process value to dynamic tsdown bundles and the Vite shell', async () => {
|
||||
process.env[PROBE_NAME] = 'shared-value'
|
||||
|
||||
const configs = clientBundle('@deepseek-ai/dsh-client-ui-sidebar', [
|
||||
'lib/types/index.js',
|
||||
'lib/types/invariant.js',
|
||||
])({ env: { DSH_BUILD_FACE: 'client' } })
|
||||
if (!Array.isArray(configs)) throw new TypeError('client bundle config must be an array')
|
||||
const dynamic = configs.find(config => config.name === '@deepseek-ai/dsh-client-ui-sidebar/client')
|
||||
expect(dynamic?.define).toMatchObject({
|
||||
'process.env': '{}',
|
||||
[PROBE_KEY]: '"shared-value"',
|
||||
})
|
||||
|
||||
const viteConfigPath = '../apps/web/vite.config.ts'
|
||||
const viteModule: unknown = await import(viteConfigPath)
|
||||
if (typeof viteModule !== 'object' || viteModule === null) {
|
||||
throw new TypeError('web Vite config module must be an object')
|
||||
}
|
||||
const viteConfig: unknown = Reflect.get(viteModule, 'default')
|
||||
if (typeof viteConfig === 'function') throw new TypeError('web Vite config must be an object')
|
||||
if (typeof viteConfig !== 'object' || viteConfig === null) {
|
||||
throw new TypeError('web Vite config must be an object')
|
||||
}
|
||||
expect(Reflect.get(viteConfig, 'define')).toMatchObject({
|
||||
'process.env': '{}',
|
||||
[PROBE_KEY]: '"shared-value"',
|
||||
})
|
||||
})
|
||||
|
||||
it('binds the recorded environment to a complete set of client artifacts', () => {
|
||||
const officialEnvironment = {
|
||||
DSH_CLIENT_BUILD_PROFILE: 'official',
|
||||
DSH_CLIENT_COMMIT_HASH: COMMIT_HASH.slice(0, 7),
|
||||
DSH_CLIENT_TITLE: 'DeepSeek Harness',
|
||||
}
|
||||
const official = buildFixture(officialEnvironment)
|
||||
const defaultBuild = buildFixture({})
|
||||
|
||||
expect(readClientBuildRecord(official, officialEnvironment).environment).toEqual(officialEnvironment)
|
||||
expect(() => { readClientBuildRecord(defaultBuild, officialEnvironment) }).toThrow(/DSH_CLIENT_/)
|
||||
expect(() => { readClientBuildRecord(join(defaultBuild, 'missing')) }).toThrow(/record.*missing/)
|
||||
|
||||
write(join(official, 'apps/web/dist/index.html'), '<main>changed</main>')
|
||||
expect(() => { readClientBuildRecord(official) }).toThrow(/artifacts differ/)
|
||||
})
|
||||
|
||||
it('keeps public client values out of workflow-wide environments', () => {
|
||||
for (const name of dshBuildWorkflows) {
|
||||
const path = `.github/workflows/${name}`
|
||||
const document: unknown = yaml.load(readFileSync(resolve(root, path), 'utf8'))
|
||||
if (typeof document !== 'object' || document === null || Array.isArray(document)) {
|
||||
throw new TypeError(`${path} must contain a workflow object`)
|
||||
}
|
||||
expect(JSON.stringify(document), path).not.toContain('DSH_CLIENT_')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,311 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import {
|
||||
existsSync,
|
||||
globSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
|
||||
/** Prefix reserved for build-time values that may be embedded in browser artifacts. */
|
||||
const CLIENT_BUILD_ENV_PREFIX = 'DSH_CLIENT_'
|
||||
|
||||
/** Non-public selector used by build orchestration to request a named client profile. */
|
||||
export const CLIENT_BUILD_PROFILE_SELECTOR = 'DSH_BUILD_CLIENT_PROFILE'
|
||||
|
||||
/** Public client environment required by official DSH artifacts. */
|
||||
const OFFICIAL_CLIENT_BUILD_ENVIRONMENT = {
|
||||
DSH_CLIENT_BUILD_PROFILE: 'official',
|
||||
DSH_CLIENT_TITLE: 'DeepSeek Harness',
|
||||
} as const
|
||||
|
||||
/** Public variable carrying the source commit embedded in client artifacts. */
|
||||
const CLIENT_COMMIT_HASH_VARIABLE = 'DSH_CLIENT_COMMIT_HASH'
|
||||
|
||||
/** Repository-relative path of the complete client build record. */
|
||||
export const CLIENT_BUILD_RECORD_PATH = '.dsh-build/client-build-environment.json'
|
||||
|
||||
const CLIENT_BUILD_RECORD_FORMAT = 1
|
||||
const CLIENT_ARTIFACT_PATTERNS = [
|
||||
'apps/web/dist/**/*',
|
||||
'packages/*/*/lib/client.js',
|
||||
'packages/*/*/lib/client.js.map',
|
||||
] as const
|
||||
|
||||
/** Public values embedded in one set of client artifacts. */
|
||||
export type ClientBuildEnvironment = Readonly<Record<string, string>>
|
||||
|
||||
/**
|
||||
* Resolve the short source commit used by browser build metadata.
|
||||
* @param root - repository root used when no explicit value is supplied.
|
||||
* @param environment - environment that may already carry a commit value.
|
||||
* @returns lowercase 7-character Git commit prefix.
|
||||
*/
|
||||
export function repositoryCommitHash(root: string, environment: NodeJS.ProcessEnv = process.env): string {
|
||||
const explicit = environment[CLIENT_COMMIT_HASH_VARIABLE]
|
||||
const value = explicit ?? execFileSync('git', ['rev-parse', 'HEAD'], {
|
||||
cwd: root,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'ignore'],
|
||||
}).trim()
|
||||
if (!/^[0-9a-f]{7,40}$/iu.test(value)) {
|
||||
throw new Error(`${CLIENT_COMMIT_HASH_VARIABLE} must be a Git commit hash; got ${JSON.stringify(value)}`)
|
||||
}
|
||||
return value.slice(0, 7).toLowerCase()
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the exact public values required by an official build at one commit.
|
||||
* @param root - repository root whose HEAD must match the built source.
|
||||
* @param environment - optional explicit commit source for non-Git build environments.
|
||||
* @returns complete official client environment.
|
||||
*/
|
||||
export function officialClientBuildEnvironment(
|
||||
root: string,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): Readonly<Record<`DSH_CLIENT_${string}`, string>> {
|
||||
return {
|
||||
DSH_CLIENT_COMMIT_HASH: repositoryCommitHash(root, environment),
|
||||
...OFFICIAL_CLIENT_BUILD_ENVIRONMENT,
|
||||
}
|
||||
}
|
||||
|
||||
/** Digest of every client artifact produced by the complete root build. */
|
||||
interface ClientArtifactDigest {
|
||||
/** Number of files covered by the digest. */
|
||||
readonly fileCount: number
|
||||
/** Lowercase SHA-256 digest of sorted paths and file contents. */
|
||||
readonly sha256: string
|
||||
}
|
||||
|
||||
/** Durable description of one complete root client build. */
|
||||
export interface ClientBuildRecord {
|
||||
/** Record schema version. */
|
||||
readonly formatVersion: number
|
||||
/** Exact public environment embedded by Vite and tsdown. */
|
||||
readonly environment: ClientBuildEnvironment
|
||||
/** Digest that binds the environment to the current artifacts. */
|
||||
readonly artifacts: ClientArtifactDigest
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect the public client environment in deterministic key order.
|
||||
* @param environment - environment inherited by the build process.
|
||||
* @returns defined `DSH_CLIENT_*` values only.
|
||||
*/
|
||||
function clientBuildEnvironment(environment: NodeJS.ProcessEnv): ClientBuildEnvironment {
|
||||
return Object.fromEntries(Object.entries(environment)
|
||||
.filter(([name, value]) => name.startsWith(CLIENT_BUILD_ENV_PREFIX) && value !== undefined)
|
||||
.sort(([left], [right]) => left.localeCompare(right))) as Record<string, string>
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the exact public environment selected for a complete client build.
|
||||
* @param environment - parent process environment.
|
||||
* @param profile - explicit profile, or the non-public selector when omitted.
|
||||
* @returns the inherited public values when no profile is selected, otherwise the named profile.
|
||||
*/
|
||||
export function resolveClientBuildEnvironment(
|
||||
environment: NodeJS.ProcessEnv,
|
||||
profile: string | undefined = environment[CLIENT_BUILD_PROFILE_SELECTOR],
|
||||
): ClientBuildEnvironment {
|
||||
if (profile === undefined) return clientBuildEnvironment(environment)
|
||||
if (profile === 'official') {
|
||||
const commitHash = environment[CLIENT_COMMIT_HASH_VARIABLE]
|
||||
if (commitHash === undefined) {
|
||||
throw new Error(`${CLIENT_COMMIT_HASH_VARIABLE} is required for the official client build profile`)
|
||||
}
|
||||
return { DSH_CLIENT_COMMIT_HASH: commitHash, ...OFFICIAL_CLIENT_BUILD_ENVIRONMENT }
|
||||
}
|
||||
throw new Error(`unknown client build profile ${JSON.stringify(profile)}; expected "official"`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct a subprocess environment containing exactly the selected public values.
|
||||
* @param environment - parent process environment.
|
||||
* @param clientEnvironment - complete public environment selected for the build.
|
||||
* @returns the parent environment with selectors and inherited public values replaced.
|
||||
*/
|
||||
export function clientBuildProcessEnvironment(
|
||||
environment: NodeJS.ProcessEnv,
|
||||
clientEnvironment: ClientBuildEnvironment,
|
||||
): NodeJS.ProcessEnv {
|
||||
const child: NodeJS.ProcessEnv = {}
|
||||
for (const [name, value] of Object.entries(environment)) {
|
||||
if (name === CLIENT_BUILD_PROFILE_SELECTOR || name.startsWith(CLIENT_BUILD_ENV_PREFIX)) continue
|
||||
child[name] = value
|
||||
}
|
||||
return { ...child, ...clientEnvironment }
|
||||
}
|
||||
|
||||
/**
|
||||
* Require the public client environment to match an artifact profile exactly.
|
||||
*
|
||||
* An exact key set matters because every prefixed value is eligible for
|
||||
* inlining: an unexpected variable can change published bytes just as surely
|
||||
* as a missing or incorrect required value.
|
||||
*
|
||||
* @param environment - public environment from a build process or build record.
|
||||
* @param expected - complete public client environment for the artifact profile.
|
||||
*/
|
||||
export function assertClientBuildEnvironment(
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
expected: Readonly<Record<`DSH_CLIENT_${string}`, string>>,
|
||||
): void {
|
||||
const actual = Object.fromEntries(Object.entries(environment)
|
||||
.filter(([name, value]) => name.startsWith(CLIENT_BUILD_ENV_PREFIX) && value !== undefined)
|
||||
.sort(([left], [right]) => left.localeCompare(right)))
|
||||
const normalizedExpected = Object.fromEntries(Object.entries(expected)
|
||||
.sort(([left], [right]) => left.localeCompare(right)))
|
||||
if (JSON.stringify(actual) === JSON.stringify(normalizedExpected)) return
|
||||
|
||||
const names = [...new Set([...Object.keys(actual), ...Object.keys(normalizedExpected)])].sort()
|
||||
const differences = names.filter(name => actual[name] !== normalizedExpected[name])
|
||||
throw new Error(`client build environment differs from the required artifact profile: ${differences.join(', ')}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create bundler substitutions for public client build environment variables.
|
||||
*
|
||||
* The empty `process.env` fallback makes an unset static property read
|
||||
* evaluate to `undefined` without providing a browser `process` global.
|
||||
* Exact substitutions remain longer matches than that fallback. Dynamic
|
||||
* property reads and enumeration deliberately observe the empty object.
|
||||
*
|
||||
* @param environment - environment inherited by the build process.
|
||||
* @returns deterministic Vite/tsdown `define` expressions.
|
||||
*/
|
||||
export function clientBuildEnvironmentDefines(
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): Record<string, string> {
|
||||
const defines: Record<string, string> = { 'process.env': '{}' }
|
||||
for (const [name, value] of Object.entries(clientBuildEnvironment(environment))) {
|
||||
defines[`process.env.${name}`] = JSON.stringify(value)
|
||||
}
|
||||
return defines
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the build record after a complete root build succeeds.
|
||||
* @param root - repository root containing the generated artifacts.
|
||||
* @param environment - exact public environment supplied to both bundlers.
|
||||
* @returns the record written to disk.
|
||||
*/
|
||||
export function writeClientBuildRecord(
|
||||
root: string,
|
||||
environment: ClientBuildEnvironment,
|
||||
): ClientBuildRecord {
|
||||
const record: ClientBuildRecord = {
|
||||
formatVersion: CLIENT_BUILD_RECORD_FORMAT,
|
||||
environment: clientBuildEnvironment(environment),
|
||||
artifacts: clientArtifactDigest(root),
|
||||
}
|
||||
const path = resolve(root, CLIENT_BUILD_RECORD_PATH)
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, `${JSON.stringify(record, null, 2)}\n`)
|
||||
return record
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a complete build record and prove it still describes the current artifacts.
|
||||
* @param root - repository root containing the record and generated artifacts.
|
||||
* @param expected - optional exact public environment required by a consumer.
|
||||
* @returns the parsed and artifact-verified record.
|
||||
*/
|
||||
export function readClientBuildRecord(
|
||||
root: string,
|
||||
expected?: Readonly<Record<`DSH_CLIENT_${string}`, string>>,
|
||||
): ClientBuildRecord {
|
||||
const path = resolve(root, CLIENT_BUILD_RECORD_PATH)
|
||||
if (!existsSync(path)) {
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} is missing; run a complete pnpm run build first`)
|
||||
}
|
||||
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(readFileSync(path, 'utf8'))
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} is invalid JSON: ${detail}`)
|
||||
}
|
||||
const record = parseClientBuildRecord(parsed)
|
||||
if (expected !== undefined) assertClientBuildEnvironment(record.environment, expected)
|
||||
|
||||
const current = clientArtifactDigest(root)
|
||||
if (current.fileCount !== record.artifacts.fileCount || current.sha256 !== record.artifacts.sha256) {
|
||||
throw new Error(
|
||||
`client artifacts differ from ${CLIENT_BUILD_RECORD_PATH}; run a complete pnpm run build before consuming them`,
|
||||
)
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
/** Return the deterministic digest of every artifact affected by the public client environment. */
|
||||
function clientArtifactDigest(root: string): ClientArtifactDigest {
|
||||
const paths = globSync([...CLIENT_ARTIFACT_PATTERNS], { cwd: root })
|
||||
.map(path => path.replaceAll('\\', '/'))
|
||||
.filter(path => statSync(resolve(root, path)).isFile())
|
||||
.sort()
|
||||
if (paths.length === 0) throw new Error('complete client build produced no Vite or dynamic client artifacts')
|
||||
|
||||
const digest = createHash('sha256')
|
||||
for (const path of paths) {
|
||||
const content = readFileSync(resolve(root, path))
|
||||
digest.update(`${Buffer.byteLength(path)}:`)
|
||||
digest.update(path)
|
||||
digest.update(`${content.byteLength}:`)
|
||||
digest.update(content)
|
||||
}
|
||||
return { fileCount: paths.length, sha256: digest.digest('hex') }
|
||||
}
|
||||
|
||||
/** Parse and validate the persisted record before any consumer trusts it. */
|
||||
function parseClientBuildRecord(value: unknown): ClientBuildRecord {
|
||||
if (!isObject(value) || !hasExactKeys(value, ['artifacts', 'environment', 'formatVersion'])) {
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid top-level schema`)
|
||||
}
|
||||
if (value.formatVersion !== CLIENT_BUILD_RECORD_FORMAT) {
|
||||
throw new Error(
|
||||
`client build record ${CLIENT_BUILD_RECORD_PATH} uses format ${String(value.formatVersion)}; expected ${String(CLIENT_BUILD_RECORD_FORMAT)}`,
|
||||
)
|
||||
}
|
||||
if (!isObject(value.environment)) {
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid environment`)
|
||||
}
|
||||
const environment: Record<string, string> = {}
|
||||
for (const [name, entry] of Object.entries(value.environment).sort(([left], [right]) => left.localeCompare(right))) {
|
||||
if (!name.startsWith(CLIENT_BUILD_ENV_PREFIX) || typeof entry !== 'string') {
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid environment entry ${name}`)
|
||||
}
|
||||
environment[name] = entry
|
||||
}
|
||||
if (!isObject(value.artifacts) || !hasExactKeys(value.artifacts, ['fileCount', 'sha256'])) {
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid artifact digest`)
|
||||
}
|
||||
if (!Number.isSafeInteger(value.artifacts.fileCount) || Number(value.artifacts.fileCount) < 1) {
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid artifact count`)
|
||||
}
|
||||
if (typeof value.artifacts.sha256 !== 'string' || !/^[0-9a-f]{64}$/.test(value.artifacts.sha256)) {
|
||||
throw new Error(`client build record ${CLIENT_BUILD_RECORD_PATH} has an invalid SHA-256 digest`)
|
||||
}
|
||||
return {
|
||||
formatVersion: CLIENT_BUILD_RECORD_FORMAT,
|
||||
environment,
|
||||
artifacts: {
|
||||
fileCount: Number(value.artifacts.fileCount),
|
||||
sha256: value.artifacts.sha256,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function hasExactKeys(value: Record<string, unknown>, expected: readonly string[]): boolean {
|
||||
const actual = Object.keys(value).sort()
|
||||
return actual.length === expected.length && actual.every((key, index) => key === expected[index])
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* CSS Modules enter client bundles through virtual modules, so the loader must
|
||||
* explicitly register the underlying stylesheet as a watch dependency.
|
||||
* Stylesheets enter client bundles through virtual modules, so the loader must
|
||||
* register their physical files as watch dependencies.
|
||||
*/
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
@@ -14,7 +14,7 @@ interface CssPlugin {
|
||||
load?: (this: { addWatchFile(id: string): void }, id: string) => Promise<string | null>
|
||||
}
|
||||
|
||||
function cssPlugin(): CssPlugin {
|
||||
function cssPlugin(name: 'dsh-css-modules-inline' | 'dsh-css-global-inline' | 'dsh-css-text-inline'): CssPlugin {
|
||||
const configs = clientBundle(
|
||||
'@deepseek-ai/dsh-client-test',
|
||||
['lib/types/index.js', 'lib/types/invariant.js'],
|
||||
@@ -22,8 +22,8 @@ function cssPlugin(): CssPlugin {
|
||||
const client = configs.find(config => config.platform === 'browser')
|
||||
if (client === undefined) throw new Error('client config missing')
|
||||
const plugins = (client as { plugins: CssPlugin[] }).plugins
|
||||
const plugin = plugins.find(candidate => candidate.name === 'dsh-css-modules-inline')
|
||||
if (plugin === undefined) throw new Error('CSS Modules plugin missing from client config')
|
||||
const plugin = plugins.find(candidate => candidate.name === name)
|
||||
if (plugin === undefined) throw new Error(`${name} missing from client config`)
|
||||
return plugin
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ describe('client bundle CSS Modules', () => {
|
||||
const stylesheet = join(root, 'Fixture.module.css')
|
||||
const importer = join(root, 'index.ts')
|
||||
await writeFile(stylesheet, '.root { color: red; }\n')
|
||||
const plugin = cssPlugin()
|
||||
const plugin = cssPlugin('dsh-css-modules-inline')
|
||||
const virtualId = plugin.resolveId?.('./Fixture.module.css', importer)
|
||||
if (typeof virtualId !== 'string' || plugin.load === undefined) {
|
||||
throw new Error('CSS Modules plugin hooks are incomplete')
|
||||
@@ -50,3 +50,51 @@ describe('client bundle CSS Modules', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('client bundle global CSS', () => {
|
||||
it('compiles a side-effect stylesheet into a watched style injector', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-client-global-css-watch-'))
|
||||
try {
|
||||
const stylesheet = join(root, 'base.css')
|
||||
const importer = join(root, 'index.ts')
|
||||
await writeFile(stylesheet, 'body { color: red; }\n')
|
||||
const plugin = cssPlugin('dsh-css-global-inline')
|
||||
const virtualId = plugin.resolveId?.('./base.css', importer)
|
||||
if (typeof virtualId !== 'string' || plugin.load === undefined) {
|
||||
throw new Error('global CSS plugin hooks are incomplete')
|
||||
}
|
||||
const watched: string[] = []
|
||||
|
||||
const output = await plugin.load.call({ addWatchFile: id => watched.push(id) }, virtualId)
|
||||
|
||||
expect(watched).toEqual([stylesheet])
|
||||
expect(output).toContain('data-plugin-css')
|
||||
expect(output).toContain('body{color:red}')
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('compiles inline stylesheets as watched text without a module side effect', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-client-inline-css-watch-'))
|
||||
try {
|
||||
const stylesheet = join(root, 'base.css')
|
||||
const importer = join(root, 'index.ts')
|
||||
await writeFile(stylesheet, 'body { color: red; }\n')
|
||||
const plugin = cssPlugin('dsh-css-text-inline')
|
||||
const virtualId = plugin.resolveId?.('./base.css?inline', importer)
|
||||
if (typeof virtualId !== 'string' || plugin.load === undefined) {
|
||||
throw new Error('inline CSS plugin hooks are incomplete')
|
||||
}
|
||||
const watched: string[] = []
|
||||
|
||||
const output = await plugin.load.call({ addWatchFile: id => watched.push(id) }, virtualId)
|
||||
|
||||
expect(watched).toEqual([stylesheet])
|
||||
expect(output).toContain('export default "body{color:red}"')
|
||||
expect(output).not.toContain('data-plugin-css')
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { CLIENT_EXTERNALS, clientBundle } from '../packages/client/tsdown.client.ts'
|
||||
import { clientBundle, requestedExternals } from '../packages/client/tsdown.client.ts'
|
||||
|
||||
type ResolveId = (source: string) => null | { id: string; external: boolean }
|
||||
|
||||
@@ -14,7 +14,10 @@ interface CssModulePlugin {
|
||||
load?: (this: { addWatchFile: (id: string) => void }, id: string) => Promise<unknown>
|
||||
}
|
||||
|
||||
function clientConfigs(id = '@deepseek-ai/dsh-client-test') {
|
||||
/** A representative dynamic bundle using the shared client baseline. */
|
||||
const REQUESTING_PACKAGE = '@deepseek-ai/dsh-client-ui-conversation'
|
||||
|
||||
function clientConfigs(id = REQUESTING_PACKAGE) {
|
||||
return clientBundle(id, ['lib/types/index.js', 'lib/types/invariant.js'])(
|
||||
{ env: { DSH_BUILD_FACE: 'client' } },
|
||||
).filter(config => config.platform === 'browser')
|
||||
@@ -36,10 +39,10 @@ function clientSourceMapPath(packagePath: string): string {
|
||||
return fileURLToPath(new URL(`../packages/${packagePath}/lib/client.js.map`, import.meta.url))
|
||||
}
|
||||
|
||||
function purityResolveId(): ResolveId {
|
||||
function purityResolveId(id = REQUESTING_PACKAGE): ResolveId {
|
||||
// libEntry is spelled at every call site (no default) so the
|
||||
// package-invariants text check can see the invariant entry per package.
|
||||
const configs = clientConfigs()
|
||||
const configs = clientConfigs(id)
|
||||
const plugins = (configs[0] as { plugins: { name: string; resolveId?: unknown }[] }).plugins
|
||||
const gate = plugins.find(p => p.name === 'dsh-client-bundle-purity')
|
||||
if (gate?.resolveId === undefined) throw new Error('purity plugin missing from client config')
|
||||
@@ -59,15 +62,16 @@ function cssModulePlugin(): CssModulePlugin {
|
||||
describe('client bundle purity gate', () => {
|
||||
const resolveId = purityResolveId()
|
||||
|
||||
it('leaves platform table entries and non-scoped specifiers alone', () => {
|
||||
it('leaves default externals and non-scoped specifiers alone', () => {
|
||||
expect(resolveId('@deepseek-ai/dsh-client-ui-slots')).toBeNull()
|
||||
expect(resolveId('@deepseek-ai/dsh-client-web-react')).toBeNull()
|
||||
expect(resolveId('@deepseek-ai/dsh-client-ui-primitives')).toBeNull()
|
||||
expect(resolveId('@deepseek-ai/dsh-client-runtime/client')).toBeNull()
|
||||
expect(resolveId('react')).toBeNull()
|
||||
expect(resolveId('zod')).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects retired table entries (web-react/store left the 8-entry seed)', () => {
|
||||
it('rejects the retired web-react platform package', () => {
|
||||
expect(() => resolveId('@deepseek-ai/dsh-client-web-react')).toThrow(/purity/)
|
||||
expect(() => resolveId('@deepseek-ai/dsh-client-web-react/store')).toThrow(/purity/)
|
||||
})
|
||||
|
||||
@@ -89,17 +93,49 @@ describe('client bundle purity gate', () => {
|
||||
expect(() => resolveId('@deepseek-ai/dsh-client-web')).toThrow(/purity/)
|
||||
})
|
||||
|
||||
it('throws on cross-plugin value imports — bare plugin names and /client subpaths alike (the rewrite arm is gone)', () => {
|
||||
it('throws on cross-plugin value imports — bare plugin names and /client subpaths alike', () => {
|
||||
expect(() => resolveId('@deepseek-ai/dsh-client-connection')).toThrow(/purity/)
|
||||
expect(() => resolveId('@deepseek-ai/dsh-client-runtime')).toThrow(/purity/)
|
||||
expect(() => resolveId('@deepseek-ai/dsh-client-ui-layout/client')).toThrow(/purity/)
|
||||
})
|
||||
|
||||
it('carries exactly one documented temporary exemption: runtime/client (store engine pending rehoming)', () => {
|
||||
it('admits the parser-preloaded runtime for every dynamic bundle', () => {
|
||||
expect(resolveId('@deepseek-ai/dsh-client-runtime/client')).toBeNull()
|
||||
const clientChannels = CLIENT_EXTERNALS.filter(
|
||||
entry => entry.startsWith('@deepseek-ai/') && entry.endsWith('/client'))
|
||||
expect(clientChannels).toEqual(['@deepseek-ai/dsh-client-runtime/client'])
|
||||
const withoutRequest = purityResolveId('@deepseek-ai/dsh-client-ui-goal')
|
||||
expect(withoutRequest('@deepseek-ai/dsh-client-runtime/client')).toBeNull()
|
||||
})
|
||||
|
||||
it('externalizes the baseline independently of each package manifest', () => {
|
||||
const requesting = clientConfigs()[0]?.deps as { neverBundle: (specifier: string) => boolean }
|
||||
const plain = clientConfigs('@deepseek-ai/dsh-client-connection')[0]?.deps as {
|
||||
neverBundle: (specifier: string) => boolean
|
||||
}
|
||||
|
||||
expect(requesting.neverBundle('react')).toBe(true)
|
||||
expect(requesting.neverBundle('zod')).toBe(false)
|
||||
expect(plain.neverBundle('react')).toBe(true)
|
||||
expect(plain.neverBundle('@deepseek-ai/dsh-client-runtime/client')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('client bundle module requests', () => {
|
||||
it('requests what the declaration lists', () => {
|
||||
const requests = requestedExternals('@deepseek-ai/dsh-client-fixture', {
|
||||
external: ['react', 'react/jsx-runtime', '@deepseek-ai/dsh-client-ui-slots'],
|
||||
})
|
||||
|
||||
expect([...requests].sort()).toEqual([
|
||||
'@deepseek-ai/dsh-client-ui-slots', 'react', 'react/jsx-runtime',
|
||||
])
|
||||
})
|
||||
|
||||
it('requests nothing when the declaration is absent', () => {
|
||||
expect(requestedExternals('@deepseek-ai/dsh-client-fixture', {}).size).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a malformed declaration instead of reading past it', () => {
|
||||
expect(() => requestedExternals('@deepseek-ai/dsh-client-fixture', { external: 'react' }))
|
||||
.toThrow(/dsh\.client\.external must be a string array/)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* Cordis YAML parsing and Loader-entry classification shared by repository checks.
|
||||
* @module scripts/cordis-yaml
|
||||
*/
|
||||
|
||||
import * as yaml from 'js-yaml'
|
||||
|
||||
/** A Loader `!!js` expression preserved as data instead of executed. */
|
||||
export interface JsExpr {
|
||||
__jsExpr: string
|
||||
}
|
||||
|
||||
const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
|
||||
kind: 'scalar',
|
||||
resolve: data => typeof data === 'string',
|
||||
construct: (data: unknown): JsExpr => {
|
||||
if (typeof data !== 'string') throw new TypeError('!!js requires a scalar string')
|
||||
return { __jsExpr: data }
|
||||
},
|
||||
})
|
||||
const schema = yaml.JSON_SCHEMA.extend(jsExprType)
|
||||
|
||||
/**
|
||||
* Parse a Cordis config while preserving Loader `!!js` expressions as data.
|
||||
* @param source - Cordis YAML source text.
|
||||
* @returns the parsed YAML value.
|
||||
*/
|
||||
export function loadCordisYaml(source: string): unknown {
|
||||
return yaml.load(source, { schema })
|
||||
}
|
||||
|
||||
/**
|
||||
* Test whether a value is a preserved Loader `!!js` expression.
|
||||
* @param value - parsed YAML value.
|
||||
* @returns whether the value contains one preserved expression.
|
||||
*/
|
||||
export function isJsExpr(value: unknown): value is JsExpr {
|
||||
return typeof value === 'object'
|
||||
&& value !== null
|
||||
&& typeof (value as Record<string, unknown>).__jsExpr === 'string'
|
||||
}
|
||||
|
||||
/**
|
||||
* Test whether a Loader entry owns nested entries in its `config` array.
|
||||
* @param value - parsed Loader entry.
|
||||
* @returns whether the entry is an explicit or package-named Cordis group.
|
||||
*/
|
||||
export function isCordisGroupEntry(value: unknown): value is Record<string, unknown> & { config: unknown[] } {
|
||||
return typeof value === 'object'
|
||||
&& value !== null
|
||||
&& Array.isArray((value as Record<string, unknown>).config)
|
||||
&& ((value as Record<string, unknown>).group === true
|
||||
|| (value as Record<string, unknown>).name === '@deepseek-ai/cordis-plugin-group')
|
||||
}
|
||||
@@ -38,4 +38,11 @@ export const coverageExemptHeavySuites: readonly CoverageExemptSuite[] = [
|
||||
{ filter: 'scripts/install-lefthook.spec.ts', exclude: 'scripts/install-lefthook.spec.ts' },
|
||||
{ filter: 'scripts/oxlint-contract.spec.ts', exclude: 'scripts/oxlint-contract.spec.ts' },
|
||||
{ filter: 'scripts/change-scope.spec.ts', exclude: 'scripts/change-scope.spec.ts' },
|
||||
{ filter: 'scripts/translation-pairing-merge.spec.ts', exclude: 'scripts/translation-pairing-merge.spec.ts' },
|
||||
// The real corpus transform runs package src only in a spawned Node process,
|
||||
// outside the parent Vitest worker's v8 coverage session.
|
||||
{
|
||||
filter: 'packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts',
|
||||
exclude: 'packages/experimental/webworker-runtime/tests/compile/transform-corpus.spec.ts',
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,257 @@
|
||||
import { access, mkdir, mkdtemp, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
COVERAGE_PARTITION_MODE_ENV,
|
||||
COVERAGE_PARTITIONS_ENV,
|
||||
COVERAGE_TEST_TIMEOUT_ENV,
|
||||
CoveragePartitionCoordinator,
|
||||
coverageTestTimeoutArgs,
|
||||
forwardedCoverageArgs,
|
||||
parseCoveragePartitionCount,
|
||||
type CoverageCommand,
|
||||
type CoverageCommandResult,
|
||||
} from './coverage-partitions.ts'
|
||||
|
||||
const passed: CoverageCommandResult = { exitCode: 0, signalCode: null }
|
||||
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
async function writeBlob(command: CoverageCommand): Promise<void> {
|
||||
if (command.blobPath === undefined) return
|
||||
await mkdir(dirname(command.blobPath), { recursive: true })
|
||||
await writeFile(command.blobPath, '{}')
|
||||
}
|
||||
|
||||
async function temporaryRoot(): Promise<string> {
|
||||
return await mkdtemp(join(tmpdir(), 'dsh-coverage-partitions-'))
|
||||
}
|
||||
|
||||
function successfulCommandRecorder(commands: CoverageCommand[]) {
|
||||
return vi.fn(async (command: CoverageCommand) => {
|
||||
commands.push(command)
|
||||
await writeBlob(command)
|
||||
return passed
|
||||
})
|
||||
}
|
||||
|
||||
describe('coverage partition count', () => {
|
||||
it.each([
|
||||
[undefined, undefined],
|
||||
['', undefined],
|
||||
['2', 2],
|
||||
['3', 3],
|
||||
])('parses %j as %j', (raw, expected) => {
|
||||
expect(parseCoveragePartitionCount(raw)).toBe(expected)
|
||||
})
|
||||
|
||||
it.each(['0', '1', '2.5', '02', 'many'])('rejects %j', (raw) => {
|
||||
expect(() => parseCoveragePartitionCount(raw))
|
||||
.toThrow(`${COVERAGE_PARTITIONS_ENV} must be an integer greater than 1`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('coverage partition timeout', () => {
|
||||
it('applies one configured timeout to tests and polling', () => {
|
||||
expect(coverageTestTimeoutArgs('30000')).toEqual([
|
||||
'--testTimeout=30000',
|
||||
'--expect.poll.timeout=30000',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps Vitest defaults when the timeout is absent', () => {
|
||||
expect(coverageTestTimeoutArgs(undefined)).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects invalid timeout input', () => {
|
||||
expect(() => coverageTestTimeoutArgs('0'))
|
||||
.toThrow(`${COVERAGE_TEST_TIMEOUT_ENV} must be a positive integer`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('coverage forwarded arguments', () => {
|
||||
it('removes one package-script separator', () => {
|
||||
expect(forwardedCoverageArgs(['--', 'scripts/example.spec.ts'])).toEqual(['scripts/example.spec.ts'])
|
||||
})
|
||||
|
||||
it('preserves direct arguments and a subsequent Vitest separator', () => {
|
||||
expect(forwardedCoverageArgs(['--testNamePattern=example'])).toEqual(['--testNamePattern=example'])
|
||||
expect(forwardedCoverageArgs(['--', '--', 'example'])).toEqual(['--', 'example'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('coverage partition coordinator', () => {
|
||||
it('runs every single-worker partition before one merged threshold check', async () => {
|
||||
const root = await temporaryRoot()
|
||||
const commands: CoverageCommand[] = []
|
||||
const runCommand = successfulCommandRecorder(commands)
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root,
|
||||
partitions: 3,
|
||||
pnpmEntrypoint: '/pnpm.cjs',
|
||||
vitestArgs: ['--testTimeout=30000'],
|
||||
runCommand,
|
||||
})
|
||||
|
||||
await expect(coordinator.run()).resolves.toBe(0)
|
||||
|
||||
expect(commands.map(command => command.label)).toEqual([
|
||||
'partition 1/3',
|
||||
'partition 2/3',
|
||||
'partition 3/3',
|
||||
'merged coverage report',
|
||||
])
|
||||
for (const [index, command] of commands.slice(0, 3).entries()) {
|
||||
expect(command.command).toBe(process.execPath)
|
||||
expect(command.args[0]).toBe('/pnpm.cjs')
|
||||
expect(command.args).toEqual(expect.arrayContaining([
|
||||
'--coverage',
|
||||
'--coverage.reportOnFailure',
|
||||
'--maxWorkers=1',
|
||||
`--shard=${index + 1}/3`,
|
||||
'--reporter=default',
|
||||
'--reporter=blob',
|
||||
'--testTimeout=30000',
|
||||
]))
|
||||
expect(command.env).toEqual({
|
||||
[COVERAGE_PARTITIONS_ENV]: undefined,
|
||||
[COVERAGE_PARTITION_MODE_ENV]: '1',
|
||||
})
|
||||
}
|
||||
const mergeCommand = commands[3]
|
||||
if (mergeCommand === undefined) throw new Error('coverage merge command was not observed')
|
||||
expect(mergeCommand.args).toContain('--coverage')
|
||||
expect(mergeCommand.args.some(argument => argument.startsWith('--merge-reports='))).toBe(true)
|
||||
expect(mergeCommand.env).toEqual({
|
||||
[COVERAGE_PARTITIONS_ENV]: undefined,
|
||||
[COVERAGE_PARTITION_MODE_ENV]: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('runs a native pnpm entrypoint directly', async () => {
|
||||
const root = await temporaryRoot()
|
||||
const commands: CoverageCommand[] = []
|
||||
const runCommand = successfulCommandRecorder(commands)
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root,
|
||||
partitions: 2,
|
||||
pnpmEntrypoint: '/tools/pnpm',
|
||||
runCommand,
|
||||
})
|
||||
|
||||
await expect(coordinator.run()).resolves.toBe(0)
|
||||
expect(commands).toHaveLength(3)
|
||||
for (const command of commands) {
|
||||
expect(command.command).toBe('/tools/pnpm')
|
||||
expect(command.args[0]).toBe('exec')
|
||||
}
|
||||
})
|
||||
|
||||
it('merges normal test failures and returns their failed status', async () => {
|
||||
const root = await temporaryRoot()
|
||||
const reported = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const runCommand = vi.fn(async (command: CoverageCommand) => {
|
||||
await writeBlob(command)
|
||||
return command.label === 'partition 2/2'
|
||||
? { exitCode: 1, signalCode: null, outputTail: 'specific Vitest failure' }
|
||||
: passed
|
||||
})
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root,
|
||||
partitions: 2,
|
||||
pnpmEntrypoint: '/pnpm.cjs',
|
||||
runCommand,
|
||||
})
|
||||
|
||||
await expect(coordinator.run()).resolves.toBe(1)
|
||||
expect(reported).toHaveBeenCalledWith('coverage-partitions: FAIL partition 2/2 (exit 1)')
|
||||
expect(reported).toHaveBeenCalledWith(
|
||||
'coverage-partitions: output tail for partition 2/2:\nspecific Vitest failure',
|
||||
)
|
||||
expect(runCommand).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('rejects a missing partition blob before merge', async () => {
|
||||
const root = await temporaryRoot()
|
||||
const runCommand = vi.fn(async (command: CoverageCommand) => {
|
||||
if (command.label !== 'partition 2/2') await writeBlob(command)
|
||||
return passed
|
||||
})
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root,
|
||||
partitions: 2,
|
||||
pnpmEntrypoint: '/pnpm.cjs',
|
||||
runCommand,
|
||||
})
|
||||
|
||||
await expect(coordinator.run()).rejects.toThrow('coverage partitions produced')
|
||||
expect(runCommand).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('reports signal termination before missing-blob validation', async () => {
|
||||
const root = await temporaryRoot()
|
||||
const reported = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
const runCommand = vi.fn(async (command: CoverageCommand) => {
|
||||
if (command.label === 'partition 1/2') await writeBlob(command)
|
||||
return command.label === 'partition 2/2'
|
||||
? { exitCode: null, signalCode: 'SIGTERM' as const }
|
||||
: passed
|
||||
})
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root,
|
||||
partitions: 2,
|
||||
pnpmEntrypoint: '/pnpm.cjs',
|
||||
runCommand,
|
||||
})
|
||||
|
||||
await expect(coordinator.run()).rejects.toThrow('coverage partitions produced')
|
||||
expect(reported).toHaveBeenCalledWith('coverage-partitions: FAIL partition 2/2 (signal SIGTERM)')
|
||||
})
|
||||
|
||||
it('waits for every partition after one spawn failure', async () => {
|
||||
const root = await temporaryRoot()
|
||||
const reported = vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
let secondFinished = false
|
||||
const runCommand = vi.fn(async (command: CoverageCommand) => {
|
||||
await writeBlob(command)
|
||||
if (command.label === 'partition 1/2') {
|
||||
return { exitCode: null, signalCode: null, error: 'spawn unavailable' }
|
||||
}
|
||||
if (command.label === 'partition 2/2') secondFinished = true
|
||||
return passed
|
||||
})
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root,
|
||||
partitions: 2,
|
||||
pnpmEntrypoint: '/pnpm.cjs',
|
||||
runCommand,
|
||||
})
|
||||
|
||||
await expect(coordinator.run()).resolves.toBe(1)
|
||||
expect(reported).toHaveBeenCalledWith('coverage-partitions: FAIL partition 1/2 (spawn unavailable)')
|
||||
expect(secondFinished).toBe(true)
|
||||
expect(runCommand).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('unlinks a link-shaped coverage path without touching its target', async () => {
|
||||
const root = await temporaryRoot()
|
||||
const target = await temporaryRoot()
|
||||
const marker = join(target, 'marker.txt')
|
||||
await writeFile(marker, 'owned elsewhere')
|
||||
await symlink(target, join(root, 'coverage'), process.platform === 'win32' ? 'junction' : 'dir')
|
||||
const runCommand = vi.fn(async (command: CoverageCommand) => {
|
||||
await writeBlob(command)
|
||||
return passed
|
||||
})
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root,
|
||||
partitions: 2,
|
||||
pnpmEntrypoint: '/pnpm.cjs',
|
||||
runCommand,
|
||||
})
|
||||
|
||||
await expect(coordinator.run()).resolves.toBe(0)
|
||||
await expect(access(marker)).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
/** Coordinate single-worker Vitest coverage partitions and one merged report. */
|
||||
import { spawn } from 'node:child_process'
|
||||
import { lstat, mkdir, readdir, rm, unlink } from 'node:fs/promises'
|
||||
import { join, relative, sep } from 'node:path'
|
||||
import { pnpmInvocation } from './pnpm-invocation.ts'
|
||||
|
||||
/** Environment variable selecting the number of instrumented coverage processes. */
|
||||
export const COVERAGE_PARTITIONS_ENV = 'DSH_COVERAGE_PARTITIONS'
|
||||
|
||||
/** Internal marker that suppresses reports and thresholds inside a partition process. */
|
||||
export const COVERAGE_PARTITION_MODE_ENV = 'DSH_COVERAGE_PARTITION_MODE'
|
||||
|
||||
/** Environment variable overriding instrumented test and polling timeouts. */
|
||||
export const COVERAGE_TEST_TIMEOUT_ENV = 'DSH_COVERAGE_TEST_TIMEOUT_MS'
|
||||
|
||||
/** One child command owned by the coverage coordinator. */
|
||||
export interface CoverageCommand {
|
||||
/** Diagnostic identity. */
|
||||
label: string
|
||||
/** Executable launched without a platform shell. */
|
||||
command: string
|
||||
/** Arguments passed to the executable. */
|
||||
args: string[]
|
||||
/** Environment additions for the child. */
|
||||
env: Record<string, string | undefined>
|
||||
/** Working directory for the child. */
|
||||
cwd: string
|
||||
/** Blob the partition must produce; absent for the merge command. */
|
||||
blobPath?: string
|
||||
}
|
||||
|
||||
/** Observable child-process completion. */
|
||||
export interface CoverageCommandResult {
|
||||
/** Numeric process status, or `null` when a signal ended the child. */
|
||||
exitCode: number | null
|
||||
/** Terminating signal, or `null` after an ordinary exit. */
|
||||
signalCode: NodeJS.Signals | null
|
||||
/** Spawn failure recorded independently from process completion. */
|
||||
error?: string
|
||||
/** Bounded combined stdout/stderr tail repeated when the command fails. */
|
||||
outputTail?: string
|
||||
}
|
||||
|
||||
/** Execute one coordinator command with inherited output. */
|
||||
export type CoverageCommandRunner = (command: CoverageCommand) => Promise<CoverageCommandResult>
|
||||
|
||||
/** Construction inputs for {@link CoveragePartitionCoordinator}. */
|
||||
export interface CoveragePartitionCoordinatorOptions {
|
||||
/** Repository root that owns coverage output. */
|
||||
root: string
|
||||
/** Number of concurrent single-worker Vitest processes. */
|
||||
partitions: number
|
||||
/** pnpm JavaScript or executable entrypoint from `npm_execpath`. */
|
||||
pnpmEntrypoint: string
|
||||
/** Additional arguments shared by every partition. */
|
||||
vitestArgs?: string[]
|
||||
/** Child executor, injectable for scheduler tests. */
|
||||
runCommand?: CoverageCommandRunner
|
||||
}
|
||||
|
||||
/** Parse an optional coverage partition count. */
|
||||
export function parseCoveragePartitionCount(raw: string | undefined): number | undefined {
|
||||
if (raw === undefined || raw === '') return undefined
|
||||
const parsed = Number.parseInt(raw, 10)
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 2 || String(parsed) !== raw) {
|
||||
throw new Error(`${COVERAGE_PARTITIONS_ENV} must be an integer greater than 1, got ${JSON.stringify(raw)}.`)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
/** Resolve the paired Vitest timeout arguments used by coverage partitions. */
|
||||
export function coverageTestTimeoutArgs(raw: string | undefined): string[] {
|
||||
if (raw === undefined || raw === '') return []
|
||||
const parsed = Number.parseInt(raw, 10)
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
|
||||
throw new Error(`${COVERAGE_TEST_TIMEOUT_ENV} must be a positive integer, got ${JSON.stringify(raw)}.`)
|
||||
}
|
||||
return [`--testTimeout=${raw}`, `--expect.poll.timeout=${raw}`]
|
||||
}
|
||||
|
||||
/** Remove pnpm's package-script separator before forwarding Vitest arguments. */
|
||||
export function forwardedCoverageArgs(args: readonly string[]): string[] {
|
||||
return [...args.slice(args[0] === '--' ? 1 : 0)]
|
||||
}
|
||||
|
||||
/** Run instrumented partitions, validate their blobs, and merge once. */
|
||||
export class CoveragePartitionCoordinator {
|
||||
private readonly root: string
|
||||
private readonly partitions: number
|
||||
private readonly pnpmEntrypoint: string
|
||||
private readonly vitestArgs: string[]
|
||||
private readonly runCommand: CoverageCommandRunner
|
||||
private readonly temporaryRoot: string
|
||||
private readonly blobsRoot: string
|
||||
|
||||
/** Create a coordinator from validated process-independent inputs. */
|
||||
public constructor(options: CoveragePartitionCoordinatorOptions) {
|
||||
if (!Number.isSafeInteger(options.partitions) || options.partitions < 2) {
|
||||
throw new Error(`coverage partitions must be an integer greater than 1, got ${String(options.partitions)}.`)
|
||||
}
|
||||
this.root = options.root
|
||||
this.partitions = options.partitions
|
||||
this.pnpmEntrypoint = options.pnpmEntrypoint
|
||||
this.vitestArgs = options.vitestArgs ?? []
|
||||
this.runCommand = options.runCommand ?? runCoverageCommand
|
||||
this.temporaryRoot = join(this.root, 'coverage', '.partitioned')
|
||||
this.blobsRoot = join(this.temporaryRoot, 'blobs')
|
||||
}
|
||||
|
||||
/**
|
||||
* Run every partition before one merged threshold check.
|
||||
* @returns zero only when every partition and the merge command succeed.
|
||||
*/
|
||||
public async run(): Promise<number> {
|
||||
await removeOwnedTree(join(this.root, 'coverage'))
|
||||
await mkdir(this.blobsRoot, { recursive: true })
|
||||
|
||||
try {
|
||||
const commands = Array.from(
|
||||
{ length: this.partitions },
|
||||
(_, index) => this.partitionCommand(index + 1),
|
||||
)
|
||||
const results = await Promise.all(commands.map(async (command) => {
|
||||
console.log(`coverage-partitions: start ${command.label}`)
|
||||
const result = await this.runCommand(command)
|
||||
if (commandFailed(result)) {
|
||||
console.error(`coverage-partitions: FAIL ${command.label} (${commandFailureReason(result)})`)
|
||||
if (result.outputTail !== undefined && result.outputTail !== '') {
|
||||
console.error(`coverage-partitions: output tail for ${command.label}:\n${result.outputTail}`)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}))
|
||||
await this.assertCompleteBlobSet(commands)
|
||||
|
||||
const mergeCommand = this.mergeCommand()
|
||||
console.log(`coverage-partitions: start ${mergeCommand.label}`)
|
||||
const mergeResult = await this.runCommand(mergeCommand)
|
||||
return results.some(commandFailed) || commandFailed(mergeResult) ? 1 : 0
|
||||
} finally {
|
||||
await removeOwnedTree(this.temporaryRoot)
|
||||
}
|
||||
}
|
||||
|
||||
private partitionCommand(index: number): CoverageCommand {
|
||||
const blobPath = join(this.blobsRoot, `partition-${index}.json`)
|
||||
const reportsDirectory = join(this.temporaryRoot, `coverage-${index}`)
|
||||
const invocation = pnpmInvocation([
|
||||
'exec',
|
||||
'vitest',
|
||||
'run',
|
||||
'--coverage',
|
||||
'--coverage.reportOnFailure',
|
||||
'--maxWorkers=1',
|
||||
`--shard=${index}/${this.partitions}`,
|
||||
'--reporter=default',
|
||||
'--reporter=blob',
|
||||
`--outputFile.blob=${this.relativePath(blobPath)}`,
|
||||
`--coverage.reportsDirectory=${this.relativePath(reportsDirectory)}`,
|
||||
...this.vitestArgs,
|
||||
], { npm_execpath: this.pnpmEntrypoint })
|
||||
return {
|
||||
label: `partition ${index}/${this.partitions}`,
|
||||
...invocation,
|
||||
env: {
|
||||
[COVERAGE_PARTITIONS_ENV]: undefined,
|
||||
[COVERAGE_PARTITION_MODE_ENV]: '1',
|
||||
},
|
||||
cwd: this.root,
|
||||
blobPath,
|
||||
}
|
||||
}
|
||||
|
||||
private mergeCommand(): CoverageCommand {
|
||||
const invocation = pnpmInvocation([
|
||||
'exec',
|
||||
'vitest',
|
||||
`--merge-reports=${this.relativePath(this.blobsRoot)}`,
|
||||
'--coverage',
|
||||
], { npm_execpath: this.pnpmEntrypoint })
|
||||
return {
|
||||
label: 'merged coverage report',
|
||||
...invocation,
|
||||
env: {
|
||||
[COVERAGE_PARTITIONS_ENV]: undefined,
|
||||
[COVERAGE_PARTITION_MODE_ENV]: undefined,
|
||||
},
|
||||
cwd: this.root,
|
||||
}
|
||||
}
|
||||
|
||||
private relativePath(path: string): string {
|
||||
return relative(this.root, path).split(sep).join('/')
|
||||
}
|
||||
|
||||
private async assertCompleteBlobSet(commands: CoverageCommand[]): Promise<void> {
|
||||
const expected = commands.map((command) => {
|
||||
if (command.blobPath === undefined) throw new Error(`${command.label} has no blob path.`)
|
||||
return this.relativePath(command.blobPath)
|
||||
}).sort()
|
||||
const actual = (await readdir(this.blobsRoot))
|
||||
.map(name => this.relativePath(join(this.blobsRoot, name)))
|
||||
.sort()
|
||||
if (actual.length !== expected.length || actual.some((name, index) => name !== expected[index])) {
|
||||
throw new Error(`coverage partitions produced ${JSON.stringify(actual)}; expected ${JSON.stringify(expected)}.`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Spawn one pnpm-backed command without a platform shell. */
|
||||
function runCoverageCommand(command: CoverageCommand): Promise<CoverageCommandResult> {
|
||||
return new Promise((resolveCommand) => {
|
||||
let outputTail = ''
|
||||
const env = { ...process.env }
|
||||
for (const [name, value] of Object.entries(command.env)) {
|
||||
if (value === undefined) Reflect.deleteProperty(env, name)
|
||||
else env[name] = value
|
||||
}
|
||||
const child = spawn(command.command, command.args, {
|
||||
cwd: command.cwd,
|
||||
env,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
child.stdout.setEncoding('utf8')
|
||||
child.stderr.setEncoding('utf8')
|
||||
child.stdout.on('data', (chunk: string) => {
|
||||
process.stdout.write(chunk)
|
||||
outputTail = appendOutputTail(outputTail, chunk)
|
||||
})
|
||||
child.stderr.on('data', (chunk: string) => {
|
||||
process.stderr.write(chunk)
|
||||
outputTail = appendOutputTail(outputTail, chunk)
|
||||
})
|
||||
child.once('error', (error: Error) => {
|
||||
resolveCommand({ exitCode: null, signalCode: null, error: error.message, outputTail })
|
||||
})
|
||||
child.once('close', (exitCode, signalCode) => {
|
||||
resolveCommand({ exitCode, signalCode, outputTail })
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function appendOutputTail(previous: string, chunk: string): string {
|
||||
const combined = previous + chunk
|
||||
return combined.length <= 65_536 ? combined : combined.slice(-65_536)
|
||||
}
|
||||
|
||||
function commandFailed(result: CoverageCommandResult): boolean {
|
||||
return result.exitCode !== 0 || result.signalCode !== null || result.error !== undefined
|
||||
}
|
||||
|
||||
function commandFailureReason(result: CoverageCommandResult): string {
|
||||
const facts = [
|
||||
result.error,
|
||||
result.exitCode === null ? undefined : `exit ${result.exitCode}`,
|
||||
result.signalCode === null ? undefined : `signal ${result.signalCode}`,
|
||||
].filter((fact): fact is string => fact !== undefined)
|
||||
return facts.join(', ') || 'no exit code or signal'
|
||||
}
|
||||
|
||||
async function removeOwnedTree(path: string): Promise<void> {
|
||||
const metadata = await lstat(path).catch((error: unknown) => {
|
||||
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return undefined
|
||||
throw error
|
||||
})
|
||||
if (metadata === undefined) return
|
||||
if (metadata.isSymbolicLink() || !metadata.isDirectory()) {
|
||||
await unlink(path)
|
||||
return
|
||||
}
|
||||
await rm(path, { recursive: true, force: true })
|
||||
}
|
||||
@@ -8,9 +8,13 @@ if (process.argv.length > 2) {
|
||||
|
||||
const child = spawn(process.execPath, [
|
||||
'--import',
|
||||
'tsx',
|
||||
'packages/examples/acp-demo/src/bin.ts',
|
||||
'--config',
|
||||
'tsx/esm',
|
||||
'apps/cli/src/bin.ts',
|
||||
'--profile',
|
||||
'acp',
|
||||
'--patch',
|
||||
'examples/acp-agent/cordis.yml',
|
||||
'--patch',
|
||||
'examples/acp-agent/code-mode.cordis.yml',
|
||||
], { stdio: 'inherit' })
|
||||
child.on('exit', (code, signal) => { process.exit(signal !== null ? 1 : code ?? 1) })
|
||||
@@ -6,8 +6,12 @@ import { spawn } from 'node:child_process'
|
||||
const SURFACES = new Map([
|
||||
// The browser surface with the cordis toolset layered on: `dsh web --config`
|
||||
// applies this overlay over the shipped web composition; it owns port 3081.
|
||||
['web', ['--import', 'tsx', 'apps/cli/src/bin.ts', 'web', '--patch', 'examples/web-cordis/cordis.yml']],
|
||||
['acp', ['--import', 'tsx', 'packages/examples/acp-demo/src/bin.ts', '--config', 'examples/acp-agent/cordis-tools.cordis.yml']],
|
||||
['web', ['--import', 'tsx/esm', 'apps/cli/src/bin.ts', 'web', '--patch', 'examples/web-cordis/cordis.yml']],
|
||||
['acp', [
|
||||
'--import', 'tsx/esm', 'apps/cli/src/bin.ts', '--profile', 'acp',
|
||||
'--patch', 'examples/acp-agent/cordis.yml',
|
||||
'--patch', 'examples/acp-agent/cordis-tools.cordis.yml',
|
||||
]],
|
||||
])
|
||||
|
||||
const surface = process.argv[2] ?? 'web'
|
||||
|
||||
+26
-1
@@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
import type { TsdownBundle } from 'tsdown'
|
||||
import { discoverPluginDirs, watchClientPlugins } from './dev-web.ts'
|
||||
import { discoverLibraryDirs, discoverPluginDirs, watchClientPlugins } from './dev-web.ts'
|
||||
|
||||
it('discovers dsh.client packages with sibling roles', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-dev-web-discovery-'))
|
||||
@@ -24,6 +24,31 @@ it('discovers dsh.client packages with sibling roles', async () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('discovers client-preset packages the shell links, excluding loader-delivered and test infrastructure', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-dev-web-library-'))
|
||||
try {
|
||||
const write = async (dir: string, manifest: unknown, config: string): Promise<void> => {
|
||||
await mkdir(join(root, dir), { recursive: true })
|
||||
await writeFile(join(root, dir, 'package.json'), JSON.stringify(manifest))
|
||||
await writeFile(join(root, dir, 'tsdown.config.ts'), config)
|
||||
}
|
||||
const clientPreset = "import { clientLibrary } from '../tsdown.client.ts'\nexport default clientLibrary('x', [])\n"
|
||||
|
||||
// Linked by the compile shell: client preset, no loader-delivered half.
|
||||
await write('packages/client/linked', {}, clientPreset)
|
||||
// Loader-delivered: discoverPluginDirs owns it, so it must not appear twice.
|
||||
await write('packages/client/delivered', { dsh: { client: { platform: 'web' } } }, clientPreset)
|
||||
// Test infrastructure builds through the preset but never enters the shell graph.
|
||||
await write('packages/test-support/harness', {}, clientPreset)
|
||||
// Host package with its own config: not a client-face build at all.
|
||||
await write('packages/host/server', {}, "import { defineConfig } from 'tsdown'\nexport default defineConfig({})\n")
|
||||
|
||||
expect(discoverLibraryDirs(root)).toEqual(['packages/client/linked'])
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rebuilds a client-plugin bundle after its source changes', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-dev-web-watch-'))
|
||||
let bundles: TsdownBundle[] = []
|
||||
|
||||
+137
-13
@@ -1,17 +1,28 @@
|
||||
/**
|
||||
* Watch-build for client-plugin HMR: runs every `dsh.client` plugin package
|
||||
* through the tsdown JS API in watch mode. Reload signaling is not this
|
||||
* script's business — the host webserver stat-polls the bundles it serves and
|
||||
* broadcasts `rebuilt` frames itself (`dsh web`), so any process that
|
||||
* rewrites `lib/client.js` files triggers reloads; this script is merely the
|
||||
* convenient way to keep them all rebuilt on source change.
|
||||
* Watch-build for the web dev loop: rebuilds every artifact the browser reads
|
||||
* from a source edit. Reload signaling is not this script's business — the host
|
||||
* webserver stat-polls the bundles it serves and broadcasts `rebuilt` frames
|
||||
* itself (`dsh web`), so any process that rewrites `lib/client.js` files
|
||||
* triggers reloads; this script is merely the convenient way to keep them all
|
||||
* rebuilt on source change.
|
||||
*
|
||||
* Usage: `pnpm exec tsx scripts/dev-web.ts [--poll[=ms]]`. Requires the
|
||||
* packages' node halves built once (`tsc -b tsconfig.build.json`): the lib
|
||||
* config's entries are tsc output. `--poll` switches the source-file watcher
|
||||
* to polling (default 500ms): network mounts (weka) deliver no inotify
|
||||
* Three stages, because the compile shell links built lib products rather than
|
||||
* sources: `tsc -b tsconfig.client.json` emits `lib/types` (the tsdown lib
|
||||
* entries are that emit, not `src`), tsdown bundles `lib/index.js` and
|
||||
* `lib/client.js`, and `vite build` rewrites `apps/web/dist`, which `dsh web`
|
||||
* serves. A missing stage does not fail — it silently shows the previous
|
||||
* artifact, so an edit appears to do nothing.
|
||||
*
|
||||
* MUST NOT run concurrently with `pnpm run build`: both write the same
|
||||
* `lib/` and `apps/web/dist/` trees.
|
||||
*
|
||||
* Usage: `pnpm exec tsx scripts/dev-web.ts [--poll[=ms]]`. Requires one prior
|
||||
* `pnpm run build`: every stage is incremental over the previous stage's output
|
||||
* and none of them bootstraps a missing tree. `--poll` switches the source
|
||||
* watchers to polling (default 500ms): network mounts (weka) deliver no inotify
|
||||
* events, so native watching sees the initial build only and never a source
|
||||
* change.
|
||||
* change. Polling has to reach tsc too — a native-watching tsc never re-emits
|
||||
* `lib/types`, which strands the other two stages on stale input.
|
||||
*
|
||||
* Each package keeps its own tsdown.config.ts untouched: this script layers
|
||||
* `watch` through API-level inline config (tsdown workspace mode fills inline
|
||||
@@ -20,11 +31,24 @@
|
||||
import { globSync, readFileSync } from 'node:fs'
|
||||
import { dirname, join, resolve, sep } from 'node:path'
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url'
|
||||
import { execa } from 'execa'
|
||||
import { build } from 'tsdown'
|
||||
import type { TsdownBundle } from 'tsdown'
|
||||
|
||||
const repoRoot = fileURLToPath(new URL('..', import.meta.url))
|
||||
|
||||
/** Client-face type emit feeding every tsdown lib entry in the watch set. */
|
||||
const CLIENT_TYPE_PROGRAM = 'tsconfig.client.json'
|
||||
|
||||
/** Compile-shell workspace whose dist `dsh web` serves. */
|
||||
const SHELL_PACKAGE = '@deepseek-ai/dsh-web-frontend'
|
||||
|
||||
/**
|
||||
* Test infrastructure builds through the client preset but never enters the
|
||||
* shell's module graph, so it is not a dev-loop artifact.
|
||||
*/
|
||||
const TEST_INFRASTRUCTURE_PREFIX = 'packages/test-support/'
|
||||
|
||||
/**
|
||||
* Discover the watch workspace by declaration: every packages/<group>/<name>
|
||||
* whose package.json carries `dsh.client` with platform "web" is a client
|
||||
@@ -44,6 +68,32 @@ export function discoverPluginDirs(root = repoRoot): string[] {
|
||||
return dirs
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover the statically linked library packages: the other half of the same
|
||||
* partition {@link discoverPluginDirs} takes. A package that builds through the
|
||||
* client preset without declaring `dsh.client` has no loader-delivered browser
|
||||
* half, so the compile shell links its `lib/index.js` instead — and an edit to
|
||||
* its source reaches the browser only once that bundle is rewritten. Deriving
|
||||
* the set from the build preset rather than a hand list keeps it correct when
|
||||
* dependency sections move around; deriving it from `dependencies` would not,
|
||||
* because client packages declare their build inputs as devDependencies.
|
||||
* @param root - repository root containing the grouped package directories.
|
||||
* @returns workspace-relative library package directories.
|
||||
*/
|
||||
export function discoverLibraryDirs(root = repoRoot): string[] {
|
||||
const dirs: string[] = []
|
||||
for (const configPath of globSync('packages/*/*/tsdown.config.ts', { cwd: root }).sort()) {
|
||||
const dir = dirname(configPath).split(sep).join('/')
|
||||
if (dir.startsWith(TEST_INFRASTRUCTURE_PREFIX)) continue
|
||||
if (!readFileSync(join(root, configPath), 'utf8').includes('tsdown.client.ts')) continue
|
||||
const manifest = JSON.parse(readFileSync(join(root, dir, 'package.json'), 'utf8')) as {
|
||||
dsh?: { client?: unknown }
|
||||
}
|
||||
if (manifest.dsh?.client === undefined) dirs.push(dir)
|
||||
}
|
||||
return dirs
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the tsdown watch build used by `pnpm run dev:web`.
|
||||
* @param root - repository or fixture root passed to tsdown.
|
||||
@@ -85,14 +135,56 @@ export async function watchClientPlugins(
|
||||
return bundles
|
||||
}
|
||||
|
||||
/**
|
||||
* Live watcher processes to terminate when this script is interrupted. Stages
|
||||
* register themselves as they start, so the set is complete from the first
|
||||
* spawn: an interrupt during a later stage's startup still tears down the
|
||||
* earlier ones instead of orphaning them.
|
||||
*/
|
||||
const stages: StageHandle[] = []
|
||||
|
||||
/**
|
||||
* Spawn one watcher stage, inheriting stdio, registering it for teardown, and
|
||||
* failing loud if it ever exits: a dead stage leaves the artifact chain silently
|
||||
* stale, which reads as "my edit did nothing" — the one failure this script
|
||||
* exists to prevent.
|
||||
* @param stage - command label used in the exit diagnostic.
|
||||
* @param command - executable, resolved from the workspace bin when local.
|
||||
* @param args - command arguments.
|
||||
* @param local - whether to resolve `command` from the workspace's installed bins.
|
||||
*/
|
||||
function spawnStage(stage: string, command: string, args: readonly string[], local: boolean): void {
|
||||
const child = execa(command, [...args], {
|
||||
cwd: repoRoot,
|
||||
stdio: 'inherit',
|
||||
preferLocal: local,
|
||||
reject: false,
|
||||
})
|
||||
stages.push({ kill: () => { child.kill() } })
|
||||
void child.then((result) => {
|
||||
console.error(`dev-web: ${stage} exited (code ${String(result.exitCode)}); the artifact chain is now stale`)
|
||||
process.exit(1)
|
||||
})
|
||||
}
|
||||
|
||||
/** The only capability this script needs from a live watcher process. */
|
||||
interface StageHandle {
|
||||
readonly kill: () => void
|
||||
}
|
||||
|
||||
const invokedPath = process.argv[1]
|
||||
const isMain = invokedPath !== undefined && import.meta.url === pathToFileURL(resolve(invokedPath)).href
|
||||
if (isMain) {
|
||||
const pluginDirs = discoverPluginDirs()
|
||||
const libraryDirs = discoverLibraryDirs()
|
||||
if (pluginDirs.length === 0) {
|
||||
console.error('dev-web: no dsh.client (platform "web") packages found under packages/')
|
||||
process.exit(1)
|
||||
}
|
||||
if (libraryDirs.length === 0) {
|
||||
console.error('dev-web: no client-preset library packages found under packages/ — the compile shell links their lib products, so an empty set means the discovery predicate is stale')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const pollArg = args.find(a => a === '--poll' || a.startsWith('--poll='))
|
||||
@@ -106,9 +198,41 @@ if (isMain) {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
await watchClientPlugins(repoRoot, pluginDirs, pollInterval)
|
||||
// Registered before any stage starts: `stages` is read at signal time, so an
|
||||
// interrupt during tsdown's initial builds still kills whatever is running.
|
||||
const stop = (): void => { for (const stage of stages) stage.kill() }
|
||||
process.once('SIGINT', stop)
|
||||
process.once('SIGTERM', stop)
|
||||
|
||||
// tsc has no polling interval flag, so `--poll` selects its fixed-interval
|
||||
// watchers rather than an interval. Dropping that translation leaves tsc
|
||||
// natively watching on a network mount where inotify never fires: it stops
|
||||
// re-emitting lib/types, and the two later stages then rebuild forever from
|
||||
// stale input without printing anything.
|
||||
spawnStage(`tsc -b ${CLIENT_TYPE_PROGRAM} --watch`, 'tsc', [
|
||||
'-b', CLIENT_TYPE_PROGRAM, '--watch', '--preserveWatchOutput',
|
||||
...pollInterval !== undefined
|
||||
? ['--watchFile', 'fixedPollingInterval', '--watchDirectory', 'fixedPollingInterval']
|
||||
: [],
|
||||
], true)
|
||||
|
||||
// tsdown's initial builds are awaited before the dist watcher starts so vite's
|
||||
// first build reads current lib bundles rather than whatever the last full
|
||||
// build left. Its own watch then covers later lib rewrites — those files are
|
||||
// in its module graph.
|
||||
await watchClientPlugins(repoRoot, [...pluginDirs, ...libraryDirs], pollInterval)
|
||||
// Through the shell's own `watch` script rather than vite's API: vite is not a
|
||||
// repository-root dependency, and more importantly the vite root is its
|
||||
// working directory — `resolve.dedupe` resolves react from that root, so
|
||||
// running vite from anywhere but apps/web silently switches which react copy
|
||||
// the bundle gets.
|
||||
spawnStage('vite build --watch', 'pnpm', ['--filter', SHELL_PACKAGE, 'run', 'watch'], false)
|
||||
|
||||
console.log(
|
||||
`dev-web: watching ${String(pluginDirs.length)} dsh.client plugin packages`
|
||||
+ `${pollInterval !== undefined ? ` (polling ${String(pollInterval)}ms)` : ''}:\n ${pluginDirs.join('\n ')}`,
|
||||
+ ` and ${String(libraryDirs.length)} statically linked library packages`
|
||||
+ (pollInterval !== undefined ? ` (polling ${String(pollInterval)}ms)` : '')
|
||||
+ `, plus tsc -b ${CLIENT_TYPE_PROGRAM} and the ${SHELL_PACKAGE} dist build:\n `
|
||||
+ [...pluginDirs, ...libraryDirs].join('\n '),
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"AGENTS.md": 1900,
|
||||
"AGENTS.md": 1950,
|
||||
"docs/AGENTS.md": 1320,
|
||||
"docs/architecture.md": 2400,
|
||||
"docs/cordis-primer.md": 600,
|
||||
|
||||
@@ -12,7 +12,7 @@ export function builtDeclarationPath(candidate: string): string {
|
||||
if (sourceFile?.[1] && sourceFile[2]) {
|
||||
return `${sourceFile[1]}/lib/types/${sourceFile[2]}.d.ts`
|
||||
}
|
||||
// Directory subpath entries (web-react's /store, runtime's /client): the
|
||||
// Directory subpath entries (for example, runtime's /client): the
|
||||
// source dir maps to the same dir under lib/types (index resolution applies).
|
||||
const sourceDir = /^(.*)\/src\/(.+)$/.exec(candidate)
|
||||
if (sourceDir?.[1] && sourceDir[2]) {
|
||||
|
||||
@@ -42,7 +42,7 @@ const MAX_DECL_CHARS = 1200
|
||||
/**
|
||||
* Line budget for ONE slot's expanded report. The whole point of narrowing to a
|
||||
* single slot is to spend less context, so a report a model cannot finish
|
||||
* reading is a defect rather than a detail. Today's widest slot renders 60
|
||||
* reading is a defect rather than a detail. The widest measured slot renders 60
|
||||
* lines, so this leaves room to document a slot properly while catching the two
|
||||
* ways a report runs away: an owner share that hands down a subsystem instead of
|
||||
* a share, and prose that grew into a manual.
|
||||
@@ -552,7 +552,6 @@ export function main(): void {
|
||||
console.log(`gen-client-catalog: wrote ${OUT}.`)
|
||||
}
|
||||
|
||||
// Run only when invoked as a script, not when imported by a test.
|
||||
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
|
||||
main()
|
||||
}
|
||||
@@ -874,7 +874,6 @@ function main(): void {
|
||||
console.log(`gen-config-catalog: wrote ${OUT}.`)
|
||||
}
|
||||
|
||||
// Run only when invoked as a script, not when imported by a test.
|
||||
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
|
||||
main()
|
||||
}
|
||||
@@ -10,7 +10,13 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'nod
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { maybeRecordPair, REGION_BEGIN, REGION_END, spliceRegion } from './gen-cordis-catalog.ts'
|
||||
import {
|
||||
localizePageRegion,
|
||||
maybeRecordPair,
|
||||
REGION_BEGIN,
|
||||
REGION_END,
|
||||
spliceRegion,
|
||||
} from './gen-cordis-catalog.ts'
|
||||
import { blobHash, renderPairMeta } from './translation-pairing.ts'
|
||||
|
||||
const PAGE = 'docs/subsystems/fix.md'
|
||||
@@ -142,3 +148,28 @@ describe('spliceRegion', () => {
|
||||
.toThrow('found 2 BEGIN/2 END')
|
||||
})
|
||||
})
|
||||
|
||||
describe('localizePageRegion', () => {
|
||||
it('changes only paired Markdown paths for the Chinese generated region', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'cordis-region-locale-'))
|
||||
roots.push(root)
|
||||
mkdirSync(join(root, 'docs/subsystems'), { recursive: true })
|
||||
mkdirSync(join(root, 'packages'), { recursive: true })
|
||||
mkdirSync(join(root, 'scripts'), { recursive: true })
|
||||
writeFileSync(join(root, 'docs/subsystems/target.md'), '# Target\n')
|
||||
writeFileSync(join(root, 'docs/subsystems/target.zh.md'), '# 目标\n')
|
||||
writeFileSync(join(root, 'docs/subsystems/excluded.md'), '# Excluded\n')
|
||||
writeFileSync(join(root, 'docs/subsystems/excluded.zh.md'), '# 排除\n')
|
||||
writeFileSync(join(root, 'packages/outside.md'), '# Outside\n')
|
||||
writeFileSync(join(root, 'packages/outside.zh.md'), '# 范围外\n')
|
||||
writeFileSync(join(root, 'scripts/translation-pairing.manifest.json'), JSON.stringify({
|
||||
excluded: ['docs/subsystems/excluded.md'],
|
||||
}))
|
||||
const region = `${REGION_BEGIN}\n[Target](target.md#api) [Excluded](excluded.md) [Outside](../../packages/outside.md)\n${REGION_END}`
|
||||
|
||||
expect(localizePageRegion(region, 'docs/subsystems/page.md', root)).toBe(region)
|
||||
expect(localizePageRegion(region, 'docs/subsystems/page.zh.md', root)).toBe(
|
||||
`${REGION_BEGIN}\n[Target](target.zh.md#api) [Excluded](excluded.md) [Outside](../../packages/outside.md)\n${REGION_END}`,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -3,8 +3,9 @@
|
||||
* Typert catalog projection. Every harness `ctx.<key>` service and event scope
|
||||
* maps to exactly one `docs/subsystems/` page through the curated tables below;
|
||||
* the generator injects each page's Cordis API reference between its GENERATED markers —
|
||||
* byte-identically into both language sides of the pair — and re-records a
|
||||
* pair's `.i18n.yaml` only when nothing outside the region changed. The
|
||||
* into both language sides of the pair, localizing paired document paths for
|
||||
* the Chinese side while retaining every other byte — and re-records a pair's
|
||||
* `.i18n.yaml` only when nothing outside the region changed. The
|
||||
* projection enforces event modes, JSDoc parameter/return completeness, and
|
||||
* signature type-link coverage; the inherited (vendor) tier renders to
|
||||
* `docs/cordis-api/inherited.md`. `--check` verifies every generated artifact.
|
||||
@@ -32,9 +33,12 @@ import { contextKeyMap, contextMergeFiles, eventNameList } from './cordis-walk.t
|
||||
import {
|
||||
blobHash,
|
||||
parsePairMeta,
|
||||
parseTranslationPairingManifest,
|
||||
partitionGeneratedRegions,
|
||||
renderPairMeta,
|
||||
translationPairSourcePredicate,
|
||||
} from './translation-pairing.ts'
|
||||
import { rewriteTranslationLinkLocales } from './translation-links.ts'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const SUBSYSTEMS_DIR = 'docs/subsystems'
|
||||
@@ -64,10 +68,13 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
commands: 'commands.md',
|
||||
compaction: 'compaction.md',
|
||||
cordisInspect: 'extensions.md',
|
||||
authorization: 'credentials.md',
|
||||
credentials: 'credentials.md',
|
||||
directoryPicker: 'workspace.md',
|
||||
deepseekLlmApiExtensions: 'llm-streaming.md',
|
||||
dynamicCordisRunner: 'extensions.md',
|
||||
e2b: 'subprocess.md',
|
||||
fileReferences: 'session-reference.md',
|
||||
fs: 'filesystem.md',
|
||||
goals: 'goal.md',
|
||||
webServer: 'web-server.md',
|
||||
@@ -97,6 +104,7 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
systemPrompt: 'system-prompt.md',
|
||||
jobs: 'jobs.md',
|
||||
sessionTelemetry: 'session-telemetry.md',
|
||||
agentTeams: 'agent-team.md',
|
||||
tokenMeter: 'token-meter.md',
|
||||
toolResultPruner: 'compaction.md',
|
||||
tools: 'tools.md',
|
||||
@@ -105,6 +113,7 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
userQuestions: 'user-questions.md',
|
||||
web: 'web.md',
|
||||
workflowEngine: 'workflow.md',
|
||||
webhookRuntime: 'webhook.md',
|
||||
workspaceRegistry: 'workspace.md',
|
||||
}
|
||||
|
||||
@@ -128,6 +137,7 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
*/
|
||||
export const SERVICE_WALK_EXEMPTIONS: Record<string, string> = {
|
||||
agent: 'not a service: the DX accessor field on Agent.ctx (root accessor defaulting to undefined) — docs/subsystems/core.md owns the Agent handle',
|
||||
appReady: 'not a service: launcher-provided successful-startup signal — packages/boot/cmdline/README.md owns the launcher contract',
|
||||
appExit: 'not a service: launcher-provided bounded process-exit callback — packages/boot/cmdline/README.md owns the launcher contract',
|
||||
cmdlineArgs: 'not a service: launcher-provided immutable app argument accessor — packages/boot/cmdline/README.md owns the launcher contract',
|
||||
configuredAgentIdentities: 'not a service: launcher-provided boot-context value (ConfiguredAgentIdentities | undefined) — packages/core/agent-loop/README.md owns this launcher contract',
|
||||
@@ -135,7 +145,8 @@ export const SERVICE_WALK_EXEMPTIONS: Record<string, string> = {
|
||||
dshHomePath: 'not a service: boot-provided root accessor function (typeof dshHomePath | undefined) for Loader !!js config expressions — packages/boot/app-boot/README.md owns the boot contract',
|
||||
launchEnvironment: 'not a service: launcher-provided root accessor value (LaunchEnvironmentSnapshot | undefined) — packages/util/launch-environment/README.md owns this launcher contract',
|
||||
connection: 'interface-typed (HostConnectionHandle); implementing class HostConnectionService is declared in rpc-host.ts — packages/client/connection/README.md owns the API',
|
||||
appShell: 'client-side interface-typed browser service — packages/client/web/README.md owns the API',
|
||||
uiRenderer: 'client-side interface-typed browser service — packages/client/ui-renderer/README.md owns the API',
|
||||
settingsSchema: 'client-side schema introspection service — packages/client/ui-settings/README.md owns the API',
|
||||
settingsScope: 'client-side settings-namespace transport service — packages/client/ui-settings/README.md owns the API',
|
||||
chatFileMentions: 'client-side slot-contract accessor (ChatFileMentions) — packages/client/ui-conversation/README.md owns the API',
|
||||
commandUi: 'client-side interface-typed browser service — packages/client/ui-commands/README.md owns the API',
|
||||
@@ -169,6 +180,7 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
|
||||
'approval': 'approval.md',
|
||||
'commands': 'commands.md',
|
||||
'cordis': 'extensions.md',
|
||||
'authorization': 'credentials.md',
|
||||
'credentials': 'credentials.md',
|
||||
'domain': 'storage.md',
|
||||
'fs': 'filesystem.md',
|
||||
@@ -181,6 +193,7 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
|
||||
'system-prompt': 'system-prompt.md',
|
||||
'session-telemetry': 'session-telemetry.md',
|
||||
'tools': 'tools.md',
|
||||
'webserver': 'web-server.md',
|
||||
'workflow': 'workflow.md',
|
||||
}
|
||||
|
||||
@@ -230,6 +243,9 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
SettleReason: 'core.md',
|
||||
AdapterRegistrationHandle: 'llm-streaming.md',
|
||||
DirectoryRegistrationHandle: 'llm-streaming.md',
|
||||
DeepSeekLlmApiExtensionMap: 'llm-streaming.md',
|
||||
DeepSeekLlmApiExtensionProvider: 'llm-streaming.md',
|
||||
DeepSeekLlmApiExtensionRequest: 'llm-streaming.md',
|
||||
LlmCallConfig: 'llm-streaming.md',
|
||||
LlmModelContext: 'llm-streaming.md',
|
||||
LlmModelReasoningInfo: 'llm-streaming.md',
|
||||
@@ -268,7 +284,9 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
RequestErrorAction: 'core.md',
|
||||
RequestFailureContext: 'core.md',
|
||||
PreparedReferencedMessage: 'session-reference.md',
|
||||
FileReferenceCandidate: 'session-reference.md',
|
||||
SessionReferenceCandidate: 'session-reference.md',
|
||||
SessionReferenceMentionCandidate: 'session-reference.md',
|
||||
SessionReferenceInput: 'session-reference.md',
|
||||
SessionEvent: 'session.md',
|
||||
SessionId: 'core.md',
|
||||
@@ -279,7 +297,10 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
ApprovalPolicy: 'approval.md',
|
||||
ApprovalRequest: 'approval.md',
|
||||
ApprovalService: 'approval.md',
|
||||
EncodedImageAttachment: 'attachment.md',
|
||||
ImageAttachmentRef: 'attachment.md',
|
||||
ImageRequestPolicy: 'attachment.md',
|
||||
RequestImageAttachment: 'attachment.md',
|
||||
SaveImageAttachment: 'attachment.md',
|
||||
StoredImageAttachment: 'attachment.md',
|
||||
ShellExecRequest: 'shell.md',
|
||||
@@ -328,6 +349,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
LspQueryResult: 'lsp.md',
|
||||
LlmAdapter: 'llm-streaming.md',
|
||||
PreparedLlmCall: 'llm-streaming.md',
|
||||
PreparedDeepSeekLlmApiExtensions: 'llm-streaming.md',
|
||||
LlmRuntime: 'llm-streaming.md',
|
||||
StreamChunk: 'llm-streaming.md',
|
||||
SkillProviderControl: 'skills.md',
|
||||
@@ -422,6 +444,18 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
JobSnapshot: 'jobs.md',
|
||||
JobStart: 'jobs.md',
|
||||
JobsChangedListener: 'jobs.md',
|
||||
CreateTeamTaskRequest: 'agent-team.md',
|
||||
SendTeamMessageRequest: 'agent-team.md',
|
||||
SendTeamMessageResult: 'agent-team.md',
|
||||
SpawnTeammateRequest: 'agent-team.md',
|
||||
SpawnTeammateResult: 'agent-team.md',
|
||||
TeamId: 'agent-team.md',
|
||||
TeamMemberView: 'agent-team.md',
|
||||
TeamMembership: 'agent-team.md',
|
||||
TeamTaskId: 'agent-team.md',
|
||||
TeamTaskView: 'agent-team.md',
|
||||
TeamWaitResult: 'agent-team.md',
|
||||
UpdateTeamTaskRequest: 'agent-team.md',
|
||||
TokenMeasurement: 'token-meter.md',
|
||||
CodeDispatchLog: 'tools.md',
|
||||
PostToolDecision: 'tools.md',
|
||||
@@ -445,8 +479,23 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
SettingsPathOp: 'settings.md',
|
||||
SettingsDescribeOptions: 'settings.md',
|
||||
SettingsUpdateSource: 'settings.md',
|
||||
AuthorizationEntry: 'credentials.md',
|
||||
AuthorizationFlow: 'credentials.md',
|
||||
AuthorizationInteraction: 'credentials.md',
|
||||
AuthorizationMethod: 'credentials.md',
|
||||
AuthorizationNotice: 'credentials.md',
|
||||
AuthorizationOutcome: 'credentials.md',
|
||||
AuthorizationPrompt: 'credentials.md',
|
||||
AuthorizationRequest: 'credentials.md',
|
||||
AuthorizationSession: 'credentials.md',
|
||||
AuthorizationSettlement: 'credentials.md',
|
||||
AuthorizationStatus: 'credentials.md',
|
||||
CredentialRef: 'credentials.md',
|
||||
CredentialKey: 'credentials.md',
|
||||
CredentialInfo: 'credentials.md',
|
||||
CredentialRecord: 'credentials.md',
|
||||
CredentialRecordEntry: 'credentials.md',
|
||||
CredentialRecordInfo: 'credentials.md',
|
||||
ResolvedCredential: 'credentials.md',
|
||||
AskUserQuestionAnswer: 'user-questions.md',
|
||||
AskUserQuestionRequest: 'user-questions.md',
|
||||
@@ -458,10 +507,13 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
WebSearchRequest: 'web.md',
|
||||
WebSearchResult: 'web.md',
|
||||
WorkflowRun: 'workflow.md',
|
||||
VerifiedWebhookDelivery: 'webhook.md',
|
||||
WebhookRule: 'webhook.md',
|
||||
PresetOption: 'permission-presets.md',
|
||||
PresetSpec: 'permission-presets.md',
|
||||
InvariantInstaller: 'invariants.md',
|
||||
WebRoute: 'web-server.md',
|
||||
IndexInjection: 'web-server.md',
|
||||
StorageBackend: 'storage.md',
|
||||
StorageForms: 'storage.md',
|
||||
Domain: 'storage.md',
|
||||
@@ -476,6 +528,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
WorkflowStartRequest: 'workflow.md',
|
||||
ProjectionDefinition: 'session-projection.md',
|
||||
SessionProjectionMap: 'session-projection.md',
|
||||
SessionProjectionStateMap: 'session-projection.md',
|
||||
ProjectionChangeListener: 'session-projection.md',
|
||||
ProjectionSnapshot: 'session-projection.md',
|
||||
ProjectionCheckpoint: 'session-projection.md',
|
||||
@@ -494,7 +547,11 @@ export const FOUNDATION_TYPE_NAMES: ReadonlySet<string> = new Set([
|
||||
'AsyncIterable',
|
||||
'Context',
|
||||
'Error',
|
||||
'EntryTree',
|
||||
'Exclude',
|
||||
'Map',
|
||||
'NonNullable',
|
||||
'Omit',
|
||||
'Partial',
|
||||
'Pick',
|
||||
'Promise',
|
||||
@@ -698,6 +755,19 @@ export interface WalkPartitionMaps {
|
||||
readonly eventWalkExemptions: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
/** Project paired Markdown destinations in one generated region to the page's locale. */
|
||||
export function localizePageRegion(region: string, pageRel: string, scanRoot: string = root): string {
|
||||
if (!pageRel.endsWith('.zh.md')) return region
|
||||
const manifest = parseTranslationPairingManifest(
|
||||
readFileSync(resolve(scanRoot, 'scripts/translation-pairing.manifest.json'), 'utf8'),
|
||||
)
|
||||
return rewriteTranslationLinkLocales(region, {
|
||||
repoRoot: scanRoot,
|
||||
sourcePath: pageRel,
|
||||
isTranslationPairSource: translationPairSourcePredicate(manifest),
|
||||
}).content
|
||||
}
|
||||
|
||||
/**
|
||||
* Judge the rendered API and the independent AST scan against the curated
|
||||
* partition maps, fail-closed in both directions for services AND events: a
|
||||
@@ -821,6 +891,7 @@ export function computeOutputs(): [string, string][] {
|
||||
)
|
||||
for (const side of [page, page.replace(/\.md$/, '.zh.md')]) {
|
||||
const rel = `${SUBSYSTEMS_DIR}/${side}`
|
||||
const localizedRegion = localizePageRegion(region, rel)
|
||||
let current: string
|
||||
try {
|
||||
current = readFileSync(resolve(root, rel), 'utf8')
|
||||
@@ -831,7 +902,7 @@ export function computeOutputs(): [string, string][] {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
outputs.push([rel, spliceRegion(current, region)])
|
||||
outputs.push([rel, spliceRegion(current, localizedRegion)])
|
||||
} catch (error) {
|
||||
problems.push(`${rel}: ${error instanceof Error ? error.message : String(error)}`)
|
||||
}
|
||||
@@ -947,7 +1018,6 @@ export function main(): void {
|
||||
console.log(`gen-cordis-catalog: ${outputs.length} artifact(s) computed, ${changedPages} written, ${recorded} pair record(s) refreshed.`)
|
||||
}
|
||||
|
||||
// Run only when invoked as a script, not when imported by a test.
|
||||
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
|
||||
main()
|
||||
}
|
||||
+49
-22
@@ -67,6 +67,7 @@ const GROUP_ORDER = [
|
||||
'core',
|
||||
'typert',
|
||||
'goal',
|
||||
'experimental',
|
||||
'process',
|
||||
'bash',
|
||||
'pty',
|
||||
@@ -79,6 +80,7 @@ const GROUP_ORDER = [
|
||||
'tasks',
|
||||
'workflow',
|
||||
'web',
|
||||
'webhook',
|
||||
'spill',
|
||||
'todo',
|
||||
'plan',
|
||||
@@ -114,6 +116,15 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
consumers: ['agent-loop', 'compaction-basic'],
|
||||
note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
|
||||
},
|
||||
{
|
||||
key: 'deepseekLlmApiExtensions',
|
||||
pkg: 'deepseek-llm-api-extensions',
|
||||
title: 'Official DeepSeek request extensions',
|
||||
mode: 'seam',
|
||||
implementations: ['session-log-deepseek', 'plugin-package-inventory-deepseek'],
|
||||
consumers: ['llm-deepseek'],
|
||||
note: 'Plugins prepare independent top-level fields; the official adapter merges them and commits their delivery state after HTTP acceptance.',
|
||||
},
|
||||
{
|
||||
key: 'tokenMeter',
|
||||
pkg: 'token-meter',
|
||||
@@ -188,6 +199,15 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
consumers: ['llm-deepseek', 'llm-pi-ai', 'apiproxy'],
|
||||
note: 'Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the web gateway exposes value-free views and write-only storage.',
|
||||
},
|
||||
{
|
||||
key: 'authorization',
|
||||
pkg: 'authorization',
|
||||
title: 'Authorization flow registry',
|
||||
mode: 'seam',
|
||||
implementations: [],
|
||||
consumers: ['llm-pi-ai'],
|
||||
note: 'Flows are registered by the plugin that knows how to obtain one credential and keyed by the record they write; the seam owns the conversation and the one-attempt-per-key lifecycle, never the protocol.',
|
||||
},
|
||||
{
|
||||
key: 'sessionTelemetry',
|
||||
pkg: 'session-telemetry',
|
||||
@@ -238,6 +258,14 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
consumers: ['session-reference', 'tool-session-query'],
|
||||
note: 'The interface supplies exact reads, filters, and traces; its concrete backend adds full-text reconciliation, ranking, snippets, and cursor generations, while the model consumer owns workspace authority and cursor-free rendering.',
|
||||
},
|
||||
{
|
||||
key: 'fileReferences',
|
||||
pkg: 'file-reference',
|
||||
title: 'File reference discovery',
|
||||
mode: 'seam',
|
||||
implementations: ['file-reference-local'],
|
||||
note: 'The interface returns path-only completion candidates within the addressed Agent cwd through its unary Remote contract; providers own namespace access and ranking without reading file contents.',
|
||||
},
|
||||
{
|
||||
key: 'sessionReferenceResolver',
|
||||
pkg: 'session-reference',
|
||||
@@ -469,6 +497,14 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
consumers: ['tool-subagent', 'tool-subagent-control', 'tool-ralph'],
|
||||
note: 'Providers implement transports; the service also owns optional Activation-based continuation orchestration, tool-subagent selects one-shot or continuable delegation, tool-subagent-control delivers follow-ups, and tool-ralph requires one fresh structured-output route.',
|
||||
},
|
||||
{
|
||||
key: 'agentTeams',
|
||||
pkg: 'agent-team',
|
||||
title: 'Agent Teams coordination domain',
|
||||
mode: 'core',
|
||||
consumers: ['tool-agent-team'],
|
||||
note: 'Owns the implicit-root roster, durable peer mailbox, shared task DAG, and continuable-child lifecycle; tool-agent-team contributes the scoped model policy and controls.',
|
||||
},
|
||||
{
|
||||
key: 'jobs',
|
||||
pkg: 'jobs',
|
||||
@@ -530,6 +566,14 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
consumers: ['tool-workflow', 'tool-ralph'],
|
||||
note: 'One engine per context, as in bash, with no named-provider registry; the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents.',
|
||||
},
|
||||
{
|
||||
key: 'webhookRuntime',
|
||||
pkg: 'webhook',
|
||||
title: 'Webhook rule runtime',
|
||||
mode: 'core',
|
||||
consumers: ['webhook-github'],
|
||||
note: 'Provider adapters dispatch authenticated deliveries; trusted plugins register independent process-local rules, and the runtime turns non-null results into ordinary Workspace-backed Sessions without delivery or completion state.',
|
||||
},
|
||||
{
|
||||
key: 'lsp',
|
||||
pkg: 'lsp',
|
||||
@@ -717,34 +761,20 @@ const APP_EXAMPLES = [
|
||||
{
|
||||
id: 'acp',
|
||||
rel: 'examples/acp-agent/composition.md',
|
||||
title: 'ACP Automation App Composition',
|
||||
title: 'ACP Automation Profile Patch',
|
||||
label: 'examples/acp-agent',
|
||||
config: 'examples/acp-agent/cordis.yml',
|
||||
summary: 'The ACP demo exposes fresh baseline-prompt agent sessions to programmatic clients over JSON-RPC stdio, with no stdout logger, human UI, or pre-created agent.',
|
||||
summary: 'The ACP example patches the shipped base + acp-app profile for demos and snapshots; dsh owns launch, and the ACP bridge exposes fresh automation sessions without a stdout logger or pre-created agent.',
|
||||
},
|
||||
]
|
||||
|
||||
type AppExample = typeof APP_EXAMPLES[number]
|
||||
|
||||
function renderAppExpansion(lines: string[], appNode: string, pluginName: string): void {
|
||||
const agentCore = nodeId('bundle', 'agent_core')
|
||||
const jsonl = nodeId('bundle', 'jsonl')
|
||||
lines.push(` ${appNode} --> ${agentCore}["@deepseek-ai/dsh-agent-spine-demo"]`)
|
||||
lines.push(` ${appNode} --> ${jsonl}["@deepseek-ai/dsh-session-persistence-jsonl"]`)
|
||||
if (pluginName === '@deepseek-ai/dsh-acp-demo') {
|
||||
lines.push(` ${appNode} --> ${nodeId('entrypoint', 'acp')}["@deepseek-ai/dsh-acp<br/>automation-only JSON-RPC stdio<br/>fresh sessions created by client"]`)
|
||||
}
|
||||
lines.push(
|
||||
` ${agentCore} --> ${nodeId('spine', 'llm')}["ctx.llm"]`,
|
||||
` ${agentCore} --> ${nodeId('spine', 'sessions')}["ctx.sessions"]`,
|
||||
` ${agentCore} --> ${nodeId('spine', 'tools')}["ctx.tools + tool-bash"]`,
|
||||
` ${agentCore} --> ${nodeId('spine', 'loop')}["ctx.agents + ctx.agentLoop"]`,
|
||||
)
|
||||
}
|
||||
|
||||
function renderAppComposition(example: AppExample): string {
|
||||
const plugins = parseExampleCordis(example.config)
|
||||
const maintenance = 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
|
||||
const maintenance = example.id === 'acp'
|
||||
? 'hybrid: the patch row list is parsed from its `cordis.yml`; the scope summary is curated'
|
||||
: 'hybrid: the leaf plugin list is parsed from its `cordis.yml`; app package expansion is curated from package source'
|
||||
const lines = generatedHeader(example.title)
|
||||
lines.push(
|
||||
example.summary,
|
||||
@@ -757,9 +787,6 @@ function renderAppComposition(example: AppExample): string {
|
||||
const pluginNode = nodeId(`plugin_${example.id}`, plugin.id)
|
||||
lines.push(` ${pluginNode}["${escLabel(plugin.id)}<br/>${escLabel(plugin.name)}"]`)
|
||||
lines.push(` cfg --> ${pluginNode}`)
|
||||
if (plugin.name === '@deepseek-ai/dsh-acp-demo') {
|
||||
renderAppExpansion(lines, pluginNode, plugin.name)
|
||||
}
|
||||
}
|
||||
lines.push(
|
||||
'```',
|
||||
|
||||
@@ -36,22 +36,27 @@ const EVENT_ENVELOPE_TYPE_NAMES = [
|
||||
|
||||
type EventEnvelopeTypeName = typeof EVENT_ENVELOPE_TYPE_NAMES[number]
|
||||
|
||||
/** Primary subsystems page for linked payload types. */
|
||||
/** Documentation target, relative to `docs/`, for linked payload types. */
|
||||
const LINK_MAP: Record<string, string> = {
|
||||
CallId: 'core.md',
|
||||
ContentBlock: 'core.md',
|
||||
MessageSource: 'core.md',
|
||||
ScheduleChange: 'schedule.md',
|
||||
StreamChunk: 'llm-streaming.md',
|
||||
TokenUsage: 'llm-streaming.md',
|
||||
TodoItem: 'session.md',
|
||||
TurnTrigger: 'session.md',
|
||||
TurnEndReason: 'session.md',
|
||||
SessionTitleEventData: 'session-title.md',
|
||||
SessionTitleLlmRequestEventData: 'session-title.md',
|
||||
SessionTitleModelProvenance: 'session-title.md',
|
||||
SessionTitleProviderId: 'session-title.md',
|
||||
SessionTitleSource: 'session-title.md',
|
||||
CallId: 'subsystems/core.md',
|
||||
ContentBlock: 'subsystems/core.md',
|
||||
MessageSource: 'subsystems/core.md',
|
||||
ScheduleChange: 'subsystems/schedule.md',
|
||||
StreamChunk: 'subsystems/llm-streaming.md',
|
||||
TokenUsage: 'subsystems/llm-streaming.md',
|
||||
TodoItem: 'subsystems/todo.md',
|
||||
TurnTrigger: 'subsystems/session.md',
|
||||
TurnEndReason: 'subsystems/session.md',
|
||||
SessionTitleEventData: 'subsystems/session-title.md',
|
||||
SessionTitleLlmRequestEventData: 'subsystems/session-title.md',
|
||||
SessionTitleModelProvenance: 'subsystems/session-title.md',
|
||||
SessionTitleProviderId: 'subsystems/session-title.md',
|
||||
SessionTitleSource: 'subsystems/session-title.md',
|
||||
TeamId: 'subsystems/agent-team.md',
|
||||
TeamMemberSnapshot: 'subsystems/agent-team.md',
|
||||
TeamMessageId: 'subsystems/agent-team.md',
|
||||
TeamMessageSnapshot: 'subsystems/agent-team.md',
|
||||
TeamTaskSnapshot: 'subsystems/agent-team.md',
|
||||
}
|
||||
|
||||
/** One log event, extracted from a `SessionEventMap` declaration. */
|
||||
@@ -336,7 +341,7 @@ function typeLinks(payload: string): string {
|
||||
if (new RegExp(`\\b${name}\\b`).test(payload)) seen.add(name)
|
||||
}
|
||||
if (seen.size === 0) return ''
|
||||
const links = [...seen].sort().map(n => `[${n}](subsystems/${LINK_MAP[n]})`)
|
||||
const links = [...seen].sort().map(n => `[${n}](${LINK_MAP[n]})`)
|
||||
return `Types: ${links.join(' · ')}`
|
||||
}
|
||||
|
||||
@@ -461,7 +466,6 @@ function main(): void {
|
||||
}
|
||||
}
|
||||
|
||||
// Run only when invoked as a script, not when imported by a test.
|
||||
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
|
||||
main()
|
||||
}
|
||||
@@ -673,7 +673,6 @@ export function render(): string {
|
||||
)
|
||||
? collectClaudeDistribution()
|
||||
: undefined
|
||||
|
||||
const nonPermissiveDev = devDeps.filter(dep => !isPermissive(dep.license))
|
||||
// A copyleft license reaching a shipped surface is a distribution decision,
|
||||
// not a rendering detail; the notices cannot quietly absorb it.
|
||||
@@ -693,7 +692,7 @@ export function render(): string {
|
||||
|
||||
DeepSeek Harness is licensed under [MIT](LICENSE). It depends on the third-party software listed below. Each project remains under its own license; nothing in this file changes those terms.
|
||||
|
||||
This file lists **direct** dependencies declared by the workspace and the explicitly disclosed official Claude platform payload closure. 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.
|
||||
This file lists **direct** dependencies declared by the workspace and the explicitly disclosed official Claude Code platform payload closure. 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.
|
||||
|
||||
The complete npm transitive closure, including the Landlock launcher workspace, is recorded with exact pinned versions in [\`pnpm-lock.yaml\`](pnpm-lock.yaml) — inspect it with \`pnpm licenses list\`. The Python closure is recorded separately in [\`python/sdk/uv.lock\`](python/sdk/uv.lock).
|
||||
|
||||
@@ -769,7 +768,6 @@ function main(): void {
|
||||
console.log(`gen-third-party-notices: wrote ${OUT}.`)
|
||||
}
|
||||
|
||||
// Run only when invoked as a script, not when imported by a test.
|
||||
if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
|
||||
main()
|
||||
}
|
||||
@@ -43,6 +43,7 @@ import * as ToolAskUser from '@deepseek-ai/dsh-tool-ask-user'
|
||||
import * as ToolBash from '@deepseek-ai/dsh-tool-bash'
|
||||
import * as ToolPwsh from '@deepseek-ai/dsh-tool-pwsh'
|
||||
import * as ToolBashPersistent from '@deepseek-ai/dsh-tool-bash-persistent'
|
||||
import * as ToolPwshPersistent from '@deepseek-ai/dsh-tool-pwsh-persistent'
|
||||
import CordisHostRunner from '@deepseek-ai/dsh-cordis-host-runner'
|
||||
import * as ToolCordis from '@deepseek-ai/dsh-tool-cordis'
|
||||
import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
|
||||
@@ -57,6 +58,8 @@ import * as ToolLsp from '@deepseek-ai/dsh-tool-lsp'
|
||||
import * as ToolSkill from '@deepseek-ai/dsh-tool-skill'
|
||||
import * as ToolSessionQuery from '@deepseek-ai/dsh-tool-session-query'
|
||||
import * as ToolTasks from '@deepseek-ai/dsh-tool-jobs'
|
||||
import type TeamService from '@deepseek-ai/dsh-experimental-agent-team'
|
||||
import * as ToolTeam from '@deepseek-ai/dsh-experimental-tool-agent-team'
|
||||
import * as ToolTodo from '@deepseek-ai/dsh-tool-todo'
|
||||
import * as ToolSubagent from '@deepseek-ai/dsh-tool-subagent'
|
||||
import * as ToolWeb from '@deepseek-ai/dsh-tool-web'
|
||||
@@ -72,6 +75,7 @@ class CatalogAttachmentStore extends AttachmentStore {
|
||||
maxImagesPerMessage: 1,
|
||||
maxMessageImageBytes: 1,
|
||||
maxImagePixels: 1,
|
||||
maxImageDimension: 1,
|
||||
mediaTypes: Object.freeze(['image/png'] as const),
|
||||
})
|
||||
|
||||
@@ -280,6 +284,19 @@ const TOOL_PACKAGES: ToolPackage[] = [
|
||||
note:
|
||||
'One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description.',
|
||||
},
|
||||
{
|
||||
pkg: '@deepseek-ai/dsh-tool-pwsh-persistent',
|
||||
dir: 'tool-pwsh-persistent',
|
||||
source: 'packages/shell/tool-pwsh-persistent/src/index.ts',
|
||||
requires: ['ctx.tools', 'ctx.terminals', 'an owning Agent at execution time'],
|
||||
writes: ['tool/call', 'PTY shell state', 'tool/result'],
|
||||
async mount(ctx) {
|
||||
await ctx.plugin(TerminalSessionService)
|
||||
await ctx.plugin(ToolPwshPersistent)
|
||||
},
|
||||
note:
|
||||
'One owner-isolated persistent pwsh tool, the Windows counterpart of the persistent bash tool; deployment composition supplies a pwsh-dialect PTY backend and may override the model-facing environment description.',
|
||||
},
|
||||
{
|
||||
pkg: '@deepseek-ai/dsh-tool-str-replace-editor',
|
||||
dir: 'tool-str-replace-editor',
|
||||
@@ -297,18 +314,18 @@ const TOOL_PACKAGES: ToolPackage[] = [
|
||||
pkg: '@deepseek-ai/dsh-tool-fs',
|
||||
dir: 'tool-fs',
|
||||
source: 'packages/fs/tool-fs/src/index.ts',
|
||||
requires: ['ctx.tools', 'ctx.fs', 'ctx.systemPrompt', 'ctx.attachments (read_image registration)', 'ctx.llm + an image-capable route (read_image execution)'],
|
||||
requires: ['ctx.tools', 'ctx.fs', 'ctx.systemPrompt', 'ctx.attachments (image-tool registration)', 'ctx.llm + an image-capable route (image-tool execution)'],
|
||||
writes: ['tool/call', 'fs/write-intent or fs/edit-intent for mutations', 'fs/observed after read presence/absence or successful file operation', 'durable attachment (read_image)', 'tool/result'],
|
||||
async mount(ctx) {
|
||||
// The tool needs `fs`; the bare provider is sufficient because policy
|
||||
// changes behavior, not schema shape. The catalog seam marker opts into
|
||||
// the attachments-conditional read_image schema without attachment I/O.
|
||||
// the attachments-conditional image schema without attachment I/O.
|
||||
await ctx.plugin(LocalFileSystem)
|
||||
await ctx.plugin(CatalogAttachmentStore)
|
||||
await ctx.plugin(ToolFs)
|
||||
},
|
||||
note:
|
||||
'The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-observation-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. `read_image` is not registered without `ctx.attachments`; its schema is route-independent, and execution refuses unless the exact routed model declares image input.',
|
||||
'The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-observation-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. The image tool is not registered without `ctx.attachments`; its schema is route-independent, and execution refuses unless the exact routed model declares image input.',
|
||||
},
|
||||
{
|
||||
pkg: '@deepseek-ai/dsh-tool-fs-search',
|
||||
@@ -506,6 +523,44 @@ const TOOL_PACKAGES: ToolPackage[] = [
|
||||
note:
|
||||
'The kind-agnostic background-job controller: background bash commands, PTY sends, and subagents are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers\' `ctx.jobs.start()`.',
|
||||
},
|
||||
{
|
||||
pkg: '@deepseek-ai/dsh-experimental-tool-agent-team',
|
||||
dir: 'tool-agent-team',
|
||||
source: 'packages/experimental/tool-agent-team/src/index.ts',
|
||||
requires: ['ctx.tools', 'ctx.systemPrompt', 'ctx.agentTeams', 'an exact live Team member Agent'],
|
||||
writes: ['tool/call', 'team/member', 'team/message/queued', 'team/message/delivered', 'team/task', 'tool/result'],
|
||||
async mount(ctx) {
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(SessionStore)
|
||||
const session = ctx.sessions.create(SessionId('tool-catalog-team-lead'))
|
||||
let agent!: Agent
|
||||
const membership = {
|
||||
get root() { return agent },
|
||||
id: session.id,
|
||||
role: 'lead' as const,
|
||||
name: 'lead',
|
||||
}
|
||||
ctx.provide('agentTeams', {
|
||||
tryMembership: (candidate: Agent) => candidate === agent ? membership : undefined,
|
||||
membership: () => membership,
|
||||
} as unknown as TeamService)
|
||||
await ctx.plugin(Object.assign((inner: Context) => {
|
||||
agent = {
|
||||
id: session.id,
|
||||
session,
|
||||
options: {},
|
||||
status: 'idle',
|
||||
} as unknown as Agent
|
||||
Object.assign(agent, { ctx: createScope(inner, agent).ctx })
|
||||
inner.agents.register(agent)
|
||||
}, { inject: ['tools', 'systemPrompt', 'agents', 'agentTeams'] }))
|
||||
await ctx.plugin(ToolTeam)
|
||||
catalogChildScopes.set(ctx, agent)
|
||||
},
|
||||
scope: ctx => catalogChildScopes.get(ctx) as Agent,
|
||||
note:
|
||||
'All ten tools are scoped to implicit Team Leads and durable teammates. The shipped dsh-base bundle keeps the package disabled; the documented Agent Teams profile patch enables it while disabling the legacy continuable-child control names.',
|
||||
},
|
||||
{
|
||||
pkg: '@deepseek-ai/dsh-tool-todo',
|
||||
dir: 'tool-todo',
|
||||
@@ -596,9 +651,9 @@ export function assertManifestComplete(packages: ToolPackage[] = TOOL_PACKAGES,
|
||||
* A tool package that boots without registering anything is a broken boot, not
|
||||
* an empty catalog section. The usual cause is an `inject` the entry's `mount`
|
||||
* does not satisfy: cordis leaves the plugin PENDING, every step here still
|
||||
* succeeds, and the generator writes a catalog missing that package's tools —
|
||||
* with the freshness gate green on it, because the omission is now what the
|
||||
* generator produces. {@link assertManifestComplete} cannot see this: the
|
||||
* succeeds, and the generator writes a catalog missing that package's tools.
|
||||
* The freshness gate stays green because regeneration reproduces the omission.
|
||||
* {@link assertManifestComplete} cannot see this: the
|
||||
* package IS listed, it just contributed nothing.
|
||||
* @param entry - the manifest entry that was booted.
|
||||
* @param harvested - how many schemas its boot registered.
|
||||
@@ -753,7 +808,6 @@ async function main(): Promise<void> {
|
||||
console.log(`gen-tool-catalog: wrote ${OUT}.`)
|
||||
}
|
||||
|
||||
// Run only when invoked as a script, not when imported by a test.
|
||||
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
|
||||
await main()
|
||||
}
|
||||
@@ -16,11 +16,13 @@ import { existsSync, globSync, mkdtempSync, readFileSync, rmSync, writeFileSync
|
||||
import { tmpdir } from 'node:os'
|
||||
import { basename, join, resolve, sep } from 'node:path'
|
||||
import {
|
||||
isTranslationPairingManifestExcluded,
|
||||
isTranslationScopeFile,
|
||||
pairAnchorOfArgument,
|
||||
parseTranslationMarkdown,
|
||||
parseTranslationPairingManifest,
|
||||
TRANSLATION_SCOPE_GLOB_EXCLUDES,
|
||||
translationPairSourcePredicate,
|
||||
translationStructureDiff,
|
||||
translationStructureSignature,
|
||||
} from './translation-pairing.ts'
|
||||
@@ -41,10 +43,11 @@ import {
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const manifest = parseTranslationPairingManifest(readFileSync(join(root, 'scripts/translation-pairing.manifest.json'), 'utf8'))
|
||||
const isTranslationPairSource = translationPairSourcePredicate(manifest)
|
||||
const terminology = readFileSync(join(root, 'docs/i18n/terminology.md'), 'utf8')
|
||||
|
||||
function isExcluded(file: string): boolean {
|
||||
return manifest.excluded.some(entry => (entry.endsWith('/') ? file.startsWith(entry) : file === entry))
|
||||
return isTranslationPairingManifestExcluded(file, manifest)
|
||||
}
|
||||
|
||||
/** Recorded hashes of one consistency record: basename → blob hash. */
|
||||
@@ -215,12 +218,23 @@ function planScope(
|
||||
/** Validate a computed mechanical counterpart and write it. */
|
||||
function applyMechanical(counterpartPath: string, sourceCurrent: string, result: string): void {
|
||||
const counterpartBase = basename(counterpartPath)
|
||||
const sourcePath = counterpartPath.endsWith('.zh.md')
|
||||
? counterpartPath.replace(/\.zh\.md$/, '.md')
|
||||
: counterpartPath.replace(/\.md$/, '.zh.md')
|
||||
const sourceBase = counterpartBase.endsWith('.zh.md')
|
||||
? counterpartBase.replace(/\.zh\.md$/, '.md')
|
||||
: counterpartBase.replace(/\.md$/, '.zh.md')
|
||||
const errors = translationStructureDiff(
|
||||
translationStructureSignature(parseTranslationMarkdown(sourceCurrent), counterpartBase),
|
||||
translationStructureSignature(parseTranslationMarkdown(result), sourceBase),
|
||||
translationStructureSignature(
|
||||
parseTranslationMarkdown(sourceCurrent),
|
||||
counterpartBase,
|
||||
{ repoRoot: root, sourcePath, isTranslationPairSource, markdown: sourceCurrent },
|
||||
),
|
||||
translationStructureSignature(
|
||||
parseTranslationMarkdown(result),
|
||||
sourceBase,
|
||||
{ repoRoot: root, sourcePath: counterpartPath, isTranslationPairSource, markdown: result },
|
||||
),
|
||||
)
|
||||
if (errors.length > 0) {
|
||||
throw new Error(`gen-translation-brief: computed mechanical update for ${counterpartPath} violates the pair structure: ${errors.join('; ')}`)
|
||||
|
||||
@@ -23,7 +23,7 @@ const OWNERSHIP_MARKER_VERSION = 1
|
||||
const OWNERSHIP_MARKER_OWNER = 'deepseek-harness worktree-local lefthook hooks'
|
||||
const INSTALL_LOCK = 'dsh-lefthook-install.lock'
|
||||
const INSTALL_LOCK_TIMEOUT_MS = 30_000
|
||||
const INSTALL_LOCK_INITIALIZATION_TIMEOUT_MS = 1_000
|
||||
const INSTALL_LOCK_INITIALIZATION_TIMEOUT_MS = 5_000
|
||||
const INSTALL_LOCK_POLL_MS = 50
|
||||
const ALLOW_HOOKS_PATH_OVERRIDE = 'DSH_LEFTHOOK_ALLOW_HOOKS_PATH_OVERRIDE'
|
||||
const REPOSITORY_EXTENSION_PATTERN = '^extensions\\.'
|
||||
|
||||
@@ -23,9 +23,9 @@ const pairingMergeDriver = 'scripts/merge-translation-pairing-driver.sh %O %A %B
|
||||
const scriptsDirectory = fileURLToPath(new URL('.', import.meta.url))
|
||||
const tsxPackageDirectory = dirname(fileURLToPath(import.meta.resolve('tsx/package.json')))
|
||||
const fixtures: string[] = []
|
||||
// Multi-worktree cases spawn several Git and Node subprocesses; coverage concurrency can
|
||||
// legitimately exceed Vitest's default deadline without changing the installer behavior.
|
||||
const MULTI_PROCESS_TEST_TIMEOUT_MS = 20_000
|
||||
// Multi-worktree cases spawn several Git and Node subprocesses; native Windows
|
||||
// coverage concurrency can delay them without changing installer behavior.
|
||||
const MULTI_PROCESS_TEST_TIMEOUT_MS = 30_000
|
||||
|
||||
interface Fixture {
|
||||
container: string
|
||||
@@ -184,7 +184,7 @@ function installLockPath(fixture: Fixture): string {
|
||||
}
|
||||
|
||||
async function waitForPath(path: string): Promise<void> {
|
||||
const deadline = Date.now() + 5_000
|
||||
const deadline = Date.now() + 10_000
|
||||
while (!existsSync(path)) {
|
||||
if (Date.now() >= deadline) throw new Error(`timed out waiting for ${path}`)
|
||||
await new Promise(resolveWait => setTimeout(resolveWait, 10))
|
||||
@@ -211,7 +211,7 @@ function runInstaller(
|
||||
})
|
||||
}
|
||||
|
||||
describe('worktree-local Lefthook installer', { timeout: 15_000 }, () => {
|
||||
describe('worktree-local Lefthook installer', { timeout: 30_000 }, () => {
|
||||
for (const [label, extraEnv] of [
|
||||
['CI', { CI: 'true' }],
|
||||
['GitHub Actions', { GITHUB_ACTIONS: 'true' }],
|
||||
@@ -529,7 +529,12 @@ describe('worktree-local Lefthook installer', { timeout: 15_000 }, () => {
|
||||
const lockPath = installLockPath(fixture)
|
||||
const runningPath = join(hooksPath(fixture, fixture.main), '.fake-lefthook-running')
|
||||
const install = runInstaller(fixture, fixture.main, { DSH_TEST_LEFTHOOK_DELAY_MS: '250' })
|
||||
await waitForPath(runningPath)
|
||||
try {
|
||||
await waitForPath(runningPath)
|
||||
} catch (error) {
|
||||
await install
|
||||
throw error
|
||||
}
|
||||
const replacementRecord = 'replacement owner\n'
|
||||
writeFileSync(lockPath, replacementRecord)
|
||||
|
||||
|
||||
@@ -18,19 +18,19 @@ interface Profile {
|
||||
// snapshot; they do not re-evaluate that deleted baseline or track its preset.
|
||||
const profiles = {
|
||||
source: {
|
||||
count: 88,
|
||||
count: 89,
|
||||
indexes: [0, 1, 4, 5],
|
||||
sha256: 'da1dfd77cb6eb66be93d8d3820f9b9b68b7aa391c24680f8851c0910298f9e3b',
|
||||
sha256: '3e8b8455827254d6da59afb803d30f062b9fe1264b4df75ce4c8cd6e742b93dd',
|
||||
},
|
||||
example: {
|
||||
count: 87,
|
||||
count: 88,
|
||||
indexes: [0, 1, 2, 4, 5],
|
||||
sha256: '6a2606053bc1ec1de3b02611de88ea51d201dac13a1f193e4934d33c08b95f08',
|
||||
sha256: 'e2b944c028ef1971302d47b2eb0e95c05e740623c7cbaebb4b1312dbf73bf156',
|
||||
},
|
||||
test: {
|
||||
count: 83,
|
||||
count: 84,
|
||||
indexes: [0, 3, 4, 5],
|
||||
sha256: '7995e14926a36c40bd65c474637735222a95fb030395681685f03060e50a7b78',
|
||||
sha256: '7800bf57f0d689a5623e4ad60315b10173158fb9cf988d3f005cb115f2245691',
|
||||
},
|
||||
} as const satisfies Record<string, Profile>
|
||||
|
||||
@@ -85,7 +85,7 @@ describe('Oxlint repository rule fingerprint', () => {
|
||||
const overrides: readonly unknown[] = parsed.overrides
|
||||
|
||||
it('pins every override field', () => {
|
||||
expect(overrides).toHaveLength(8)
|
||||
expect(overrides).toHaveLength(9)
|
||||
})
|
||||
|
||||
it.each(Object.entries(profiles))('pins the %s rule profile', (_name, profile) => {
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* Gate for the invariant `FALLBACK_LOCALE` rests on: every shipped dictionary
|
||||
* declares the same keys in `zh` and `en`.
|
||||
*
|
||||
* The locale runtime resolves a key through the active locale, then through
|
||||
* the single fallback locale (`en`), then surfaces the key itself. With
|
||||
* symmetric dictionaries that middle step always resolves, so one constant can
|
||||
* serve as both the opening locale and the dictionary fallback. A key added to
|
||||
* only one side breaks that: a reader of the other language sees a bare key
|
||||
* such as `list.aria` instead of text. This gate fails on the asymmetry rather
|
||||
* than waiting for the bare key to reach a UI.
|
||||
*
|
||||
* Discovery is deliberately broad, because a gate that silently narrows is
|
||||
* worse than no gate. It sweeps every workspace package (not just
|
||||
* `packages/client`), reads dictionaries wherever they are declared —
|
||||
* `locales.ts`, a `locales/` directory, or inline in the plugin body — and
|
||||
* pairs `zh`/`en` across sibling files as well as within one module. A `zh`
|
||||
* dictionary whose `en` counterpart cannot be found anywhere is an error, not
|
||||
* a skip.
|
||||
*/
|
||||
|
||||
import type { Dirent } from 'node:fs'
|
||||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { dirname, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import ts from 'typescript'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const root = fileURLToPath(new URL('..', import.meta.url))
|
||||
|
||||
/** Repo-relative path with `/` separators, so messages and suffix tests match on every OS. */
|
||||
function relative(file: string): string {
|
||||
return file.slice(root.length).replaceAll('\\', '/')
|
||||
}
|
||||
|
||||
/** Every `.ts` source file under each workspace package's `src`, excluding declarations. */
|
||||
function sourceFiles(): string[] {
|
||||
const files: string[] = []
|
||||
const packagesRoot = resolve(root, 'packages')
|
||||
for (const group of directories(packagesRoot)) {
|
||||
for (const pkg of directories(resolve(packagesRoot, group))) {
|
||||
walk(resolve(packagesRoot, group, pkg, 'src'), files)
|
||||
}
|
||||
}
|
||||
return files.sort()
|
||||
}
|
||||
|
||||
/** Immediate subdirectory names, or none when the path is not a directory. */
|
||||
function directories(dir: string): string[] {
|
||||
return readEntries(dir).filter(entry => entry.isDirectory()).map(entry => entry.name)
|
||||
}
|
||||
|
||||
/**
|
||||
* Directory entries, treating only a genuinely absent directory as empty.
|
||||
* Any other failure (`EACCES`, I/O) rethrows: silently reading it as "absent"
|
||||
* would narrow the sweep and let the gate pass while checking less.
|
||||
* @param dir - absolute directory path.
|
||||
* @returns entries, or none when the directory does not exist.
|
||||
*/
|
||||
function readEntries(dir: string): Dirent[] {
|
||||
try {
|
||||
return readdirSync(dir, { withFileTypes: true })
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function walk(dir: string, out: string[]): void {
|
||||
for (const entry of readEntries(dir)) {
|
||||
const full = resolve(dir, entry.name)
|
||||
if (entry.isDirectory()) walk(full, out)
|
||||
else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')) out.push(full)
|
||||
}
|
||||
}
|
||||
|
||||
/** One discovered dictionary: which file and export name declared it. */
|
||||
interface Dictionary {
|
||||
/** Repo-relative declaring file. */
|
||||
file: string
|
||||
/** Export name, or the registration site for an inline literal. */
|
||||
name: string
|
||||
/** Declared keys, sorted. */
|
||||
keys: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys of every top-level `export const <name> = { ... }` object literal whose
|
||||
* name identifies a locale dictionary, plus inline `register(ns, locale, {...})`
|
||||
* literals. Read from the AST so the gate never executes package code.
|
||||
* @param file - absolute path of a candidate module.
|
||||
* @returns discovered dictionaries, keyed by locale-bearing name.
|
||||
*/
|
||||
function dictionariesIn(file: string): Dictionary[] {
|
||||
const text = readFileSync(file, 'utf8')
|
||||
// Cheap pre-filter: parsing every package source is wasteful. The pattern
|
||||
// must admit every shape `localeOf` accepts, or a file would be skipped
|
||||
// before parsing — the silent narrowing this gate exists to prevent. A bare
|
||||
// `\b(zh|en)\b` misses `zhSettings`/`accessZh`, because `\b` does not hold
|
||||
// between `h` and an uppercase letter.
|
||||
if (!/\b(zh|en)\b|\b(zh|en)[A-Z]|(Zh|En)\b/.test(text)) return []
|
||||
const source = ts.createSourceFile(file, text, ts.ScriptTarget.ESNext, true)
|
||||
const found: Dictionary[] = []
|
||||
const rel = relative(file)
|
||||
|
||||
// Module-scope variable declarations, keyed by name. A 3-arg
|
||||
// `register(NS, 'zh'|'en', dict)` whose third argument is an identifier —
|
||||
// e.g. a local dictionary variable rather than an inline literal — resolves
|
||||
// through here so the gate still verifies its symmetry.
|
||||
const moduleConsts = new Map<string, ts.Expression>()
|
||||
for (const statement of source.statements) {
|
||||
if (!ts.isVariableStatement(statement)) continue
|
||||
for (const decl of statement.declarationList.declarations) {
|
||||
if (ts.isIdentifier(decl.name) && decl.initializer !== undefined) {
|
||||
moduleConsts.set(decl.name.text, decl.initializer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const statement of source.statements) {
|
||||
if (!ts.isVariableStatement(statement)) continue
|
||||
if (statement.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) !== true) continue
|
||||
for (const decl of statement.declarationList.declarations) {
|
||||
if (!ts.isIdentifier(decl.name)) continue
|
||||
const literal = unwrap(decl.initializer)
|
||||
if (literal === undefined || !ts.isObjectLiteralExpression(literal)) continue
|
||||
if (localeOf(decl.name.text) === undefined) continue
|
||||
found.push({ file: rel, name: decl.name.text, keys: keysOf(literal) })
|
||||
}
|
||||
}
|
||||
|
||||
// A 3-arg `register(ns, 'zh'|'en', dict)` call whose dictionary argument we
|
||||
// cannot turn into an object literal. We refuse instead of skipping: a
|
||||
// registration we cannot measure is exactly the silent narrowing this gate
|
||||
// exists to catch.
|
||||
const refuse = (ns: string, tag: string, why: string): never => {
|
||||
throw new Error(`cannot verify register('${ns}', '${tag}', ...) in ${rel}: ${why}`)
|
||||
}
|
||||
|
||||
// Inline registrations, two shapes. A `[['zh', {...}], ['en', {...}]]` pair
|
||||
// handed to a registration loop keys off the enclosing array; separate
|
||||
// `register(NS, 'zh', {...})` / `register(NS, 'en', {...})` calls key off the
|
||||
// namespace argument, so the two calls pair with each other.
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (ts.isCallExpression(node)) {
|
||||
const callee = node.expression
|
||||
const name = ts.isPropertyAccessExpression(callee)
|
||||
? callee.name.text
|
||||
: ts.isIdentifier(callee) && callee.text === 'register' ? 'register' : undefined
|
||||
if (name === 'register' && node.arguments.length >= 3) {
|
||||
const [ns, tag, dict] = node.arguments
|
||||
if (ns === undefined || tag === undefined || !ts.isStringLiteral(tag)) return
|
||||
if (tag.text !== 'zh' && tag.text !== 'en') return
|
||||
const raw = unwrap(dict)
|
||||
const literal = raw !== undefined && ts.isIdentifier(raw)
|
||||
? (() => {
|
||||
const resolved = moduleConsts.get(raw.text)
|
||||
return resolved === undefined ? undefined : unwrap(resolved)
|
||||
})()
|
||||
: raw
|
||||
const why = raw !== undefined && ts.isIdentifier(raw)
|
||||
? `third argument ${raw.text} does not resolve to an inline or module-scope object literal`
|
||||
: 'third argument is neither an object literal nor a resolvable dictionary variable'
|
||||
if (literal === undefined || !ts.isObjectLiteralExpression(literal)) {
|
||||
// The dictionary argument must resolve to an object literal; the
|
||||
// gate refuses rather than skips, so the symmetry it verifies never
|
||||
// silently narrows.
|
||||
refuse(ns.getText(source), tag.text, why)
|
||||
}
|
||||
const dictionary: ts.ObjectLiteralExpression = literal as ts.ObjectLiteralExpression
|
||||
// The namespace expression's source text identifies the pair, so the
|
||||
// zh and en calls for one namespace meet and calls for different
|
||||
// namespaces stay apart.
|
||||
found.push({ file: rel, name: `${tag.text}@register:${ns.getText(source)}`, keys: keysOf(dictionary) })
|
||||
}
|
||||
}
|
||||
if (ts.isArrayLiteralExpression(node) && node.elements.length === 2) {
|
||||
const site = source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1
|
||||
for (const element of node.elements) {
|
||||
if (!ts.isArrayLiteralExpression(element) || element.elements.length !== 2) continue
|
||||
const [tag, dict] = element.elements
|
||||
const literal = unwrap(dict)
|
||||
if (tag === undefined || !ts.isStringLiteral(tag)) continue
|
||||
if (literal === undefined || !ts.isObjectLiteralExpression(literal)) continue
|
||||
if (tag.text !== 'zh' && tag.text !== 'en') continue
|
||||
found.push({ file: rel, name: `${tag.text}@inline:${site}`, keys: keysOf(literal) })
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(source)
|
||||
return found
|
||||
}
|
||||
|
||||
/** Declared property names of an object literal, sorted. */
|
||||
function keysOf(literal: ts.ObjectLiteralExpression): string[] {
|
||||
const keys: string[] = []
|
||||
for (const prop of literal.properties) {
|
||||
if (!ts.isPropertyAssignment(prop)) continue
|
||||
if (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) keys.push(prop.name.text)
|
||||
}
|
||||
return keys.sort()
|
||||
}
|
||||
|
||||
/** Look through `satisfies`/`as`/parenthesized wrappers to the literal. */
|
||||
function unwrap(node: ts.Expression | undefined): ts.Expression | undefined {
|
||||
let current = node
|
||||
while (
|
||||
current !== undefined
|
||||
&& (ts.isSatisfiesExpression(current) || ts.isAsExpression(current) || ts.isParenthesizedExpression(current))
|
||||
) {
|
||||
current = current.expression
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
/**
|
||||
* The locale a dictionary name declares, and the namespace-ish remainder that
|
||||
* identifies which pair it belongs to. `zh`/`en`, `zhSettings`/`enSettings`,
|
||||
* and `settingsZh`/`settingsEn` are the shapes this repo uses. A name-prefix
|
||||
* shape requires an uppercase ASCII letter at the third position (`[A-Z]`),
|
||||
* matching the admission of the cheap pre-filter, so `zh2Foo`/`zh_probe`
|
||||
* cannot be treated as dictionaries in one place and skipped in another.
|
||||
* @param name - export name or synthetic inline name.
|
||||
* @returns locale plus pair key, or undefined when the name names no locale.
|
||||
*/
|
||||
function localeOf(name: string): { locale: 'zh' | 'en'; pair: string } | undefined {
|
||||
for (const locale of ['zh', 'en'] as const) {
|
||||
const other = locale === 'zh' ? 'Zh' : 'En'
|
||||
if (name === locale) return { locale, pair: '' }
|
||||
// Synthetic names for inline shapes carry their own pair key after the
|
||||
// first ':' (the enclosing array's line, or the namespace expression).
|
||||
if (name.startsWith(`${locale}@`)) return { locale, pair: name.slice(name.indexOf(':')) }
|
||||
if (name.startsWith(locale) && name.length > 2 && /[A-Z]/.test(name[2] ?? '')) {
|
||||
return { locale, pair: name.slice(2) }
|
||||
}
|
||||
if (name.endsWith(other)) return { locale, pair: name.slice(0, -2) }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
describe('shipped locale dictionaries', () => {
|
||||
it('declares the same keys in zh and en, so the single fallback locale always resolves', () => {
|
||||
const files = sourceFiles()
|
||||
// Guard the discovery itself: an empty or narrowed sweep would pass every
|
||||
// assertion below while checking nothing.
|
||||
expect(files.length).toBeGreaterThan(500)
|
||||
|
||||
// Pair within a file first; a dictionary whose counterpart is not in the
|
||||
// same module then pairs with a sibling in the same directory. Both shapes
|
||||
// ship here: `locales/settings.ts` exports zh+en together, while
|
||||
// `locales/zh.ts` + `locales/en.ts` split the common pair across files.
|
||||
const perFile = new Map<string, Dictionary[]>()
|
||||
for (const file of files) {
|
||||
const dicts = dictionariesIn(file)
|
||||
if (dicts.length > 0) perFile.set(relative(file), dicts)
|
||||
}
|
||||
|
||||
const groups = new Map<string, Map<'zh' | 'en', Dictionary>>()
|
||||
const place = (key: string, locale: 'zh' | 'en', dict: Dictionary): void => {
|
||||
const slot = groups.get(key) ?? new Map<'zh' | 'en', Dictionary>()
|
||||
if (slot.has(locale)) {
|
||||
throw new Error(`two ${locale} dictionaries claim pair ${key}: ${slot.get(locale)?.file} and ${dict.file}`)
|
||||
}
|
||||
slot.set(locale, dict)
|
||||
groups.set(key, slot)
|
||||
}
|
||||
|
||||
for (const [rel, dicts] of perFile) {
|
||||
for (const dict of dicts) {
|
||||
const parsed = localeOf(dict.name)
|
||||
if (parsed === undefined) continue
|
||||
const sameFileCounterpart = dicts.some((other) => {
|
||||
const otherParsed = localeOf(other.name)
|
||||
return otherParsed !== undefined
|
||||
&& otherParsed.pair === parsed.pair
|
||||
&& otherParsed.locale !== parsed.locale
|
||||
})
|
||||
// Same-file pairs key by file so two pairs in one directory stay
|
||||
// distinct; split pairs key by directory so siblings meet.
|
||||
const key = sameFileCounterpart ? `${rel}::${parsed.pair}` : `${dirname(rel)}::${parsed.pair}`
|
||||
place(key, parsed.locale, dict)
|
||||
}
|
||||
}
|
||||
|
||||
const problems: string[] = []
|
||||
let comparedPairs = 0
|
||||
for (const [key, slot] of [...groups].sort()) {
|
||||
const zh = slot.get('zh')
|
||||
const en = slot.get('en')
|
||||
if (zh === undefined || en === undefined) {
|
||||
const present = zh ?? en
|
||||
problems.push(`${present?.file} declares ${present?.name} with no counterpart for pair ${key}`)
|
||||
continue
|
||||
}
|
||||
comparedPairs++
|
||||
const zhOnly = zh.keys.filter(k => !en.keys.includes(k))
|
||||
const enOnly = en.keys.filter(k => !zh.keys.includes(k))
|
||||
if (zhOnly.length > 0) problems.push(`${zh.file} ${zh.name} has keys absent from ${en.name}: ${zhOnly.join(', ')}`)
|
||||
if (enOnly.length > 0) problems.push(`${en.file} ${en.name} has keys absent from ${zh.name}: ${enOnly.join(', ')}`)
|
||||
}
|
||||
|
||||
// The shipped dictionary count only grows; a collapse means discovery or
|
||||
// pairing broke, which would hide real asymmetry.
|
||||
expect(comparedPairs).toBeGreaterThan(25)
|
||||
expect(problems).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -56,6 +56,101 @@ export function visitMarkdown(node: Nodes, visitor: (node: Nodes) => boolean | v
|
||||
}
|
||||
}
|
||||
|
||||
/** Markdown nodes whose authored destination occupies a replaceable source range. */
|
||||
export type MarkdownDestinationNode = Extract<Nodes, { type: 'link' | 'image' | 'definition' }>
|
||||
|
||||
/** One authored Markdown destination and its absolute source offsets. */
|
||||
export interface MarkdownDestination {
|
||||
start: number
|
||||
end: number
|
||||
url: string
|
||||
}
|
||||
|
||||
/** Whether a Markdown URL is external, repository-root absolute, or purely in-page. */
|
||||
export function isExternalOrAbsoluteMarkdownUrl(url: string): boolean {
|
||||
return url.startsWith('#')
|
||||
|| url.startsWith('//')
|
||||
|| url.startsWith('/')
|
||||
|| /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
|
||||
}
|
||||
|
||||
/** Split one Markdown URL without normalizing its query or fragment suffix. */
|
||||
export function splitMarkdownUrlTarget(url: string): { path: string; suffix: string } {
|
||||
const boundary = url.search(/[?#]/)
|
||||
if (boundary === -1) return { path: url, suffix: '' }
|
||||
return { path: url.slice(0, boundary), suffix: url.slice(boundary) }
|
||||
}
|
||||
|
||||
function skipWhitespace(source: string, start: number): number {
|
||||
let index = start
|
||||
while (/\s/.test(source[index] ?? '')) index += 1
|
||||
return index
|
||||
}
|
||||
|
||||
function labelEnd(source: string): number {
|
||||
const first = source.indexOf('[')
|
||||
if (first === -1) return -1
|
||||
let depth = 0
|
||||
for (let index = first; index < source.length; index += 1) {
|
||||
const char = source[index]
|
||||
if (char === '\\') index += 1
|
||||
else if (char === '[') depth += 1
|
||||
else if (char === ']') {
|
||||
depth -= 1
|
||||
if (depth === 0) return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function destinationRange(rawNode: string, type: MarkdownDestinationNode['type']): { start: number; end: number } {
|
||||
const endOfLabel = labelEnd(rawNode)
|
||||
if (endOfLabel === -1) throw new Error(`markdown: cannot locate label end in ${JSON.stringify(rawNode)}`)
|
||||
let start: number
|
||||
if (type === 'definition') {
|
||||
const colon = rawNode.indexOf(':', endOfLabel + 1)
|
||||
if (colon === -1) throw new Error(`markdown: cannot locate definition separator in ${JSON.stringify(rawNode)}`)
|
||||
start = skipWhitespace(rawNode, colon + 1)
|
||||
} else {
|
||||
if (rawNode[endOfLabel + 1] !== '(') {
|
||||
throw new Error(`markdown: cannot locate inline destination in ${JSON.stringify(rawNode)}`)
|
||||
}
|
||||
start = skipWhitespace(rawNode, endOfLabel + 2)
|
||||
}
|
||||
if (rawNode[start] === '<') {
|
||||
for (let index = start + 1; index < rawNode.length; index += 1) {
|
||||
if (rawNode[index] === '\\') index += 1
|
||||
else if (rawNode[index] === '>') return { start: start + 1, end: index }
|
||||
}
|
||||
throw new Error(`markdown: cannot locate angle-bracket destination end in ${JSON.stringify(rawNode)}`)
|
||||
}
|
||||
let depth = 0
|
||||
for (let index = start; index < rawNode.length; index += 1) {
|
||||
const char = rawNode[index]
|
||||
if (char === '\\') index += 1
|
||||
else if (char === '(') depth += 1
|
||||
else if (char === ')') {
|
||||
if (depth === 0) return { start, end: index }
|
||||
depth -= 1
|
||||
} else if (/\s/.test(char ?? '') && depth === 0) {
|
||||
return { start, end: index }
|
||||
}
|
||||
}
|
||||
return { start, end: rawNode.length }
|
||||
}
|
||||
|
||||
/** Locate one parsed destination in the original Markdown without reserializing it. */
|
||||
export function markdownDestination(source: string, node: MarkdownDestinationNode): MarkdownDestination {
|
||||
const start = node.position?.start.offset
|
||||
const end = node.position?.end.offset
|
||||
if (start === undefined || end === undefined) {
|
||||
throw new Error(`markdown: destination ${JSON.stringify(node.url)} has no source offsets`)
|
||||
}
|
||||
const range = destinationRange(source.slice(start, end), node.type)
|
||||
const absolute = { start: start + range.start, end: start + range.end }
|
||||
return { ...absolute, url: source.slice(absolute.start, absolute.end) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract every parsed code block with its info string, in document order.
|
||||
* @param source - Markdown source to scan.
|
||||
|
||||
@@ -4,6 +4,7 @@ import { execFileSync } from 'node:child_process'
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import {
|
||||
mergeTranslationPairingRecords,
|
||||
repositoryTranslationPairSource,
|
||||
resolveTranslationPairingConflicts,
|
||||
} from './translation-pairing-merge.ts'
|
||||
|
||||
@@ -16,7 +17,7 @@ try {
|
||||
const root = execFileSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).trim()
|
||||
if (args[0] === '--resolve') {
|
||||
if (args.length !== 1) throw new Error('--resolve takes no paths; it inspects the unmerged index')
|
||||
const resolved = resolveTranslationPairingConflicts(root)
|
||||
const resolved = resolveTranslationPairingConflicts(root, repositoryTranslationPairSource(root))
|
||||
if (resolved.length === 0) {
|
||||
console.log('merge-translation-pairing: no unresolved pairing records')
|
||||
} else {
|
||||
@@ -36,6 +37,7 @@ try {
|
||||
readFileSync(ancestorPath, 'utf8'),
|
||||
readFileSync(currentPath, 'utf8'),
|
||||
readFileSync(otherPath, 'utf8'),
|
||||
repositoryTranslationPairSource(root),
|
||||
)
|
||||
writeFileSync(currentPath, result.record)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Temporary branch-convergence command for canonical packed session fixtures.
|
||||
* Temporary branch-convergence command for canonical projected session fixtures.
|
||||
*
|
||||
* @see ../.agents/notes/proposed/process/2026-07-26-remove-packed-session-fixture-migrator.md
|
||||
*/
|
||||
@@ -18,4 +18,4 @@ for (const fixture of changed) {
|
||||
writeFileSync(resolve(root, fixture.path), fixture.canonical)
|
||||
console.log(fixture.path)
|
||||
}
|
||||
console.log(`packed session fixtures: ${changed.length} rewritten, ${fixtures.length} inspected`)
|
||||
console.log(`session snapshot fixtures: ${changed.length} rewritten, ${fixtures.length} inspected`)
|
||||
@@ -1,8 +1,8 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { join, relative } from 'node:path'
|
||||
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
|
||||
import { basename, dirname, join, relative } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { flattenDiagnosticMessageText, parseConfigFileTextToJson } from 'typescript'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
@@ -39,6 +39,26 @@ function normalizedOutput(result: ReturnType<typeof runOxlint>): string {
|
||||
return `${result.stdout}${result.stderr}`.replaceAll('\\', '/')
|
||||
}
|
||||
|
||||
/** @returns A transient filename excluded from concurrent repository-wide glob discovery. */
|
||||
function hiddenProbeName(prefix: string, suffix: string, extension = '.ts'): string {
|
||||
return `.${prefix}-${suffix}${extension}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish a complete probe so concurrent repository scans never read a partial write.
|
||||
* @param path - Final probe path that the owning project must discover.
|
||||
* @param source - Complete TypeScript source to publish.
|
||||
*/
|
||||
async function publishProbe(path: string, source: string): Promise<void> {
|
||||
const staging = join(dirname(path), `.${basename(path)}.staging`)
|
||||
try {
|
||||
await writeFile(staging, source)
|
||||
await rename(staging, path)
|
||||
} finally {
|
||||
await rm(staging, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function writeContractConfig(suffix: string): Promise<string> {
|
||||
const path = join(repositoryRoot, `.oxlintrc.contract-${suffix}.json`)
|
||||
await writeFile(path, JSON.stringify({ extends: ['./.oxlintrc.json'], ignorePatterns: [] }))
|
||||
@@ -59,7 +79,8 @@ describe('Oxlint executable contract', () => {
|
||||
['example', 'examples/headless-agent/tests', 'tsconfig.host.json'],
|
||||
['website', 'website', 'tsconfig.host.json'],
|
||||
] as const
|
||||
const source = `export function probePromise(): Promise<void> {
|
||||
const source = `/** Produce a settled promise for type-aware linting. */
|
||||
export function probePromise(): Promise<void> {
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
@@ -70,7 +91,7 @@ probePromise()
|
||||
const paths: Array<readonly [label: string, path: string, tsconfig: string]> = []
|
||||
for (const [label, parent, tsconfig, extension = '.ts'] of probes) {
|
||||
const path = join(repositoryRoot, parent, `oxlint-contract-${suffix}${extension}`)
|
||||
await writeFile(path, source)
|
||||
await publishProbe(path, source)
|
||||
paths.push([label, relative(repositoryRoot, path), tsconfig])
|
||||
}
|
||||
const clientScript = 'scripts/client-bundle-purity.spec.ts'
|
||||
@@ -88,7 +109,7 @@ probePromise()
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.status, output).toBe(1)
|
||||
for (const [label, path, tsconfig] of paths) {
|
||||
expect(output, label).toContain(`${path.replaceAll('\\', '/')}:5:1: Promises must be awaited`)
|
||||
expect(output, label).toContain(`${path.replaceAll('\\', '/')}:6:1: Promises must be awaited`)
|
||||
expect(output, `${label} project`).toContain(
|
||||
`Got tsconfig for file ${join(repositoryRoot, path).replaceAll('\\', '/')}: ${join(repositoryRoot, tsconfig).replaceAll('\\', '/')}`,
|
||||
)
|
||||
@@ -110,7 +131,7 @@ probePromise()
|
||||
it('runs JavaScript compatibility and nursery rules', async () => {
|
||||
const suffix = randomUUID()
|
||||
const configPath = await writeContractConfig(suffix)
|
||||
const path = join(repositoryRoot, 'scripts', `oxlint-contract-${suffix}.ts`)
|
||||
const path = join(repositoryRoot, 'scripts', hiddenProbeName('oxlint-contract', suffix))
|
||||
const source = `export function firstProbe(): number {
|
||||
const first = 1
|
||||
const second = 2
|
||||
@@ -230,7 +251,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
|
||||
it('reports an unused suppression', async () => {
|
||||
const suffix = randomUUID()
|
||||
const configPath = await writeContractConfig(suffix)
|
||||
const path = join(repositoryRoot, 'scripts', `oxlint-contract-${suffix}.ts`)
|
||||
const path = join(repositoryRoot, 'scripts', hiddenProbeName('oxlint-contract', suffix))
|
||||
|
||||
try {
|
||||
await writeFile(path, '// oxlint-disable-next-line no-console\nexport const value = 1\n')
|
||||
@@ -280,7 +301,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
|
||||
expect(stagedConfig.ignorePatterns).not.toContain('packages/typert/generator/tests/fixtures/type-model/**')
|
||||
|
||||
const suffix = randomUUID()
|
||||
const path = join(repositoryRoot, 'scripts', `staged-lint-probe-${suffix}.ts`)
|
||||
const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix))
|
||||
try {
|
||||
await writeFile(path, 'export const value={answer:1};\n')
|
||||
const lint = runOxlint([
|
||||
@@ -303,7 +324,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
|
||||
|
||||
it('preserves successful fix output channels', async () => {
|
||||
const suffix = randomUUID()
|
||||
const path = join(repositoryRoot, 'scripts', `staged-lint-probe-${suffix}.ts`)
|
||||
const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix))
|
||||
|
||||
try {
|
||||
await writeFile(path, '// oxlint-disable-next-line no-console\nexport const value = 1\n')
|
||||
@@ -327,7 +348,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
|
||||
|
||||
it('prints only the final diagnostics when a fix retry still fails', async () => {
|
||||
const suffix = randomUUID()
|
||||
const path = join(repositoryRoot, 'scripts', `staged-lint-probe-${suffix}.ts`)
|
||||
const path = join(repositoryRoot, 'scripts', hiddenProbeName('staged-lint-probe', suffix))
|
||||
|
||||
try {
|
||||
await writeFile(path, `export const longProbe = ${'1 + '.repeat(80)}1\n`)
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { pnpmInvocation } from './pnpm-invocation.ts'
|
||||
|
||||
describe('pnpm invocation', () => {
|
||||
it.each([
|
||||
'/tools/pnpm.js',
|
||||
'/tools/pnpm.cjs',
|
||||
'/tools/pnpm.mjs',
|
||||
'/tools/PNPM.CJS',
|
||||
'/tools/with spaces/工具/$pnpm;.mjs',
|
||||
])('runs the JavaScript entrypoint %j through Node', (entrypoint) => {
|
||||
expect(pnpmInvocation(['run', 'build'], { npm_execpath: entrypoint })).toEqual({
|
||||
command: process.execPath,
|
||||
args: [entrypoint, 'run', 'build'],
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
'/tools/pnpm',
|
||||
'/tools/with spaces/$pnpm;',
|
||||
String.raw`C:\Program Files\工具\$pnpm;\pnpm.exe`,
|
||||
])('runs the executable entrypoint %j directly', (entrypoint) => {
|
||||
expect(pnpmInvocation(['run', 'build'], { npm_execpath: entrypoint })).toEqual({
|
||||
command: entrypoint,
|
||||
args: ['run', 'build'],
|
||||
})
|
||||
})
|
||||
|
||||
it.each([undefined, ''])('rejects an unavailable lifecycle entrypoint', (entrypoint) => {
|
||||
expect(() => pnpmInvocation([], { npm_execpath: entrypoint }))
|
||||
.toThrow('npm_execpath is unavailable; invoke the script through pnpm run')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Resolve shell-free child-process invocations for the pnpm process that launched a package script. */
|
||||
|
||||
/**
|
||||
* Resolve pnpm's executable and arguments from its lifecycle environment.
|
||||
* @param args - Arguments to pass to pnpm.
|
||||
* @param environment - Lifecycle environment containing `npm_execpath`.
|
||||
* @returns A command and argument array suitable for `spawn` or `spawnSync` without a shell.
|
||||
*/
|
||||
export function pnpmInvocation(
|
||||
args: readonly string[],
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): { command: string; args: string[] } {
|
||||
const entrypoint = environment.npm_execpath
|
||||
if (entrypoint === undefined || entrypoint === '') {
|
||||
throw new Error('pnpm invocation: npm_execpath is unavailable; invoke the script through pnpm run.')
|
||||
}
|
||||
if (/\.[cm]?js$/iu.test(entrypoint)) {
|
||||
return { command: process.execPath, args: [entrypoint, ...args] }
|
||||
}
|
||||
return { command: entrypoint, args: [...args] }
|
||||
}
|
||||
@@ -28,5 +28,5 @@ printf '%s\n' "$root/usr/bin" >> "$GITHUB_PATH"
|
||||
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 \
|
||||
|| echo 'apparmor userns knob absent — the functional probe decides'
|
||||
"$root/usr/bin/bwrap" --version
|
||||
"$root/usr/bin/bwrap" --ro-bind / / --dev /dev --proc /proc --die-with-parent -- true
|
||||
"$root/usr/bin/bwrap" --ro-bind / / --dev /dev --unshare-pid --proc /proc --die-with-parent -- true
|
||||
echo 'bubblewrap functional probe passed'
|
||||
@@ -3,11 +3,16 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, globSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { basename, join, resolve } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { basename, dirname, join, resolve } from 'node:path'
|
||||
import { fromMarkdown } from 'mdast-util-from-markdown'
|
||||
import { gfmFromMarkdown } from 'mdast-util-gfm'
|
||||
import { gfm } from 'micromark-extension-gfm'
|
||||
import type { Nodes } from 'mdast'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { docsPages, landingLink, routeLink, sectionSpec, type DocsPage } from '../website/docs.ts'
|
||||
import {
|
||||
addProjectionFrontmatter, projectedPageContent, publishableImage, rewriteMarkdown,
|
||||
addProjectionFrontmatter, emitRawMarkdownPages, llmsTxt, projectedPageContent, publishableImage,
|
||||
rawMarkdownFiles, rawMarkdownPageContent, rawMarkdownRoute, resolveRepositoryRef, rewriteMarkdown,
|
||||
} from './project-doc-site.ts'
|
||||
|
||||
const roots: string[] = []
|
||||
@@ -91,6 +96,16 @@ describe('publishableImage', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveRepositoryRef', () => {
|
||||
it('defaults to public master instead of a private workflow SHA', () => {
|
||||
expect(resolveRepositoryRef({ GITHUB_SHA: 'private-sha' })).toBe('master')
|
||||
})
|
||||
|
||||
it('accepts an explicit public repository ref', () => {
|
||||
expect(resolveRepositoryRef({ DOCS_REPOSITORY_REF: 'public-sha' })).toBe('public-sha')
|
||||
})
|
||||
})
|
||||
|
||||
describe('rewriteMarkdown', () => {
|
||||
it('maps published pages and pins unpublished source links', () => {
|
||||
const { root, pages } = fixture()
|
||||
@@ -213,10 +228,15 @@ describe('rewriteMarkdown', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('routes a pair switcher across locales while ordinary links stay in locale', () => {
|
||||
it('routes switchers across locales and explicit locale siblings within their locale', () => {
|
||||
const { root, pages } = fixture()
|
||||
writeFileSync(join(root, 'docs/a.zh.md'), '# A\n')
|
||||
const paired = pages.filter(page => page.source !== 'docs/a.md')
|
||||
writeFileSync(join(root, 'docs/b.zh.md'), '# B\n')
|
||||
const paired = pages.filter(page => page.source !== 'docs/a.md').map(page => (
|
||||
page.locale === 'root' && page.source === 'docs/b.md'
|
||||
? { ...page, source: 'docs/b.zh.md', sourceAliases: ['docs/b.md'] }
|
||||
: page
|
||||
))
|
||||
paired.push(
|
||||
{
|
||||
locale: 'root', contentLocale: 'zh-CN', source: 'docs/a.zh.md', sourceAliases: ['docs/a.md'],
|
||||
@@ -227,7 +247,7 @@ describe('rewriteMarkdown', () => {
|
||||
route: 'en/guide/a.md', label: 'A', sidebar: 'en-guide', section: 'Test', order: 1,
|
||||
},
|
||||
)
|
||||
expect(rewriteMarkdown('[English](a.md) [B](b.md)\n', {
|
||||
expect(rewriteMarkdown('[English](a.md) [B](b.zh.md)\n', {
|
||||
locale: 'root',
|
||||
sourcePath: 'docs/a.zh.md',
|
||||
route: 'guide/a.md',
|
||||
@@ -235,6 +255,14 @@ describe('rewriteMarkdown', () => {
|
||||
repoRoot: root,
|
||||
repositoryRef: 'abc123',
|
||||
})).toBe('[English](../en/guide/a.md) [B](../reference-root/b.md)\n')
|
||||
expect(rewriteMarkdown('[中文](a.zh.md) [B](b.md)\n', {
|
||||
locale: 'en',
|
||||
sourcePath: 'docs/a.md',
|
||||
route: 'en/guide/a.md',
|
||||
pages: paired,
|
||||
repoRoot: root,
|
||||
repositoryRef: 'abc123',
|
||||
})).toBe('[中文](../../guide/a.md) [B](../reference/b.md)\n')
|
||||
})
|
||||
|
||||
it('fails loud when a relative target is missing', () => {
|
||||
@@ -287,6 +315,37 @@ describe('docsPages locale routes', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('projects the audited tutorial entry links from explicit locale index pages', () => {
|
||||
const entries = [
|
||||
['docs/user/develop/basic/config.md', '../framework/index.md'],
|
||||
['docs/user/develop/basic/publish.md', '../framework/index.md'],
|
||||
['docs/user/develop/basic/tool.md', './index.md'],
|
||||
['docs/user/develop/basic/tool.md', '../practice/index.md'],
|
||||
['docs/user/develop/framework/events.md', '../practice/index.md'],
|
||||
['docs/user/develop/framework/service.md', '../practice/index.md'],
|
||||
['docs/user/develop/practice/index.md', '../basic/index.md'],
|
||||
['docs/user/guide/index.md', '../develop/basic/index.md'],
|
||||
] as const
|
||||
|
||||
for (const [englishSource, englishTarget] of entries) {
|
||||
for (const locale of ['en', 'root'] as const) {
|
||||
const source = locale === 'root' ? englishSource.replace(/\.md$/, '.zh.md') : englishSource
|
||||
const target = locale === 'root' ? englishTarget.replace(/\.md$/, '.zh.md') : englishTarget
|
||||
const page = docsPages.find(candidate => candidate.locale === locale && candidate.source === source)
|
||||
expect(page, `${locale}:${source}`).toBeDefined()
|
||||
expect(readFileSync(resolve(repositoryRoot, source), 'utf8')).toContain(`](${target})`)
|
||||
expect(rewriteMarkdown(`[Entry](${target})\n`, {
|
||||
locale,
|
||||
sourcePath: source,
|
||||
route: page!.route,
|
||||
pages: docsPages,
|
||||
repoRoot: repositoryRoot,
|
||||
repositoryRef: 'abc123',
|
||||
})).toBe(`[Entry](${englishTarget})\n`)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('indexes every subsystem page in both sides of the folder README', () => {
|
||||
const pages = globSync(join(repositoryRoot, 'docs/subsystems/*.md'))
|
||||
.map(page => basename(page))
|
||||
@@ -295,11 +354,22 @@ describe('docsPages locale routes', () => {
|
||||
expect(pages.length).toBeGreaterThan(0)
|
||||
for (const readme of ['README.md', 'README.zh.md']) {
|
||||
const rows = readFileSync(join(repositoryRoot, 'docs/subsystems', readme), 'utf8')
|
||||
const missing = pages.filter(page => !rows.includes(`| [${page}](${page}) |`))
|
||||
const missing = pages.filter((page) => {
|
||||
const target = readme.endsWith('.zh.md') ? page.replace(/\.md$/, '.zh.md') : page
|
||||
return !rows.includes(`| [${page}](${target}) |`)
|
||||
})
|
||||
expect(missing, `${readme} must carry one table row per subsystem page`).toEqual([])
|
||||
}
|
||||
})
|
||||
|
||||
it('places the shared todo fragment alias on the translated todo section', () => {
|
||||
const catalog = readFileSync(resolve(repositoryRoot, 'docs/tool-catalog.zh.md'), 'utf8')
|
||||
expect(catalog.match(/<a id="deepseek-aidsh-tool-todo"><\/a>/g)).toHaveLength(1)
|
||||
expect(catalog).toContain(
|
||||
'<a id="deepseek-aidsh-tool-todo"></a>\n\n## `@deepseek-ai/dsh-tool-todo`',
|
||||
)
|
||||
})
|
||||
|
||||
it('projects every published subsystem page in Chinese', () => {
|
||||
const rootPages = docsPages.filter(page => (
|
||||
page.locale === 'root' && page.route.startsWith('reference/subsystems/')
|
||||
@@ -492,3 +562,207 @@ describe('projectedPageContent', () => {
|
||||
.toThrow('locale home source "docs/index.zh.md" must start with YAML frontmatter')
|
||||
})
|
||||
})
|
||||
|
||||
describe('rawMarkdownPageContent', () => {
|
||||
it('keeps the home body the rendered site omits and drops the VitePress frontmatter', () => {
|
||||
expect(rawMarkdownPageContent(
|
||||
'---\nlayout: false\nhead:\n - - meta\n - http-equiv: refresh\n content: 0; url=./guide/quickstart\n---\n\n# Harness\n\nEnglish | [中文](./index.md)\n\nBody.\n',
|
||||
'docs/user/index.zh.md',
|
||||
)).toBe('# Harness\n\nBody.\n')
|
||||
})
|
||||
|
||||
it('drops the language switcher and repository badge like the rendered site', () => {
|
||||
const badge = '[](https://github.com/deepseek-ai/deepseek-harness)'
|
||||
expect(rawMarkdownPageContent(`# Guide\n\nEnglish | [中文](./x)\n\nBody.\n\n${badge}\n`, 'docs/guide.md'))
|
||||
.toBe('# Guide\n\nBody.\n')
|
||||
})
|
||||
|
||||
it('rejects unclosed frontmatter and names the page', () => {
|
||||
// The twin pass is the first place an ordinary page's frontmatter is
|
||||
// parsed, so an anonymous error would leave 168 routes to search.
|
||||
expect(() => rawMarkdownPageContent('---\nlayout: false\n', 'docs/broken.md'))
|
||||
.toThrow('project-doc-site: "docs/broken.md" has unclosed YAML frontmatter')
|
||||
})
|
||||
})
|
||||
|
||||
describe('emitRawMarkdownPages', () => {
|
||||
function mirrorDir(): string {
|
||||
const out = mkdtempSync(join(tmpdir(), 'dsh-doc-mirror-'))
|
||||
roots.push(out)
|
||||
return out
|
||||
}
|
||||
|
||||
it('writes every route with rewritten links, placed images, and no projection frontmatter', () => {
|
||||
const { root, pages } = fixture()
|
||||
writeFileSync(join(root, 'docs/a.md'), '[B](b.md) \n')
|
||||
const out = mirrorDir()
|
||||
|
||||
// The real path, because image placement proves containment via realpath.
|
||||
emitRawMarkdownPages(out, { pages, repoRoot: realpathSync(root), repositoryRef: 'abc123' })
|
||||
|
||||
expect(readFileSync(join(out, 'a.md'), 'utf8')).toBe('[B](./reference-root/b.md) \n')
|
||||
expect(readFileSync(join(out, 'en/a.md'), 'utf8')).toBe('[B](./reference/b.md) \n')
|
||||
expect(readFileSync(join(out, 'reference-root/b.md'), 'utf8')).toBe('# B\n')
|
||||
expect(existsSync(join(out, 'logo.svg'))).toBe(true)
|
||||
expect(existsSync(join(out, 'en/logo.svg'))).toBe(true)
|
||||
})
|
||||
|
||||
it('emits the full body of a locale home page', () => {
|
||||
const { root, pages } = fixture()
|
||||
writeFileSync(join(root, 'docs/home.md'), '---\nlayout: false\n---\n\n# Home\n\n[A](a.md)\n')
|
||||
pages.push({
|
||||
locale: 'root', contentLocale: 'zh-CN', source: 'docs/home.md', route: 'index.md',
|
||||
label: 'Home', sidebar: null, section: 'Home', order: 0,
|
||||
})
|
||||
const out = mirrorDir()
|
||||
|
||||
emitRawMarkdownPages(out, { pages, repoRoot: root, repositoryRef: 'abc123' })
|
||||
|
||||
expect(readFileSync(join(out, 'index.md'), 'utf8')).toBe('# Home\n\n[A](./a.md)\n')
|
||||
})
|
||||
|
||||
it('emits a parent-level alias for an index route with links recomputed', () => {
|
||||
// A copied alias would carry the index page's relative links one directory
|
||||
// too high, so the alias is its own projection over the alias route.
|
||||
const { root, pages } = fixture()
|
||||
writeFileSync(join(root, 'docs/c.md'), '# C\n\n[A](a.md)\n')
|
||||
pages.push({
|
||||
locale: 'root', contentLocale: 'en-US', source: 'docs/c.md', route: 'guide/index.md',
|
||||
label: 'C', sidebar: 'zh-guide', section: 'Test', order: 3,
|
||||
})
|
||||
const out = mirrorDir()
|
||||
|
||||
emitRawMarkdownPages(out, { pages, repoRoot: root, repositoryRef: 'abc123' })
|
||||
|
||||
expect(readFileSync(join(out, 'guide/index.md'), 'utf8')).toBe('# C\n\n[A](../a.md)\n')
|
||||
expect(readFileSync(join(out, 'guide.md'), 'utf8')).toBe('# C\n\n[A](./a.md)\n')
|
||||
})
|
||||
|
||||
it('refuses to overwrite a file the build already carries', () => {
|
||||
// The twin pass writes into a populated build directory, and VitePress has
|
||||
// already copied `website/public/` there; a page image sharing one of
|
||||
// those names must fail loud instead of silently replacing the site file.
|
||||
const { root, pages } = fixture()
|
||||
writeFileSync(join(root, 'docs/a.md'), '\n')
|
||||
const out = mirrorDir()
|
||||
writeFileSync(join(out, 'logo.svg'), 'public copy\n')
|
||||
|
||||
expect(() => {
|
||||
emitRawMarkdownPages(out, { pages, repoRoot: realpathSync(root), repositoryRef: 'abc123' })
|
||||
}).toThrow('would overwrite')
|
||||
expect(readFileSync(join(out, 'logo.svg'), 'utf8')).toBe('public copy\n')
|
||||
})
|
||||
})
|
||||
|
||||
describe('rawMarkdownFiles', () => {
|
||||
it('lists every route plus a parent alias per index route', () => {
|
||||
const files = rawMarkdownFiles()
|
||||
for (const page of docsPages) expect(files).toContain(page.route)
|
||||
expect(files).toContain('reference.md')
|
||||
expect(files).toContain('en/reference.md')
|
||||
expect(files).toContain('en.md')
|
||||
// The root home has no parent to alias into; `/` is documented as `/index.md`.
|
||||
expect(files).not.toContain('.md')
|
||||
expect(new Set(files).size).toBe(files.length)
|
||||
})
|
||||
})
|
||||
|
||||
describe('raw Markdown projection of the published manifest', () => {
|
||||
let mirror: string
|
||||
|
||||
// Coverage instrumentation on a loaded CI runner stretches the full-manifest
|
||||
// emission and the 181-file link walk past vitest's 5s default.
|
||||
beforeAll(() => {
|
||||
mirror = mkdtempSync(join(tmpdir(), 'dsh-doc-mirror-real-'))
|
||||
emitRawMarkdownPages(mirror, { pages: docsPages, repoRoot: repositoryRoot, repositoryRef: 'master' })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(() => {
|
||||
rmSync(mirror, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('emits every published route and every index alias', () => {
|
||||
for (const file of rawMarkdownFiles()) {
|
||||
expect(existsSync(join(mirror, file)), file).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('emits home pages with their bodies instead of the frontmatter stub', () => {
|
||||
for (const route of ['index.md', 'en/index.md']) {
|
||||
const home = readFileSync(join(mirror, route), 'utf8')
|
||||
expect(home.startsWith('---'), route).toBe(false)
|
||||
expect(home, route).toContain('# DeepSeek Harness')
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves every relative link inside the emitted tree', { timeout: 60_000 }, () => {
|
||||
// Raw pages are read outside the site, so a relative target that only the
|
||||
// rendered site serves would strand every agent following it.
|
||||
const broken: string[] = []
|
||||
for (const file of globSync('**/*.md', { cwd: mirror }).sort()) {
|
||||
for (const target of relativeTargets(readFileSync(join(mirror, file), 'utf8'))) {
|
||||
if (!existsSync(resolve(mirror, dirname(file), target))) broken.push(`${file}: ${target}`)
|
||||
}
|
||||
}
|
||||
expect(broken).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
function relativeTargets(markdown: string): string[] {
|
||||
const tree = fromMarkdown(markdown, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
|
||||
const targets: string[] = []
|
||||
const visit = (node: Nodes): void => {
|
||||
if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) {
|
||||
const external = node.url.startsWith('#')
|
||||
|| node.url.startsWith('/')
|
||||
|| /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(node.url)
|
||||
const path = node.url.split(/[?#]/)[0] ?? ''
|
||||
if (!external && path !== '') targets.push(decodeURIComponent(path))
|
||||
}
|
||||
if ('children' in node) {
|
||||
for (const child of node.children) visit(child)
|
||||
}
|
||||
}
|
||||
visit(tree)
|
||||
return targets
|
||||
}
|
||||
|
||||
describe('llmsTxt', () => {
|
||||
const site = { base: '/x/', title: 'DeepSeek Harness', description: '插件化 SDK' }
|
||||
|
||||
it('lists every sidebar page as a base-prefixed raw-Markdown link', () => {
|
||||
const text = llmsTxt(site)
|
||||
for (const page of docsPages) {
|
||||
if (page.sidebar === null) expect(text, page.route).not.toContain(`](/x/${page.route})`)
|
||||
else expect(text, page.route).toContain(`- [${page.label}](/x/${page.route}): ${page.section}`)
|
||||
}
|
||||
})
|
||||
|
||||
it('groups the two locale trees under their own headings', () => {
|
||||
const text = llmsTxt(site)
|
||||
expect(text.indexOf('## 简体中文')).toBeGreaterThan(-1)
|
||||
expect(text.indexOf('## English')).toBeGreaterThan(text.indexOf('## 简体中文'))
|
||||
})
|
||||
|
||||
it('carries the site identity and the raw-Markdown convention', () => {
|
||||
const text = llmsTxt(site)
|
||||
expect(text.startsWith('# DeepSeek Harness\n')).toBe(true)
|
||||
expect(text).toContain('> 插件化 SDK')
|
||||
expect(text).toMatch(/`\.md`/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('rawMarkdownRoute', () => {
|
||||
it('projects one published route on demand', () => {
|
||||
const { root, pages } = fixture()
|
||||
writeFileSync(join(root, 'docs/a.md'), '# A\n\n[B](b.md)\n')
|
||||
|
||||
expect(rawMarkdownRoute('en/a.md', { pages, repoRoot: root, repositoryRef: 'abc123' }))
|
||||
.toBe('# A\n\n[B](./reference/b.md)\n')
|
||||
})
|
||||
|
||||
it('returns undefined for a path the manifest does not publish', () => {
|
||||
const { root, pages } = fixture()
|
||||
expect(rawMarkdownRoute('en/missing.md', { pages, repoRoot: root, repositoryRef: 'abc123' })).toBeUndefined()
|
||||
})
|
||||
})
|
||||
+229
-114
@@ -3,6 +3,9 @@
|
||||
*
|
||||
* The generated tree is disposable: sources stay in their owning `docs/`
|
||||
* tier, while this adapter rewrites cross-source links for the public site.
|
||||
* The same projection also emits a raw-Markdown twin of every route into the
|
||||
* build output, so a page's URL, minus any trailing slash, plus `.md` serves
|
||||
* it as plain Markdown.
|
||||
*/
|
||||
|
||||
import {
|
||||
@@ -13,23 +16,33 @@ import { fromMarkdown } from 'mdast-util-from-markdown'
|
||||
import { gfmFromMarkdown } from 'mdast-util-gfm'
|
||||
import { gfm } from 'micromark-extension-gfm'
|
||||
import type { Nodes } from 'mdast'
|
||||
import { docsPages, type DocsLocale, type DocsPage } from '../website/docs.ts'
|
||||
import { docsPages, localeCollections, orderedPages, type DocsLocale, type DocsPage } from '../website/docs.ts'
|
||||
import {
|
||||
isExternalOrAbsoluteMarkdownUrl,
|
||||
markdownDestination,
|
||||
splitMarkdownUrlTarget,
|
||||
} from './markdown.ts'
|
||||
|
||||
const REPOSITORY_URL = 'https://github.com/deepseek-ai/deepseek-harness'
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const generatedRoot = resolve(root, 'website/.generated')
|
||||
|
||||
/**
|
||||
* Resolve the public repository ref used by projected source links.
|
||||
*
|
||||
* @param environment Build environment containing an optional explicit public ref.
|
||||
* @returns The configured public ref, or `master`.
|
||||
*/
|
||||
export function resolveRepositoryRef(environment: NodeJS.ProcessEnv): string {
|
||||
return environment.DOCS_REPOSITORY_REF ?? 'master'
|
||||
}
|
||||
|
||||
interface Replacement {
|
||||
start: number
|
||||
end: number
|
||||
value: string
|
||||
}
|
||||
|
||||
interface DestinationRange {
|
||||
start: number
|
||||
end: number
|
||||
}
|
||||
|
||||
type RewritableNode = Extract<Nodes, { type: 'link' | 'image' | 'definition' }>
|
||||
|
||||
/** Inputs for rewriting one canonical Markdown page. */
|
||||
@@ -55,94 +68,12 @@ function repoPath(absPath: string, repoRoot: string): string {
|
||||
return relative(repoRoot, absPath).split(sep).join('/')
|
||||
}
|
||||
|
||||
function isExternalOrSiteAbsolute(url: string): boolean {
|
||||
return url.startsWith('#')
|
||||
|| url.startsWith('//')
|
||||
|| url.startsWith('/')
|
||||
|| /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
|
||||
}
|
||||
|
||||
function skipWhitespace(source: string, start: number): number {
|
||||
let index = start
|
||||
while (/\s/.test(source[index] ?? '')) index += 1
|
||||
return index
|
||||
}
|
||||
|
||||
function labelEnd(source: string): number {
|
||||
const first = source.indexOf('[')
|
||||
if (first === -1) return -1
|
||||
let depth = 0
|
||||
for (let index = first; index < source.length; index += 1) {
|
||||
const char = source[index]
|
||||
if (char === '\\') {
|
||||
index += 1
|
||||
} else if (char === '[') {
|
||||
depth += 1
|
||||
} else if (char === ']') {
|
||||
depth -= 1
|
||||
if (depth === 0) return index
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
function destinationRange(rawNode: string, type: 'link' | 'image' | 'definition'): DestinationRange {
|
||||
const endOfLabel = labelEnd(rawNode)
|
||||
if (endOfLabel === -1) {
|
||||
throw new Error(`project-doc-site: cannot locate label end in ${JSON.stringify(rawNode)}.`)
|
||||
}
|
||||
|
||||
let start: number
|
||||
if (type === 'definition') {
|
||||
const colon = rawNode.indexOf(':', endOfLabel + 1)
|
||||
if (colon === -1) {
|
||||
throw new Error(`project-doc-site: cannot locate definition separator in ${JSON.stringify(rawNode)}.`)
|
||||
}
|
||||
start = skipWhitespace(rawNode, colon + 1)
|
||||
} else {
|
||||
if (rawNode[endOfLabel + 1] !== '(') {
|
||||
throw new Error(`project-doc-site: cannot locate inline destination in ${JSON.stringify(rawNode)}.`)
|
||||
}
|
||||
start = skipWhitespace(rawNode, endOfLabel + 2)
|
||||
}
|
||||
|
||||
if (rawNode[start] === '<') {
|
||||
for (let index = start + 1; index < rawNode.length; index += 1) {
|
||||
if (rawNode[index] === '\\') index += 1
|
||||
else if (rawNode[index] === '>') return { start: start + 1, end: index }
|
||||
}
|
||||
throw new Error(`project-doc-site: cannot locate angle-bracket destination end in ${JSON.stringify(rawNode)}.`)
|
||||
}
|
||||
|
||||
let depth = 0
|
||||
for (let index = start; index < rawNode.length; index += 1) {
|
||||
const char = rawNode[index]
|
||||
if (char === '\\') {
|
||||
index += 1
|
||||
} else if (char === '(') {
|
||||
depth += 1
|
||||
} else if (char === ')') {
|
||||
if (depth === 0) return { start, end: index }
|
||||
depth -= 1
|
||||
} else if (/\s/.test(char ?? '') && depth === 0) {
|
||||
return { start, end: index }
|
||||
}
|
||||
}
|
||||
return { start, end: rawNode.length }
|
||||
}
|
||||
|
||||
// `#fragment` suffixes pass through verbatim. Generated cordis-surface
|
||||
// headings carry explicit `<a id>` anchors with the GitHub slug, so those
|
||||
// fragments resolve on the published site too; hand-written headings rely on
|
||||
// VitePress's own slugger, which differs from GitHub's for punctuation-heavy
|
||||
// text — hand-authored cross-page fragments should prefer plain-text headings
|
||||
// or explicit anchors.
|
||||
function splitTarget(url: string): { path: string; suffix: string } {
|
||||
const boundary = url.search(/[?#]/)
|
||||
if (boundary === -1) return { path: url, suffix: '' }
|
||||
return { path: url.slice(0, boundary), suffix: url.slice(boundary) }
|
||||
}
|
||||
|
||||
function decodePath(path: string): string {
|
||||
try {
|
||||
return decodeURIComponent(path)
|
||||
@@ -229,8 +160,8 @@ export function rewriteMarkdown(source: string, options: RewriteMarkdownOptions)
|
||||
const replacements: Replacement[] = []
|
||||
|
||||
const rewrite = (node: RewritableNode): void => {
|
||||
if (isExternalOrSiteAbsolute(node.url)) return
|
||||
const { path, suffix } = splitTarget(node.url)
|
||||
if (isExternalOrAbsoluteMarkdownUrl(node.url)) return
|
||||
const { path, suffix } = splitMarkdownUrlTarget(node.url)
|
||||
if (path === '') return
|
||||
const { absPath, line } = resolveRepositoryTarget(sourceAbs, path, options.repoRoot)
|
||||
const targetPath = repoPath(absPath, options.repoRoot)
|
||||
@@ -247,16 +178,10 @@ export function rewriteMarkdown(source: string, options: RewriteMarkdownOptions)
|
||||
? `${options.placeImage(absPath)}${suffix}`
|
||||
: githubTarget(absPath, line, suffix, options.repositoryRef, options.repoRoot, node.type === 'image')
|
||||
|
||||
const start = node.position?.start.offset
|
||||
const end = node.position?.end.offset
|
||||
if (start === undefined || end === undefined) {
|
||||
throw new Error(`project-doc-site: link ${JSON.stringify(node.url)} has no source offsets.`)
|
||||
}
|
||||
const rawNode = source.slice(start, end)
|
||||
const rawDestination = destinationRange(rawNode, node.type)
|
||||
const destination = markdownDestination(source, node)
|
||||
replacements.push({
|
||||
start: start + rawDestination.start,
|
||||
end: start + rawDestination.end,
|
||||
start: destination.start,
|
||||
end: destination.end,
|
||||
value: nextUrl,
|
||||
})
|
||||
}
|
||||
@@ -395,34 +320,66 @@ export function docsSourceFiles(): string[] {
|
||||
return [...new Set([...docsPages.map(page => resolve(root, page.source)), ...referencedImages()])]
|
||||
}
|
||||
|
||||
/** Rebuild the disposable VitePress source tree from the publication manifest. */
|
||||
export function projectDocs(): void {
|
||||
/** Manifest and repository inputs for one projection pass. */
|
||||
export interface ProjectionContext {
|
||||
/** Pages to project. */
|
||||
pages: DocsPage[]
|
||||
/** Repository root every source and placed image must live under. */
|
||||
repoRoot: string
|
||||
/** Public ref used by projected GitHub links. */
|
||||
repositoryRef: string
|
||||
}
|
||||
|
||||
function defaultProjectionContext(): ProjectionContext {
|
||||
return { pages: docsPages, repoRoot: root, repositoryRef: resolveRepositoryRef(process.env) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Project every page and its images into one target tree.
|
||||
*
|
||||
* `entries` are what gets emitted; link resolution always reads the canonical
|
||||
* `context.pages`, so an alias entry sharing a source with its index route
|
||||
* emits at its own path while links keep targeting canonical routes.
|
||||
*/
|
||||
function projectPagesInto(
|
||||
targetRoot: string,
|
||||
context: ProjectionContext,
|
||||
pageContent: (markdown: string, page: DocsPage) => string,
|
||||
entries: DocsPage[] = context.pages,
|
||||
): void {
|
||||
const routes = new Set<string>()
|
||||
/** Projected path to the repository file that claimed it, pages and images alike. */
|
||||
const claimed = new Map<string, string>()
|
||||
const repositoryRef = process.env.GITHUB_SHA ?? 'master'
|
||||
rmSync(generatedRoot, { recursive: true, force: true })
|
||||
|
||||
/** Reserve one projected path, refusing a second source for it. */
|
||||
const claim = (target: string, sourceAbs: string): void => {
|
||||
const holder = claimed.get(target)
|
||||
if (holder !== undefined && holder !== sourceAbs) {
|
||||
throw new Error(
|
||||
`project-doc-site: ${repoPath(sourceAbs, root)} and ${repoPath(holder, root)}`
|
||||
+ ` both project to ${relative(generatedRoot, target).split(sep).join('/')}.`,
|
||||
`project-doc-site: ${repoPath(sourceAbs, context.repoRoot)} and ${repoPath(holder, context.repoRoot)}`
|
||||
+ ` both project to ${relative(targetRoot, target).split(sep).join('/')}.`,
|
||||
)
|
||||
}
|
||||
// A file the projection did not claim is another producer's output — in
|
||||
// the twin pass, the build VitePress just wrote, including `public/`
|
||||
// copies. Overwriting one would silently corrupt the site.
|
||||
if (holder === undefined && existsSync(target)) {
|
||||
throw new Error(
|
||||
`project-doc-site: ${repoPath(sourceAbs, context.repoRoot)} would overwrite existing build file`
|
||||
+ ` ${relative(targetRoot, target).split(sep).join('/')}.`,
|
||||
)
|
||||
}
|
||||
claimed.set(target, sourceAbs)
|
||||
}
|
||||
|
||||
for (const page of docsPages) {
|
||||
for (const page of entries) {
|
||||
if (routes.has(page.route)) throw new Error(`project-doc-site: duplicate route ${JSON.stringify(page.route)}.`)
|
||||
routes.add(page.route)
|
||||
const sourceAbs = resolve(root, page.source)
|
||||
const sourceAbs = resolve(context.repoRoot, page.source)
|
||||
if (!existsSync(sourceAbs) || !lstatSync(sourceAbs).isFile()) {
|
||||
throw new Error(`project-doc-site: source ${JSON.stringify(page.source)} does not exist or is not a file.`)
|
||||
}
|
||||
const output = resolve(generatedRoot, page.route)
|
||||
const output = resolve(targetRoot, page.route)
|
||||
// Claimed before the images are placed: a page and an image landing on one
|
||||
// path would otherwise overwrite each other in whichever order they ran.
|
||||
claim(output, sourceAbs)
|
||||
@@ -432,14 +389,14 @@ export function projectDocs(): void {
|
||||
sourcePath: page.source,
|
||||
locale: page.locale,
|
||||
route: page.route,
|
||||
pages: docsPages,
|
||||
repoRoot: root,
|
||||
repositoryRef,
|
||||
pages: context.pages,
|
||||
repoRoot: context.repoRoot,
|
||||
repositoryRef: context.repositoryRef,
|
||||
placeImage: (absPath) => {
|
||||
const real = publishableImage(absPath, root)
|
||||
const real = publishableImage(absPath, context.repoRoot)
|
||||
if (real === undefined) {
|
||||
throw new Error(
|
||||
`project-doc-site: ${page.source} references image ${repoPath(absPath, root)},`
|
||||
`project-doc-site: ${page.source} references image ${repoPath(absPath, context.repoRoot)},`
|
||||
+ ' which is not a regular file inside the repository.',
|
||||
)
|
||||
}
|
||||
@@ -455,6 +412,164 @@ export function projectDocs(): void {
|
||||
return `./${encodeURI(name)}`
|
||||
},
|
||||
})
|
||||
writeFileSync(output, addProjectionFrontmatter(projectedPageContent(projected, page), page))
|
||||
writeFileSync(output, pageContent(projected, page))
|
||||
}
|
||||
}
|
||||
|
||||
/** Rebuild the disposable VitePress source tree from the publication manifest. */
|
||||
export function projectDocs(): void {
|
||||
rmSync(generatedRoot, { recursive: true, force: true })
|
||||
projectPagesInto(generatedRoot, defaultProjectionContext(), (markdown, page) =>
|
||||
addProjectionFrontmatter(projectedPageContent(markdown, page), page))
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip the leading YAML frontmatter of a projected page.
|
||||
*
|
||||
* @param markdown Rewritten canonical Markdown content.
|
||||
* @param source Repository-relative page source, named by the failure.
|
||||
* @returns The content after the frontmatter block, or the input when none opens it.
|
||||
*/
|
||||
function withoutFrontmatter(markdown: string, source: string): string {
|
||||
if (!markdown.startsWith('---\n')) return markdown
|
||||
const closingDelimiter = '\n---\n'
|
||||
const closing = markdown.indexOf(closingDelimiter, 4)
|
||||
if (closing === -1) {
|
||||
throw new Error(`project-doc-site: ${JSON.stringify(source)} has unclosed YAML frontmatter.`)
|
||||
}
|
||||
return markdown.slice(closing + closingDelimiter.length).replace(/^\n+/, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw-Markdown twin of one published page.
|
||||
*
|
||||
* Frontmatter is VitePress rendering configuration and is dropped. A locale
|
||||
* home page therefore keeps its body here, while the rendered site truncates
|
||||
* it to the frontmatter redirect.
|
||||
*
|
||||
* @param markdown Rewritten canonical Markdown content.
|
||||
* @param source Repository-relative page source, named by frontmatter failures.
|
||||
* @returns Plain Markdown without frontmatter or repository chrome.
|
||||
*/
|
||||
export function rawMarkdownPageContent(markdown: string, source: string): string {
|
||||
return withoutRepositoryChrome(withoutFrontmatter(markdown, source))
|
||||
}
|
||||
|
||||
/**
|
||||
* Parent-level alias route of an index route, or `undefined` for other routes.
|
||||
*
|
||||
* The rendered site shows an index route as a directory URL, so "append
|
||||
* `.md`" naturally lands on `<dir>.md` once the trailing slash is dropped.
|
||||
* The root `index.md` has no parent to alias into.
|
||||
*/
|
||||
function indexAliasRoute(route: string): string | undefined {
|
||||
const match = /^(.+)\/index\.md$/.exec(route)
|
||||
return match?.[1] === undefined ? undefined : `${match[1]}.md`
|
||||
}
|
||||
|
||||
/**
|
||||
* Site-relative Markdown files the raw-Markdown projection emits: every
|
||||
* route, plus one parent-level alias per index route.
|
||||
*
|
||||
* @param pages Pages to project, defaulting to the publication manifest.
|
||||
* @returns The emitted paths, routes first.
|
||||
*/
|
||||
export function rawMarkdownFiles(pages: DocsPage[] = docsPages): string[] {
|
||||
const aliases = pages.map(page => indexAliasRoute(page.route)).filter(alias => alias !== undefined)
|
||||
return [...pages.map(page => page.route), ...aliases]
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit the raw-Markdown twin of every published route into a built site, so
|
||||
* static hosting serves the page's URL, minus any trailing slash, plus `.md`
|
||||
* as plain Markdown. Each index route also emits a parent-level alias twin,
|
||||
* projected over the alias route so its relative links stay correct.
|
||||
* Referenced images are copied beside the pages, keeping the same relative
|
||||
* URLs valid in both trees. Existing build files stay in place, and a name
|
||||
* collision with one fails the emission.
|
||||
*
|
||||
* @param outDir Build output directory to emit into.
|
||||
* @param context Manifest and repository inputs, defaulting to this repository.
|
||||
*/
|
||||
export function emitRawMarkdownPages(outDir: string, context: ProjectionContext = defaultProjectionContext()): void {
|
||||
const aliases = context.pages.flatMap((page) => {
|
||||
const alias = indexAliasRoute(page.route)
|
||||
return alias === undefined ? [] : [{ ...page, route: alias }]
|
||||
})
|
||||
projectPagesInto(
|
||||
outDir,
|
||||
context,
|
||||
(markdown, page) => rawMarkdownPageContent(markdown, page.source),
|
||||
[...context.pages, ...aliases],
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw Markdown served for one site route.
|
||||
*
|
||||
* Dev-server counterpart of {@link emitRawMarkdownPages}: images are not
|
||||
* copied because the generated tree already serves them beside the page.
|
||||
*
|
||||
* @param route Manifest route, including its `.md` suffix.
|
||||
* @param context Manifest and repository inputs, defaulting to this repository.
|
||||
* @returns The projected page, or `undefined` when the manifest does not publish the route.
|
||||
*/
|
||||
export function rawMarkdownRoute(route: string, context: ProjectionContext = defaultProjectionContext()): string | undefined {
|
||||
const page = context.pages.find(candidate => candidate.route === route)
|
||||
if (page === undefined) return undefined
|
||||
const markdown = readFileSync(resolve(context.repoRoot, page.source), 'utf8')
|
||||
return rawMarkdownPageContent(rewriteMarkdown(markdown, {
|
||||
sourcePath: page.source,
|
||||
locale: page.locale,
|
||||
route: page.route,
|
||||
pages: context.pages,
|
||||
repoRoot: context.repoRoot,
|
||||
repositoryRef: context.repositoryRef,
|
||||
placeImage: absPath => `./${encodeURI(basename(absPath))}`,
|
||||
}), page.source)
|
||||
}
|
||||
|
||||
/** Site identity written into llms.txt. */
|
||||
export interface LlmsTxtSite {
|
||||
/** Site base path, carrying the leading and trailing slashes VitePress requires. */
|
||||
base: string
|
||||
/** Site title. */
|
||||
title: string
|
||||
/** Site description. */
|
||||
description: string
|
||||
}
|
||||
|
||||
/** Locale groups llms.txt lists, in the order the site's navigation presents them. */
|
||||
const llmsTxtLocales: readonly { heading: string; locale: DocsLocale }[] = [
|
||||
{ heading: '简体中文', locale: 'root' },
|
||||
{ heading: 'English', locale: 'en' },
|
||||
]
|
||||
|
||||
/**
|
||||
* The llms.txt index of every published page's raw-Markdown twin.
|
||||
*
|
||||
* Links are site-absolute so an agent resolves them against the host it
|
||||
* fetched llms.txt from; locale home pages stay out because this file is the
|
||||
* agent-facing entry point itself.
|
||||
*
|
||||
* @param site Site identity and base path.
|
||||
* @returns llms.txt content listing both locale trees.
|
||||
*/
|
||||
export function llmsTxt(site: LlmsTxtSite): string {
|
||||
const lines = [
|
||||
`# ${site.title}`,
|
||||
'',
|
||||
`> ${site.description}`,
|
||||
'',
|
||||
'页面 URL 去掉末尾斜杠再加 `.md` 即为该页原始 Markdown(根路径用 `/index.md`);下方列表是各页精确地址。Drop any trailing slash and append `.md` to a page URL for its raw Markdown (the site root is `/index.md`); the list below carries the exact addresses.',
|
||||
]
|
||||
for (const { heading, locale } of llmsTxtLocales) {
|
||||
lines.push('', `## ${heading}`, '')
|
||||
for (const collection of localeCollections[locale]) {
|
||||
for (const page of orderedPages(locale, collection)) {
|
||||
lines.push(`- [${page.label}](${site.base}${page.route}): ${page.section}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return `${lines.join('\n')}\n`
|
||||
}
|
||||
@@ -13,7 +13,11 @@ afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function fixture(exportPath = './lib/index.js'): string {
|
||||
function fixture(options: {
|
||||
exportPath?: string
|
||||
indexSource?: string
|
||||
files?: Record<string, string>
|
||||
} = {}): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-publint-all-'))
|
||||
roots.push(root)
|
||||
const packageDir = join(root, 'packages/core/probe')
|
||||
@@ -26,10 +30,14 @@ function fixture(exportPath = './lib/index.js'): string {
|
||||
engines: { node: '>=22.19' },
|
||||
sideEffects: false,
|
||||
files: ['lib'],
|
||||
exports: { '.': { default: exportPath } },
|
||||
exports: { '.': { default: options.exportPath ?? './lib/index.js' } },
|
||||
}, null, 2)}\n`)
|
||||
writeFileSync(join(packageDir, 'README.md'), '# Probe\n')
|
||||
writeFileSync(join(packageDir, 'lib/index.js'), 'export const probe = true\n')
|
||||
writeFileSync(join(packageDir, 'lib/index.js'), options.indexSource ?? 'export const probe = true\n')
|
||||
for (const [path, source] of Object.entries(options.files ?? {})) {
|
||||
mkdirSync(join(packageDir, path, '..'), { recursive: true })
|
||||
writeFileSync(join(packageDir, path), source)
|
||||
}
|
||||
writeFileSync(join(packageDir, 'unpublished.js'), 'export const hidden = true\n')
|
||||
return root
|
||||
}
|
||||
@@ -54,14 +62,34 @@ describe('publint package runner', () => {
|
||||
})
|
||||
|
||||
it('rejects an export that exists in the workspace but is not published', () => {
|
||||
const result = run(fixture('./unpublished.js'))
|
||||
const result = run(fixture({ exportPath: './unpublished.js' }))
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stdout).toContain('unpublished.js')
|
||||
})
|
||||
|
||||
it('rejects a public export whose built file is missing', () => {
|
||||
const result = run(fixture('./lib/missing.js'))
|
||||
const result = run(fixture({ exportPath: './lib/missing.js' }))
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stdout).toContain('missing.js')
|
||||
})
|
||||
|
||||
it('accepts published relative JavaScript and CSS targets', () => {
|
||||
const result = run(fixture({
|
||||
indexSource: "export { helper } from './helper.js'\nimport './theme.css'\n",
|
||||
files: {
|
||||
'lib/helper.js': 'export const helper = true\n',
|
||||
'lib/theme.css': ':root {}\n',
|
||||
},
|
||||
}))
|
||||
expect(result.status, result.stderr).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects unpublished relative JavaScript and CSS targets', () => {
|
||||
const result = run(fixture({
|
||||
indexSource: "export { helper } from './missing.js'\nimport './missing.css'\n",
|
||||
}))
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toContain('imports "./missing.js"')
|
||||
expect(result.stderr).toContain('imports "./missing.css"')
|
||||
})
|
||||
})
|
||||
+105
-8
@@ -7,10 +7,11 @@ import {
|
||||
statSync,
|
||||
} from 'node:fs'
|
||||
import { availableParallelism } from 'node:os'
|
||||
import { dirname, relative, resolve, sep } from 'node:path'
|
||||
import { dirname, posix, relative, resolve, sep } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { publint, type Message, type PackFile } from 'publint'
|
||||
import { formatMessage } from 'publint/utils'
|
||||
import ts from 'typescript'
|
||||
|
||||
const CONCURRENCY_ENV = 'DSH_PUBLINT_CONCURRENCY'
|
||||
const repositoryRoot = resolve(import.meta.dirname, '..')
|
||||
@@ -32,8 +33,21 @@ interface PackageManifest {
|
||||
}
|
||||
|
||||
type PublintResult =
|
||||
| { path: string; status: 'passed'; messages: Message[]; manifest: Record<string, unknown> }
|
||||
| { path: string; status: 'failed'; messages: Message[]; manifest: Record<string, unknown>; failure?: string }
|
||||
| {
|
||||
path: string
|
||||
status: 'passed'
|
||||
messages: Message[]
|
||||
closureViolations: string[]
|
||||
manifest: Record<string, unknown>
|
||||
}
|
||||
| {
|
||||
path: string
|
||||
status: 'failed'
|
||||
messages: Message[]
|
||||
closureViolations: string[]
|
||||
manifest: Record<string, unknown>
|
||||
failure?: string
|
||||
}
|
||||
|
||||
function workspacePackages(): PackageTarget[] {
|
||||
return globSync('packages/*/*/package.json', { cwd: packagesRoot })
|
||||
@@ -103,21 +117,101 @@ function addPath(path: string, paths: Set<string>): void {
|
||||
}
|
||||
}
|
||||
|
||||
interface RelativeImport {
|
||||
specifier: string
|
||||
line: number
|
||||
}
|
||||
|
||||
/** Return relative imports whose targets are absent from the publication view. */
|
||||
function publicationClosureViolations(target: PackageTarget, files: readonly PackFile[]): string[] {
|
||||
const published = new Set(files.map(file => file.name))
|
||||
const violations: string[] = []
|
||||
for (const file of files) {
|
||||
if (!/\.(?:js|mjs|cjs)$/.test(file.name)) continue
|
||||
const bytes = file.data instanceof ArrayBuffer ? new Uint8Array(file.data) : file.data
|
||||
const source = typeof bytes === 'string' ? bytes : Buffer.from(bytes).toString('utf8')
|
||||
for (const imported of relativeImports(file.name, source)) {
|
||||
const resolved = posix.normalize(posix.join(posix.dirname(file.name), imported.specifier))
|
||||
if (resolutionCandidates(resolved).some(candidate => published.has(candidate))) continue
|
||||
violations.push(
|
||||
`${target.path}/${file.name.slice('package/'.length)}:${String(imported.line)}`
|
||||
+ ` imports ${JSON.stringify(imported.specifier)}, but ${target.manifest.name ?? target.path}`
|
||||
+ ` does not publish ${JSON.stringify(resolved.slice('package/'.length))}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
/** Paths a relative JavaScript module request can resolve to in a published package. */
|
||||
function resolutionCandidates(target: string): string[] {
|
||||
const base = target.replace(/\/+$/, '')
|
||||
return [
|
||||
target,
|
||||
...['.js', '.mjs', '.cjs', '/index.js', '/index.mjs', '/index.cjs'].map(suffix => base + suffix),
|
||||
]
|
||||
}
|
||||
|
||||
/** Extract relative static imports, re-exports, dynamic imports, and requires. */
|
||||
function relativeImports(file: string, sourceText: string): RelativeImport[] {
|
||||
const source = ts.createSourceFile(file, sourceText, ts.ScriptTarget.Latest, false, ts.ScriptKind.JS)
|
||||
const imports: RelativeImport[] = []
|
||||
const record = (node: ts.Node, literal: ts.Expression | undefined): void => {
|
||||
if (literal === undefined || !ts.isStringLiteralLike(literal) || !literal.text.startsWith('.')) return
|
||||
imports.push({
|
||||
specifier: literal.text,
|
||||
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
|
||||
})
|
||||
}
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
|
||||
record(node, node.moduleSpecifier)
|
||||
} else if (ts.isCallExpression(node)
|
||||
&& (node.expression.kind === ts.SyntaxKind.ImportKeyword
|
||||
|| ts.isIdentifier(node.expression) && node.expression.text === 'require')) {
|
||||
record(node, node.arguments[0])
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
visit(source)
|
||||
return imports
|
||||
}
|
||||
|
||||
/**
|
||||
* publint reads the CommonJS interop preamble inside the prebuilt browser
|
||||
* bundles and reports CJS-written-as-ESM. Node never resolves those files:
|
||||
* `lib/client.js` is evaluated by the page module system as a classic script,
|
||||
* and `lib/worker.js` by `new Worker(url, { type: 'module' })` — both outside
|
||||
* the Node resolution publint models. Exactly that verdict on exactly those
|
||||
* files is suppressed; every other publint error stays fatal.
|
||||
*/
|
||||
function isBrowserBundleFormatFalsePositive(message: Message): boolean {
|
||||
if (message.code !== 'FILE_INVALID_FORMAT') return false
|
||||
const filePath = (message.args as { actualFilePath?: string }).actualFilePath ?? ''
|
||||
const exportKey = Array.isArray(message.path) ? message.path.join('/') : ''
|
||||
return /(^|\/)lib\/(client|worker)\.js$/.test(filePath)
|
||||
|| /(^|\/)\.\/(client|worker)$/.test(exportKey)
|
||||
}
|
||||
|
||||
async function runPublint(target: PackageTarget): Promise<PublintResult> {
|
||||
try {
|
||||
const files = publicationFiles(target)
|
||||
const closureViolations = publicationClosureViolations(target, files)
|
||||
const result = await publint({
|
||||
pkgDir: 'package',
|
||||
pack: { files: publicationFiles(target) },
|
||||
pack: { files },
|
||||
})
|
||||
const manifest = result.pkg as Record<string, unknown>
|
||||
return result.messages.some(message => message.type === 'error')
|
||||
? { path: target.path, status: 'failed', messages: result.messages, manifest }
|
||||
: { path: target.path, status: 'passed', messages: result.messages, manifest }
|
||||
const messages = result.messages.filter(message => !isBrowserBundleFormatFalsePositive(message))
|
||||
return messages.some(message => message.type === 'error') || closureViolations.length > 0
|
||||
? { path: target.path, status: 'failed', messages, closureViolations, manifest }
|
||||
: { path: target.path, status: 'passed', messages, closureViolations, manifest }
|
||||
} catch (error: unknown) {
|
||||
return {
|
||||
path: target.path,
|
||||
status: 'failed',
|
||||
messages: [],
|
||||
closureViolations: [],
|
||||
manifest: target.manifest as Record<string, unknown>,
|
||||
failure: error instanceof Error ? error.message : String(error),
|
||||
}
|
||||
@@ -150,7 +244,10 @@ function printResult(result: PublintResult): void {
|
||||
for (const message of result.messages) {
|
||||
console.log(formatMessage(message, result.manifest, { color: false }) ?? message.code)
|
||||
}
|
||||
if (result.status === 'passed' && result.messages.length === 0) console.log('All good!')
|
||||
for (const violation of result.closureViolations) console.error(violation)
|
||||
if (result.status === 'passed' && result.messages.length === 0 && result.closureViolations.length === 0) {
|
||||
console.log('All good!')
|
||||
}
|
||||
}
|
||||
|
||||
const packages = workspacePackages()
|
||||
|
||||
@@ -24,7 +24,7 @@ const DEFAULT_REGISTRY = 'https://registry.npm.harnessment.com'
|
||||
const DEFAULT_OUTPUT_DIRECTORY = '.artifacts/npm-baseline'
|
||||
const PACKAGE_PATTERNS = [
|
||||
'vendor/*/package.json',
|
||||
'packages/*/*/package.json',
|
||||
'packages/!(experimental)/*/package.json',
|
||||
'apps/*/package.json',
|
||||
] as const
|
||||
const DEPENDENCY_SECTIONS = [
|
||||
@@ -42,7 +42,7 @@ node, bin_path, cwd, timeout_seconds = sys.argv[1:]
|
||||
pid, fd = pty.fork()
|
||||
if pid == 0:
|
||||
os.chdir(cwd)
|
||||
os.execvpe(node, [node, bin_path, "web", "--host", "127.0.0.1", "--port", "0"], os.environ.copy())
|
||||
os.execvpe(node, [node, bin_path, "web", "--no-open", "--host", "127.0.0.1", "--port", "0"], os.environ.copy())
|
||||
|
||||
output = bytearray()
|
||||
ready_seen = False
|
||||
|
||||
+60
-13
@@ -3,7 +3,8 @@
|
||||
* readable from the repository rather than derived inside CI
|
||||
* ([rationale](../../.agents/notes/implemented/process/2026-08-10-npm-release-sequences.md)).
|
||||
*
|
||||
* The dsh family shares one version across its members and the workspace root:
|
||||
* The dsh family shares one version across its publishable members, private
|
||||
* package manifests, and the workspace root:
|
||||
* `major`, `minor`, `patch`, or an explicit `x.y.z` (including a prerelease such
|
||||
* as `0.0.1-rc.1`). The vendored family has one version line per package, but
|
||||
* every release advances and publishes the complete family so the next release
|
||||
@@ -14,7 +15,7 @@
|
||||
* the tag after the commit merges. CI never writes to the repository.
|
||||
*/
|
||||
|
||||
import { readFileSync, writeFileSync } from 'node:fs'
|
||||
import { globSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { join, matchesGlob } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { releaseFamily, type ReleaseFamily, type ReleaseMember } from './families.ts'
|
||||
@@ -39,16 +40,22 @@ const ROOT_MANIFEST = 'package.json'
|
||||
|
||||
/** One manifest the bump rewrites, and the tag its new version will carry. */
|
||||
interface PlannedVersion {
|
||||
readonly manifestPath: string
|
||||
readonly label: string
|
||||
readonly from: string
|
||||
readonly to: string
|
||||
/** The tag this version publishes from, or undefined for a non-published manifest. */
|
||||
readonly tag: string | undefined
|
||||
}
|
||||
|
||||
/** One private dsh package whose version follows the publishable family. */
|
||||
interface PrivateDshVersion {
|
||||
/** Repository-relative manifest path. */
|
||||
readonly manifestPath: string
|
||||
/** Label for the log line. */
|
||||
/** Package directory used in bump output. */
|
||||
readonly label: string
|
||||
/** The version the manifest currently carries. */
|
||||
readonly from: string
|
||||
/** The version to write. */
|
||||
readonly to: string
|
||||
/** The tag this version publishes from, or undefined for the workspace root. */
|
||||
readonly tag: string | undefined
|
||||
/** Current manifest version. */
|
||||
readonly version: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -236,14 +243,43 @@ function rootVersion(root: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan the dsh family's rewrite: one version for every member and the root.
|
||||
* Discover private package manifests that share the dsh version without joining
|
||||
* its publish set.
|
||||
* @param root - repository root.
|
||||
* @returns Private package manifests sorted by path.
|
||||
*/
|
||||
function privateDshVersions(root: string): PrivateDshVersion[] {
|
||||
return globSync('packages/*/*/package.json', { cwd: root })
|
||||
.map(path => path.replaceAll('\\', '/'))
|
||||
.sort()
|
||||
.flatMap((manifestPath) => {
|
||||
const parsed: unknown = JSON.parse(readFileSync(join(root, manifestPath), 'utf8'))
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error(`${manifestPath} is not a JSON object`)
|
||||
}
|
||||
const manifest = parsed as Record<string, unknown>
|
||||
if (manifest.private !== true) return []
|
||||
if (typeof manifest.version !== 'string') {
|
||||
throw new Error(`${manifestPath} must declare a string version`)
|
||||
}
|
||||
return [{
|
||||
manifestPath,
|
||||
label: manifestPath.slice(0, -'/package.json'.length),
|
||||
version: manifest.version,
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Plan the dsh family's rewrite: one version for every publishable member,
|
||||
* private package, and the root.
|
||||
* @param family - the dsh family.
|
||||
* @param root - repository root.
|
||||
* @param members - the family's members.
|
||||
* @param request - `major`, `minor`, `patch`, or an explicit version.
|
||||
* @returns The manifests to rewrite and the shared target version.
|
||||
*/
|
||||
function planShared(
|
||||
export function planShared(
|
||||
family: ReleaseFamily,
|
||||
root: string,
|
||||
members: readonly ReleaseMember[],
|
||||
@@ -259,13 +295,24 @@ function planShared(
|
||||
]
|
||||
for (const member of members) {
|
||||
planned.push({
|
||||
manifestPath: join(member.directory, 'package.json'),
|
||||
manifestPath: `${member.directory}/package.json`,
|
||||
label: member.directory,
|
||||
from: member.version,
|
||||
to: version,
|
||||
tag: family.tagFor({ ...member, version }),
|
||||
})
|
||||
}
|
||||
const publishableManifests = new Set(members.map(member => `${member.directory}/package.json`))
|
||||
for (const entry of privateDshVersions(root)) {
|
||||
if (publishableManifests.has(entry.manifestPath)) continue
|
||||
planned.push({
|
||||
manifestPath: entry.manifestPath,
|
||||
label: entry.label,
|
||||
from: entry.version,
|
||||
to: version,
|
||||
tag: undefined,
|
||||
})
|
||||
}
|
||||
return { planned, version }
|
||||
}
|
||||
|
||||
@@ -287,7 +334,7 @@ function planPerPackage(
|
||||
const tagged = lastTaggedVersion(family, member)
|
||||
const to = nextVendorVersion(member.version, tagged, prerelease)
|
||||
planned.push({
|
||||
manifestPath: join(member.directory, 'package.json'),
|
||||
manifestPath: `${member.directory}/package.json`,
|
||||
label: member.directory,
|
||||
from: member.version,
|
||||
to,
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
/** Release family discovery, publish order, tag naming, and the bump judgements. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { officialClientBuildEnvironment, writeClientBuildRecord } from '../client-build-environment.ts'
|
||||
import { releaseFamily, type ReleaseMember } from './families.ts'
|
||||
import { compareVersions, nextVendorVersion, reachesPayload } from './bump.ts'
|
||||
import { compareVersions, nextVendorVersion, planShared, reachesPayload } from './bump.ts'
|
||||
|
||||
/**
|
||||
* A release member standing in for a manifest on disk.
|
||||
@@ -15,7 +19,53 @@ function member(directory: string, name: string, manifest: Record<string, unknow
|
||||
return { directory, name, version: '0.0.1', manifest }
|
||||
}
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function write(path: string, content: string): void {
|
||||
mkdirSync(dirname(path), { recursive: true })
|
||||
writeFileSync(path, content)
|
||||
}
|
||||
|
||||
function buildFixture(environment: Record<string, string>): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-release-build-'))
|
||||
roots.push(root)
|
||||
write(join(root, 'apps/web/dist/index.html'), '<main></main>')
|
||||
write(join(root, 'packages/client/example/lib/client.js'), 'module.exports = {}\n')
|
||||
writeClientBuildRecord(root, environment)
|
||||
return root
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('release families', () => {
|
||||
it('excludes private experimental packages from the dsh release', () => {
|
||||
const members = releaseFamily('dsh').members(resolve(import.meta.dirname, '../..'))
|
||||
|
||||
expect(members.some(member => member.directory.startsWith('packages/experimental/'))).toBe(false)
|
||||
expect(members.map(member => member.name)).not.toContain('@deepseek-ai/dsh-experimental-agent-team')
|
||||
})
|
||||
|
||||
it('bumps private dsh packages without adding release tags', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-release-version-'))
|
||||
roots.push(root)
|
||||
write(join(root, 'package.json'), '{"version":"0.0.1"}\n')
|
||||
write(join(root, 'packages/experimental/prototype/package.json'), '{"version":"0.0.1","private":true}\n')
|
||||
write(join(root, 'packages/core/unselected/package.json'), '{"version":"0.0.1"}\n')
|
||||
|
||||
const dsh = releaseFamily('dsh')
|
||||
const published = member('packages/core/published', '@deepseek-ai/dsh-published')
|
||||
const { planned } = planShared(dsh, root, [published], '0.0.2')
|
||||
|
||||
expect(planned.map(entry => ({ path: entry.manifestPath, tag: entry.tag }))).toEqual([
|
||||
{ path: 'package.json', tag: undefined },
|
||||
{ path: 'packages/core/published/package.json', tag: 'dsh-v0.0.2' },
|
||||
{ path: 'packages/experimental/prototype/package.json', tag: undefined },
|
||||
])
|
||||
})
|
||||
|
||||
it('names one tag for the whole dsh family and one per vendored package', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const vendor = releaseFamily('vendor')
|
||||
@@ -49,6 +99,23 @@ describe('release families', () => {
|
||||
expect(() => { vendor.verifyVersions([{ ...members[0]!, version: 'latest' }]) }).toThrow(/unpublishable version/)
|
||||
})
|
||||
|
||||
it('requires a current official client build only for dsh artifacts', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const vendor = releaseFamily('vendor')
|
||||
const officialEnvironment = officialClientBuildEnvironment(resolve(import.meta.dirname, '../..'))
|
||||
vi.stubEnv('DSH_CLIENT_COMMIT_HASH', officialEnvironment.DSH_CLIENT_COMMIT_HASH)
|
||||
const official = buildFixture(officialEnvironment)
|
||||
const defaultBuild = buildFixture({})
|
||||
|
||||
expect(() => { dsh.verifyBuildArtifacts(official) }).not.toThrow()
|
||||
expect(() => { dsh.verifyBuildArtifacts(defaultBuild) }).toThrow(/DSH_CLIENT_TITLE/)
|
||||
expect(() => { dsh.verifyBuildArtifacts(join(defaultBuild, 'missing')) }).toThrow(/record.*missing/)
|
||||
expect(() => { vendor.verifyBuildArtifacts(join(defaultBuild, 'missing')) }).not.toThrow()
|
||||
|
||||
write(join(official, 'packages/client/example/lib/client.js'), 'module.exports = { changed: true }\n')
|
||||
expect(() => { dsh.verifyBuildArtifacts(official) }).toThrow(/artifacts differ/)
|
||||
})
|
||||
|
||||
it('publishes a dependency before its consumer, and orders ties by name', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const members = [
|
||||
@@ -57,7 +124,7 @@ describe('release families', () => {
|
||||
member('packages/a/zebra', '@deepseek-ai/dsh-zebra'),
|
||||
]
|
||||
|
||||
expect(dsh.publishOrder(members).map(entry => entry.name)).toEqual([
|
||||
expect(dsh.publishOrder(members).order.map(entry => entry.name)).toEqual([
|
||||
'@deepseek-ai/dsh-library',
|
||||
'@deepseek-ai/dsh-consumer',
|
||||
'@deepseek-ai/dsh-zebra',
|
||||
@@ -74,6 +141,92 @@ describe('release families', () => {
|
||||
expect(() => { dsh.publishOrder(members) }).toThrow(/dependency cycle/)
|
||||
})
|
||||
|
||||
it('publishes a peer before its consumer', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const members = [
|
||||
member('packages/a/consumer', '@deepseek-ai/dsh-consumer', { peerDependencies: { '@deepseek-ai/dsh-zebra': 'workspace:^' } }),
|
||||
member('packages/a/zebra', '@deepseek-ai/dsh-zebra'),
|
||||
]
|
||||
|
||||
// Name order alone would place the consumer first; the peer edge moves it.
|
||||
expect(dsh.publishOrder(members).order.map(entry => entry.name)).toEqual([
|
||||
'@deepseek-ai/dsh-zebra',
|
||||
'@deepseek-ai/dsh-consumer',
|
||||
])
|
||||
})
|
||||
|
||||
it('orders around a peer cycle rather than refusing to publish, and reports the edge it dropped', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const members = [
|
||||
member('packages/a/left', '@deepseek-ai/dsh-left', { peerDependencies: { '@deepseek-ai/dsh-right': 'workspace:^' } }),
|
||||
member('packages/a/right', '@deepseek-ai/dsh-right', { peerDependencies: { '@deepseek-ai/dsh-left': 'workspace:^' } }),
|
||||
]
|
||||
|
||||
// Sibling packages declare each other as peers, and npm treats an unmet peer
|
||||
// as a warning, so this pair has to publish rather than fail the release.
|
||||
const plan = dsh.publishOrder(members)
|
||||
expect(plan.order.map(entry => entry.name)).toEqual([
|
||||
'@deepseek-ai/dsh-right',
|
||||
'@deepseek-ai/dsh-left',
|
||||
])
|
||||
// One of the two edges has to give, and which one it is belongs in the log.
|
||||
expect(plan.droppedPeerEdges).toEqual([
|
||||
{ consumer: '@deepseek-ai/dsh-right', peer: '@deepseek-ai/dsh-left' },
|
||||
])
|
||||
})
|
||||
|
||||
it('honours an install edge even when a peer cycle surrounds it', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const members = [
|
||||
member('packages/a/base', '@deepseek-ai/dsh-base', { peerDependencies: { '@deepseek-ai/dsh-consumer': 'workspace:^' } }),
|
||||
member('packages/a/consumer', '@deepseek-ai/dsh-consumer', {
|
||||
dependencies: { '@deepseek-ai/dsh-base': 'workspace:^' },
|
||||
peerDependencies: { '@deepseek-ai/dsh-base': 'workspace:^' },
|
||||
}),
|
||||
]
|
||||
|
||||
// The install edge is absolute: base publishes first, and the peer edge that
|
||||
// would reverse it is the one dropped.
|
||||
const plan = dsh.publishOrder(members)
|
||||
expect(plan.order.map(entry => entry.name)).toEqual([
|
||||
'@deepseek-ai/dsh-base',
|
||||
'@deepseek-ai/dsh-consumer',
|
||||
])
|
||||
expect(plan.droppedPeerEdges).toEqual([
|
||||
{ consumer: '@deepseek-ai/dsh-base', peer: '@deepseek-ai/dsh-consumer' },
|
||||
])
|
||||
})
|
||||
|
||||
it('refuses an order that would publish a consumer before a dependency it installs', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const members = [
|
||||
member('packages/a/alpha', '@deepseek-ai/dsh-alpha', { peerDependencies: { '@deepseek-ai/dsh-bravo': 'workspace:^' } }),
|
||||
member('packages/a/bravo', '@deepseek-ai/dsh-bravo', { peerDependencies: { '@deepseek-ai/dsh-charlie': 'workspace:^' } }),
|
||||
member('packages/a/charlie', '@deepseek-ai/dsh-charlie', { dependencies: { '@deepseek-ai/dsh-alpha': 'workspace:^' } }),
|
||||
]
|
||||
|
||||
// A cycle of two peer edges closed by one install edge: dropping a peer edge
|
||||
// would order this, and the traversal drops the install edge instead. That
|
||||
// order would publish charlie before the alpha it installs, so it is refused
|
||||
// here rather than published.
|
||||
expect(() => { dsh.publishOrder(members) }).toThrow(/no publish order honours @deepseek-ai\/dsh-charlie -> @deepseek-ai\/dsh-alpha/)
|
||||
})
|
||||
|
||||
it('ignores devDependencies when ordering', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const members = [
|
||||
member('packages/a/alpha', '@deepseek-ai/dsh-alpha', { devDependencies: { '@deepseek-ai/dsh-zebra': 'workspace:^' } }),
|
||||
member('packages/a/zebra', '@deepseek-ai/dsh-zebra'),
|
||||
]
|
||||
|
||||
// A dev dependency is absent from the published package, so it must not move
|
||||
// the consumer behind it.
|
||||
expect(dsh.publishOrder(members).order.map(entry => entry.name)).toEqual([
|
||||
'@deepseek-ai/dsh-alpha',
|
||||
'@deepseek-ai/dsh-zebra',
|
||||
])
|
||||
})
|
||||
|
||||
it('applies the harness payload policy to dsh and keeps upstream payloads for vendored packages', () => {
|
||||
const dsh = releaseFamily('dsh')
|
||||
const vendor = releaseFamily('vendor')
|
||||
|
||||
+152
-32
@@ -11,23 +11,56 @@
|
||||
|
||||
import { globSync, readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import {
|
||||
officialClientBuildEnvironment,
|
||||
readClientBuildRecord,
|
||||
} from '../client-build-environment.ts'
|
||||
import { validateTarballPayload } from '../publication-payload.ts'
|
||||
|
||||
/** Dependency sections that constrain publish order: a consumer must publish after its dependency. */
|
||||
const ORDER_SECTIONS = ['dependencies', 'optionalDependencies'] as const
|
||||
/**
|
||||
* Dependency sections a consumer must publish after, because npm resolves them
|
||||
* when the package is installed: publishing a consumer first would leave a
|
||||
* window where its own tree cannot be assembled.
|
||||
*/
|
||||
const INSTALL_SECTIONS = ['dependencies', 'optionalDependencies'] as const
|
||||
|
||||
/**
|
||||
* Peer declarations also order the publication, but they cannot constrain it.
|
||||
* npm never installs a peer on the package's behalf — an unmet peer is a
|
||||
* warning, not a resolution failure — and sibling packages legitimately declare
|
||||
* each other as peers, which makes these edges the ones that close cycles. They
|
||||
* order what they can and are dropped where they would deadlock.
|
||||
*/
|
||||
const PEER_SECTIONS = ['peerDependencies'] as const
|
||||
|
||||
/** The workspace root manifest, which is never a release member. */
|
||||
const WORKSPACE_ROOT_PACKAGE = '@deepseek-ai/dsh-root'
|
||||
|
||||
/** One peer declaration the publish order leaves unordered. */
|
||||
interface DroppedPeerEdge {
|
||||
readonly consumer: string
|
||||
/** The declared peer, which publishes after `consumer` or alongside it in a cycle. */
|
||||
readonly peer: string
|
||||
}
|
||||
|
||||
/**
|
||||
* A family's publish order together with the ordering it could not honour.
|
||||
*
|
||||
* The dropped edges are part of the result rather than a detail of forming it:
|
||||
* a release drops real ordering constraints, and the operator reading the pack
|
||||
* log is the only one who can judge whether a newly dropped edge is expected.
|
||||
*/
|
||||
export interface PublishPlan {
|
||||
readonly order: readonly ReleaseMember[]
|
||||
/** Peer declarations left unordered, in the order the traversal reached them. */
|
||||
readonly droppedPeerEdges: readonly DroppedPeerEdge[]
|
||||
}
|
||||
|
||||
/** One publishable package of a release family. */
|
||||
export interface ReleaseMember {
|
||||
/** Repository-relative package directory, for example `packages/core/session`. */
|
||||
readonly directory: string
|
||||
/** Package name from its manifest. */
|
||||
readonly name: string
|
||||
/** Package version from its manifest. */
|
||||
readonly version: string
|
||||
/** The parsed manifest, for payload policy and publication checks. */
|
||||
readonly manifest: Readonly<Record<string, unknown>>
|
||||
}
|
||||
|
||||
@@ -59,23 +92,28 @@ function requireString(manifest: Record<string, unknown>, field: string, context
|
||||
|
||||
/** The executable a family's installed artifacts are driven through. */
|
||||
export interface InstalledEntry {
|
||||
/** Package that carries the executable. */
|
||||
readonly packageName: string
|
||||
/** Path to the executable inside that package. */
|
||||
readonly binPath: string
|
||||
}
|
||||
|
||||
/** A release sequence: its members, its version baseline, and its tag naming. */
|
||||
export abstract class ReleaseFamily {
|
||||
/** Workflow-facing identifier, also the `--family` argument. */
|
||||
/** Workflow-facing `--family` identifier. */
|
||||
abstract readonly id: string
|
||||
|
||||
/** Glob patterns, relative to the repository root, that select this family's manifests. */
|
||||
/** Repository-relative glob patterns selecting this family's manifests. */
|
||||
abstract readonly patterns: readonly string[]
|
||||
|
||||
/** Git tag prefix this family publishes from. */
|
||||
abstract readonly tagPrefix: string
|
||||
|
||||
/**
|
||||
* Assert that built artifacts match this release family's required profile.
|
||||
* Families without environment-selected artifacts accept every build tree.
|
||||
* @param _root - repository root containing generated artifacts.
|
||||
*/
|
||||
verifyBuildArtifacts(_root: string): void {}
|
||||
|
||||
/**
|
||||
* Discover this family's members.
|
||||
* @param root - repository root.
|
||||
@@ -107,45 +145,122 @@ export abstract class ReleaseFamily {
|
||||
}
|
||||
|
||||
/**
|
||||
* Order members so every package publishes after the family members it depends on.
|
||||
* Order members so every package publishes after the family members it
|
||||
* depends on, which is what makes a partial publication self-consistent: an
|
||||
* interrupted run leaves a prefix whose packages never point at something
|
||||
* absent from the registry.
|
||||
*
|
||||
* Install edges are honoured absolutely — a cycle among them is a defect this
|
||||
* reports rather than works around. Peer edges order what they can and are
|
||||
* dropped where honouring one would deadlock: sibling packages declare each
|
||||
* other as peers, and npm treats an unmet peer as a warning rather than a
|
||||
* resolution failure ([rationale](../../.agents/notes/implemented/process/2026-08-10-npm-release-sequences.md)).
|
||||
* Every dropped edge is reported, because dropping one is a decision about a
|
||||
* real release rather than an implementation detail.
|
||||
* @param members - this family's members.
|
||||
* @returns The same members in publish order; ties break by name for determinism.
|
||||
* @returns The order, ties broken by name for determinism, and the peer edges it left unordered.
|
||||
*/
|
||||
publishOrder(members: readonly ReleaseMember[]): ReleaseMember[] {
|
||||
publishOrder(members: readonly ReleaseMember[]): PublishPlan {
|
||||
const byName = new Map(members.map(member => [member.name, member]))
|
||||
const ordered: ReleaseMember[] = []
|
||||
const placed = new Set<string>()
|
||||
const visiting = new Set<string>()
|
||||
const byNameSorted = [...members].sort((left, right) => left.name.localeCompare(right.name))
|
||||
const edges = (member: ReleaseMember, sections: readonly string[]): ReleaseMember[] =>
|
||||
this.orderEdges(member, byName, sections)
|
||||
|
||||
const visit = (member: ReleaseMember, path: readonly string[]): void => {
|
||||
if (placed.has(member.name)) return
|
||||
if (visiting.has(member.name)) {
|
||||
// Install edges alone must be acyclic, and that is checked on its own graph:
|
||||
// a peer edge leading into an install edge would otherwise read as a cycle
|
||||
// where the install edges are perfectly orderable.
|
||||
const installVisiting = new Set<string>()
|
||||
const installDone = new Set<string>()
|
||||
const checkInstall = (member: ReleaseMember, path: readonly string[]): void => {
|
||||
if (installDone.has(member.name)) return
|
||||
if (installVisiting.has(member.name)) {
|
||||
throw new Error(`dependency cycle in release family ${this.id}: ${[...path, member.name].join(' -> ')}`)
|
||||
}
|
||||
visiting.add(member.name)
|
||||
for (const dependency of this.orderEdges(member, byName)) {
|
||||
visit(dependency, [...path, member.name])
|
||||
installVisiting.add(member.name)
|
||||
for (const dependency of edges(member, INSTALL_SECTIONS)) checkInstall(dependency, [...path, member.name])
|
||||
installVisiting.delete(member.name)
|
||||
installDone.add(member.name)
|
||||
}
|
||||
for (const member of byNameSorted) checkInstall(member, [])
|
||||
|
||||
// Emit the order over both kinds of edge. A node already on the stack closes
|
||||
// a cycle, and that cycle carries at least one peer edge because the install
|
||||
// edges were just proved acyclic — but the back edge that reaches the stacked
|
||||
// node is not necessarily the peer one, so the post-condition below decides
|
||||
// whether the emitted order survived.
|
||||
const ordered: ReleaseMember[] = []
|
||||
const droppedPeerEdges: DroppedPeerEdge[] = []
|
||||
const placed = new Set<string>()
|
||||
const onStack = new Set<string>()
|
||||
// Members reachable from one member through install edges. A peer edge is
|
||||
// dropped when the peer installs the member declaring it: honouring it would
|
||||
// emit a package before something it installs, and the install edge wins.
|
||||
const installClosure = (member: ReleaseMember): Set<string> => {
|
||||
const reached = new Set<string>()
|
||||
const walk = (current: ReleaseMember): void => {
|
||||
for (const dependency of edges(current, INSTALL_SECTIONS)) {
|
||||
if (reached.has(dependency.name)) continue
|
||||
reached.add(dependency.name)
|
||||
walk(dependency)
|
||||
}
|
||||
}
|
||||
visiting.delete(member.name)
|
||||
walk(member)
|
||||
return reached
|
||||
}
|
||||
const visit = (member: ReleaseMember): void => {
|
||||
if (placed.has(member.name) || onStack.has(member.name)) return
|
||||
onStack.add(member.name)
|
||||
for (const dependency of edges(member, INSTALL_SECTIONS)) visit(dependency)
|
||||
for (const peer of edges(member, PEER_SECTIONS)) {
|
||||
if (installClosure(peer).has(member.name)) {
|
||||
droppedPeerEdges.push({ consumer: member.name, peer: peer.name })
|
||||
continue
|
||||
}
|
||||
// A peer already on the stack is an ancestor, so it publishes after this
|
||||
// member rather than before it: the edge is dropped, not honoured.
|
||||
if (onStack.has(peer.name)) droppedPeerEdges.push({ consumer: member.name, peer: peer.name })
|
||||
visit(peer)
|
||||
}
|
||||
onStack.delete(member.name)
|
||||
placed.add(member.name)
|
||||
ordered.push(member)
|
||||
}
|
||||
for (const member of byNameSorted) visit(member)
|
||||
|
||||
for (const member of [...members].sort((left, right) => left.name.localeCompare(right.name))) {
|
||||
visit(member, [])
|
||||
// A cycle mixing both kinds of edge can put an install edge's target on the
|
||||
// stack, where the traversal skips it like a peer edge and emits a consumer
|
||||
// before something it installs. Nothing downstream can detect that, and it
|
||||
// would only surface as an unresolvable install for whoever consumes the
|
||||
// published packages, so the emitted order is checked against the edges it
|
||||
// exists to honour.
|
||||
const position = new Map(ordered.map((entry, index) => [entry.name, index]))
|
||||
for (const [index, member] of ordered.entries()) {
|
||||
for (const dependency of edges(member, INSTALL_SECTIONS)) {
|
||||
const dependencyIndex = position.get(dependency.name)
|
||||
if (dependencyIndex !== undefined && dependencyIndex < index) continue
|
||||
throw new Error(
|
||||
`release family ${this.id}: no publish order honours ${member.name} -> ${dependency.name};`
|
||||
+ ' a cycle mixing peer and dependency declarations reaches this dependency through a peer edge',
|
||||
)
|
||||
}
|
||||
}
|
||||
return ordered
|
||||
return { order: ordered, droppedPeerEdges }
|
||||
}
|
||||
|
||||
/**
|
||||
* The family members one member depends on at runtime.
|
||||
* The family members one member declares in the given sections.
|
||||
* @param member - the dependent member.
|
||||
* @param byName - every family member by package name.
|
||||
* @returns Dependencies inside this family, sorted by name.
|
||||
* @param sections - manifest sections to read.
|
||||
* @returns Members of this family named there, sorted by name.
|
||||
*/
|
||||
private orderEdges(member: ReleaseMember, byName: ReadonlyMap<string, ReleaseMember>): ReleaseMember[] {
|
||||
private orderEdges(
|
||||
member: ReleaseMember,
|
||||
byName: ReadonlyMap<string, ReleaseMember>,
|
||||
sections: readonly string[],
|
||||
): ReleaseMember[] {
|
||||
const edges: ReleaseMember[] = []
|
||||
for (const section of ORDER_SECTIONS) {
|
||||
for (const section of sections) {
|
||||
const dependencies = member.manifest[section]
|
||||
if (dependencies === null || typeof dependencies !== 'object' || Array.isArray(dependencies)) continue
|
||||
for (const name of Object.keys(dependencies)) {
|
||||
@@ -193,12 +308,17 @@ export abstract class ReleaseFamily {
|
||||
abstract readonly installedEntry: InstalledEntry | undefined
|
||||
}
|
||||
|
||||
/** `packages/*` and `apps/*`: one shared version across the whole family. */
|
||||
/** Release packages and apps: one shared version across the whole family. */
|
||||
class DshFamily extends ReleaseFamily {
|
||||
readonly id = 'dsh'
|
||||
readonly patterns = ['packages/*/*/package.json', 'apps/*/package.json'] as const
|
||||
readonly patterns = ['packages/!(experimental)/*/package.json', 'apps/*/package.json'] as const
|
||||
readonly tagPrefix = 'dsh-v'
|
||||
|
||||
/** Require current artifacts from a complete official client build. */
|
||||
override verifyBuildArtifacts(root: string): void {
|
||||
readClientBuildRecord(root, officialClientBuildEnvironment(root))
|
||||
}
|
||||
|
||||
/**
|
||||
* Require one version across the family, the way a single tag can name it.
|
||||
* @param members - this family's members.
|
||||
|
||||
@@ -45,7 +45,8 @@ function main(): void {
|
||||
const family = releaseFamily(values.family)
|
||||
const root = process.cwd()
|
||||
const destination = resolve(root, values.out ?? DEFAULT_OUTPUT)
|
||||
const members = family.publishOrder(family.members(root))
|
||||
const members = family.publishOrder(family.members(root)).order
|
||||
family.verifyBuildArtifacts(root)
|
||||
family.verifyVersions(members)
|
||||
|
||||
rmSync(destination, { recursive: true, force: true })
|
||||
|
||||
@@ -9,9 +9,7 @@ import { fileURLToPath } from 'node:url'
|
||||
|
||||
/** Where and with what environment a release step runs a command. */
|
||||
export interface RunOptions {
|
||||
/** Working directory; defaults to the current one. */
|
||||
readonly cwd?: string
|
||||
/** Child environment; defaults to this process's. */
|
||||
readonly env?: NodeJS.ProcessEnv
|
||||
}
|
||||
|
||||
@@ -19,9 +17,7 @@ export interface RunOptions {
|
||||
export interface CommandResult {
|
||||
/** Exit status, or null when a signal ended the process. */
|
||||
readonly status: number | null
|
||||
/** Captured standard output. */
|
||||
readonly stdout: string
|
||||
/** Captured standard error. */
|
||||
readonly stderr: string
|
||||
}
|
||||
|
||||
@@ -38,6 +34,27 @@ export function attempt(command: string, args: readonly string[], options: RunOp
|
||||
return { status: result.status, stdout: result.stdout, stderr: result.stderr }
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a command, then echo and return its captured output. Output is buffered
|
||||
* until exit and stdout precedes stderr.
|
||||
* @param command - executable name.
|
||||
* @param args - command arguments.
|
||||
* @param options - working directory and environment.
|
||||
* @returns The exit status and captured streams.
|
||||
*/
|
||||
export function attemptEchoed(command: string, args: readonly string[], options: RunOptions = {}): CommandResult {
|
||||
const result = spawnSync(command, [...args], {
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
encoding: 'utf8',
|
||||
stdio: ['inherit', 'pipe', 'pipe'],
|
||||
})
|
||||
if (result.error !== undefined) throw result.error
|
||||
if (result.stdout !== '') process.stdout.write(result.stdout)
|
||||
if (result.stderr !== '') process.stderr.write(result.stderr)
|
||||
return { status: result.status, stdout: result.stdout, stderr: result.stderr }
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a command, capture its standard output, and fail on a non-zero exit.
|
||||
* @param command - executable name.
|
||||
@@ -67,11 +84,7 @@ export function run(command: string, args: readonly string[], options: RunOption
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this module is the process entry point.
|
||||
*
|
||||
* The release scripts are both commands and modules: a test imports their pure
|
||||
* logic, and importing a module runs its body, so an unguarded `main()` would
|
||||
* run the wrong command with the wrong arguments.
|
||||
* Return whether Node started the given module as the process entry point.
|
||||
* @param moduleUrl - the caller's `import.meta.url`.
|
||||
* @returns True when Node started this module.
|
||||
*/
|
||||
|
||||
@@ -18,7 +18,7 @@ import { join, resolve } from 'node:path'
|
||||
import { setTimeout as sleep } from 'node:timers/promises'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { releaseFamily } from './families.ts'
|
||||
import { attempt, isEntry } from './process.ts'
|
||||
import { attempt, attemptEchoed, isEntry } from './process.ts'
|
||||
import { packedIdentity, readPublishOrder } from './tarball.ts'
|
||||
|
||||
/**
|
||||
@@ -102,7 +102,7 @@ async function publishTarball(tarball: string, name: string, version: string): P
|
||||
// command-line flag could not serve both and would override the manifest
|
||||
// that does. Each packed manifest decides, and
|
||||
// check-workspace-constraints holds every manifest to its sequence's level.
|
||||
const result = attempt('npm', ['publish', tarball, ...tagArgs])
|
||||
const result = attemptEchoed('npm', ['publish', tarball, ...tagArgs])
|
||||
const output = `${result.stdout}${result.stderr}`
|
||||
if (result.status === 0) return
|
||||
|
||||
@@ -136,9 +136,15 @@ async function main(): Promise<void> {
|
||||
const family = releaseFamily(values.family)
|
||||
const directory = resolve(process.cwd(), values.from)
|
||||
|
||||
// Every entry in the order settles as either published or already present, so
|
||||
// one counter answers "how far along is this run" for whoever is watching a
|
||||
// release that takes minutes per family.
|
||||
const order = readPublishOrder(directory)
|
||||
const total = String(order.length)
|
||||
let published = 0
|
||||
let skipped = 0
|
||||
for (const filename of readPublishOrder(directory)) {
|
||||
for (const [index, filename] of order.entries()) {
|
||||
const progress = `[${String(index + 1)}/${total}]`
|
||||
const tarball = join(directory, filename)
|
||||
const { name, version } = packedIdentity(tarball)
|
||||
const state = registryState(name, version)
|
||||
@@ -151,7 +157,7 @@ async function main(): Promise<void> {
|
||||
+ '\nBump the version, or investigate why the build is not reproducible.',
|
||||
)
|
||||
}
|
||||
console.log(`release publish: ${name}@${version} already published, skipping`)
|
||||
console.log(`release publish: ${progress} ${name}@${version} already published, skipping`)
|
||||
skipped += 1
|
||||
continue
|
||||
}
|
||||
@@ -159,11 +165,14 @@ async function main(): Promise<void> {
|
||||
// only skips does not wait at all.
|
||||
if (published > 0) await sleep(PUBLISH_SPACING_MS)
|
||||
await publishTarball(tarball, name, version)
|
||||
console.log(`release publish: ${name}@${version} published`)
|
||||
console.log(`release publish: ${progress} ${name}@${version} published`)
|
||||
published += 1
|
||||
}
|
||||
|
||||
console.log(`release publish: family ${family.id}, ${String(published)} published, ${String(skipped)} already present`)
|
||||
console.log(
|
||||
`release publish: family ${family.id}, ${total} member(s),`
|
||||
+ ` ${String(published)} published, ${String(skipped)} already present`,
|
||||
)
|
||||
}
|
||||
|
||||
if (isEntry(import.meta.url)) await main()
|
||||
@@ -9,7 +9,33 @@
|
||||
|
||||
import { parseArgs } from 'node:util'
|
||||
import { isEntry } from './process.ts'
|
||||
import { releaseFamily, type ReleaseFamily, type ReleaseMember } from './families.ts'
|
||||
import { releaseFamily, type PublishPlan, type ReleaseFamily, type ReleaseMember } from './families.ts'
|
||||
|
||||
/**
|
||||
* Print the publish order the release will follow, and the peer declarations it
|
||||
* leaves unordered.
|
||||
*
|
||||
* The order is the release's own plan: an interrupted publication leaves exactly
|
||||
* a prefix of it, so reading it is how anyone judges what a partial run left on
|
||||
* the registry, and printing it on every pull request is what makes a change to
|
||||
* the order reviewable rather than only observable during a publication.
|
||||
* @param family - the release family.
|
||||
* @param plan - the resolved order and its dropped edges.
|
||||
*/
|
||||
function reportPublishOrder(family: ReleaseFamily, plan: PublishPlan): void {
|
||||
console.log(`release verify: publish order for family ${family.id}, ${String(plan.order.length)} member(s):`)
|
||||
const width = String(plan.order.length).length
|
||||
for (const [index, member] of plan.order.entries()) {
|
||||
console.log(` ${String(index + 1).padStart(width, ' ')} ${member.name}@${member.version}`)
|
||||
}
|
||||
if (plan.droppedPeerEdges.length === 0) return
|
||||
console.log(
|
||||
`release verify: ${String(plan.droppedPeerEdges.length)} peer declaration(s) publish unordered,`
|
||||
+ ' because the peer cannot precede the package declaring it without contradicting a dependency edge'
|
||||
+ ' or its own cycle. npm treats an unmet peer as a warning, so this orders nothing and blocks nothing:',
|
||||
)
|
||||
for (const edge of plan.droppedPeerEdges) console.log(` ${edge.consumer} -> ${edge.peer}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert every member may be published: npm refuses a `private` package.
|
||||
@@ -55,6 +81,16 @@ function main(): void {
|
||||
const family = releaseFamily(values.family)
|
||||
const members = family.members(process.cwd())
|
||||
family.verifyVersions(members)
|
||||
// Resolve the publish order here, before the build: an install-edge cycle
|
||||
// makes the order unrepresentable, and that has to surface at the first gate
|
||||
// rather than when pack is already writing tarballs.
|
||||
const plan = family.publishOrder(members)
|
||||
if (plan.order.length !== members.length) {
|
||||
throw new Error(
|
||||
`release family ${family.id}: publish order covers ${String(plan.order.length)} of ${String(members.length)} members`,
|
||||
)
|
||||
}
|
||||
reportPublishOrder(family, plan)
|
||||
|
||||
const publishing = process.env.RELEASE_PUBLISH === 'true'
|
||||
if (publishing) {
|
||||
@@ -64,7 +100,11 @@ function main(): void {
|
||||
|
||||
const versions = [...new Set(members.map(member => member.version))]
|
||||
const summary = versions.length === 1 ? versions[0] : `${String(versions.length)} versions`
|
||||
console.log(`release verify: family ${family.id}, ${String(members.length)} member(s), ${summary}${publishing ? ', publish gates passed' : ''}`)
|
||||
console.log(
|
||||
`release verify: family ${family.id}, ${String(members.length)} member(s), ${summary},`
|
||||
+ ` publish order resolved, ${String(plan.droppedPeerEdges.length)} peer declaration(s) unordered`
|
||||
+ (publishing ? ', publish gates passed' : ''),
|
||||
)
|
||||
}
|
||||
|
||||
if (isEntry(import.meta.url)) main()
|
||||
@@ -77,8 +77,6 @@ interface GenericSkip {
|
||||
}
|
||||
|
||||
const GENERIC_SKIPS: readonly GenericSkip[] = [
|
||||
// `vendorPackages` lists vendor/ directory names, joined with 'vendor' below it.
|
||||
{ file: 'packages/examples/acp-demo/tests/built-bin.e2e.ts', upstream: ['cordis', 'cosmokit', 'schemastery'] },
|
||||
// `Symbol.for('schemastery')` and the `vendor:` metadata field are upstream identifiers.
|
||||
{ file: 'vendor/schemastery/src/index.ts', upstream: ['schemastery'] },
|
||||
// Asserts the vendored-manifest table, which gains an upstream-name column.
|
||||
@@ -104,6 +102,35 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [
|
||||
// GROUP_ORDER holds `packages/<group>/` directory names, not package names.
|
||||
{ file: 'scripts/gen-module-graph.ts', upstream: ['cordis'] },
|
||||
{ file: 'scripts/gen-doc-graphs.ts', upstream: ['cordis'] },
|
||||
// `cordis/*` is the extensions event domain, not a package subpath. The
|
||||
// generated catalogs and every producer/consumer must preserve that wire id.
|
||||
{ file: 'docs/event-producer-consumer.md', upstream: ['cordis'] },
|
||||
{ file: 'docs/event-producer-consumer.zh.md', upstream: ['cordis'] },
|
||||
{ file: 'docs/subsystems/extensions.md', upstream: ['cordis'] },
|
||||
{ file: 'docs/subsystems/extensions.zh.md', upstream: ['cordis'] },
|
||||
{ file: 'packages/api/remotes/src/remote-events.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-client-runner/src/client/index.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-client-runner/src/client/runtime.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-client-runner/tests/orchestrator.client.spec.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-client-runner/tests/plugin.client.spec.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-host-runner/src/index.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-host-runner/src/inspect-registry.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-host-runner/src/types.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-host-runner/tests/helpers.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-host-runner/tests/runner.spec.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/cordis-host-runner/tests/versioning.spec.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/tool-cordis/src/api-catalog.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/tool-cordis/src/providers.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/ui-cordis/src/client/index.ts', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/ui-cordis/src/client/inventory.ts', upstream: ['cordis'] },
|
||||
{ file: 'scripts/gen-cordis-catalog.ts', upstream: ['cordis'] },
|
||||
// The UI locale namespace and input-trigger source id are product keys.
|
||||
{ file: 'packages/client/ui-settings-plugin-inventory/src/client/PluginInventorySettingsTab.tsx', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/ui-cordis/src/client/CordisActionRow.tsx', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/ui-cordis/src/client/CordisDefineRow.tsx', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/ui-cordis/src/client/CordisPanel.tsx', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/ui-cordis/src/client/CordisRunRow.tsx', upstream: ['cordis'] },
|
||||
{ file: 'packages/extensions/ui-cordis/src/client/locales.ts', upstream: ['cordis'] },
|
||||
]
|
||||
|
||||
/** A string that must appear exactly `count` times once the rescope has run. */
|
||||
@@ -132,7 +159,6 @@ const POSTCONDITIONS: readonly PostCondition[] = [
|
||||
// The preset id the shipped composition documents to its own model.
|
||||
{ file: 'apps/cli/config/agent-presets/cordis/agent.cordis.yml', text: 'The `cordis` agent preset', count: 1 },
|
||||
{ file: 'apps/cli/config/agent-presets/cordis/agent.cordis.yml', text: 'corrupting the `cordis` preset', count: 1 },
|
||||
{ file: 'packages/examples/acp-demo/tests/built-bin.e2e.ts', text: '\'cordis\', \'loader\', \'include\', \'timer\', \'hmr\', \'logger-console\',', count: 1 },
|
||||
]
|
||||
|
||||
/**
|
||||
@@ -275,8 +301,8 @@ const EXACT_EDITS: readonly ExactEdit[] = [
|
||||
replace: `/**
|
||||
* Vendored framework libraries: rescoped into @deepseek-ai, so the gate below
|
||||
* would read them as plugin packages. They carry no cross-plugin runtime
|
||||
* identity to share — the framework itself is a platform module (external),
|
||||
* while these are ordinary libraries a browser bundle inlines.
|
||||
* identity to share — the framework itself is a requested module-table row
|
||||
* (external), while these are ordinary libraries a browser bundle inlines.
|
||||
*/
|
||||
const VENDORED_LIBRARY = /^@deepseek-ai\\/(cosmokit|schemastery)(\\/|$)/
|
||||
|
||||
@@ -405,8 +431,8 @@ const VENDORED_LIBRARY = /^@deepseek-ai\\/(cosmokit|schemastery)(\\/|$)/
|
||||
expect: 1,
|
||||
},
|
||||
{
|
||||
// The framework peer is no longer a registry name, so the rehearsal must install this
|
||||
// repository's vendored copies; cosmokit comes along as cordis's own dependency.
|
||||
// The framework peer is a rescoped package, so the rehearsal installs this
|
||||
// repository's vendored copies; cosmokit arrives as cordis's dependency.
|
||||
id: 'packed-install-vendored-peer',
|
||||
file: 'packages/sandbox/sandbox-local/tests/packed-install.e2e.ts',
|
||||
find: ` 'packages/runtime-diagnostics/invariants',
|
||||
@@ -523,7 +549,7 @@ function rewriteLine(line: string, file: string, all: readonly Pattern[]): strin
|
||||
* Markdown splits in two. Every fence is code a reader copies or a
|
||||
* configuration they mount, so every fence follows the rename regardless of its
|
||||
* info string. Prose follows it only under `docs/`, where a sentence quoting
|
||||
* `` `cordis` `` teaches a name this repository no longer resolves; elsewhere
|
||||
* `` `cordis` `` teaches an unresolved package name; elsewhere
|
||||
* prose is a record of what was true when it was written, and the same spelling
|
||||
* can mean something else entirely — the Python SDK's `cordis` option, or the
|
||||
* unvendored `@cordisjs/plugin-http`.
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/** CLI entry for partitioned Vitest coverage. */
|
||||
import { resolve } from 'node:path'
|
||||
import {
|
||||
COVERAGE_PARTITIONS_ENV,
|
||||
COVERAGE_TEST_TIMEOUT_ENV,
|
||||
CoveragePartitionCoordinator,
|
||||
coverageTestTimeoutArgs,
|
||||
forwardedCoverageArgs,
|
||||
parseCoveragePartitionCount,
|
||||
} from './coverage-partitions.ts'
|
||||
|
||||
const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV])
|
||||
if (partitions === undefined) {
|
||||
throw new Error(`${COVERAGE_PARTITIONS_ENV} is required by partitioned coverage.`)
|
||||
}
|
||||
const pnpmEntrypoint = process.env.npm_execpath
|
||||
if (pnpmEntrypoint === undefined || pnpmEntrypoint === '') {
|
||||
throw new Error('partitioned coverage must be invoked through a pnpm package script.')
|
||||
}
|
||||
|
||||
const coordinator = new CoveragePartitionCoordinator({
|
||||
root: resolve(import.meta.dirname, '..'),
|
||||
partitions,
|
||||
pnpmEntrypoint,
|
||||
vitestArgs: [
|
||||
...coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV]),
|
||||
...forwardedCoverageArgs(process.argv.slice(2)),
|
||||
],
|
||||
})
|
||||
process.exitCode = await coordinator.run()
|
||||
+164
-7
@@ -31,9 +31,9 @@ function resultFor(subject: Gate, status: GateResult['status'] = 'passed'): Gate
|
||||
}
|
||||
}
|
||||
|
||||
function withPnpmEntrypoint<T>(action: () => T): T {
|
||||
function withPnpmEntrypoint<T>(action: () => T, entrypoint = '/private/pnpm.cjs'): T {
|
||||
const previous = process.env.npm_execpath
|
||||
process.env.npm_execpath = '/private/pnpm.cjs'
|
||||
process.env.npm_execpath = entrypoint
|
||||
try {
|
||||
return action()
|
||||
} finally {
|
||||
@@ -69,6 +69,7 @@ describe('gate graph validation', () => {
|
||||
'ci-windows-observational',
|
||||
'node-compat',
|
||||
'check-all',
|
||||
'hygiene',
|
||||
'doc-sync',
|
||||
] as const)('constructs and executes preflight for a valid non-empty %s graph', async (mode) => {
|
||||
const subject = withPnpmEntrypoint(() => gatesForMode(mode))
|
||||
@@ -83,6 +84,40 @@ describe('gate graph validation', () => {
|
||||
expect(ids).toContain('public-repository-links')
|
||||
})
|
||||
|
||||
it('keeps the hygiene aggregate aligned with the package script checks', () => {
|
||||
const ids = withPnpmEntrypoint(() => gatesForMode('hygiene').map(subject => subject.id))
|
||||
|
||||
expect(ids).toEqual([
|
||||
'rescope-vendor', 'knip', 'publint', 'constraints', 'application-entrypoints',
|
||||
'dsh-package-licenses', 'package-invariants', 'built-package-invariants', 'node-next-types',
|
||||
'optional-dependency-imports', 'client-packages', 'cordis-config',
|
||||
'runtime-closure', 'vendored-links',
|
||||
])
|
||||
expect(defaultConcurrency('hygiene', ids.length, 8)).toEqual({
|
||||
workers: 4,
|
||||
source: '8 available CPU(s), hygiene cap 4',
|
||||
})
|
||||
})
|
||||
|
||||
it('schedules the longest documentation leaves before short checks', () => {
|
||||
const ids = withPnpmEntrypoint(() => gatesForMode('doc-sync').map(subject => subject.id))
|
||||
|
||||
expect(ids.slice(0, 10)).toEqual([
|
||||
'doc-typecheck', 'docs-site-build', 'doc-graphs', 'markdown-links', 'type-equivalence',
|
||||
'cordis-catalog', 'mermaid', 'scoped-events', 'translation-pairing', 'markdown-wrap',
|
||||
])
|
||||
})
|
||||
|
||||
it('launches a native pnpm entrypoint directly', () => {
|
||||
const entrypoint = String.raw`C:\Program Files\pnpm\pnpm.exe`
|
||||
const subject = withPnpmEntrypoint(() => gatesForMode('ci-windows-blocking')[0], entrypoint)
|
||||
|
||||
expect(subject).toMatchObject({
|
||||
command: entrypoint,
|
||||
args: ['run', 'build'],
|
||||
})
|
||||
})
|
||||
|
||||
it.each(['ci-primary', 'ci-static', 'check-all'] as const)(
|
||||
'keeps the DSH package license policy in %s',
|
||||
(mode) => {
|
||||
@@ -92,20 +127,97 @@ describe('gate graph validation', () => {
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps native Windows coverage blocking while portability inventory remains observational', () => {
|
||||
const gates = withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))
|
||||
const byId = new Map(gates.map(subject => [subject.id, subject]))
|
||||
it.each(['ci-primary', 'ci-static', 'check-all'] as const)(
|
||||
'keeps the client dependency policy in %s',
|
||||
(mode) => {
|
||||
const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
|
||||
|
||||
expect(ids).toContain('client-packages')
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
|
||||
'keeps application entrypoint enforcement in %s',
|
||||
(mode) => {
|
||||
const ids = withPnpmEntrypoint(() => gatesForMode(mode).map(subject => subject.id))
|
||||
|
||||
expect(ids).toContain('application-entrypoints')
|
||||
},
|
||||
)
|
||||
|
||||
it('keeps native Windows coverage blocking while retaining the observational inventory', () => {
|
||||
const complete = withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))
|
||||
const observational = withPnpmEntrypoint(() => gatesForMode('ci-windows-observational'))
|
||||
.filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
|
||||
const byId = new Map(complete.map(subject => [subject.id, subject]))
|
||||
|
||||
expect(byId.get('coverage')?.allowFailure).not.toBe(true)
|
||||
expect(byId.get('coverage-exempt-heavy')?.allowFailure).not.toBe(true)
|
||||
expect(byId.get('duplication')?.allowFailure).toBe(true)
|
||||
expect(byId.get('coverage-exempt-heavy')?.needs).toContain('build')
|
||||
expect(byId.get('coverage-exempt-heavy')?.after).toContain('coverage')
|
||||
expect(observational).not.toHaveLength(0)
|
||||
for (const gate of observational) {
|
||||
const completeGate = byId.get(gate.id)
|
||||
expect(completeGate?.allowFailure).toBe(true)
|
||||
expect(completeGate?.after).toContain('coverage')
|
||||
expect(completeGate?.after).not.toContain('coverage-exempt-heavy')
|
||||
expect(completeGate?.needs).toEqual(gate.needs)
|
||||
}
|
||||
})
|
||||
|
||||
it('applies one configured test and polling timeout to both coverage gates', () => {
|
||||
const gates = withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', '15000', () =>
|
||||
withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))
|
||||
|
||||
for (const id of ['coverage', 'coverage-exempt-heavy']) {
|
||||
expect(gates.find(subject => subject.id === id)?.args).toEqual(expect.arrayContaining([
|
||||
'--testTimeout=15000',
|
||||
'--expect.poll.timeout=15000',
|
||||
]))
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps Vitest timeout defaults when the coverage override is absent', () => {
|
||||
const gates = withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', undefined, () =>
|
||||
withPnpmEntrypoint(() => gatesForMode('ci-windows-complete')))
|
||||
|
||||
for (const id of ['coverage', 'coverage-exempt-heavy']) {
|
||||
expect(gates.find(subject => subject.id === id)?.args).not.toEqual(expect.arrayContaining([
|
||||
expect.stringMatching(/^--(?:testTimeout|expect\.poll\.timeout)=/),
|
||||
]))
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an invalid coverage timeout before starting a gate', () => {
|
||||
expect(() => withEnv('DSH_COVERAGE_TEST_TIMEOUT_MS', '0', () =>
|
||||
withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))))
|
||||
.toThrow('DSH_COVERAGE_TEST_TIMEOUT_MS must be a positive integer')
|
||||
})
|
||||
|
||||
it('selects partitioned coverage only when explicitly configured', () => {
|
||||
const coverage = withEnv('DSH_COVERAGE_PARTITIONS', '3', () =>
|
||||
withPnpmEntrypoint(() => gatesForMode('ci-windows-complete').find(subject => subject.id === 'coverage')))
|
||||
|
||||
expect(coverage).toMatchObject({
|
||||
displayCommand: 'DSH_COVERAGE_PARTITIONS=3 pnpm run test:coverage:partitioned',
|
||||
args: ['/private/pnpm.cjs', 'run', 'test:coverage:partitioned'],
|
||||
streamOutput: true,
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects an invalid coverage partition count before starting a gate', () => {
|
||||
expect(() => withEnv('DSH_COVERAGE_PARTITIONS', '1', () =>
|
||||
withPnpmEntrypoint(() => gatesForMode('ci-windows-complete'))))
|
||||
.toThrow('DSH_COVERAGE_PARTITIONS must be an integer greater than 1')
|
||||
})
|
||||
|
||||
it.each([
|
||||
['empty', [], /gate graph has no gates/],
|
||||
['duplicate ids', [gate('same'), gate('same')], /duplicate gate id "same"/],
|
||||
['unknown dependencies', [gate('subject', { needs: ['missing'] })], /depends on unknown gate "missing"/],
|
||||
['unknown ordering predecessors', [gate('subject', { after: ['missing'] })], /waits for unknown gate "missing"/],
|
||||
['cycles', [gate('first', { needs: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/],
|
||||
['mixed cycles', [gate('first', { after: ['second'] }), gate('second', { needs: ['first'] })], /dependency cycle: first -> second -> first/],
|
||||
] as const)('rejects %s before starting a child', async (_label, invalid, message) => {
|
||||
const execute = vi.fn(async (subject: Gate) => resultFor(subject))
|
||||
|
||||
@@ -131,6 +243,29 @@ describe('gate graph validation', () => {
|
||||
expect(execute).toHaveBeenCalledWith(root)
|
||||
expect(results[0]).toMatchObject({ gate: dependent, status: 'skipped', error: 'dependency failed or skipped: root' })
|
||||
})
|
||||
|
||||
it('runs an ordered follower after its predecessor fails', async () => {
|
||||
const follower = gate('follower', { after: ['root'] })
|
||||
const root = gate('root')
|
||||
const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed'))
|
||||
|
||||
const results = await runGates([follower, root], 2, execute)
|
||||
|
||||
expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower'])
|
||||
expect(results.map(result => result.status)).toEqual(['passed', 'failed'])
|
||||
})
|
||||
|
||||
it('runs an ordered follower after its predecessor is skipped', async () => {
|
||||
const follower = gate('follower', { after: ['dependent'] })
|
||||
const dependent = gate('dependent', { needs: ['root'] })
|
||||
const root = gate('root')
|
||||
const execute = vi.fn(async (subject: Gate) => resultFor(subject, subject === root ? 'failed' : 'passed'))
|
||||
|
||||
const results = await runGates([follower, dependent, root], 2, execute)
|
||||
|
||||
expect(execute.mock.calls.map(([subject]) => subject.id)).toEqual(['root', 'follower'])
|
||||
expect(results.map(result => result.status)).toEqual(['passed', 'skipped', 'failed'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('Oxlint gate', () => {
|
||||
@@ -252,7 +387,13 @@ describe('Node 24 lane ownership', () => {
|
||||
'built-bin-smoke',
|
||||
])
|
||||
expect(subject.find(item => item.id === 'publint')?.needs).toEqual(['build'])
|
||||
expect(subject.find(item => item.id === 'built-package-invariants')?.needs).toEqual(['publint'])
|
||||
expect(subject.find(item => item.id === 'build')?.env).toEqual({
|
||||
DSH_BUILD_CLIENT_PROFILE: 'official',
|
||||
})
|
||||
expect(subject.find(item => item.id === 'node-compat')?.env).toEqual({
|
||||
DSH_BUILD_CLIENT_PROFILE: 'official',
|
||||
})
|
||||
expect(subject.find(item => item.id === 'built-package-invariants')?.needs).toEqual(['build'])
|
||||
expect(subject.find(item => item.id === 'lint-and-duplication')?.needs).toEqual(['built-package-invariants'])
|
||||
for (const id of [
|
||||
'snapshot',
|
||||
@@ -294,6 +435,22 @@ describe('Linux primary graph', () => {
|
||||
})
|
||||
|
||||
describe('gate process outcomes', () => {
|
||||
it('streams selected gate output without retaining it', async () => {
|
||||
const write = vi.spyOn(process.stdout, 'write').mockReturnValue(true)
|
||||
try {
|
||||
const result = await runGate(gate('streamed', {
|
||||
args: ['-e', "process.stdout.write('live output')"],
|
||||
streamOutput: true,
|
||||
}))
|
||||
|
||||
expect(result.status).toBe('passed')
|
||||
expect(result.output).toEqual([])
|
||||
expect(write).toHaveBeenCalledWith('live output')
|
||||
} finally {
|
||||
write.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')('reports signal termination independently from exit status', async () => {
|
||||
const result = await runGate(gate('terminated', {
|
||||
args: ['-e', "process.kill(process.pid, 'SIGTERM')"],
|
||||
|
||||
+155
-73
@@ -9,7 +9,15 @@ import { spawn } from 'node:child_process'
|
||||
import { availableParallelism } from 'node:os'
|
||||
import { resolve } from 'node:path'
|
||||
import { performance } from 'node:perf_hooks'
|
||||
import { CLIENT_BUILD_PROFILE_SELECTOR } from './client-build-environment.ts'
|
||||
import { COVERAGE_EXEMPT_ENV, coverageExemptHeavySuites } from './coverage-exempt.ts'
|
||||
import {
|
||||
COVERAGE_PARTITIONS_ENV,
|
||||
COVERAGE_TEST_TIMEOUT_ENV,
|
||||
coverageTestTimeoutArgs,
|
||||
parseCoveragePartitionCount,
|
||||
} from './coverage-partitions.ts'
|
||||
import { pnpmInvocation } from './pnpm-invocation.ts'
|
||||
|
||||
/** A named aggregate exposed by the gate runner. */
|
||||
export type Mode =
|
||||
@@ -26,6 +34,7 @@ export type Mode =
|
||||
| 'ci-windows-observational'
|
||||
| 'node-compat'
|
||||
| 'check-all'
|
||||
| 'hygiene'
|
||||
| 'doc-sync'
|
||||
|
||||
type GateResultStatus = 'passed' | 'failed' | 'skipped'
|
||||
@@ -39,8 +48,13 @@ export interface Gate {
|
||||
command: string
|
||||
args: string[]
|
||||
needs?: string[]
|
||||
/** Gate ids that must settle, regardless of outcome, before this gate starts. */
|
||||
after?: string[]
|
||||
env?: Record<string, string | undefined>
|
||||
/** Keep a failure visible without failing the aggregate. */
|
||||
allowFailure?: boolean
|
||||
/** Write child output as it arrives instead of buffering it until completion. */
|
||||
streamOutput?: boolean
|
||||
}
|
||||
|
||||
/** The observed outcome of one gate process. */
|
||||
@@ -111,11 +125,12 @@ function parseMode(raw: string | undefined): Mode {
|
||||
case 'ci-windows-observational':
|
||||
case 'node-compat':
|
||||
case 'check-all':
|
||||
case 'hygiene':
|
||||
case 'doc-sync':
|
||||
return raw
|
||||
default:
|
||||
throw new Error(
|
||||
`run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-snapshot | ci-artifacts | ci-consumers | ci-windows-blocking | ci-windows-complete | ci-windows-observational | node-compat | check-all | doc-sync, got ${JSON.stringify(raw)}.`,
|
||||
`run-gates: expected mode ci-primary | ci-linux-primary | ci-static | ci-lint-contracts-ready | ci-coverage | ci-snapshot | ci-artifacts | ci-consumers | ci-windows-blocking | ci-windows-complete | ci-windows-observational | node-compat | check-all | hygiene | doc-sync, got ${JSON.stringify(raw)}.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -135,7 +150,7 @@ export function defaultConcurrency(
|
||||
if (selectedMode === 'ci-consumers') return { workers: total, source: 'ci-consumers gate count' }
|
||||
// Local modes cap workers: several doc gates each build a full ts.Program,
|
||||
// so an uncapped default on a large host trades wall clock for memory blowups.
|
||||
const localCap = selectedMode === 'check-all' || selectedMode === 'doc-sync'
|
||||
const localCap = selectedMode === 'check-all' || selectedMode === 'hygiene' || selectedMode === 'doc-sync'
|
||||
const modeLimit = localCap ? Math.min(4, available) : available
|
||||
return {
|
||||
workers: Math.min(total, modeLimit),
|
||||
@@ -165,6 +180,14 @@ function pnpmScript(id: string, script: string, options: Partial<Gate> = {}): Ga
|
||||
}
|
||||
}
|
||||
|
||||
/** Build official client artifacts inside a CI aggregate without changing sibling gate environments. */
|
||||
function ciBuildGate(id = 'build', options: Partial<Gate> = {}): Gate {
|
||||
return pnpmScript(id, 'build', {
|
||||
...options,
|
||||
env: { ...options.env, [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
|
||||
})
|
||||
}
|
||||
|
||||
function pnpmExec(id: string, args: string[], options: Partial<Gate> = {}): Gate {
|
||||
return {
|
||||
id,
|
||||
@@ -175,15 +198,6 @@ function pnpmExec(id: string, args: string[], options: Partial<Gate> = {}): Gate
|
||||
}
|
||||
}
|
||||
|
||||
function pnpmInvocation(args: string[]): Pick<Gate, 'command' | 'args'> {
|
||||
const entrypoint = process.env.npm_execpath
|
||||
if (entrypoint === undefined || entrypoint === '') {
|
||||
throw new Error('run-gates: npm_execpath is unavailable; invoke the runner through a pnpm package script.')
|
||||
}
|
||||
// Windows cannot spawn the pnpm.cmd shim directly; the JavaScript entrypoint keeps every host shell-free.
|
||||
return { command: process.execPath, args: [entrypoint, ...args] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct the complete gate list for a named aggregate.
|
||||
* @param selected - aggregate mode to construct.
|
||||
@@ -205,7 +219,7 @@ export function gatesForMode(selected: Mode): Gate[] {
|
||||
case 'ci-coverage':
|
||||
return coverageGates()
|
||||
case 'ci-snapshot':
|
||||
return [pnpmScript('build', 'build'), snapshotGate()]
|
||||
return [ciBuildGate(), snapshotGate()]
|
||||
case 'ci-artifacts':
|
||||
return ciArtifactGates()
|
||||
case 'ci-consumers':
|
||||
@@ -237,6 +251,13 @@ export function gatesForMode(selected: Mode): Gate[] {
|
||||
}),
|
||||
pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
|
||||
]
|
||||
case 'hygiene':
|
||||
return [
|
||||
...hygieneLeafGates(),
|
||||
pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
|
||||
pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
|
||||
pnpmScript('vendored-links', 'verify-vendored-links', { label: 'vendored links' }),
|
||||
]
|
||||
case 'doc-sync':
|
||||
return docSyncLeafGates()
|
||||
}
|
||||
@@ -245,10 +266,15 @@ export function gatesForMode(selected: Mode): Gate[] {
|
||||
function ciSharedStaticGates(): Gate[] {
|
||||
return [
|
||||
pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
|
||||
pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
|
||||
pnpmScript('constraints', 'constraints'),
|
||||
pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
|
||||
pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
|
||||
pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
|
||||
pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
|
||||
label: 'optional dependency imports',
|
||||
}),
|
||||
pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
|
||||
pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
|
||||
]
|
||||
}
|
||||
@@ -272,7 +298,7 @@ function ciPrimaryGates(): Gate[] {
|
||||
// The prepared typecheck and build both drive Client tsc, while build also
|
||||
// repeats the Host contract pass. Wait for all three consumers so build
|
||||
// neither races tsbuildinfo nor replaces declarations while they are read.
|
||||
pnpmScript('build', 'build', { needs: ['typecheck', 'lint', 'doc-typecheck'] }),
|
||||
ciBuildGate('build', { needs: ['typecheck', 'lint', 'doc-typecheck'] }),
|
||||
pnpmScript('publint', 'publint', { needs: ['build'] }),
|
||||
pnpmScript('node-next-types', 'verify-node-next-types', {
|
||||
label: 'node-next types',
|
||||
@@ -354,7 +380,7 @@ function runningNodeMajor(): number {
|
||||
function ciStaticGates(options: { ownsBuild: boolean }): Gate[] {
|
||||
return [
|
||||
...ciSharedStaticGates(),
|
||||
...options.ownsBuild ? [pnpmScript('build', 'build')] : [],
|
||||
...options.ownsBuild ? [ciBuildGate()] : [],
|
||||
...docSyncLeafGates({
|
||||
includeDocTypecheck: options.ownsBuild,
|
||||
...options.ownsBuild
|
||||
@@ -373,7 +399,7 @@ function ciStaticGates(options: { ownsBuild: boolean }): Gate[] {
|
||||
|
||||
function ciArtifactGates(): Gate[] {
|
||||
return [
|
||||
pnpmScript('build', 'build'),
|
||||
ciBuildGate(),
|
||||
pnpmScript('publint', 'publint', { needs: ['build'] }),
|
||||
pnpmScript('node-next-types', 'verify-node-next-types', {
|
||||
label: 'node-next types',
|
||||
@@ -388,10 +414,13 @@ function ciConsumerGates(): Gate[] {
|
||||
const builtTree = ['build']
|
||||
const validatedBuild = ['built-package-invariants']
|
||||
return [
|
||||
pnpmScript('build', 'build'),
|
||||
pnpmScript('node-compat', 'check:node-compat', { label: 'Node compatibility' }),
|
||||
ciBuildGate(),
|
||||
pnpmScript('node-compat', 'check:node-compat', {
|
||||
label: 'Node compatibility',
|
||||
env: { [CLIENT_BUILD_PROFILE_SELECTOR]: 'official' },
|
||||
}),
|
||||
pnpmScript('publint', 'publint', { needs: builtTree }),
|
||||
builtPackageInvariantsGate(['publint']),
|
||||
builtPackageInvariantsGate(builtTree),
|
||||
pnpmScript('lint-and-duplication', 'check:ci:lint:contracts-ready', {
|
||||
label: 'lint and duplication',
|
||||
needs: validatedBuild,
|
||||
@@ -411,6 +440,20 @@ function ciConsumerGates(): Gate[] {
|
||||
}
|
||||
|
||||
function webSnapshotGate(needs: string[]): Gate {
|
||||
const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS
|
||||
if (workerRaw !== undefined && workerRaw !== '') {
|
||||
const workers = Number.parseInt(workerRaw, 10)
|
||||
if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) {
|
||||
throw new Error(`run-gates: DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`)
|
||||
}
|
||||
return pnpmScript('web-snapshot', 'test:web:ci', {
|
||||
label: 'web browser snapshot',
|
||||
displayCommand: `DSH_SNAPSHOT=replay DSH_WEB_SNAPSHOT_WORKERS=${workers} pnpm run test:web:ci`,
|
||||
env: { DSH_SNAPSHOT: 'replay' },
|
||||
needs,
|
||||
streamOutput: true,
|
||||
})
|
||||
}
|
||||
return pnpmScript('web-snapshot', 'test:web:built', {
|
||||
label: 'web browser snapshot',
|
||||
displayCommand: 'DSH_SNAPSHOT=replay pnpm run test:web:built',
|
||||
@@ -421,21 +464,32 @@ function webSnapshotGate(needs: string[]): Gate {
|
||||
|
||||
function ciWindowsBlockingGates(): Gate[] {
|
||||
return [
|
||||
pnpmScript('windows-build', 'build', { label: 'build' }),
|
||||
ciBuildGate('windows-build', { label: 'build' }),
|
||||
pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
|
||||
]
|
||||
}
|
||||
|
||||
function ciWindowsCompleteGates(): Gate[] {
|
||||
const coverage = coverageGates().map(gate => gate.id === 'coverage-exempt-heavy'
|
||||
? {
|
||||
...gate,
|
||||
needs: [...new Set(['build', ...(gate.needs ?? [])])],
|
||||
after: [...new Set(['coverage', ...(gate.after ?? [])])],
|
||||
}
|
||||
: gate)
|
||||
const observational = ciWindowsObservationalGates()
|
||||
// The required production site replaces the observational MPA build; both
|
||||
// VitePress modes write the same output directory and cannot overlap.
|
||||
.filter(gate => gate.id !== 'build' && gate.id !== 'docs-site-build')
|
||||
.map(gate => ({ ...gate, allowFailure: true }))
|
||||
.map(gate => ({
|
||||
...gate,
|
||||
allowFailure: true,
|
||||
after: [...new Set(['coverage', ...(gate.after ?? [])])],
|
||||
}))
|
||||
return [
|
||||
pnpmScript('build', 'build'),
|
||||
ciBuildGate(),
|
||||
pnpmScript('windows-site', 'docs:build', { label: 'production site' }),
|
||||
...coverageGates(),
|
||||
...coverage,
|
||||
...observational,
|
||||
]
|
||||
}
|
||||
@@ -475,13 +529,17 @@ function lintGate(options: { needs?: string[] } = {}): Gate {
|
||||
// under v8 instrumentation while contributing nothing the thresholds need
|
||||
// (membership rules in scripts/coverage-exempt.ts).
|
||||
//
|
||||
// DSH_COVERAGE_MAX_WORKERS is the lane's worker budget, so the two parallel
|
||||
// gates split it instead of each claiming it whole (the failover pool's
|
||||
// 8 x 6-instance bound assumes one lane never exceeds its value). The exempt
|
||||
// DSH_COVERAGE_MAX_WORKERS is the ordinary lane's worker budget, so the two
|
||||
// parallel gates split it instead of each claiming it whole. When
|
||||
// DSH_COVERAGE_PARTITIONS is set, its single-worker processes replace the
|
||||
// instrumented share while this budget still sizes the exempt gate. The exempt
|
||||
// gate's wall clock is dominated by its longest single file, so it takes the
|
||||
// small share. A budget of 1 gives each gate 1 worker; lanes that need a
|
||||
// strict total of one (the serial reference jobs) also set
|
||||
// DSH_GATE_CONCURRENCY=1, which keeps the gates from overlapping at all.
|
||||
// small share. A budget of 1 gives each gate 1 worker; lanes that need a strict
|
||||
// total of one (the serial reference jobs) also set DSH_GATE_CONCURRENCY=1,
|
||||
// which keeps the gates from overlapping at all.
|
||||
// DSH_COVERAGE_TEST_TIMEOUT_MS raises Vitest's per-test and expect.poll
|
||||
// defaults together for instrumented lanes whose scheduling overhead exceeds
|
||||
// those defaults. Explicit fixture timeouts remain authoritative.
|
||||
function coverageWorkerArgs(): { instrumented: string[]; exempt: string[] } {
|
||||
const [flag] = positiveIntArg('DSH_COVERAGE_MAX_WORKERS', '--maxWorkers')
|
||||
if (flag === undefined) return { instrumented: [], exempt: [] }
|
||||
@@ -496,21 +554,33 @@ function coverageWorkerArgs(): { instrumented: string[]; exempt: string[] } {
|
||||
|
||||
function coverageGates(): Gate[] {
|
||||
const workers = coverageWorkerArgs()
|
||||
return [
|
||||
pnpmExec('coverage', [
|
||||
const timeouts = coverageTestTimeoutArgs(process.env[COVERAGE_TEST_TIMEOUT_ENV])
|
||||
const partitions = parseCoveragePartitionCount(process.env[COVERAGE_PARTITIONS_ENV])
|
||||
const instrumented = partitions === undefined
|
||||
? pnpmExec('coverage', [
|
||||
'vitest',
|
||||
'run',
|
||||
'--coverage',
|
||||
...workers.instrumented,
|
||||
...timeouts,
|
||||
], {
|
||||
label: 'test:coverage',
|
||||
env: { [COVERAGE_EXEMPT_ENV]: '1' },
|
||||
}),
|
||||
})
|
||||
: pnpmScript('coverage', 'test:coverage:partitioned', {
|
||||
label: 'test:coverage',
|
||||
displayCommand: `${COVERAGE_PARTITIONS_ENV}=${partitions} pnpm run test:coverage:partitioned`,
|
||||
env: { [COVERAGE_EXEMPT_ENV]: '1' },
|
||||
streamOutput: true,
|
||||
})
|
||||
return [
|
||||
instrumented,
|
||||
pnpmExec('coverage-exempt-heavy', [
|
||||
'vitest',
|
||||
'run',
|
||||
...coverageExemptHeavySuites.map(suite => suite.filter),
|
||||
...workers.exempt,
|
||||
...timeouts,
|
||||
], {
|
||||
label: 'test:coverage-exempt-heavy',
|
||||
}),
|
||||
@@ -558,6 +628,7 @@ function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
|
||||
pnpmScript('knip', 'knip'),
|
||||
pnpmScript('publint', 'publint', artifactOptions),
|
||||
pnpmScript('constraints', 'constraints'),
|
||||
pnpmScript('application-entrypoints', 'verify-application-entrypoints', { label: 'application entrypoints' }),
|
||||
pnpmScript('dsh-package-licenses', 'verify-dsh-package-licenses', { label: 'DSH package licenses' }),
|
||||
pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
|
||||
builtPackageInvariantsGate(options.artifactNeeds),
|
||||
@@ -565,6 +636,10 @@ function hygieneLeafGates(options: { artifactNeeds?: string[] } = {}): Gate[] {
|
||||
label: 'node-next types',
|
||||
...artifactOptions,
|
||||
}),
|
||||
pnpmScript('optional-dependency-imports', 'verify-optional-dependency-imports', {
|
||||
label: 'optional dependency imports',
|
||||
}),
|
||||
pnpmScript('client-packages', 'verify-client-packages', { label: 'client packages' }),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -579,38 +654,38 @@ function docSyncLeafGates(options: {
|
||||
if (options.docTypecheckNeeds !== undefined) docTypecheckOptions.needs = options.docTypecheckNeeds
|
||||
if (options.docTypecheckEnv !== undefined) docTypecheckOptions.env = options.docTypecheckEnv
|
||||
return [
|
||||
// Stable FIFO starts the longest leaves first; only docs-site-build writes website/.generated.
|
||||
...options.includeDocTypecheck === false
|
||||
? []
|
||||
: [pnpmScript('doc-typecheck', options.docTypecheckScript ?? 'doc-typecheck', docTypecheckOptions)],
|
||||
pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
|
||||
pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
|
||||
pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
|
||||
pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
|
||||
pnpmScript('cordis-catalog', 'verify-cordis-catalog', { label: 'cordis catalog' }),
|
||||
pnpmScript('mermaid', 'verify-mermaid'),
|
||||
pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
|
||||
pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
|
||||
pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
|
||||
pnpmScript('client-catalog', 'verify-client-catalog', { label: 'client catalog' }),
|
||||
pnpmScript('export-jsdoc', 'verify-export-jsdoc', { label: 'export jsdoc' }),
|
||||
pnpmScript('tool-catalog', 'verify-tool-catalog', { label: 'tool catalog' }),
|
||||
pnpmScript('config-catalog', 'verify-config-catalog', { label: 'config catalog' }),
|
||||
pnpmScript('persistence-catalog', 'verify-persistence-catalog', { label: 'persistence catalog' }),
|
||||
pnpmScript('doc-graphs', 'verify-doc-graphs', { label: 'doc graphs' }),
|
||||
pnpmScript('scoped-events', 'verify-scoped-events', { label: 'scoped events' }),
|
||||
pnpmScript('markdown-wrap', 'verify-md-wrap', { label: 'markdown wrap' }),
|
||||
pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
|
||||
pnpmScript('public-repository-links', 'verify-public-repository-links', { label: 'public repository links' }),
|
||||
pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
|
||||
pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
|
||||
pnpmScript('config-source-ownership', 'verify-config-source-ownership', { label: 'config source ownership' }),
|
||||
pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
|
||||
pnpmScript('mermaid', 'verify-mermaid'),
|
||||
pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
|
||||
pnpmScript('agent-note-format', 'verify-agent-note-format', { label: 'agent note format' }),
|
||||
pnpmScript('archived-agent-notes', 'verify-archived-agent-notes', { label: 'archived agent notes' }),
|
||||
pnpmScript('type-equivalence', 'verify-type-equiv', { label: 'type equivalence' }),
|
||||
pnpmScript('skill-invocation-metadata', 'verify-skill-invocation-metadata', { label: 'skill invocation metadata' }),
|
||||
pnpmScript('translation-prompt', 'verify-translation-prompt', { label: 'translation prompt' }),
|
||||
pnpmScript('translation-pairing', 'verify-translation-pairing', { label: 'translation pairing' }),
|
||||
pnpmScript('doc-budgets', 'verify-doc-budgets', { label: 'doc budgets' }),
|
||||
pnpmExec('docs-site-projection', ['vitest', 'run', 'scripts/project-doc-site.spec.ts', 'scripts/verify-doc-site-fragments.spec.ts'], {
|
||||
label: 'documentation site checks',
|
||||
}),
|
||||
// Keep the VitePress build itself in one gate because projection rewrites website/.generated.
|
||||
pnpmScript('docs-site-build', options.docsBuildScript ?? 'docs:build', { label: 'documentation build' }),
|
||||
pnpmScript('package-readme-limitations', 'verify-package-readme-limitations', { label: 'package README limitations' }),
|
||||
]
|
||||
}
|
||||
@@ -623,7 +698,6 @@ function builtBinSmokeGate(needs: string[] = ['build']): Gate {
|
||||
'vitest.e2e.config.ts',
|
||||
'examples/headless-agent/tests/keyless-smoke.e2e.ts',
|
||||
'apps/cli/tests/built-bin.e2e.ts',
|
||||
'packages/examples/acp-demo/tests/built-bin.e2e.ts',
|
||||
'packages/host/directory-picker-native/tests/built-worker.e2e.ts',
|
||||
'packages/sdk/server/tests/built-scope-carrier.e2e.ts',
|
||||
'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
|
||||
@@ -660,6 +734,11 @@ function validateGateGraph(gates: readonly Gate[]): void {
|
||||
throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} depends on unknown gate ${JSON.stringify(dependency)}.`)
|
||||
}
|
||||
}
|
||||
for (const predecessor of gate.after ?? []) {
|
||||
if (!ids.has(predecessor)) {
|
||||
throw new Error(`run-gates: gate ${JSON.stringify(gate.id)} waits for unknown gate ${JSON.stringify(predecessor)}.`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cycle = findDependencyCycle(gates)
|
||||
@@ -681,8 +760,8 @@ function findDependencyCycle(gates: readonly Gate[]): string[] | undefined {
|
||||
|
||||
active.set(id, path.length)
|
||||
path.push(id)
|
||||
for (const dependency of gate.needs ?? []) {
|
||||
const cycle = visit(dependency)
|
||||
for (const predecessor of [...(gate.needs ?? []), ...(gate.after ?? [])]) {
|
||||
const cycle = visit(predecessor)
|
||||
if (cycle !== undefined) return cycle
|
||||
}
|
||||
path.pop()
|
||||
@@ -723,7 +802,7 @@ export async function runGates(
|
||||
for (;;) {
|
||||
let madeProgress = false
|
||||
while (running.length < maxActive) {
|
||||
const ready = gates.find(gate => states.get(gate.id) === 'pending' && dependenciesPassed(gate, states))
|
||||
const ready = gates.find(gate => states.get(gate.id) === 'pending' && predecessorsReady(gate, states))
|
||||
if (ready === undefined) break
|
||||
states.set(ready.id, 'running')
|
||||
running.push({ gate: ready, promise: execute(ready) })
|
||||
@@ -732,32 +811,24 @@ export async function runGates(
|
||||
}
|
||||
|
||||
if (running.length === 0) {
|
||||
let pending = gates.filter(gate => states.get(gate.id) === 'pending')
|
||||
while (pending.length > 0) {
|
||||
const gate = pending.find(item => (item.needs ?? []).some((id) => {
|
||||
const state = states.get(id)
|
||||
return state === 'failed' || state === 'skipped'
|
||||
}))
|
||||
if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
|
||||
const failedDeps = (gate.needs ?? []).filter((id) => {
|
||||
const state = states.get(id)
|
||||
return state === 'failed' || state === 'skipped'
|
||||
})
|
||||
const result: GateResult = {
|
||||
gate,
|
||||
status: 'skipped',
|
||||
durationMs: 0,
|
||||
output: [],
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
|
||||
}
|
||||
states.set(gate.id, 'skipped')
|
||||
results.set(gate.id, result)
|
||||
observe(result)
|
||||
pending = pending.filter(item => item !== gate)
|
||||
const pending = gates.filter(gate => states.get(gate.id) === 'pending')
|
||||
if (pending.length === 0) break
|
||||
const gate = pending.find(item => (item.needs ?? []).some(id => gateFailed(states.get(id))))
|
||||
if (gate === undefined) throw new Error('run-gates: validated graph stalled without a failed dependency.')
|
||||
const failedDeps = (gate.needs ?? []).filter(id => gateFailed(states.get(id)))
|
||||
const result: GateResult = {
|
||||
gate,
|
||||
status: 'skipped',
|
||||
durationMs: 0,
|
||||
output: [],
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
error: `dependency failed or skipped: ${failedDeps.join(', ')}`,
|
||||
}
|
||||
break
|
||||
states.set(gate.id, 'skipped')
|
||||
results.set(gate.id, result)
|
||||
observe(result)
|
||||
continue
|
||||
}
|
||||
|
||||
if (!madeProgress) {
|
||||
@@ -776,8 +847,17 @@ export async function runGates(
|
||||
})
|
||||
}
|
||||
|
||||
function dependenciesPassed(gate: Gate, states: Map<string, GateState>): boolean {
|
||||
function predecessorsReady(gate: Gate, states: Map<string, GateState>): boolean {
|
||||
return (gate.needs ?? []).every(id => states.get(id) === 'passed')
|
||||
&& (gate.after ?? []).every(id => gateSettled(states.get(id)))
|
||||
}
|
||||
|
||||
function gateSettled(state: GateState | undefined): boolean {
|
||||
return state === 'passed' || state === 'failed' || state === 'skipped'
|
||||
}
|
||||
|
||||
function gateFailed(state: GateState | undefined): boolean {
|
||||
return state === 'failed' || state === 'skipped'
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -802,10 +882,12 @@ export async function runGate(gate: Gate): Promise<GateResult> {
|
||||
child.stdout.setEncoding('utf8')
|
||||
child.stderr.setEncoding('utf8')
|
||||
child.stdout.on('data', (chunk: string) => {
|
||||
output.push({ stream: 'stdout', text: chunk })
|
||||
if (gate.streamOutput === true) process.stdout.write(chunk)
|
||||
else output.push({ stream: 'stdout', text: chunk })
|
||||
})
|
||||
child.stderr.on('data', (chunk: string) => {
|
||||
output.push({ stream: 'stderr', text: chunk })
|
||||
if (gate.streamOutput === true) process.stderr.write(chunk)
|
||||
else output.push({ stream: 'stderr', text: chunk })
|
||||
})
|
||||
child.on('error', (error) => {
|
||||
spawnError = `failed to start command: ${error.message}`
|
||||
@@ -859,7 +941,7 @@ function printResult(result: GateResult): void {
|
||||
console.error(`command: ${result.gate.displayCommand}`)
|
||||
console.error(`outcome: ${formatGateResultReason(result)}`)
|
||||
}
|
||||
printOutput(result.output)
|
||||
if (result.gate.streamOutput !== true) printOutput(result.output)
|
||||
}
|
||||
|
||||
function printSummary(results: GateResult[], durationMs: number): void {
|
||||
|
||||
@@ -16,6 +16,18 @@ describe('Oxlint invocation', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('uses location-preserving diagnostics in CI', () => {
|
||||
expect(resolveOxlintInvocation(['.'], { CI: 'true', DSH_OXLINT_THREADS: '4' })).toEqual({
|
||||
args: ['.', '--format=unix', '--threads=4'],
|
||||
env: { CI: 'true', DSH_OXLINT_THREADS: '4', GOMAXPROCS: '4' },
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves an explicitly selected CI formatter', () => {
|
||||
expect(resolveOxlintInvocation(['.', '--format', 'github'], { CI: 'true' }).args)
|
||||
.toEqual(['.', '--format', 'github'])
|
||||
})
|
||||
|
||||
it.each(['0', '-1', '1.5', 'auto'])('rejects invalid worker bound %s', (value) => {
|
||||
expect(() => resolveOxlintInvocation(['.'], { DSH_OXLINT_THREADS: value }))
|
||||
.toThrow('DSH_OXLINT_THREADS must be a positive integer')
|
||||
|
||||
+12
-2
@@ -10,6 +10,14 @@ function isFixInvocation(args: readonly string[]): boolean {
|
||||
return args.some(arg => FIX_FLAGS.has(arg))
|
||||
}
|
||||
|
||||
function hasOutputFormat(args: readonly string[]): boolean {
|
||||
return args.some(arg =>
|
||||
arg === '-f'
|
||||
|| arg.startsWith('-f=')
|
||||
|| arg === '--format'
|
||||
|| arg.startsWith('--format='))
|
||||
}
|
||||
|
||||
/** Complete Oxlint child-process arguments and environment. */
|
||||
export interface OxlintInvocation {
|
||||
readonly args: readonly string[]
|
||||
@@ -23,8 +31,10 @@ export interface OxlintInvocation {
|
||||
* @returns the complete CLI arguments and child environment.
|
||||
*/
|
||||
export function resolveOxlintInvocation(args: readonly string[], env: NodeJS.ProcessEnv): OxlintInvocation {
|
||||
const resolvedArgs = [...args]
|
||||
if (env.CI === 'true' && !hasOutputFormat(args)) resolvedArgs.push('--format=unix')
|
||||
const raw = env.DSH_OXLINT_THREADS
|
||||
if (raw === undefined || raw === '') return { args: [...args], env: { ...env } }
|
||||
if (raw === undefined || raw === '') return { args: resolvedArgs, env: { ...env } }
|
||||
const parsed = Number.parseInt(raw, 10)
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || String(parsed) !== raw) {
|
||||
throw new Error(`run-oxlint: DSH_OXLINT_THREADS must be a positive integer, got ${JSON.stringify(raw)}.`)
|
||||
@@ -33,7 +43,7 @@ export function resolveOxlintInvocation(args: readonly string[], env: NodeJS.Pro
|
||||
throw new Error('run-oxlint: use DSH_OXLINT_THREADS instead of passing --threads directly.')
|
||||
}
|
||||
return {
|
||||
args: [...args, `--threads=${raw}`],
|
||||
args: [...resolvedArgs, `--threads=${raw}`],
|
||||
env: { ...env, GOMAXPROCS: raw },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/** Run serial browser owners before one bounded snapshot pool. */
|
||||
import { spawn } from 'node:child_process'
|
||||
import { pnpmInvocation } from './pnpm-invocation.ts'
|
||||
|
||||
const serialFiles = [
|
||||
'apps/web/tests/hmr-live.e2e.ts',
|
||||
'apps/web/tests/cordis-tool-round.e2e.ts',
|
||||
]
|
||||
const workerRaw = process.env.DSH_WEB_SNAPSHOT_WORKERS
|
||||
const workers = Number.parseInt(workerRaw ?? '', 10)
|
||||
if (!Number.isSafeInteger(workers) || workers < 2 || String(workers) !== workerRaw) {
|
||||
throw new Error(`DSH_WEB_SNAPSHOT_WORKERS must be an integer greater than 1, got ${JSON.stringify(workerRaw)}.`)
|
||||
}
|
||||
const invocation = pnpmInvocation(['exec', 'vitest', 'run', '--config', 'vitest.web.config.ts'])
|
||||
let serialStatus = 0
|
||||
for (const file of serialFiles) {
|
||||
serialStatus = await run(invocation.command, [...invocation.args, file])
|
||||
if (serialStatus !== 0) break
|
||||
}
|
||||
if (serialStatus === 0) {
|
||||
process.exitCode = await run(invocation.command, [
|
||||
...invocation.args,
|
||||
...serialFiles.map(file => `--exclude=${file}`),
|
||||
'--fileParallelism',
|
||||
`--maxWorkers=${String(workers)}`,
|
||||
])
|
||||
} else {
|
||||
process.exitCode = serialStatus
|
||||
}
|
||||
|
||||
function run(command: string, args: string[]): Promise<number> {
|
||||
return new Promise((resolveRun, reject) => {
|
||||
const child = spawn(command, args, { stdio: 'inherit' })
|
||||
child.once('error', reject)
|
||||
child.once('exit', (exitCode, signalCode) => {
|
||||
if (signalCode !== null) {
|
||||
console.error(`web snapshots terminated by ${signalCode}`)
|
||||
resolveRun(1)
|
||||
return
|
||||
}
|
||||
resolveRun(exitCode ?? 1)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
/** Repository-wide canonical-layout check for committed session fixtures. */
|
||||
/** Repository-wide canonical-layout check for committed session snapshots. */
|
||||
|
||||
import { resolve } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
@@ -6,7 +6,7 @@ import { inspectSessionFixtureLayouts } from './session-fixture-layout.ts'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
|
||||
it('keeps every session-format JSONL fixture in canonical packed layout', () => {
|
||||
it('keeps every session-format JSONL fixture projected into canonical packed layout', () => {
|
||||
const nonCanonical = inspectSessionFixtureLayouts(root)
|
||||
.filter(fixture => fixture.source !== fixture.canonical)
|
||||
.map(fixture => fixture.path)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { decodeStorageRecord, type SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { type SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
|
||||
import { canonicalSessionFixture } from './session-fixture-layout.ts'
|
||||
|
||||
const HEADER = ' {"type":"session","version":0,"id":"fixture","createdAt":1,"delegationDepth":0} '
|
||||
@@ -22,8 +23,7 @@ function unpackedFixture(): string {
|
||||
}
|
||||
|
||||
function decodedBody(content: string): SessionEvent[] {
|
||||
return content.trimEnd().split('\n').slice(1)
|
||||
.flatMap(line => decodeStorageRecord(JSON.parse(line) as unknown))
|
||||
return parseSessionLog(content)
|
||||
}
|
||||
|
||||
describe('canonicalSessionFixture', () => {
|
||||
@@ -31,8 +31,12 @@ describe('canonicalSessionFixture', () => {
|
||||
const canonical = canonicalSessionFixture(unpackedFixture(), 'fixture.jsonl')
|
||||
expect(canonical).toBeDefined()
|
||||
expect(canonical?.split('\n')[0]).toBe(HEADER)
|
||||
expect(JSON.parse(canonical?.split('\n')[1] ?? '{}')).toMatchObject({ type: 'text-chunks' })
|
||||
expect(decodedBody(canonical ?? '')).toStrictEqual(chunkRun())
|
||||
const packed = JSON.parse(canonical?.split('\n')[1] ?? '{}') as Record<string, unknown>
|
||||
expect(packed).toMatchObject({ type: 'text-chunks' })
|
||||
expect(packed).not.toHaveProperty('seq0')
|
||||
expect(packed).not.toHaveProperty('time0')
|
||||
expect(decodedBody(canonical ?? '').map(({ seq: _seq, time: _time, ...event }) => event))
|
||||
.toStrictEqual(chunkRun().map(({ seq: _seq, time: _time, ...event }) => event))
|
||||
})
|
||||
|
||||
it('ignores JSONL whose first record is not a session header', () => {
|
||||
@@ -45,13 +49,22 @@ describe('canonicalSessionFixture', () => {
|
||||
expect(canonicalSessionFixture(packed ?? '')).toBe(packed)
|
||||
})
|
||||
|
||||
it('is idempotent for an already projected fixture', () => {
|
||||
const projected = [
|
||||
HEADER,
|
||||
'{"type":"turn/start","data":{"turn":1,"seq":99,"time":100}}',
|
||||
'',
|
||||
].join('\n')
|
||||
expect(canonicalSessionFixture(projected)).toBe(projected)
|
||||
})
|
||||
|
||||
it('fails loud on malformed records after a session header', () => {
|
||||
expect(() => canonicalSessionFixture(`${HEADER}\n{not-json}\n`, 'broken.jsonl'))
|
||||
.toThrow(/broken\.jsonl:2: invalid JSON/)
|
||||
.toThrow(/broken\.jsonl: session snapshot line 2 contains invalid JSON/)
|
||||
})
|
||||
|
||||
it('labels malformed packed rows with the fixture path and line', () => {
|
||||
expect(() => canonicalSessionFixture(`${HEADER}\n{"type":"text-chunks"}\n`, 'broken.jsonl'))
|
||||
.toThrow(/broken\.jsonl:2: invalid session storage record: malformed text-chunks storage row/)
|
||||
.toThrow(/broken\.jsonl: session snapshot line 2: malformed text-chunks storage row/)
|
||||
})
|
||||
})
|
||||
@@ -1,97 +1,85 @@
|
||||
/** Canonical packed-row layout helpers for repository session fixtures. */
|
||||
/** Canonical packed-row and envelope projection helpers for repository session fixtures. */
|
||||
|
||||
import { deepStrictEqual } from 'node:assert'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { decodeStorageRecord, packChunkRuns, type SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { packChunkRuns, type SessionEvent } from '@deepseek-ai/dsh-session'
|
||||
import { parseSessionLog } from '@deepseek-ai/dsh-llm-replay'
|
||||
|
||||
/** One repository session fixture and its canonical packed representation. */
|
||||
/** One repository session fixture and its canonical projected representation. */
|
||||
export interface SessionFixtureLayout {
|
||||
/** Repository-relative path with `/` separators. */
|
||||
path: string
|
||||
/** Current fixture bytes decoded as UTF-8. */
|
||||
source: string
|
||||
/** Canonical packed fixture bytes. */
|
||||
/** Canonical projected fixture bytes. */
|
||||
canonical: string
|
||||
}
|
||||
|
||||
interface RecordLine {
|
||||
line: number
|
||||
text: string
|
||||
}
|
||||
|
||||
function recordLines(content: string): RecordLine[] {
|
||||
return content.split(/\r?\n/).flatMap((text, index) => (
|
||||
text.trim().length === 0 ? [] : [{ line: index + 1, text }]
|
||||
))
|
||||
}
|
||||
|
||||
function parseRecord(line: RecordLine, label: string): unknown {
|
||||
try {
|
||||
return JSON.parse(line.text) as unknown
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(`${label}:${line.line}: invalid JSON: ${detail}`, { cause: error })
|
||||
}
|
||||
}
|
||||
|
||||
function isSessionHeader(value: unknown): boolean {
|
||||
return value !== null && typeof value === 'object' && (value as { type?: unknown }).type === 'session'
|
||||
}
|
||||
|
||||
function decodeBody(lines: readonly RecordLine[], label: string): SessionEvent[] {
|
||||
return lines.flatMap((line) => {
|
||||
const record = parseRecord(line, label)
|
||||
try {
|
||||
return decodeStorageRecord(record)
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(`${label}:${line.line}: invalid session storage record: ${detail}`, { cause: error })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function renderFixture(headerLine: string, events: readonly SessionEvent[]): string {
|
||||
return [
|
||||
headerLine,
|
||||
...packChunkRuns(events).map(record => JSON.stringify(record)),
|
||||
...packChunkRuns(events).map((stored) => {
|
||||
const record = stored as unknown as Record<string, unknown>
|
||||
delete record.seq
|
||||
delete record.time
|
||||
delete record.seq0
|
||||
delete record.time0
|
||||
return JSON.stringify(record)
|
||||
}),
|
||||
'',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function withoutEnvelope(events: readonly SessionEvent[]): Array<Omit<SessionEvent, 'seq' | 'time'>> {
|
||||
return events.map((event) => {
|
||||
const { seq: _seq, time: _time, ...projected } = event
|
||||
return projected
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonicalize one JSONL document when its first record is a session header.
|
||||
* The header line remains byte-identical; body records decode to logical events
|
||||
* and re-encode with {@link packChunkRuns}. Non-session JSONL returns undefined.
|
||||
* The header line remains byte-identical; body records decode to logical events,
|
||||
* re-encode with {@link packChunkRuns}, and omit storage sequence/time envelopes.
|
||||
* Non-session JSONL returns undefined.
|
||||
*
|
||||
* @param content - JSONL source text.
|
||||
* @param label - path-like diagnostic label.
|
||||
* @returns Canonical text for a session fixture, otherwise undefined.
|
||||
*/
|
||||
export function canonicalSessionFixture(content: string, label = '<session-fixture>'): string | undefined {
|
||||
const lines = recordLines(content)
|
||||
const header = lines[0]
|
||||
if (header === undefined) return undefined
|
||||
const headerLine = content.split(/\r?\n/).find(line => line.trim().length > 0)
|
||||
if (headerLine === undefined) return undefined
|
||||
|
||||
let headerValue: unknown
|
||||
try {
|
||||
headerValue = JSON.parse(header.text) as unknown
|
||||
headerValue = JSON.parse(headerLine) as unknown
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
if (!isSessionHeader(headerValue)) return undefined
|
||||
|
||||
const events = decodeBody(lines.slice(1), label)
|
||||
const canonical = renderFixture(header.text, events)
|
||||
const canonicalLines = recordLines(canonical)
|
||||
const decoded = decodeBody(canonicalLines.slice(1), label)
|
||||
let events
|
||||
try {
|
||||
deepStrictEqual(decoded, events)
|
||||
events = parseSessionLog(content)
|
||||
} catch (error) {
|
||||
throw new Error(`${label}: packed rewrite changed the decoded event stream`, { cause: error })
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(`${label}: ${detail}`, { cause: error })
|
||||
}
|
||||
if (renderFixture(header.text, decoded) !== canonical) {
|
||||
const canonical = renderFixture(headerLine, events)
|
||||
const decoded = parseSessionLog(canonical)
|
||||
try {
|
||||
deepStrictEqual(withoutEnvelope(decoded), withoutEnvelope(events))
|
||||
} catch (error) {
|
||||
throw new Error(`${label}: packed snapshot rewrite changed the event payload stream`, { cause: error })
|
||||
}
|
||||
if (renderFixture(headerLine, decoded) !== canonical) {
|
||||
throw new Error(`${label}: packed rewrite is not idempotent`)
|
||||
}
|
||||
return canonical
|
||||
|
||||
+412
-36
@@ -9,6 +9,7 @@ import json
|
||||
import os
|
||||
import queue
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
@@ -28,9 +29,13 @@ WORKFLOW_WORKER_TEXT = "workflow worker smoke ok"
|
||||
MINIMAL_PROMPT = "Exercise the packaged minimal agent's persistent Bash and string-replacement editor."
|
||||
MINIMAL_TEXT = "minimal agent smoke ok"
|
||||
MINIMAL_EDITOR_PATH_PREFIX = "Editor path: "
|
||||
MINIMAL_SYSTEM_PROMPT = "You are a helpful software engineer assistant."
|
||||
FS_SEARCH_PROMPT = "Exercise the packaged filesystem search tools."
|
||||
FS_SEARCH_TEXT = "filesystem search smoke ok"
|
||||
FS_SEARCH_MARKER = "PACKAGED_FS_SEARCH_OK"
|
||||
MCP_PROMPT = "Exercise the packaged MCP client with one external stdio server."
|
||||
MCP_TEXT = "MCP client smoke ok"
|
||||
MINIMAL_CORDIS = (
|
||||
Path(__file__).resolve().parent.parent / "examples" / "jsonrpc-agent" / "minimal.cordis.yml"
|
||||
Path(__file__).resolve().parent.parent / "examples" / "python-sdk-agent" / "minimal.cordis.yml"
|
||||
)
|
||||
MINIMAL_BASH_COMMAND = (
|
||||
"counter=$(( ${counter:-0} + 1 )); export counter; "
|
||||
@@ -65,13 +70,27 @@ SNAPSHOT_WORKFLOW_SCRIPT = (
|
||||
f"const reply = await agent('{SNAPSHOT_WORKFLOW_CHILD_PROMPT}', {{ label: 'workflow-child' }})\n"
|
||||
"return { reply }"
|
||||
)
|
||||
SNAPSHOT_DIRECTORY = (
|
||||
ADVANCED_SNAPSHOT_DIRECTORY = (
|
||||
Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "advanced"
|
||||
)
|
||||
SNAPSHOT_FILENAMES = ("result.json", "session.jsonl", "session.1.jsonl", "session.2.jsonl")
|
||||
ADVANCED_SNAPSHOT_FILENAMES = ("result.json", "session.jsonl", "session.1.jsonl", "session.2.jsonl")
|
||||
MINIMAL_SNAPSHOT_DIRECTORY = (
|
||||
Path(__file__).resolve().parent / "snapshots" / "python-sdk-single-exe" / "minimal"
|
||||
)
|
||||
MINIMAL_SNAPSHOT_FILENAMES = ("model-visible.json",)
|
||||
# The agent loop's dynamic runtime-context snapshot is the one model-visible message this
|
||||
# expected output cannot carry: the same composition emits it on macOS and not on Linux
|
||||
# (deepseek-harness#2488), and the file must replay on both. Everything else is compared.
|
||||
RUNTIME_CONTEXT_PREFIX = "Current runtime context"
|
||||
CUSTOM_CORDIS = """\
|
||||
- id: sdk-jsonrpc-server
|
||||
name: '@deepseek-ai/dsh-sdk-jsonrpc-server'
|
||||
- id: deepseek-llm-api-extensions
|
||||
name: '@deepseek-ai/dsh-deepseek-llm-api-extensions'
|
||||
- id: session-log-deepseek
|
||||
name: '@deepseek-ai/dsh-session-log-deepseek'
|
||||
config:
|
||||
enabled: true
|
||||
- id: agent-core
|
||||
name: '@deepseek-ai/dsh-agent-spine-demo'
|
||||
config:
|
||||
@@ -109,6 +128,144 @@ CUSTOM_CORDIS = """\
|
||||
- id: cordis-tool
|
||||
name: '@deepseek-ai/dsh-tool-cordis'
|
||||
"""
|
||||
FS_SEARCH_CORDIS = """\
|
||||
- id: sdk-jsonrpc-server
|
||||
name: '@deepseek-ai/dsh-sdk-jsonrpc-server'
|
||||
- id: agent-core
|
||||
name: '@deepseek-ai/dsh-agent-spine-demo'
|
||||
config:
|
||||
workspaceContext: false
|
||||
skills:
|
||||
enabled: false
|
||||
toolBash: false
|
||||
toolJobs: false
|
||||
- id: sessions
|
||||
name: '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
config:
|
||||
root: !!js process.env.DSH_SESSION_ROOT
|
||||
compression: 'none'
|
||||
- id: subprocess
|
||||
name: '@deepseek-ai/dsh-subprocess-local'
|
||||
- id: fs-search
|
||||
name: '@deepseek-ai/dsh-tool-fs-search'
|
||||
config:
|
||||
sampleOverCapGlobResults: false
|
||||
"""
|
||||
MCP_SERVER_SCRIPT = """\
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
log_path = os.environ.get("MCP_SMOKE_LOG")
|
||||
|
||||
|
||||
def send(message):
|
||||
sys.stdout.write(json.dumps(message, separators=(",", ":")) + "\\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
for line in sys.stdin:
|
||||
request = json.loads(line)
|
||||
if log_path is not None:
|
||||
with open(log_path, "a", encoding="utf-8") as log:
|
||||
log.write(str(request.get("method")) + "\\n")
|
||||
request_id = request.get("id")
|
||||
if request_id is None:
|
||||
continue
|
||||
method = request.get("method")
|
||||
if method == "initialize":
|
||||
send({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"result": {
|
||||
"protocolVersion": request["params"]["protocolVersion"],
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "python-wheel-fixture", "version": "1.0.0"},
|
||||
},
|
||||
})
|
||||
elif method == "tools/list":
|
||||
# Keep discovery pending long enough that an SDK runtime answering
|
||||
# initialize before discovery completes makes its first model request
|
||||
# without this tool and fails deterministically.
|
||||
time.sleep(0.25)
|
||||
send({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"result": {
|
||||
"tools": [{
|
||||
"name": "add",
|
||||
"description": "Add two numbers.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
|
||||
"required": ["a", "b"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
}],
|
||||
},
|
||||
})
|
||||
elif method == "tools/call":
|
||||
params = request["params"]
|
||||
if params.get("name") != "add" or params.get("arguments") != {"a": 19, "b": 23}:
|
||||
send({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"error": {"code": -32602, "message": "unexpected tool call"},
|
||||
})
|
||||
continue
|
||||
send({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"result": {"content": [{"type": "text", "text": "42"}]},
|
||||
})
|
||||
else:
|
||||
send({
|
||||
"jsonrpc": "2.0",
|
||||
"id": request_id,
|
||||
"error": {"code": -32601, "message": f"unsupported method: {method}"},
|
||||
})
|
||||
"""
|
||||
|
||||
|
||||
def mcp_cordis(server_script: Path) -> str:
|
||||
"""Build an external config that mounts the packaged MCP client."""
|
||||
return json.dumps([
|
||||
{
|
||||
"id": "sdk-jsonrpc-server",
|
||||
"name": "@deepseek-ai/dsh-sdk-jsonrpc-server",
|
||||
},
|
||||
{
|
||||
"id": "agent-core",
|
||||
"name": "@deepseek-ai/dsh-agent-spine-demo",
|
||||
"config": {
|
||||
"workspaceContext": False,
|
||||
"skills": {"enabled": False},
|
||||
"toolBash": False,
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": "sessions",
|
||||
"name": "@deepseek-ai/dsh-session-persistence-jsonl",
|
||||
"config": {"root": "./sessions", "compression": "none"},
|
||||
},
|
||||
{
|
||||
"id": "mcp-fixture",
|
||||
"name": "@deepseek-ai/dsh-mcp-client",
|
||||
"config": {
|
||||
"serverName": "fixture",
|
||||
"transport": "stdio",
|
||||
"command": sys.executable,
|
||||
"args": [str(server_script)],
|
||||
"env": {"MCP_SMOKE_LOG": str(server_script.with_suffix(".log"))},
|
||||
"failOnStartupError": True,
|
||||
"reconnect": {"enabled": False},
|
||||
},
|
||||
},
|
||||
], indent=2)
|
||||
|
||||
|
||||
class MockModelHandler(BaseHTTPRequestHandler):
|
||||
"""Return deterministic text, worker, and orchestration completions."""
|
||||
|
||||
@@ -143,6 +300,12 @@ def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
|
||||
if latest.get("role") == "tool":
|
||||
call_id, tool_name = latest_tool_call(messages)
|
||||
tool_text = message_text(latest.get("content"))
|
||||
mcp = mcp_tool_followup(call_id, tool_name, tool_text)
|
||||
if mcp is not None:
|
||||
return mcp
|
||||
fs_search = fs_search_tool_followup(call_id, tool_name, tool_text)
|
||||
if fs_search is not None:
|
||||
return fs_search
|
||||
minimal = minimal_tool_followup(body, call_id, tool_name, tool_text)
|
||||
if minimal is not None:
|
||||
return minimal
|
||||
@@ -170,17 +333,9 @@ def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
|
||||
),
|
||||
None,
|
||||
)
|
||||
# The minimal composition's assembled system prompt, advertised tool schemas, and
|
||||
# model-visible messages are pinned by its snapshot, not asserted here.
|
||||
if minimal_prompt is not None:
|
||||
names = advertised_tool_names(body)
|
||||
if names != {"bash", "str_replace_editor"}:
|
||||
raise AssertionError(f"minimal agent smoke advertised unexpected tools: {names}")
|
||||
system_prompts = [
|
||||
message_text(message.get("content"))
|
||||
for message in messages
|
||||
if isinstance(message, dict) and message.get("role") == "system"
|
||||
]
|
||||
if system_prompts != [MINIMAL_SYSTEM_PROMPT]:
|
||||
raise AssertionError(f"minimal agent smoke assembled unexpected system prompts: {system_prompts}")
|
||||
return tool_call_chunks(
|
||||
"minimal-bash-1",
|
||||
"bash",
|
||||
@@ -192,6 +347,8 @@ def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
|
||||
SNAPSHOT_PROMPT,
|
||||
CODE_PROMPT,
|
||||
WORKFLOW_PROMPT,
|
||||
FS_SEARCH_PROMPT,
|
||||
MCP_PROMPT,
|
||||
}
|
||||
prompt = next(
|
||||
(candidate for candidate in user_prompts if candidate in scenario_prompts),
|
||||
@@ -233,9 +390,60 @@ def completion_chunks(body: dict[str, object]) -> list[dict[str, object]]:
|
||||
},
|
||||
},
|
||||
)
|
||||
if prompt == FS_SEARCH_PROMPT:
|
||||
assert_advertised_tool(body, "grep")
|
||||
assert_advertised_tool(body, "glob")
|
||||
return tool_call_chunks(
|
||||
"fs-search-grep",
|
||||
"grep",
|
||||
{"pattern": FS_SEARCH_MARKER, "path": "."},
|
||||
)
|
||||
if prompt == MCP_PROMPT:
|
||||
assert_advertised_tool(body, "mcp__fixture__add")
|
||||
return tool_call_chunks(
|
||||
"mcp-add",
|
||||
"mcp__fixture__add",
|
||||
{"a": 19, "b": 23},
|
||||
)
|
||||
return text_chunks(EXPECTED_TEXT)
|
||||
|
||||
|
||||
def mcp_tool_followup(
|
||||
call_id: str,
|
||||
tool_name: str,
|
||||
tool_text: str,
|
||||
) -> list[dict[str, object]] | None:
|
||||
"""Verify one tool call through the packaged MCP client."""
|
||||
if call_id != "mcp-add":
|
||||
return None
|
||||
if tool_name != "mcp__fixture__add" or "42" not in tool_text:
|
||||
raise AssertionError(f"packaged MCP call returned an unexpected result: {tool_name}: {tool_text}")
|
||||
return text_chunks(MCP_TEXT)
|
||||
|
||||
|
||||
def fs_search_tool_followup(
|
||||
call_id: str,
|
||||
tool_name: str,
|
||||
tool_text: str,
|
||||
) -> list[dict[str, object]] | None:
|
||||
"""Exercise both ripgrep-backed tools through the packaged executable."""
|
||||
if not call_id.startswith("fs-search-"):
|
||||
return None
|
||||
if call_id == "fs-search-grep" and tool_name == "grep":
|
||||
if "needle.txt" not in tool_text or FS_SEARCH_MARKER not in tool_text:
|
||||
raise AssertionError(f"packaged grep returned no marker: {tool_text}")
|
||||
return tool_call_chunks(
|
||||
"fs-search-glob",
|
||||
"glob",
|
||||
{"pattern": "**/*.txt"},
|
||||
)
|
||||
if call_id == "fs-search-glob" and tool_name == "glob":
|
||||
if "needle.txt" not in tool_text:
|
||||
raise AssertionError(f"packaged glob returned no fixture path: {tool_text}")
|
||||
return text_chunks(FS_SEARCH_TEXT)
|
||||
raise AssertionError(f"unexpected filesystem-search follow-up: {call_id} {tool_name}: {tool_text}")
|
||||
|
||||
|
||||
def minimal_tool_followup(
|
||||
body: dict[str, object],
|
||||
call_id: str,
|
||||
@@ -477,16 +685,16 @@ def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--scenario",
|
||||
choices=("all", "sdk-default", "sdk-custom", "sdk-minimal", "sdk-snapshot", "direct"),
|
||||
choices=("all", "sdk-default", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-mcp", "sdk-snapshot", "direct"),
|
||||
default="all",
|
||||
)
|
||||
parser.add_argument("--exe", type=Path)
|
||||
parser.add_argument("--update-snapshots", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.scenario in {"all", "sdk-custom", "sdk-minimal", "sdk-snapshot", "direct"} and args.exe is None:
|
||||
if args.scenario in {"all", "sdk-custom", "sdk-minimal", "sdk-fs-search", "sdk-snapshot", "direct"} and args.exe is None:
|
||||
parser.error("--exe is required for custom, minimal, snapshot, and direct scenarios")
|
||||
if args.update_snapshots and args.scenario not in {"all", "sdk-snapshot"}:
|
||||
parser.error("--update-snapshots requires --scenario sdk-snapshot or all")
|
||||
if args.update_snapshots and args.scenario not in {"all", "sdk-minimal", "sdk-snapshot"}:
|
||||
parser.error("--update-snapshots requires --scenario sdk-minimal, sdk-snapshot, or all")
|
||||
if args.exe is not None and not args.exe.is_file():
|
||||
parser.error(f"runtime executable does not exist: {args.exe}")
|
||||
|
||||
@@ -498,7 +706,12 @@ def main() -> None:
|
||||
smoke_sdk_custom(model.url, args.exe.resolve())
|
||||
if args.scenario in {"all", "sdk-minimal"}:
|
||||
assert args.exe is not None
|
||||
smoke_sdk_minimal(model.url, args.exe.resolve())
|
||||
smoke_sdk_minimal(model.url, args.exe.resolve(), args.update_snapshots)
|
||||
if args.scenario in {"all", "sdk-fs-search"}:
|
||||
assert args.exe is not None
|
||||
smoke_sdk_fs_search(model.url, args.exe.resolve())
|
||||
if args.scenario in {"all", "sdk-mcp"}:
|
||||
smoke_sdk_mcp(model.url, None if args.exe is None else args.exe.resolve())
|
||||
if args.scenario in {"all", "sdk-snapshot"}:
|
||||
assert args.exe is not None
|
||||
smoke_sdk_snapshot(model.url, args.exe.resolve(), args.update_snapshots)
|
||||
@@ -558,10 +771,12 @@ def smoke_sdk_custom(base_url: str, executable: Path) -> None:
|
||||
assert_session_log(sessions, root, EXPECTED_TEXT, CODE_WORKER_TEXT, WORKFLOW_WORKER_TEXT)
|
||||
|
||||
|
||||
def smoke_sdk_minimal(base_url: str, executable: Path) -> None:
|
||||
def smoke_sdk_minimal(base_url: str, executable: Path, update_snapshots: bool) -> None:
|
||||
"""Exercise the checked-in minimal composition through the packaged executable."""
|
||||
from deepseek_harness import DeepSeekHarness
|
||||
|
||||
# One mock model serves every scenario of a run, so the snapshot takes this turn's slice.
|
||||
first_request = len(MockModelHandler.requests)
|
||||
with tempfile.TemporaryDirectory(prefix="dsh-sdk-minimal-") as temporary:
|
||||
root = Path(temporary).resolve()
|
||||
editor_path = root / "created.txt"
|
||||
@@ -587,6 +802,73 @@ def smoke_sdk_minimal(base_url: str, executable: Path) -> None:
|
||||
raise AssertionError(f"packaged editor wrote unexpected content: {editor_path.read_text()!r}")
|
||||
assert_session_log(sessions, root, MINIMAL_TEXT, "COUNT=1", "COUNT=2 CWD=/tmp")
|
||||
|
||||
files = build_minimal_snapshot_files(MockModelHandler.requests[first_request:], root)
|
||||
compare_snapshot_files(
|
||||
files, update_snapshots, MINIMAL_SNAPSHOT_DIRECTORY, MINIMAL_SNAPSHOT_FILENAMES,
|
||||
)
|
||||
|
||||
|
||||
def smoke_sdk_fs_search(base_url: str, executable: Path) -> None:
|
||||
"""Exercise real grep and glob spawns through the packaged executable."""
|
||||
from deepseek_harness import DeepSeekHarness
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="dsh-sdk-fs-search-") as temporary:
|
||||
root = Path(temporary).resolve()
|
||||
(root / "needle.txt").write_text(f"{FS_SEARCH_MARKER}\n")
|
||||
sessions = root / "sessions"
|
||||
cordis = root / "cordis.yml"
|
||||
cordis.write_text(FS_SEARCH_CORDIS)
|
||||
with DeepSeekHarness(
|
||||
provider="deepseek-official",
|
||||
model="smoke-model",
|
||||
cwd=str(root),
|
||||
session_root=str(sessions),
|
||||
cordis=str(cordis),
|
||||
runtime_bin=str(executable),
|
||||
api_key="sk-keyless-smoke",
|
||||
base_url=base_url,
|
||||
request_timeout_seconds=60,
|
||||
) as harness:
|
||||
result = harness.run(FS_SEARCH_PROMPT, session_id="fs-search-smoke")
|
||||
|
||||
assert result.final_response == FS_SEARCH_TEXT, result.final_response
|
||||
assert_session_log(sessions, root, FS_SEARCH_TEXT, FS_SEARCH_MARKER, "needle.txt")
|
||||
|
||||
|
||||
def smoke_sdk_mcp(base_url: str, executable: Path | None) -> None:
|
||||
"""Discover and call an external stdio MCP tool through the packaged client."""
|
||||
from deepseek_harness import DeepSeekHarness
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="dsh-sdk-mcp-") as temporary:
|
||||
root = Path(temporary).resolve()
|
||||
sessions = root / "sessions"
|
||||
server_script = root / "mcp_server.py"
|
||||
server_script.write_text(MCP_SERVER_SCRIPT)
|
||||
cordis = root / "cordis.yml"
|
||||
cordis.write_text(mcp_cordis(server_script))
|
||||
discovery_log = server_script.with_suffix(".log")
|
||||
with DeepSeekHarness(
|
||||
provider="deepseek-official",
|
||||
model="smoke-model",
|
||||
cwd=str(root),
|
||||
session_root=str(sessions),
|
||||
cordis=str(cordis),
|
||||
runtime_bin=None if executable is None else str(executable),
|
||||
api_key="sk-keyless-smoke",
|
||||
base_url=base_url,
|
||||
request_timeout_seconds=60,
|
||||
) as harness:
|
||||
result = harness.run(MCP_PROMPT, session_id="mcp-smoke")
|
||||
|
||||
assert result.final_response == MCP_TEXT, result.final_response
|
||||
assert discovery_log.read_text().splitlines() == [
|
||||
"initialize",
|
||||
"notifications/initialized",
|
||||
"tools/list",
|
||||
"tools/call",
|
||||
]
|
||||
assert_session_log(sessions, root, MCP_TEXT, "mcp__fixture__add", "42")
|
||||
|
||||
|
||||
def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool) -> None:
|
||||
"""Drive and compare the advanced SDK/executable behavioral snapshot."""
|
||||
@@ -628,7 +910,9 @@ def smoke_sdk_snapshot(base_url: str, executable: Path, update_snapshots: bool)
|
||||
raise AssertionError("second advanced child log has no workflow-subagent result")
|
||||
|
||||
files = build_snapshot_files(result, logs, child_ids, root)
|
||||
compare_snapshot_files(files, update_snapshots)
|
||||
compare_snapshot_files(
|
||||
files, update_snapshots, ADVANCED_SNAPSHOT_DIRECTORY, ADVANCED_SNAPSHOT_FILENAMES,
|
||||
)
|
||||
|
||||
|
||||
def smoke_direct(base_url: str, executable: Path) -> None:
|
||||
@@ -802,6 +1086,79 @@ def snapshot_child_ids(result: "RunResult") -> list[str]:
|
||||
return child_ids
|
||||
|
||||
|
||||
def build_minimal_snapshot_files(
|
||||
requests: list[dict[str, object]],
|
||||
cwd: Path,
|
||||
) -> dict[str, str]:
|
||||
"""Render the minimal composition's model-visible surface as expected output.
|
||||
|
||||
Every assembled system prompt, advertised tool schema, and system or user message is
|
||||
kept verbatim: they carry what the deployment actually shows the model, so a plugin
|
||||
that contributes an unintended system section or user message cannot pass unnoticed.
|
||||
Assistant and tool payloads keep only their call identity, and the dynamic
|
||||
runtime-context snapshot is dropped, because their text differs across the platforms
|
||||
this expected output must replay on.
|
||||
"""
|
||||
snapshot = []
|
||||
for body in requests:
|
||||
messages = body.get("messages")
|
||||
if not isinstance(messages, list):
|
||||
raise AssertionError(f"minimal model request has no messages: {body}")
|
||||
snapshot.append({
|
||||
"tools": minimal_snapshot_text(body.get("tools"), cwd),
|
||||
"messages": [
|
||||
minimal_snapshot_message(message, cwd)
|
||||
for message in messages
|
||||
if not is_runtime_context_message(message)
|
||||
],
|
||||
})
|
||||
return {"model-visible.json": json.dumps(snapshot, indent=2, ensure_ascii=False) + "\n"}
|
||||
|
||||
|
||||
def is_runtime_context_message(message: object) -> bool:
|
||||
"""Identify the agent loop's dynamic runtime-context snapshot, current or cleared."""
|
||||
return (
|
||||
isinstance(message, dict)
|
||||
and message.get("role") == "user"
|
||||
and message_text(message.get("content")).startswith(RUNTIME_CONTEXT_PREFIX)
|
||||
)
|
||||
|
||||
|
||||
def minimal_snapshot_message(message: object, cwd: Path) -> dict[str, object]:
|
||||
"""Reduce one model-visible message to its stable, behavior-carrying parts."""
|
||||
if not isinstance(message, dict):
|
||||
raise AssertionError(f"minimal model request has an invalid message: {message}")
|
||||
role = message.get("role")
|
||||
if role in ("system", "user"):
|
||||
return {"role": role, "text": minimal_snapshot_text(message_text(message.get("content")), cwd)}
|
||||
if role == "assistant":
|
||||
calls = message.get("tool_calls")
|
||||
if not isinstance(calls, list):
|
||||
raise AssertionError(f"minimal assistant message has no tool calls: {message}")
|
||||
return {
|
||||
"role": role,
|
||||
"toolCalls": [
|
||||
{"id": call.get("id"), "name": (call.get("function") or {}).get("name")}
|
||||
for call in calls
|
||||
if isinstance(call, dict)
|
||||
],
|
||||
}
|
||||
if role == "tool":
|
||||
return {"role": role, "toolCallId": message.get("tool_call_id"), "text": "{{tool-result}}"}
|
||||
raise AssertionError(f"minimal model request has an unexpected message role: {message}")
|
||||
|
||||
|
||||
def minimal_snapshot_text(value: object, cwd: Path) -> object:
|
||||
"""Replace the scenario's temporary working directory everywhere it appears."""
|
||||
if isinstance(value, str):
|
||||
return value.replace(str(cwd), "{{cwd}}")
|
||||
if isinstance(value, list):
|
||||
return [minimal_snapshot_text(item, cwd) for item in value]
|
||||
if isinstance(value, dict):
|
||||
return {key: minimal_snapshot_text(item, cwd) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
def build_snapshot_files(
|
||||
result: "RunResult",
|
||||
logs: dict[str, list[dict[str, object]]],
|
||||
@@ -831,15 +1188,17 @@ def build_snapshot_files(
|
||||
files = {
|
||||
"result.json": json.dumps(normalized_result, indent=2, ensure_ascii=False) + "\n",
|
||||
"session.jsonl": render_jsonl(
|
||||
[normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]]
|
||||
project_session_snapshot([
|
||||
normalize_snapshot_value(record, replacements) for record in logs[SNAPSHOT_SESSION_ID]
|
||||
])
|
||||
),
|
||||
}
|
||||
for index, child_id in enumerate(child_ids, start=1):
|
||||
files[f"session.{index}.jsonl"] = render_jsonl(
|
||||
[normalize_snapshot_value(record, replacements) for record in logs[child_id]]
|
||||
project_session_snapshot([
|
||||
normalize_snapshot_value(record, replacements) for record in logs[child_id]
|
||||
])
|
||||
)
|
||||
if tuple(files) != SNAPSHOT_FILENAMES:
|
||||
raise AssertionError(f"advanced snapshot file set drifted: {tuple(files)}")
|
||||
return files
|
||||
|
||||
|
||||
@@ -930,27 +1289,44 @@ def render_jsonl(records: list[object]) -> str:
|
||||
)
|
||||
|
||||
|
||||
def compare_snapshot_files(files: dict[str, str], update: bool) -> None:
|
||||
"""Write or exactly compare the advanced executable snapshot files."""
|
||||
def project_session_snapshot(records: list[dict[str, object]]) -> list[dict[str, object]]:
|
||||
"""Omit storage sequence/time envelopes from snapshot body records."""
|
||||
projected = [dict(record) for record in records]
|
||||
for record in projected[1:]:
|
||||
for key in ("seq", "time", "seq0", "time0"):
|
||||
record.pop(key, None)
|
||||
return projected
|
||||
|
||||
|
||||
def compare_snapshot_files(
|
||||
files: dict[str, str],
|
||||
update: bool,
|
||||
directory: Path,
|
||||
filenames: tuple[str, ...],
|
||||
) -> None:
|
||||
"""Write or exactly compare one scenario's expected snapshot files."""
|
||||
scenario = directory.name
|
||||
if tuple(files) != filenames:
|
||||
raise AssertionError(f"{scenario} snapshot builder produced {tuple(files)}, expected {filenames}")
|
||||
if update:
|
||||
SNAPSHOT_DIRECTORY.mkdir(parents=True, exist_ok=True)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
for name, content in files.items():
|
||||
(SNAPSHOT_DIRECTORY / name).write_text(content, encoding="utf-8")
|
||||
print(f"smoke-python-runtime: updated snapshots in {SNAPSHOT_DIRECTORY}")
|
||||
(directory / name).write_text(content, encoding="utf-8")
|
||||
print(f"smoke-python-runtime: updated snapshots in {directory}")
|
||||
|
||||
existing = {
|
||||
path.name
|
||||
for path in SNAPSHOT_DIRECTORY.iterdir()
|
||||
for path in directory.iterdir()
|
||||
if path.is_file()
|
||||
} if SNAPSHOT_DIRECTORY.is_dir() else set()
|
||||
expected = set(SNAPSHOT_FILENAMES)
|
||||
} if directory.is_dir() else set()
|
||||
expected = set(filenames)
|
||||
if existing != expected:
|
||||
raise AssertionError(
|
||||
"advanced snapshot files differ: "
|
||||
f"{scenario} snapshot files differ: "
|
||||
f"missing={sorted(expected - existing)}, unexpected={sorted(existing - expected)}"
|
||||
)
|
||||
for name, actual in files.items():
|
||||
expected_text = (SNAPSHOT_DIRECTORY / name).read_text(encoding="utf-8")
|
||||
expected_text = (directory / name).read_text(encoding="utf-8")
|
||||
if actual == expected_text:
|
||||
continue
|
||||
diff = "".join(difflib.unified_diff(
|
||||
@@ -960,7 +1336,7 @@ def compare_snapshot_files(files: dict[str, str], update: bool) -> None:
|
||||
tofile=f"actual/{name}",
|
||||
))
|
||||
raise AssertionError(
|
||||
f"advanced executable snapshot mismatch in {name}; "
|
||||
f"{scenario} executable snapshot mismatch in {name}; "
|
||||
"rerun with --update-snapshots after reviewing the behavior\n"
|
||||
f"{diff}"
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,19 +1,20 @@
|
||||
{"type":"session","version":0,"id":"{{child-1}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","origin":"subagent","delegationDepth":1}
|
||||
{"type":"agent/inbox/spliced","seq":0,"time":0,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}}
|
||||
{"type":"turn/start","seq":1,"time":0,"data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","seq":2,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"subagent/descriptor","seq":3,"time":0,"data":{"version":2,"mode":"one-shot","provider":"spawn","label":"Check direct child"}}
|
||||
{"type":"step/start","seq":4,"time":0,"data":{"turn":1,"step":1}}
|
||||
{"type":"user/message","seq":5,"time":0,"data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","seq":6,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"session/title","seq":7,"time":0,"data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[5],"source":{"kind":"fallback"}}}
|
||||
{"type":"request/header","seq":8,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}}
|
||||
{"type":"request/context","seq":9,"time":0,"data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
|
||||
{"type":"assistant/chunk","seq":10,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
|
||||
{"type":"assistant/chunk","seq":11,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"DIRECT_CHILD_OK"}}}
|
||||
{"type":"assistant/chunk","seq":12,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}}}
|
||||
{"type":"assistant/chunk","seq":13,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":14,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
|
||||
{"type":"assistant/message","seq":15,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[10,11,12,13,14],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":16,"time":0,"data":{"turn":1,"step":1}}
|
||||
{"type":"turn/end","seq":17,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"subagent/descriptor","data":{"version":2,"mode":"one-shot","provider":"spawn","label":"Check direct child"}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[5],"source":{"kind":"fallback"}}}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","throughSeq":9}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"DIRECT_CHILD_OK"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[11,12,13,14,15],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
@@ -1,19 +1,20 @@
|
||||
{"type":"session","version":0,"id":"{{child-2}}","createdAt":0,"cwd":"{{cwd}}","parentSession":"{{parent}}","origin":"subagent","delegationDepth":1}
|
||||
{"type":"agent/inbox/spliced","seq":0,"time":0,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}}
|
||||
{"type":"turn/start","seq":1,"time":0,"data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","seq":2,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"subagent/descriptor","seq":3,"time":0,"data":{"version":2,"mode":"one-shot","provider":"spawn"}}
|
||||
{"type":"step/start","seq":4,"time":0,"data":{"turn":1,"step":1}}
|
||||
{"type":"user/message","seq":5,"time":0,"data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","seq":6,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"session/title","seq":7,"time":0,"data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[5],"source":{"kind":"fallback"}}}
|
||||
{"type":"request/header","seq":8,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}}
|
||||
{"type":"request/context","seq":9,"time":0,"data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
|
||||
{"type":"assistant/chunk","seq":10,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
|
||||
{"type":"assistant/chunk","seq":11,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"WORKFLOW_CHILD_OK"}}}
|
||||
{"type":"assistant/chunk","seq":12,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}}}
|
||||
{"type":"assistant/chunk","seq":13,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":14,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
|
||||
{"type":"assistant/message","seq":15,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[10,11,12,13,14],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":16,"time":0,"data":{"turn":1,"step":1}}
|
||||
{"type":"turn/end","seq":17,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"subagent/descriptor","data":{"version":2,"mode":"one-shot","provider":"spawn"}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"plugin","plugin":"@deepseek-ai/dsh-system-prompt","form":"snapshot","sections":[{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[5],"source":{"kind":"fallback"}}}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","throughSeq":9}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"text-delta","index":0,"text":"WORKFLOW_CHILD_OK"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[11,12,13,14,15],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
@@ -1,85 +1,92 @@
|
||||
{"type":"session","version":0,"id":"{{parent}}","createdAt":0,"cwd":"{{cwd}}","delegationDepth":0}
|
||||
{"type":"agent/inbox/spliced","seq":0,"time":0,"data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}}
|
||||
{"type":"turn/start","seq":1,"time":0,"data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","seq":2,"time":0,"data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","seq":3,"time":0,"data":{"turn":1,"step":1}}
|
||||
{"type":"user/message","seq":4,"time":0,"data":{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"session/title","seq":5,"time":0,"data":{"title":"Run the advanced packaged-runtime snapsh","messageSeqs":[4],"source":{"kind":"fallback"}}}
|
||||
{"type":"request/header","seq":6,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}}
|
||||
{"type":"request/context","seq":7,"time":0,"data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
|
||||
{"type":"assistant/chunk","seq":8,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","seq":9,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-define","name":"cordis_define","argumentsDelta":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}}
|
||||
{"type":"assistant/chunk","seq":10,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}}}
|
||||
{"type":"assistant/chunk","seq":11,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":12,"time":0,"data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","seq":13,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[8,9,10,11,12],"surfaceOp":"append"}
|
||||
{"type":"tool/call","seq":14,"time":0,"data":{"turn":1,"step":1,"callId":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}
|
||||
{"type":"tool/result","seq":15,"time":0,"data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"advanced-define"},"content":[{"type":"tool-result","toolCallId":"advanced-define","content":[{"type":"text","text":"Defined snap-1/pkg-1 (Snapshot Double); it is not running yet. Use cordis_run to activate this Package."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1"}},"sourceEventSeqs":[14],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":16,"time":0,"data":{"turn":1,"step":1}}
|
||||
{"type":"step/start","seq":17,"time":0,"data":{"turn":1,"step":2}}
|
||||
{"type":"assistant/chunk","seq":18,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","seq":19,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-run","name":"cordis_run","argumentsDelta":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}}
|
||||
{"type":"assistant/chunk","seq":20,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}}}
|
||||
{"type":"assistant/chunk","seq":21,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":22,"time":0,"data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","seq":23,"time":0,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[18,19,20,21,22],"surfaceOp":"append"}
|
||||
{"type":"tool/call","seq":24,"time":0,"data":{"turn":1,"step":2,"callId":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}
|
||||
{"type":"tool/result","seq":25,"time":0,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"advanced-run"},"content":[{"type":"tool-result","toolCallId":"advanced-run","content":[{"type":"text","text":"snap-1/pkg-1 is running (run-1)."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1","pluginRunId":"run-1"}},"sourceEventSeqs":[24],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":26,"time":0,"data":{"turn":1,"step":2}}
|
||||
{"type":"step/start","seq":27,"time":0,"data":{"turn":1,"step":3}}
|
||||
{"type":"request/header","seq":28,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"change"}}
|
||||
{"type":"assistant/chunk","seq":29,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","seq":30,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-code","name":"run_code","argumentsDelta":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}}
|
||||
{"type":"assistant/chunk","seq":31,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}}}
|
||||
{"type":"assistant/chunk","seq":32,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":33,"time":0,"data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","seq":34,"time":0,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[29,30,31,32,33],"surfaceOp":"append"}
|
||||
{"type":"tool/call","seq":35,"time":0,"data":{"turn":1,"step":3,"callId":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}
|
||||
{"type":"tool/code-dispatch-start","seq":36,"time":0,"data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21}}}
|
||||
{"type":"tool/code-dispatch","seq":37,"time":0,"data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21},"isError":false,"content":[{"type":"text","text":"42"}]}}
|
||||
{"type":"tool/result","seq":38,"time":0,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"advanced-code"},"content":[{"type":"tool-result","toolCallId":"advanced-code","content":[{"type":"text","text":"42"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[35],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":39,"time":0,"data":{"turn":1,"step":3}}
|
||||
{"type":"step/start","seq":40,"time":0,"data":{"turn":1,"step":4}}
|
||||
{"type":"assistant/chunk","seq":41,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","seq":42,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-direct-child","name":"subagent","argumentsDelta":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}}
|
||||
{"type":"assistant/chunk","seq":43,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}}}
|
||||
{"type":"assistant/chunk","seq":44,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":45,"time":0,"data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","seq":46,"time":0,"data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[41,42,43,44,45],"surfaceOp":"append"}
|
||||
{"type":"tool/call","seq":47,"time":0,"data":{"turn":1,"step":4,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}
|
||||
{"type":"tool/result","seq":48,"time":0,"data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-direct-child"},"content":[{"type":"tool-result","toolCallId":"advanced-direct-child","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[47],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":49,"time":0,"data":{"turn":1,"step":4}}
|
||||
{"type":"step/start","seq":50,"time":0,"data":{"turn":1,"step":5}}
|
||||
{"type":"assistant/chunk","seq":51,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","seq":52,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-workflow","name":"workflow","argumentsDelta":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}}
|
||||
{"type":"assistant/chunk","seq":53,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}}}
|
||||
{"type":"assistant/chunk","seq":54,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":55,"time":0,"data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","seq":56,"time":0,"data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[51,52,53,54,55],"surfaceOp":"append"}
|
||||
{"type":"tool/call","seq":57,"time":0,"data":{"turn":1,"step":5,"callId":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}
|
||||
{"type":"tool-workflow/run-start","seq":58,"time":0,"data":{"runId":"{{workflow-run}}","name":"advanced-exe-snapshot"}}
|
||||
{"type":"tool-workflow/agent-start","seq":59,"time":0,"data":{"runId":"{{workflow-run}}","seq":1,"label":"workflow-child","phase":"Delegate","childId":"{{child-2}}"}}
|
||||
{"type":"tool-workflow/agent-end","seq":60,"time":0,"data":{"runId":"{{workflow-run}}","seq":1,"outcome":"completed"}}
|
||||
{"type":"tool-workflow/run-end","seq":61,"time":0,"data":{"runId":"{{workflow-run}}","stopReason":"completed"}}
|
||||
{"type":"tool/result","seq":62,"time":0,"data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-exe-snapshot\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[57],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":63,"time":0,"data":{"turn":1,"step":5}}
|
||||
{"type":"step/start","seq":64,"time":0,"data":{"turn":1,"step":6}}
|
||||
{"type":"assistant/chunk","seq":65,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","seq":66,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-undefine","name":"cordis_undefine","argumentsDelta":"{\"pluginId\": \"snap-1\"}"}}}
|
||||
{"type":"assistant/chunk","seq":67,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}}}
|
||||
{"type":"assistant/chunk","seq":68,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":69,"time":0,"data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","seq":70,"time":0,"data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[65,66,67,68,69],"surfaceOp":"append"}
|
||||
{"type":"tool/call","seq":71,"time":0,"data":{"turn":1,"step":6,"callId":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}
|
||||
{"type":"tool/result","seq":72,"time":0,"data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"advanced-undefine"},"content":[{"type":"tool-result","toolCallId":"advanced-undefine","content":[{"type":"text","text":"Removed dynamic Plugin snap-1 and all of its Packages."}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[71],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":73,"time":0,"data":{"turn":1,"step":6}}
|
||||
{"type":"step/start","seq":74,"time":0,"data":{"turn":1,"step":7}}
|
||||
{"type":"request/header","seq":75,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"change"}}
|
||||
{"type":"assistant/chunk","seq":76,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
|
||||
{"type":"assistant/chunk","seq":77,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_EXECUTABLE_OK"}}}
|
||||
{"type":"assistant/chunk","seq":78,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}}}}
|
||||
{"type":"assistant/chunk","seq":79,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","seq":80,"time":0,"data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
|
||||
{"type":"assistant/message","seq":81,"time":0,"data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[76,77,78,79,80],"surfaceOp":"append"}
|
||||
{"type":"step/end","seq":82,"time":0,"data":{"turn":1,"step":7}}
|
||||
{"type":"turn/end","seq":83,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}}
|
||||
{"type":"turn/start","data":{"turn":1}}
|
||||
{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}}
|
||||
{"type":"step/start","data":{"turn":1,"step":1}}
|
||||
{"type":"user/message","data":{"content":[{"type":"text","text":"Run the advanced packaged-runtime snapshot scenario."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
|
||||
{"type":"session/title","data":{"title":"Run the advanced packaged-runtime snapsh","messageSeqs":[4],"source":{"kind":"fallback"}}}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"initial"}}
|
||||
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":7}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-define","name":"cordis_define","argumentsDelta":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":1,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[9,10,11,12,13],"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":1,"callId":"advanced-define","name":"cordis_define","arguments":"{\"plugin\": {\"kind\": \"new\", \"idPrefix\": \"snap\"}, \"name\": \"Snapshot Double\", \"purpose\": \"Expose a deterministic doubling tool for executable snapshot verification.\", \"code\": {\"host\": \"return (ctx) => {\\n harness.registerTool(ctx, harness.defineTool({\\n name: 'snapshot_double',\\n description: 'Double a number for executable snapshot verification.',\\n parameters: { value: { type: 'number', required: true } },\\n output: {\\n schema: { type: 'number' },\\n render(_args, value) {\\n return [{ type: 'text', text: String(value) }]\\n }\\n },\\n async execute(args) {\\n return args.value * 2\\n }\\n }))\\n}\\n\"}}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"source":{"kind":"tool","callId":"advanced-define"},"content":[{"type":"tool-result","toolCallId":"advanced-define","content":[{"type":"text","text":"Defined snap-1/pkg-1 (Snapshot Double); it is not running yet. Use cordis_run to activate this Package."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1"}},"sourceEventSeqs":[15],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"step/start","data":{"turn":1,"step":2}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":18}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-run","name":"cordis_run","argumentsDelta":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":2,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[20,21,22,23,24],"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":2,"callId":"advanced-run","name":"cordis_run","arguments":"{\"pluginId\": \"snap-1\", \"packageId\": \"pkg-1\", \"mode\": \"run\"}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool","callId":"advanced-run"},"content":[{"type":"tool-result","toolCallId":"advanced-run","content":[{"type":"text","text":"snap-1/pkg-1 is running (run-1)."}],"isError":false}],"role":"user","id":"{{messageId}}"},"meta":{"pluginId":"snap-1","packageId":"pkg-1","pluginRunId":"run-1"}},"sourceEventSeqs":[26],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":2}}
|
||||
{"type":"step/start","data":{"turn":1,"step":3}}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","snapshot_double","subagent","workflow"]},"reason":"change"}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":30}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-code","name":"run_code","argumentsDelta":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":3,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[32,33,34,35,36],"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":3,"callId":"advanced-code","name":"run_code","arguments":"{\"code\": \"return await tools.snapshot_double({ value: 21 })\", \"description\": \"Run the temporary Plugin tool\"}"}}
|
||||
{"type":"tool/code-dispatch-start","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21}}}
|
||||
{"type":"tool/code-dispatch","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:code:1","name":"snapshot_double","arguments":{"value":21},"isError":false,"content":[{"type":"text","text":"42"}]}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool","callId":"advanced-code"},"content":[{"type":"tool-result","toolCallId":"advanced-code","content":[{"type":"text","text":"42"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[38],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":3}}
|
||||
{"type":"step/start","data":{"turn":1,"step":4}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":43}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-direct-child","name":"subagent","argumentsDelta":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":4,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[45,46,47,48,49],"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":4,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":4,"message":{"source":{"kind":"tool","callId":"advanced-direct-child"},"content":[{"type":"tool-result","toolCallId":"advanced-direct-child","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[51],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":4}}
|
||||
{"type":"step/start","data":{"turn":1,"step":5}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":54}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-workflow","name":"workflow","argumentsDelta":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":5,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[56,57,58,59,60],"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":5,"callId":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}
|
||||
{"type":"tool-workflow/run-start","data":{"runId":"{{workflow-run}}","name":"advanced-exe-snapshot"}}
|
||||
{"type":"tool-workflow/agent-start","data":{"runId":"{{workflow-run}}","seq":1,"label":"workflow-child","phase":"Delegate","childId":"{{child-2}}"}}
|
||||
{"type":"tool-workflow/agent-end","data":{"runId":"{{workflow-run}}","seq":1,"outcome":"completed"}}
|
||||
{"type":"tool-workflow/run-end","data":{"runId":"{{workflow-run}}","stopReason":"completed"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":5,"message":{"source":{"kind":"tool","callId":"advanced-workflow"},"content":[{"type":"tool-result","toolCallId":"advanced-workflow","content":[{"type":"text","text":"workflow \"advanced-exe-snapshot\" completed (1 agent).\nReturn value:\n{\n \"reply\": \"WORKFLOW_CHILD_OK\"\n}"}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[62],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":5}}
|
||||
{"type":"step/start","data":{"turn":1,"step":6}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":69}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"tool-call-delta","index":0,"id":"advanced-undefine","name":"cordis_undefine","argumentsDelta":"{\"pluginId\": \"snap-1\"}"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":6,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[71,72,73,74,75],"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":6,"callId":"advanced-undefine","name":"cordis_undefine","arguments":"{\"pluginId\": \"snap-1\"}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":6,"message":{"source":{"kind":"tool","callId":"advanced-undefine"},"content":[{"type":"tool-result","toolCallId":"advanced-undefine","content":[{"type":"text","text":"Removed dynamic Plugin snap-1 and all of its Packages."}],"isError":false}],"role":"user","id":"{{messageId}}"}},"sourceEventSeqs":[77],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":6}}
|
||||
{"type":"step/start","data":{"turn":1,"step":7}}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"system":"{{system}}","tools":["cordis_define","cordis_inspect_list","cordis_inspect_query","cordis_inspect_self","cordis_run","cordis_stop","cordis_undefine","job_kill","job_list","job_output","run_code","subagent","workflow"]},"reason":"change"}}
|
||||
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","throughSeq":81}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-start","index":0,"blockType":"text"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"text-delta","index":0,"text":"ADVANCED_EXECUTABLE_OK"}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}}}
|
||||
{"type":"assistant/chunk","data":{"turn":1,"step":7,"chunk":{"type":"finish","reason":{"kind":"stop"}}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model"},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3}},"sourceEventSeqs":[83,84,85,86,87],"surfaceOp":"append"}
|
||||
{"type":"step/end","data":{"turn":1,"step":7}}
|
||||
{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}}
|
||||
@@ -0,0 +1,430 @@
|
||||
[
|
||||
{
|
||||
"tools": [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "bash",
|
||||
"description": "Run commands in a bash shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* You do have access to a mirror of common linux and python packages via apt and pip.\n* State is persistent across command calls and discussions with the user.\n* To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The bash command to run. Relative path is preferred in the command."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "str_replace_editor",
|
||||
"description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.",
|
||||
"enum": [
|
||||
"view",
|
||||
"create",
|
||||
"str_replace",
|
||||
"insert"
|
||||
]
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`."
|
||||
},
|
||||
"file_text": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `create` command, with the content of the file to be created."
|
||||
},
|
||||
"insert_line": {
|
||||
"type": "integer",
|
||||
"description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`."
|
||||
},
|
||||
"new_str": {
|
||||
"type": "string",
|
||||
"description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert."
|
||||
},
|
||||
"old_str": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `str_replace` command containing the string in `path` to replace."
|
||||
},
|
||||
"view_range": {
|
||||
"type": "array",
|
||||
"description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command",
|
||||
"path"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"text": "You are a helpful software engineer assistant."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tools": [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "bash",
|
||||
"description": "Run commands in a bash shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* You do have access to a mirror of common linux and python packages via apt and pip.\n* State is persistent across command calls and discussions with the user.\n* To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The bash command to run. Relative path is preferred in the command."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "str_replace_editor",
|
||||
"description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.",
|
||||
"enum": [
|
||||
"view",
|
||||
"create",
|
||||
"str_replace",
|
||||
"insert"
|
||||
]
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`."
|
||||
},
|
||||
"file_text": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `create` command, with the content of the file to be created."
|
||||
},
|
||||
"insert_line": {
|
||||
"type": "integer",
|
||||
"description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`."
|
||||
},
|
||||
"new_str": {
|
||||
"type": "string",
|
||||
"description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert."
|
||||
},
|
||||
"old_str": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `str_replace` command containing the string in `path` to replace."
|
||||
},
|
||||
"view_range": {
|
||||
"type": "array",
|
||||
"description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command",
|
||||
"path"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"text": "You are a helpful software engineer assistant."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"toolCalls": [
|
||||
{
|
||||
"id": "minimal-bash-1",
|
||||
"name": "bash"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"toolCallId": "minimal-bash-1",
|
||||
"text": "{{tool-result}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tools": [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "bash",
|
||||
"description": "Run commands in a bash shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* You do have access to a mirror of common linux and python packages via apt and pip.\n* State is persistent across command calls and discussions with the user.\n* To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The bash command to run. Relative path is preferred in the command."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "str_replace_editor",
|
||||
"description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.",
|
||||
"enum": [
|
||||
"view",
|
||||
"create",
|
||||
"str_replace",
|
||||
"insert"
|
||||
]
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`."
|
||||
},
|
||||
"file_text": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `create` command, with the content of the file to be created."
|
||||
},
|
||||
"insert_line": {
|
||||
"type": "integer",
|
||||
"description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`."
|
||||
},
|
||||
"new_str": {
|
||||
"type": "string",
|
||||
"description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert."
|
||||
},
|
||||
"old_str": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `str_replace` command containing the string in `path` to replace."
|
||||
},
|
||||
"view_range": {
|
||||
"type": "array",
|
||||
"description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command",
|
||||
"path"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"text": "You are a helpful software engineer assistant."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"toolCalls": [
|
||||
{
|
||||
"id": "minimal-bash-1",
|
||||
"name": "bash"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"toolCallId": "minimal-bash-1",
|
||||
"text": "{{tool-result}}"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"toolCalls": [
|
||||
{
|
||||
"id": "minimal-bash-2",
|
||||
"name": "bash"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"toolCallId": "minimal-bash-2",
|
||||
"text": "{{tool-result}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"tools": [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "bash",
|
||||
"description": "Run commands in a bash shell\n* When invoking this tool, the contents of the \"command\" parameter does NOT need to be XML-escaped.\n* You don't have access to the internet via this tool.\n* You do have access to a mirror of common linux and python packages via apt and pip.\n* State is persistent across command calls and discussions with the user.\n* To inspect a particular line range of a file, e.g. lines 10-25, try 'sed -n 10,25p /path/to/the/file'.\n* Please avoid commands that may produce a very large amount of output.\n* Please run long lived commands in the background, e.g. 'sleep 10 &' or start a server in the background.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The bash command to run. Relative path is preferred in the command."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "str_replace_editor",
|
||||
"description": "Custom editing tool for viewing, creating and editing files\n* State is persistent across command calls and discussions with the user\n* If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep\n* The `create` command cannot be used if the specified `path` already exists as a file\n* If a `command` generates a long output, it will be truncated and marked with `<response clipped>`\n\nNotes for using the `str_replace` command:\n* The `old_str` parameter should match EXACTLY one or more consecutive lines from the original file. Be mindful of whitespaces!\n* If the `old_str` parameter is not unique in the file, the replacement will not be performed. Make sure to include enough context in `old_str` to make it unique\n* The `new_str` parameter should contain the edited lines that should replace the `old_str`",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"command": {
|
||||
"type": "string",
|
||||
"description": "The commands to run. Allowed options are: `view`, `create`, `str_replace`, `insert`.",
|
||||
"enum": [
|
||||
"view",
|
||||
"create",
|
||||
"str_replace",
|
||||
"insert"
|
||||
]
|
||||
},
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Absolute path to file or directory, e.g. `/repo/file.py` or `/repo`."
|
||||
},
|
||||
"file_text": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `create` command, with the content of the file to be created."
|
||||
},
|
||||
"insert_line": {
|
||||
"type": "integer",
|
||||
"description": "Required parameter of `insert` command. The `new_str` will be inserted AFTER the line `insert_line` of `path`."
|
||||
},
|
||||
"new_str": {
|
||||
"type": "string",
|
||||
"description": "Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert."
|
||||
},
|
||||
"old_str": {
|
||||
"type": "string",
|
||||
"description": "Required parameter of `str_replace` command containing the string in `path` to replace."
|
||||
},
|
||||
"view_range": {
|
||||
"type": "array",
|
||||
"description": "Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.",
|
||||
"items": {
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"command",
|
||||
"path"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"text": "You are a helpful software engineer assistant."
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"text": "Exercise the packaged minimal agent's persistent Bash and string-replacement editor.\nEditor path: {{cwd}}/created.txt"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"toolCalls": [
|
||||
{
|
||||
"id": "minimal-bash-1",
|
||||
"name": "bash"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"toolCallId": "minimal-bash-1",
|
||||
"text": "{{tool-result}}"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"toolCalls": [
|
||||
{
|
||||
"id": "minimal-bash-2",
|
||||
"name": "bash"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"toolCallId": "minimal-bash-2",
|
||||
"text": "{{tool-result}}"
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"toolCalls": [
|
||||
{
|
||||
"id": "minimal-editor",
|
||||
"name": "str_replace_editor"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"role": "tool",
|
||||
"toolCallId": "minimal-editor",
|
||||
"text": "{{tool-result}}"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
@@ -4,7 +4,7 @@
|
||||
"messages": [
|
||||
{
|
||||
"role": "system",
|
||||
"content": "# Translation Prompt\n\nYou are a senior technical translator specializing in LLM and agent development documentation. Your task is to translate the complete source document from English to Chinese, producing natural, professional technical prose.\n\nRead each complete semantic unit, understand it, and restate it as a native technical author would write it in the target language. Do not mechanically preserve source-language syntax. Then verify the translation against the source clause by clause: preserve every proposition and add none. Fluency never justifies losing or altering meaning, and completeness never justifies unnatural word-for-word prose.\n\n## Priority\n\nApply these authorities in order:\n\n1. Preserve the source meaning and the required document structure, protected content, and formatting.\n2. Follow the injected terminology table exactly.\n3. Use the injected whole-document gold pairs to calibrate target-language voice and phrasing.\n4. Apply the general writing guidance and illustrative examples in this prompt.\n\nA lower-priority rule may refine but never override a higher-priority requirement. Gold pairs calibrate voice; they are not a translation memory. No style preference, gold-pair phrasing, or embedded example may override source meaning, required structure, protected content, or the terminology table.\n\n## Quality Requirements\n\n### Structure and Format Preservation\n- Output a complete translated document that maintains the same document frame as the source: heading hierarchy and order, list kinds and item counts, ordered-list starts, table rows and columns, link targets, and code blocks.\n- Paragraph boundaries may change within the same structural unit when the target language needs different semantic grouping. Do not merge or move content across headings, list items, table cells, or other independent structural units.\n- Keep each prose paragraph on one physical line. Use paragraph breaks, not hard-wrapped lines inside a paragraph.\n- Fenced code blocks must be byte-identical to the source, including info strings, whitespace, and ALL comments inside them. Do NOT translate or reformat any content inside code blocks. This is a hard rule with no exceptions.\n- Inline code spans must be kept verbatim. This includes commands, flags, paths, identifiers, API and event names, config keys, protocol values, version numbers, and other machine-readable tokens. Never translate or reformat them.\n- Every relative link must point to the same target as in the source. Translate link text; do not change link targets.\n- Language switcher line: when an English source contains `English | [中文](source-filename.zh.md)`, write `[English](source-filename.md) | 中文`. When a Chinese source contains `[English](source-filename.md) | 中文`, write `English | [中文](source-filename.zh.md)`. Do NOT copy the source switcher unchanged. If the source has no switcher, do not invent a filename or switcher; the pipeline inserts the canonical target switcher after parsing `<final>`.\n- Preserve emphasis marker types and the semantic spans they cover. Do not add, remove, move, or change bold and italic markers.\n\n### Faithfulness\n- Preserve every proposition in the source and add none. Every sentence, list item, note, FIXME, warning, example, caveat, prerequisite, and guarantee must have an equivalent in the translation. Count list items on both sides.\n- Preserve actors, objects, conditions, exceptions, negation, modality, causal relationships, and distinctions between concepts.\n- Preserve the exact strength and orientation of contracts. Completion and lifecycle conditions, failure behavior, directions and data flow, normal and exceptional result channels, ownership changes, and quantitative bounds must not be weakened, strengthened, reversed, or merged.\n- Translate ideas rather than source-language idioms, but never use fluency as a reason to omit or alter meaning.\n\n### Tone and Style\n- The translation must read as if originally written in the target language by a native technical author. If an expression sounds like a word-for-word rendering from the source language, rephrase it.\n- Write in a professional, formal tone appropriate for developer documentation. Never use colloquial or casual expressions.\n- Name an actor when the target language would otherwise obscure an actor that the source states or unambiguously implies. Never invent responsibility merely to avoid a passive construction.\n- Prefer established target-language engineering terms over literal renderings. Replace metaphors with direct descriptions that preserve the source meaning.\n- Use polite imperative forms where the text instructs the reader to do something. In Chinese, address the reader as `你`, not `您`.\n- Keep the author's register: concise stays concise, detailed stays detailed.\n\n### Sentence Structure\n- Break long sentences where the target language needs a pause. Avoid run-on sentences.\n- UseLine truncated
|
||||
"content": "# Translation Prompt\n\nYou are a senior technical translator specializing in LLM and agent development documentation. Your task is to translate the complete source document from English to Chinese, producing natural, professional technical prose.\n\nRead each complete semantic unit, understand it, and restate it as a native technical author would write it in the target language. Do not mechanically preserve source-language syntax. Then verify the translation against the source clause by clause: preserve every proposition and add none. Fluency never justifies losing or altering meaning, and completeness never justifies unnatural word-for-word prose.\n\n## Priority\n\nApply these authorities in order:\n\n1. Preserve the source meaning and the required document structure, protected content, and formatting.\n2. Follow the injected terminology table exactly.\n3. Use the injected whole-document gold pairs to calibrate target-language voice and phrasing.\n4. Apply the general writing guidance and illustrative examples in this prompt.\n\nA lower-priority rule may refine but never override a higher-priority requirement. Gold pairs calibrate voice; they are not a translation memory. No style preference, gold-pair phrasing, or embedded example may override source meaning, required structure, protected content, or the terminology table.\n\n## Quality Requirements\n\n### Structure and Format Preservation\n- Output a complete translated document that maintains the same document frame as the source: heading hierarchy and order, list kinds and item counts, ordered-list starts, table rows and columns, link order and semantic targets, and code blocks.\n- Paragraph boundaries may change within the same structural unit when the target language needs different semantic grouping. Do not merge or move content across headings, list items, table cells, or other independent structural units.\n- Keep each prose paragraph on one physical line. Use paragraph breaks, not hard-wrapped lines inside a paragraph.\n- Fenced code blocks must be byte-identical to the source, including info strings, whitespace, and ALL comments inside them. Do NOT translate or reformat any content inside code blocks. This is a hard rule with no exceptions.\n- Inline code spans must be kept verbatim. This includes commands, flags, paths, identifiers, API and event names, config keys, protocol values, version numbers, and other machine-readable tokens. Never translate or reformat them.\n- Every repository-relative document link must keep the source link's semantic target and exact query/fragment suffix. When the target belongs to the active bilingual corpus, English output uses its `.md` path and Chinese output uses its `.zh.md` path; a missing counterpart in that corpus is an error, while targets outside it keep the original path. External URLs, images, and pure in-page fragments stay unchanged. Translate link text.\n- Language switcher line: when an English source contains `English | [中文](source-filename.zh.md)`, write `[English](source-filename.md) | 中文`. When a Chinese source contains `[English](source-filename.md) | 中文`, write `English | [中文](source-filename.zh.md)`. Do NOT copy the source switcher unchanged. If the source has no switcher, do not invent a filename or switcher; the pipeline inserts the canonical target switcher after parsing `<final>`.\n- Preserve emphasis marker types and the semantic spans they cover. Do not add, remove, move, or change bold and italic markers.\n\n### Faithfulness\n- Preserve every proposition in the source and add none. Every sentence, list item, note, FIXME, warning, example, caveat, prerequisite, and guarantee must have an equivalent in the translation. Count list items on both sides.\n- Preserve actors, objects, conditions, exceptions, negation, modality, causal relationships, and distinctions between concepts.\n- Preserve the exact strength and orientation of contracts. Completion and lifecycle conditions, failure behavior, directions and data flow, normal and exceptional result channels, ownership changes, and quantitative bounds must not be weakened, strengthened, reversed, or merged.\n- Translate ideas rather than source-language idioms, but never use fluency as a reason to omit or alter meaning.\n\n### Tone and Style\n- The translation must read as if originally written in the target language by a native technical author. If an expression sounds like a word-for-word rendering from the source language, rephrase it.\n- Write in a professional, formal tone appropriate for developer documentation. Never use colloquial or casual expressions.\n- Name an actor when the target language would otherwise obscure an actor that the source states or unambiguously implies. Never invent responsibility merely to avoid a passive construction.\n- Prefer established target-language engineering terms over literal renderings. Replace metaphors with direct descriptions that preserve the source meaninLine truncated
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
|
||||
@@ -117,6 +117,7 @@ class TestAttachmentStore extends AttachmentStore {
|
||||
maxImagesPerMessage: 1,
|
||||
maxMessageImageBytes: 1,
|
||||
maxImagePixels: 1,
|
||||
maxImageDimension: 1,
|
||||
mediaTypes: ['image/png'],
|
||||
}
|
||||
|
||||
|
||||
@@ -215,6 +215,8 @@ describe('brief rendering', () => {
|
||||
expect(brief).toContain('## First-occurrence notes')
|
||||
expect(brief).toContain('agent(智能体)')
|
||||
expect(brief).toContain('首次出现 annotations attach to the document-wide first occurrence only')
|
||||
expect(brief).toContain('targets in the active bilingual corpus use `.zh.md` for Chinese')
|
||||
expect(brief).toContain('a missing in-scope counterpart is an error')
|
||||
expect(brief).toContain('verify-translation-pairing --write docs/foo.md')
|
||||
})
|
||||
|
||||
@@ -266,6 +268,8 @@ describe('brief rendering', () => {
|
||||
scope: { kind: 'units', bundles: [bundle], firstOccurrenceNotes: [] },
|
||||
})
|
||||
expect(brief).toContain('exactly what the new Chinese states')
|
||||
expect(brief).toContain('targets in the active bilingual corpus use `.md` for English')
|
||||
expect(brief).toContain('targets outside the corpus keep the authored path')
|
||||
expect(brief).toContain('verify-translation-pairing --write docs/foo.md')
|
||||
})
|
||||
|
||||
|
||||
@@ -386,7 +386,7 @@ const ZH_TARGET_DIGEST = [
|
||||
'- Nothing added, nothing dropped: the Chinese must state exactly what the new English states.',
|
||||
'- Write natural institutional technical Chinese, not word-by-word gloss; terse stays terse.',
|
||||
'- Code fences byte-identical to the English side, comments included; inline code spans verbatim.',
|
||||
'- Relative links keep the `.md` target; only the switcher line links `.zh.md`.',
|
||||
'- Repository-relative document links keep the same semantic target and exact query/fragment; targets in the active bilingual corpus use `.zh.md` for Chinese, a missing in-scope counterpart is an error, and targets outside the corpus keep the authored path. The switcher remains the cross-locale exception.',
|
||||
'- Structure mirrors the counterpart: heading depths and order, list kinds and item counts, table rows and columns.',
|
||||
'- 首次出现 annotations attach to the document-wide first occurrence only; later occurrences use the bare form, and an empty 首次出现 cell means never gloss.',
|
||||
'- Typography: one half-width space between Chinese and Latin or digits; full-width punctuation in Chinese prose; 顿号 for enumerations; second person is 你.',
|
||||
@@ -398,7 +398,7 @@ const EN_TARGET_DIGEST = [
|
||||
'- Nothing added, nothing dropped: the English must state exactly what the new Chinese states.',
|
||||
'- Write concise professional developer prose, not word-by-word gloss; terse stays terse.',
|
||||
'- Code fences byte-identical to the Chinese side, comments included; inline code spans verbatim.',
|
||||
'- Relative links keep the `.md` target; only the switcher line links `.zh.md`.',
|
||||
'- Repository-relative document links keep the same semantic target and exact query/fragment; targets in the active bilingual corpus use `.md` for English, a missing in-scope counterpart is an error, and targets outside the corpus keep the authored path. The switcher remains the cross-locale exception.',
|
||||
'- Structure mirrors the counterpart: heading depths and order, list kinds and item counts, table rows and columns.',
|
||||
'- One physical line per paragraph; exactly one trailing newline.',
|
||||
]
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
/** Regression coverage for locale-aware bilingual Markdown links. */
|
||||
|
||||
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
normalizeTranslationMarkdownLinks,
|
||||
rewriteTranslationLinkLocales,
|
||||
translationLinkLocaleViolations,
|
||||
type TranslationLinkContext,
|
||||
} from './translation-links.ts'
|
||||
import { removeFixtureSafely } from './test-fixture-cleanup.ts'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) removeFixtureSafely(root)
|
||||
})
|
||||
|
||||
function fixture(): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-translation-links-'))
|
||||
roots.push(root)
|
||||
mkdirSync(join(root, 'docs/section'), { recursive: true })
|
||||
mkdirSync(join(root, 'packages'), { recursive: true })
|
||||
writeFileSync(join(root, 'docs/guide.md'), '# Guide\n')
|
||||
writeFileSync(join(root, 'docs/guide.zh.md'), '# 指南\n')
|
||||
writeFileSync(join(root, 'docs/reference.md'), '# Overview\n')
|
||||
writeFileSync(join(root, 'docs/reference.zh.md'), '# 概览\n')
|
||||
writeFileSync(join(root, 'docs/unpaired.md'), '# Only\n')
|
||||
writeFileSync(join(root, 'docs/section/index.md'), '# Section\n')
|
||||
writeFileSync(join(root, 'docs/section/index.zh.md'), '# 章节\n')
|
||||
writeFileSync(join(root, 'packages/outside.md'), '# Outside\n')
|
||||
writeFileSync(join(root, 'packages/outside.zh.md'), '# 范围外\n')
|
||||
return root
|
||||
}
|
||||
|
||||
function linkContext(
|
||||
root: string,
|
||||
sourcePath: string,
|
||||
repositoryFileExists?: (repoPath: string) => boolean,
|
||||
): TranslationLinkContext {
|
||||
return {
|
||||
repoRoot: root,
|
||||
sourcePath,
|
||||
isTranslationPairSource: path => path.startsWith('docs/'),
|
||||
...(repositoryFileExists === undefined ? {} : { repositoryFileExists }),
|
||||
}
|
||||
}
|
||||
|
||||
function expectUnchangedLinkInput(root: string, input: string): void {
|
||||
const context = linkContext(root, 'docs/guide.md')
|
||||
expect(translationLinkLocaleViolations(input, context)).toEqual([])
|
||||
expect(rewriteTranslationLinkLocales(input, context)).toEqual({ content: input, rewritten: 0 })
|
||||
expect(normalizeTranslationMarkdownLinks(input, context)).toBe(input)
|
||||
}
|
||||
|
||||
describe('translation link locale validation', () => {
|
||||
it('rejects a Chinese link to the English sibling with an exact diagnostic', () => {
|
||||
const root = fixture()
|
||||
expect(translationLinkLocaleViolations(
|
||||
'# 指南\n\n正文。\n\n[概览](reference.md?view=full#overview)\n',
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
)).toEqual([{
|
||||
sourcePath: 'docs/guide.zh.md',
|
||||
line: 5,
|
||||
url: 'reference.md?view=full#overview',
|
||||
expectedUrl: 'reference.zh.md?view=full#overview',
|
||||
}])
|
||||
})
|
||||
|
||||
it('rewrites an encoded exact filename without changing its query or fragment suffix', () => {
|
||||
const root = fixture()
|
||||
const input = '[概览](reference%2Emd?view=full&mode=all#overview)\n'
|
||||
expect(translationLinkLocaleViolations(
|
||||
input,
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
)[0]).toMatchObject({
|
||||
url: 'reference%2Emd?view=full&mode=all#overview',
|
||||
expectedUrl: 'reference.zh.md?view=full&mode=all#overview',
|
||||
})
|
||||
expect(rewriteTranslationLinkLocales(input, linkContext(root, 'docs/guide.zh.md'))).toEqual({
|
||||
content: '[概览](reference.zh.md?view=full&mode=all#overview)\n',
|
||||
rewritten: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('encodes each exact path segment with only RFC 3986 unreserved characters', () => {
|
||||
const root = fixture()
|
||||
const input = '[保留](a%29%23%3Fb%2Emd?view=full#section)\n'
|
||||
const repositoryFiles = new Set(['docs/a)#?b.md', 'docs/a)#?b.zh.md'])
|
||||
expect(rewriteTranslationLinkLocales(
|
||||
input,
|
||||
linkContext(root, 'docs/guide.zh.md', path => repositoryFiles.has(path)),
|
||||
)).toEqual({
|
||||
content: '[保留](a%29%23%3Fb.zh.md?view=full#section)\n',
|
||||
rewritten: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts the target-locale sibling and an out-of-scope target with its own sibling', () => {
|
||||
const root = fixture()
|
||||
expect(translationLinkLocaleViolations(
|
||||
'[paired](reference.zh.md) [outside](../packages/outside.md)\n',
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
)).toEqual([])
|
||||
})
|
||||
|
||||
it('does not fall back when an active target is missing its locale sibling', () => {
|
||||
const root = fixture()
|
||||
expect(translationLinkLocaleViolations(
|
||||
'[missing](unpaired.md)\n',
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
)[0]).toMatchObject({ expectedUrl: 'unpaired.zh.md' })
|
||||
})
|
||||
|
||||
it('requires English sources to use the English sibling', () => {
|
||||
const root = fixture()
|
||||
expect(translationLinkLocaleViolations(
|
||||
'[Reference](reference.zh.md)\n',
|
||||
linkContext(root, 'docs/guide.md'),
|
||||
)[0]).toMatchObject({
|
||||
url: 'reference.zh.md',
|
||||
expectedUrl: 'reference.md',
|
||||
})
|
||||
})
|
||||
|
||||
it('does not infer an index page from a directory target', () => {
|
||||
const root = fixture()
|
||||
const input = '[Section](section/)\n'
|
||||
expect(translationLinkLocaleViolations(input, linkContext(root, 'docs/guide.zh.md'))).toEqual([])
|
||||
expect(rewriteTranslationLinkLocales(input, linkContext(root, 'docs/guide.zh.md')))
|
||||
.toEqual({ content: input, rewritten: 0 })
|
||||
})
|
||||
|
||||
it('exempts the language switcher target explicitly', () => {
|
||||
const root = fixture()
|
||||
expect(translationLinkLocaleViolations(
|
||||
'# 指南\n\n[English](guide.md) | 中文\n',
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
['guide.md'],
|
||||
)).toEqual([])
|
||||
})
|
||||
|
||||
it('does not exempt an ordinary body link to the counterpart', () => {
|
||||
const root = fixture()
|
||||
const markdown = '# 指南\n\n[English](guide.md) | 中文\n\n[正文](guide.md)\n'
|
||||
expect(translationLinkLocaleViolations(
|
||||
markdown,
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
['guide.md'],
|
||||
)).toEqual([{
|
||||
sourcePath: 'docs/guide.zh.md',
|
||||
line: 5,
|
||||
url: 'guide.md',
|
||||
expectedUrl: 'guide.zh.md',
|
||||
}])
|
||||
expect(rewriteTranslationLinkLocales(
|
||||
markdown,
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
['guide.md'],
|
||||
).content).toBe('# 指南\n\n[English](guide.md) | 中文\n\n[正文](guide.zh.md)\n')
|
||||
})
|
||||
|
||||
it('uses the selected content plane for target existence without deriving scope from siblings', () => {
|
||||
const root = fixture()
|
||||
const staged = new Set(['docs/reference.md', 'docs/reference.zh.md'])
|
||||
expect(translationLinkLocaleViolations(
|
||||
'[概览](reference.md)\n',
|
||||
linkContext(root, 'docs/guide.zh.md', path => staged.has(path)),
|
||||
)).toHaveLength(1)
|
||||
staged.delete('docs/reference.zh.md')
|
||||
expect(translationLinkLocaleViolations(
|
||||
'[概览](reference.md)\n',
|
||||
linkContext(root, 'docs/guide.zh.md', path => staged.has(path)),
|
||||
)).toHaveLength(1)
|
||||
staged.delete('docs/reference.md')
|
||||
expect(translationLinkLocaleViolations(
|
||||
'[概览](reference.md)\n',
|
||||
linkContext(root, 'docs/guide.zh.md', path => staged.has(path)),
|
||||
)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('translation link rewriting and normalization', () => {
|
||||
it('rewrites only the destination while preserving the suffix and title', () => {
|
||||
const root = fixture()
|
||||
const input = '[概览](reference.md?view=full&mode=all#overview "reference.md title")\n'
|
||||
expect(rewriteTranslationLinkLocales(
|
||||
input,
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
)).toEqual({
|
||||
content: '[概览](reference.zh.md?view=full&mode=all#overview "reference.md title")\n',
|
||||
rewritten: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('rewrites link definitions without changing their labels', () => {
|
||||
const root = fixture()
|
||||
expect(rewriteTranslationLinkLocales(
|
||||
'[概览][ref]\n\n[ref]: <reference.md#overview> "title"\n',
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
).content).toBe('[概览][ref]\n\n[ref]: <reference.zh.md#overview> "title"\n')
|
||||
})
|
||||
|
||||
it('uses only the first duplicate reference definition', () => {
|
||||
const root = fixture()
|
||||
expect(translationLinkLocaleViolations(
|
||||
'[概览][ref]\n\n[ref]: reference.zh.md\n[ref]: reference.md\n',
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
)).toEqual([])
|
||||
})
|
||||
|
||||
it('does not treat an image-only definition as a document link', () => {
|
||||
const root = fixture()
|
||||
const input = '![preview][asset]\n\n[asset]: reference.zh.md#overview\n'
|
||||
expectUnchangedLinkInput(root, input)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'<https://example.com/reference.md>\n',
|
||||
'https://example.com/reference.md\n',
|
||||
])('leaves GFM autolink source unchanged: %s', (input) => {
|
||||
const root = fixture()
|
||||
expectUnchangedLinkInput(root, input)
|
||||
})
|
||||
|
||||
it('normalizes only paired locale paths and retains other bytes', () => {
|
||||
const root = fixture()
|
||||
const english = '[Reference](reference.md#overview) [Outside](../packages/outside.md)\n'
|
||||
const chinese = '[Reference](reference.zh.md#overview) [Outside](../packages/outside.md)\n'
|
||||
expect(normalizeTranslationMarkdownLinks(
|
||||
english,
|
||||
linkContext(root, 'docs/guide.md'),
|
||||
)).toBe(normalizeTranslationMarkdownLinks(
|
||||
chinese,
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
))
|
||||
})
|
||||
|
||||
it('retains authored query bytes during normalization', () => {
|
||||
const root = fixture()
|
||||
const escaped = '[Reference](reference.md?x=1&y=2#overview)\n'
|
||||
const literal = '[Reference](reference.zh.md?x=1&y=2#overview)\n'
|
||||
expect(normalizeTranslationMarkdownLinks(
|
||||
escaped,
|
||||
linkContext(root, 'docs/guide.md'),
|
||||
)).not.toBe(normalizeTranslationMarkdownLinks(
|
||||
literal,
|
||||
linkContext(root, 'docs/guide.zh.md'),
|
||||
))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,328 @@
|
||||
/** Locale-aware resolution and byte-preserving rewrites for bilingual Markdown links. */
|
||||
|
||||
import { existsSync, statSync } from 'node:fs'
|
||||
import { posix, resolve } from 'node:path'
|
||||
import type { Nodes } from 'mdast'
|
||||
import {
|
||||
isExternalOrAbsoluteMarkdownUrl,
|
||||
markdownDestination,
|
||||
parseMarkdown,
|
||||
splitMarkdownUrlTarget,
|
||||
visitMarkdown,
|
||||
type MarkdownDestination,
|
||||
} from './markdown.ts'
|
||||
|
||||
/** Repository and source document used to resolve one relative link. */
|
||||
export interface TranslationLinkContext {
|
||||
/** Absolute repository root. */
|
||||
repoRoot: string
|
||||
/** Repository-relative Markdown source path. */
|
||||
sourcePath: string
|
||||
/** Whether an English Markdown path belongs to the active bilingual corpus. */
|
||||
isTranslationPairSource: (sourcePath: string) => boolean
|
||||
/** Selected content plane; defaults to regular files in the working tree. */
|
||||
repositoryFileExists?: (repoPath: string) => boolean
|
||||
}
|
||||
|
||||
/** One relative document link whose target uses the wrong locale sibling. */
|
||||
export interface TranslationLinkLocaleViolation {
|
||||
sourcePath: string
|
||||
line: number
|
||||
url: string
|
||||
expectedUrl: string
|
||||
}
|
||||
|
||||
/** Result of rewriting wrong-locale relative document links. */
|
||||
export interface TranslationLinkRewriteResult {
|
||||
content: string
|
||||
rewritten: number
|
||||
}
|
||||
|
||||
interface TranslationPairTarget {
|
||||
source: string
|
||||
zh: string
|
||||
}
|
||||
|
||||
interface ResolvedTranslationLink {
|
||||
pair: TranslationPairTarget
|
||||
targetPath: string
|
||||
suffix: string
|
||||
expectedPath: string
|
||||
expectedUrl: string
|
||||
locale: 'en' | 'zh'
|
||||
}
|
||||
|
||||
interface Replacement {
|
||||
start: number
|
||||
end: number
|
||||
value: string
|
||||
}
|
||||
|
||||
type LinkNode = Extract<Nodes, { type: 'link' | 'definition' }>
|
||||
|
||||
/** Offset of the one top-level switcher link immediately following the H1. */
|
||||
export function languageSwitcherLinkOffset(
|
||||
tree: Nodes,
|
||||
markdown: string,
|
||||
acceptedTargets: string | readonly string[],
|
||||
): number | undefined {
|
||||
if (tree.type !== 'root') return undefined
|
||||
const accepted = new Set(typeof acceptedTargets === 'string' ? [acceptedTargets] : acceptedTargets)
|
||||
const headingIndex = tree.children.findIndex(node => node.type === 'heading' && node.depth === 1)
|
||||
if (headingIndex < 0) return undefined
|
||||
for (const node of tree.children.slice(headingIndex + 1)) {
|
||||
if (node.type === 'heading') return undefined
|
||||
if (node.type !== 'paragraph' || node.position === undefined) continue
|
||||
const start = node.position.start.offset
|
||||
const end = node.position.end.offset
|
||||
if (start === undefined || end === undefined) continue
|
||||
const authored = markdown.slice(start, end)
|
||||
if (!/^(?:English \| \[中文\]\([^\n]+\)|\[English\]\([^\n]+\) \| 中文)$/.test(authored)) continue
|
||||
const links = node.children.filter((child): child is Extract<Nodes, { type: 'link' }> => child.type === 'link')
|
||||
if (links.length === 1 && accepted.has(links[0]?.url ?? '')) {
|
||||
return links[0]?.position?.start.offset
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** Whether the tree carries its canonical top-level language switcher. */
|
||||
export function hasLanguageSwitcher(
|
||||
tree: Nodes,
|
||||
markdown: string,
|
||||
acceptedTargets: string | readonly string[],
|
||||
): boolean {
|
||||
return languageSwitcherLinkOffset(tree, markdown, acceptedTargets) !== undefined
|
||||
}
|
||||
|
||||
function decodePath(path: string): string {
|
||||
try {
|
||||
return decodeURIComponent(path)
|
||||
} catch {
|
||||
return path
|
||||
}
|
||||
}
|
||||
|
||||
function worktreeFileExists(repoRoot: string, repoPath: string): boolean {
|
||||
try {
|
||||
const path = resolve(repoRoot, repoPath)
|
||||
return existsSync(path) && statSync(path).isFile()
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function repositoryFileExists(context: TranslationLinkContext, repoPath: string): boolean {
|
||||
return context.repositoryFileExists?.(repoPath) ?? worktreeFileExists(context.repoRoot, repoPath)
|
||||
}
|
||||
|
||||
function repositoryRelativePath(path: string): string | undefined {
|
||||
const normalized = posix.normalize(path)
|
||||
if (normalized === '' || normalized === '.' || normalized === '..' || normalized.startsWith('../') || posix.isAbsolute(normalized)) {
|
||||
return undefined
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function resolveRepositoryTarget(
|
||||
rawPath: string,
|
||||
context: TranslationLinkContext,
|
||||
): string | undefined {
|
||||
const decoded = decodePath(rawPath)
|
||||
const exact = repositoryRelativePath(posix.join(posix.dirname(context.sourcePath), decoded))
|
||||
if (exact === undefined) return undefined
|
||||
return repositoryFileExists(context, exact) ? exact : undefined
|
||||
}
|
||||
|
||||
function translationPairTarget(targetPath: string, context: TranslationLinkContext): TranslationPairTarget | undefined {
|
||||
const source = targetPath.endsWith('.zh.md')
|
||||
? targetPath.replace(/\.zh\.md$/, '.md')
|
||||
: targetPath.endsWith('.md') ? targetPath : undefined
|
||||
if (source === undefined || !context.isTranslationPairSource(source)) return undefined
|
||||
const zh = source.replace(/\.md$/, '.zh.md')
|
||||
return { source, zh }
|
||||
}
|
||||
|
||||
function encodePathSegment(segment: string): string {
|
||||
return encodeURIComponent(segment).replace(/[!'()*]/g, character => (
|
||||
`%${character.charCodeAt(0).toString(16).toUpperCase()}`
|
||||
))
|
||||
}
|
||||
|
||||
function relativeExpectedPath(
|
||||
context: TranslationLinkContext,
|
||||
expectedPath: string,
|
||||
rawPath: string,
|
||||
): string {
|
||||
const relative = posix.relative(posix.dirname(context.sourcePath), expectedPath)
|
||||
const encoded = relative.split('/').map(encodePathSegment).join('/')
|
||||
return rawPath.startsWith('./') && !encoded.startsWith('.') ? `./${encoded}` : encoded
|
||||
}
|
||||
|
||||
function expectedLocalePath(
|
||||
rawPath: string,
|
||||
locale: 'en' | 'zh',
|
||||
context: TranslationLinkContext,
|
||||
expectedPath: string,
|
||||
): string {
|
||||
if (locale === 'zh' && rawPath.endsWith('.md') && !rawPath.endsWith('.zh.md')) {
|
||||
return rawPath.replace(/\.md$/, '.zh.md')
|
||||
}
|
||||
if (locale === 'en' && rawPath.endsWith('.zh.md')) return rawPath.replace(/\.zh\.md$/, '.md')
|
||||
return relativeExpectedPath(context, expectedPath, rawPath)
|
||||
}
|
||||
|
||||
function resolveTranslationLink(
|
||||
url: string,
|
||||
context: TranslationLinkContext,
|
||||
authoredUrl: string,
|
||||
): ResolvedTranslationLink | undefined {
|
||||
if (isExternalOrAbsoluteMarkdownUrl(url)) return undefined
|
||||
const { path } = splitMarkdownUrlTarget(url)
|
||||
const authored = splitMarkdownUrlTarget(authoredUrl)
|
||||
if (path === '') return undefined
|
||||
const targetPath = resolveRepositoryTarget(path, context)
|
||||
if (targetPath === undefined) return undefined
|
||||
const pair = translationPairTarget(targetPath, context)
|
||||
if (pair === undefined) return undefined
|
||||
const locale = context.sourcePath.endsWith('.zh.md') ? 'zh' : 'en'
|
||||
const expectedPath = locale === 'zh' ? pair.zh : pair.source
|
||||
return {
|
||||
pair,
|
||||
targetPath,
|
||||
suffix: authored.suffix,
|
||||
expectedPath,
|
||||
expectedUrl: `${expectedLocalePath(authored.path, locale, context, expectedPath)}${authored.suffix}`,
|
||||
locale,
|
||||
}
|
||||
}
|
||||
|
||||
function hasExpectedLocale(resolved: ResolvedTranslationLink): boolean {
|
||||
return resolved.targetPath === resolved.expectedPath
|
||||
}
|
||||
|
||||
function replacementFor(destination: MarkdownDestination, value: string): Replacement {
|
||||
return { start: destination.start, end: destination.end, value }
|
||||
}
|
||||
|
||||
function authoredExternalTarget(markdown: string, node: LinkNode): string {
|
||||
const start = node.position?.start.offset
|
||||
const end = node.position?.end.offset
|
||||
if (start === undefined || end === undefined) {
|
||||
throw new Error(`translation-links: external link ${JSON.stringify(node.url)} has no source offsets`)
|
||||
}
|
||||
const raw = markdown.slice(start, end)
|
||||
if (node.type === 'definition' || raw.startsWith('[')) return markdownDestination(markdown, node).url
|
||||
if (raw.startsWith('<') && raw.endsWith('>')) return raw.slice(1, -1)
|
||||
return raw
|
||||
}
|
||||
|
||||
function applyReplacements(markdown: string, replacements: Replacement[]): string {
|
||||
let output = markdown
|
||||
for (const replacement of replacements.sort((left, right) => right.start - left.start)) {
|
||||
output = output.slice(0, replacement.start) + replacement.value + output.slice(replacement.end)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
function visitDocumentLinkNodes(
|
||||
markdown: string,
|
||||
skipTargets: readonly string[],
|
||||
visitor: (node: LinkNode) => void,
|
||||
): void {
|
||||
const tree = parseMarkdown(markdown)
|
||||
const switcherOffset = languageSwitcherLinkOffset(tree, markdown, skipTargets)
|
||||
const referencedIdentifiers = new Set<string>()
|
||||
const visitedDefinitions = new Set<string>()
|
||||
visitMarkdown(tree, (node) => {
|
||||
if (node.type === 'linkReference') referencedIdentifiers.add(node.identifier)
|
||||
})
|
||||
visitMarkdown(tree, (node) => {
|
||||
if (node.type === 'link' && node.position?.start.offset === switcherOffset) return
|
||||
if (node.type === 'link') {
|
||||
visitor(node)
|
||||
} else if (node.type === 'definition'
|
||||
&& referencedIdentifiers.has(node.identifier)
|
||||
&& !visitedDefinitions.has(node.identifier)) {
|
||||
visitedDefinitions.add(node.identifier)
|
||||
visitor(node)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function visitResolvedDocumentLinks(
|
||||
markdown: string,
|
||||
context: TranslationLinkContext,
|
||||
skipTargets: readonly string[],
|
||||
visitor: (node: LinkNode, destination: MarkdownDestination, resolved: ResolvedTranslationLink) => void,
|
||||
): void {
|
||||
visitDocumentLinkNodes(markdown, skipTargets, (node) => {
|
||||
if (isExternalOrAbsoluteMarkdownUrl(node.url)) return
|
||||
const destination = markdownDestination(markdown, node)
|
||||
const resolved = resolveTranslationLink(node.url, context, destination.url)
|
||||
if (resolved !== undefined) visitor(node, destination, resolved)
|
||||
})
|
||||
}
|
||||
|
||||
/** Return one violation per wrong-locale link or link definition. */
|
||||
export function translationLinkLocaleViolations(
|
||||
markdown: string,
|
||||
context: TranslationLinkContext,
|
||||
skipTargets: readonly string[] = [],
|
||||
): TranslationLinkLocaleViolation[] {
|
||||
const violations: TranslationLinkLocaleViolation[] = []
|
||||
visitResolvedDocumentLinks(markdown, context, skipTargets, (node, destination, resolved) => {
|
||||
if (hasExpectedLocale(resolved)) return
|
||||
violations.push({
|
||||
sourcePath: context.sourcePath,
|
||||
line: node.position?.start.line ?? 0,
|
||||
url: destination.url,
|
||||
expectedUrl: resolved.expectedUrl,
|
||||
})
|
||||
})
|
||||
return violations
|
||||
}
|
||||
|
||||
/** Rewrite wrong-locale document links without reserializing surrounding Markdown. */
|
||||
export function rewriteTranslationLinkLocales(
|
||||
markdown: string,
|
||||
context: TranslationLinkContext,
|
||||
skipTargets: readonly string[] = [],
|
||||
): TranslationLinkRewriteResult {
|
||||
const replacements: Replacement[] = []
|
||||
visitResolvedDocumentLinks(markdown, context, skipTargets, (_node, destination, resolved) => {
|
||||
if (hasExpectedLocale(resolved)) return
|
||||
replacements.push(replacementFor(destination, resolved.expectedUrl))
|
||||
})
|
||||
return { content: applyReplacements(markdown, replacements), rewritten: replacements.length }
|
||||
}
|
||||
|
||||
/** Normalize only paired-document locale paths while retaining every other byte and URL suffix. */
|
||||
export function normalizeTranslationMarkdownLinks(
|
||||
markdown: string,
|
||||
context: TranslationLinkContext,
|
||||
skipTargets: readonly string[] = [],
|
||||
): string {
|
||||
const replacements: Replacement[] = []
|
||||
visitResolvedDocumentLinks(markdown, context, skipTargets, (_node, destination, resolved) => {
|
||||
replacements.push(replacementFor(
|
||||
destination,
|
||||
`dsh-translation-target:${resolved.pair.source}${resolved.suffix}`,
|
||||
))
|
||||
})
|
||||
return applyReplacements(markdown, replacements)
|
||||
}
|
||||
|
||||
/** Semantic target of one authored inline link or referenced definition. */
|
||||
export function semanticTranslationLinkNodeTarget(
|
||||
node: LinkNode,
|
||||
markdown: string,
|
||||
context: TranslationLinkContext,
|
||||
): string {
|
||||
if (isExternalOrAbsoluteMarkdownUrl(node.url)) return authoredExternalTarget(markdown, node)
|
||||
const destination = markdownDestination(markdown, node)
|
||||
const resolved = resolveTranslationLink(node.url, context, destination.url)
|
||||
return resolved === undefined
|
||||
? destination.url
|
||||
: `dsh-translation-target:${resolved.pair.source}${resolved.suffix}`
|
||||
}
|
||||
@@ -42,12 +42,48 @@ export function runGit(root: string, args: string[], operation: string, input?:
|
||||
|
||||
/** One regular stage-zero Git index entry and its exact blob bytes. */
|
||||
export interface GitIndexBlob {
|
||||
/** Object ID recorded in the index. */
|
||||
objectId: string
|
||||
/** Blob bytes stored under that object ID. */
|
||||
content: Buffer
|
||||
}
|
||||
|
||||
/** Every stage-zero path currently present in the Git index. */
|
||||
export function gitIndexPaths(root: string): Set<string> {
|
||||
const paths = new Set<string>()
|
||||
const entries = runGit(root, ['ls-files', '--stage', '-z'], 'listing Git index paths')
|
||||
.toString('utf8')
|
||||
.split('\0')
|
||||
.filter(Boolean)
|
||||
for (const entry of entries) {
|
||||
const match = /^\d+ [0-9a-f]+ ([0-3])\t([\s\S]+)$/.exec(entry)
|
||||
if (!match?.[1] || match[2] === undefined) throw new Error('git ls-files --stage returned a malformed entry')
|
||||
if (match[1] === '0') paths.add(match[2])
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths visible to a custom merge driver from the current index plus every
|
||||
* merge head Git advertises through `GITHEAD_<oid>` environment entries.
|
||||
*
|
||||
* Git invokes custom drivers before it writes clean additions from the other
|
||||
* heads into stage zero. The explicit post-conflict resolver has no GITHEAD
|
||||
* entries and therefore uses the already-merged index alone.
|
||||
*/
|
||||
export function gitMergeInputPaths(root: string, environment: NodeJS.ProcessEnv = process.env): Set<string> {
|
||||
const paths = gitIndexPaths(root)
|
||||
const heads = Object.keys(environment)
|
||||
.flatMap(key => /^GITHEAD_([0-9a-f]{40})$/.exec(key)?.[1] ?? [])
|
||||
.sort()
|
||||
for (const head of heads) {
|
||||
const files = runGit(root, ['ls-tree', '-r', '--name-only', '-z', head], `listing merge-head ${head} paths`)
|
||||
.toString('utf8')
|
||||
.split('\0')
|
||||
.filter(Boolean)
|
||||
for (const file of files) paths.add(file)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
/**
|
||||
* Read one path from the Git index without consulting working-tree bytes.
|
||||
*
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
mkdtempSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs'
|
||||
@@ -15,8 +16,8 @@ import { fileURLToPath } from 'node:url'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { gitBlobHash, storeGitBlob } from './translation-pairing-git.ts'
|
||||
import {
|
||||
mergeTranslationPairingRecords,
|
||||
resolveTranslationPairingConflicts,
|
||||
mergeTranslationPairingRecords as mergeTranslationPairingRecordsWithScope,
|
||||
resolveTranslationPairingConflicts as resolveTranslationPairingConflictsWithScope,
|
||||
} from './translation-pairing-merge.ts'
|
||||
import {
|
||||
renderTranslationPairingRecord,
|
||||
@@ -35,6 +36,27 @@ interface Fixture {
|
||||
root: string
|
||||
}
|
||||
|
||||
function mergeTranslationPairingRecords(
|
||||
root: string,
|
||||
metaPath: string,
|
||||
ancestorRecord: string,
|
||||
currentRecord: string,
|
||||
otherRecord: string,
|
||||
) {
|
||||
return mergeTranslationPairingRecordsWithScope(
|
||||
root,
|
||||
metaPath,
|
||||
ancestorRecord,
|
||||
currentRecord,
|
||||
otherRecord,
|
||||
() => true,
|
||||
)
|
||||
}
|
||||
|
||||
function resolveTranslationPairingConflicts(root: string): string[] {
|
||||
return resolveTranslationPairingConflictsWithScope(root, () => true)
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const fixture of fixtures.splice(0)) removeFixtureSafely(fixture)
|
||||
})
|
||||
@@ -252,6 +274,19 @@ describe('translation pairing merge composition', { timeout: 15_000 }, () => {
|
||||
)).toThrow('pairing record escapes the repository')
|
||||
})
|
||||
|
||||
it('rejects a pairing record excluded from the active corpus', () => {
|
||||
const fixture = createFixture(false)
|
||||
|
||||
expect(() => mergeTranslationPairingRecordsWithScope(
|
||||
fixture.root,
|
||||
'docs/guide.i18n.yaml',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
() => false,
|
||||
)).toThrow('docs/guide.i18n.yaml is excluded from the active bilingual documentation corpus')
|
||||
})
|
||||
|
||||
it('merges the owner blobs named by three valid records', () => {
|
||||
const fixture = createFixture(false)
|
||||
git(fixture, ['config', 'merge.default', 'text'])
|
||||
@@ -271,6 +306,48 @@ describe('translation pairing merge composition', { timeout: 15_000 }, () => {
|
||||
expect(result.zhHash).toBe(gitBlobHash(Buffer.from(mergedZh)))
|
||||
})
|
||||
|
||||
it('accepts locale-specific paths to the same paired document', () => {
|
||||
const fixture = createFixture(false)
|
||||
write(fixture.root, 'docs/reference.md', '# Overview\n')
|
||||
write(fixture.root, 'docs/reference.zh.md', '# 概览\n')
|
||||
git(fixture, ['add', 'docs/reference.md', 'docs/reference.zh.md'])
|
||||
const source = baseSource.replace('Alpha base.', '[Reference](reference.md#overview)')
|
||||
const zh = baseZh.replace('甲基础。', '[参考](reference.zh.md#overview)')
|
||||
const ancestor = record(fixture.root, 'docs/guide.md', source, zh)
|
||||
const current = record(fixture.root, 'docs/guide.md', source, zh)
|
||||
const other = record(fixture.root, 'docs/guide.md', source, zh)
|
||||
rmSync(join(fixture.root, 'docs/reference.md'))
|
||||
rmSync(join(fixture.root, 'docs/reference.zh.md'))
|
||||
|
||||
expect(mergeTranslationPairingRecords(
|
||||
fixture.root,
|
||||
'docs/guide.i18n.yaml',
|
||||
ancestor,
|
||||
current,
|
||||
other,
|
||||
).zhContent.toString('utf8')).toBe(zh)
|
||||
})
|
||||
|
||||
it('rejects a clean merge whose Chinese link uses the English sibling', () => {
|
||||
const fixture = createFixture(false)
|
||||
write(fixture.root, 'docs/reference.md', '# Overview\n')
|
||||
write(fixture.root, 'docs/reference.zh.md', '# 概览\n')
|
||||
git(fixture, ['add', 'docs/reference.md', 'docs/reference.zh.md'])
|
||||
const source = baseSource.replace('Alpha base.', '[Reference](reference.md)')
|
||||
const zh = baseZh.replace('甲基础。', '[参考](reference.md)')
|
||||
const ancestor = record(fixture.root, 'docs/guide.md', source, zh)
|
||||
const current = record(fixture.root, 'docs/guide.md', source, zh)
|
||||
const other = record(fixture.root, 'docs/guide.md', source, zh)
|
||||
|
||||
expect(() => mergeTranslationPairingRecords(
|
||||
fixture.root,
|
||||
'docs/guide.i18n.yaml',
|
||||
ancestor,
|
||||
current,
|
||||
other,
|
||||
)).toThrow('docs/guide.zh.md:5 clean merge uses "reference.md"; expected "reference.zh.md"')
|
||||
})
|
||||
|
||||
it('merges a generated source without an English language switcher', () => {
|
||||
const fixture = createFixture(false)
|
||||
const ancestor = record(fixture.root, 'docs/module-graph.md', generatedBaseSource, generatedBaseZh)
|
||||
@@ -414,6 +491,49 @@ describe('translation pairing merge composition', { timeout: 15_000 }, () => {
|
||||
expectMergedPair(fixture)
|
||||
})
|
||||
|
||||
it('sees a paired link target added by the other branch', () => {
|
||||
const fixture = createFixture()
|
||||
commitPair(fixture, baseSource, baseZh, 'base')
|
||||
git(fixture, ['switch', '-c', 'current'])
|
||||
commitPair(fixture, currentSource, currentZh, 'current guide')
|
||||
git(fixture, ['switch', 'master'])
|
||||
record(
|
||||
fixture.root,
|
||||
'docs/guide.md',
|
||||
baseSource.replace('Beta base.', '[Reference](reference.md#overview)'),
|
||||
baseZh.replace('乙基础。', '[参考](reference.zh.md#overview)'),
|
||||
)
|
||||
record(
|
||||
fixture.root,
|
||||
'docs/reference.md',
|
||||
'# Reference\n\nEnglish | [中文](reference.zh.md)\n\nOverview.\n',
|
||||
'# 参考\n\n[English](reference.md) | 中文\n\n概览。\n',
|
||||
)
|
||||
git(fixture, ['add', '.'])
|
||||
git(fixture, ['commit', '-m', 'other guide and target'])
|
||||
git(fixture, ['switch', 'current'])
|
||||
installFixtureRuntime(fixture.root)
|
||||
git(fixture, [
|
||||
'config',
|
||||
'merge.dsh-translation-pairing.driver',
|
||||
'scripts/merge-translation-pairing-driver.sh %O %A %B %P',
|
||||
])
|
||||
|
||||
const merge = spawnSync('git', ['-C', fixture.root, 'merge', '--no-edit', 'master'], {
|
||||
encoding: 'utf8',
|
||||
env: fixture.env,
|
||||
})
|
||||
|
||||
expect(merge.status, merge.stderr).toBe(0)
|
||||
expect(git(fixture, ['diff', '--name-only', '--diff-filter=U'])).toBe('')
|
||||
expect(readFileSync(join(fixture.root, 'docs/guide.md'), 'utf8')).toContain(
|
||||
'[Reference](reference.md#overview)',
|
||||
)
|
||||
expect(readFileSync(join(fixture.root, 'docs/guide.zh.md'), 'utf8')).toContain(
|
||||
'[参考](reference.zh.md#overview)',
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves an ordinary recoverable conflict when the configured runtime is unavailable', () => {
|
||||
const fixture = createFixture()
|
||||
const records = createDivergedPair(fixture)
|
||||
|
||||
@@ -7,6 +7,7 @@ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
||||
import {
|
||||
GIT_COMMAND_MAX_BUFFER,
|
||||
gitBlobHash,
|
||||
gitMergeInputPaths,
|
||||
readGitIndexBlob,
|
||||
runGit,
|
||||
storeGitBlob,
|
||||
@@ -14,12 +15,17 @@ import {
|
||||
import {
|
||||
isTranslationScopeFile,
|
||||
languageSwitcherTargets,
|
||||
linksTo,
|
||||
parseTranslationMarkdown,
|
||||
parseTranslationPairingManifest,
|
||||
requiresSourceLanguageSwitcher,
|
||||
translationPairSourcePredicate,
|
||||
translationStructureDiff,
|
||||
translationStructureSignature,
|
||||
} from './translation-pairing.ts'
|
||||
import {
|
||||
hasLanguageSwitcher,
|
||||
translationLinkLocaleViolations,
|
||||
} from './translation-links.ts'
|
||||
import {
|
||||
parseTranslationPairingRecord,
|
||||
renderTranslationPairingRecord,
|
||||
@@ -162,20 +168,62 @@ function loadRecordOwners(
|
||||
}
|
||||
}
|
||||
|
||||
function assertMergedPairStructure(paths: TranslationPairPaths, source: Buffer, zh: Buffer): void {
|
||||
const sourceTree = parseTranslationMarkdown(source.toString('utf8'))
|
||||
const zhTree = parseTranslationMarkdown(zh.toString('utf8'))
|
||||
function assertMergedPairStructure(
|
||||
root: string,
|
||||
paths: TranslationPairPaths,
|
||||
source: Buffer,
|
||||
zh: Buffer,
|
||||
isTranslationPairSource: (sourcePath: string) => boolean,
|
||||
): void {
|
||||
const sourceText = source.toString('utf8')
|
||||
const zhText = zh.toString('utf8')
|
||||
const sourceTree = parseTranslationMarkdown(sourceText)
|
||||
const zhTree = parseTranslationMarkdown(zhText)
|
||||
const indexFiles = gitMergeInputPaths(root)
|
||||
const repositoryFileExists = (path: string): boolean => indexFiles.has(path)
|
||||
const sourceSwitcherTargets = languageSwitcherTargets(paths.source)
|
||||
const zhSwitcherTargets = languageSwitcherTargets(paths.zh)
|
||||
if (requiresSourceLanguageSwitcher(paths.source) && !linksTo(sourceTree, zhSwitcherTargets)) {
|
||||
if (requiresSourceLanguageSwitcher(paths.source)
|
||||
&& !hasLanguageSwitcher(sourceTree, sourceText, zhSwitcherTargets)) {
|
||||
throw new Error(`${paths.source} clean merge lost its language-switcher link to ${basename(paths.zh)}`)
|
||||
}
|
||||
if (!linksTo(zhTree, sourceSwitcherTargets)) {
|
||||
if (!hasLanguageSwitcher(zhTree, zhText, sourceSwitcherTargets)) {
|
||||
throw new Error(`${paths.zh} clean merge lost its language-switcher link to ${basename(paths.source)}`)
|
||||
}
|
||||
const localeViolations = [
|
||||
...translationLinkLocaleViolations(sourceText, {
|
||||
repoRoot: root,
|
||||
sourcePath: paths.source,
|
||||
isTranslationPairSource,
|
||||
repositoryFileExists,
|
||||
}, zhSwitcherTargets),
|
||||
...translationLinkLocaleViolations(zhText, {
|
||||
repoRoot: root,
|
||||
sourcePath: paths.zh,
|
||||
isTranslationPairSource,
|
||||
repositoryFileExists,
|
||||
}, sourceSwitcherTargets),
|
||||
]
|
||||
if (localeViolations.length > 0) {
|
||||
const violation = localeViolations[0]
|
||||
if (violation === undefined) throw new Error('translation locale violation disappeared')
|
||||
throw new Error(`${violation.sourcePath}:${violation.line} clean merge uses ${JSON.stringify(violation.url)}; expected ${JSON.stringify(violation.expectedUrl)}`)
|
||||
}
|
||||
const divergences = translationStructureDiff(
|
||||
translationStructureSignature(sourceTree, zhSwitcherTargets),
|
||||
translationStructureSignature(zhTree, sourceSwitcherTargets),
|
||||
translationStructureSignature(sourceTree, zhSwitcherTargets, {
|
||||
repoRoot: root,
|
||||
sourcePath: paths.source,
|
||||
isTranslationPairSource,
|
||||
repositoryFileExists,
|
||||
markdown: sourceText,
|
||||
}),
|
||||
translationStructureSignature(zhTree, sourceSwitcherTargets, {
|
||||
repoRoot: root,
|
||||
sourcePath: paths.zh,
|
||||
isTranslationPairSource,
|
||||
repositoryFileExists,
|
||||
markdown: zhText,
|
||||
}),
|
||||
)
|
||||
if (divergences.length > 0) {
|
||||
throw new Error(`${paths.source} and ${paths.zh} clean merges diverge structurally: ${divergences.join('; ')}`)
|
||||
@@ -212,19 +260,23 @@ export function mergeTranslationPairingRecords(
|
||||
ancestorRecord: string,
|
||||
currentRecord: string,
|
||||
otherRecord: string,
|
||||
isTranslationPairSource: (sourcePath: string) => boolean,
|
||||
): TranslationPairingMergeResult {
|
||||
const normalizedMeta = normalizeMetaPath(root, metaPath)
|
||||
if (!isTranslationScopeFile(normalizedMeta)) {
|
||||
throw new Error(`${normalizedMeta} is outside the active bilingual documentation corpus`)
|
||||
}
|
||||
const paths = translationPairPathsFromMeta(normalizedMeta)
|
||||
if (!isTranslationPairSource(paths.source)) {
|
||||
throw new Error(`${normalizedMeta} is excluded from the active bilingual documentation corpus`)
|
||||
}
|
||||
assertDefaultTextMerge(root, paths)
|
||||
const ancestor = loadRecordOwners(root, 'ancestor', ancestorRecord, paths)
|
||||
const current = loadRecordOwners(root, 'current', currentRecord, paths)
|
||||
const other = loadRecordOwners(root, 'other', otherRecord, paths)
|
||||
const sourceContent = mergeBlobTriplet(root, paths.source, ancestor.source, current.source, other.source)
|
||||
const zhContent = mergeBlobTriplet(root, paths.zh, ancestor.zh, current.zh, other.zh)
|
||||
assertMergedPairStructure(paths, sourceContent, zhContent)
|
||||
assertMergedPairStructure(root, paths, sourceContent, zhContent, isTranslationPairSource)
|
||||
const sourceHash = storeGitBlob(root, sourceContent)
|
||||
const zhHash = storeGitBlob(root, zhContent)
|
||||
return {
|
||||
@@ -236,6 +288,16 @@ export function mergeTranslationPairingRecords(
|
||||
}
|
||||
}
|
||||
|
||||
/** Read the repository manifest and return its active bilingual-source predicate. */
|
||||
export function repositoryTranslationPairSource(root: string): (sourcePath: string) => boolean {
|
||||
const path = 'scripts/translation-pairing.manifest.json'
|
||||
const content = readGitIndexBlob(root, path)?.content ?? readFileSync(join(root, path))
|
||||
const manifest = parseTranslationPairingManifest(
|
||||
content.toString('utf8'),
|
||||
)
|
||||
return translationPairSourcePredicate(manifest)
|
||||
}
|
||||
|
||||
function unmergedSidecars(root: string): Map<string, UnmergedStages> {
|
||||
const output = runGit(root, ['ls-files', '--unmerged', '-z'], 'listing unresolved merge entries').toString('utf8')
|
||||
const records = new Map<string, UnmergedStages>()
|
||||
@@ -289,7 +351,10 @@ function assertUneditedSidecar(
|
||||
* @param root - Repository root with an in-progress merge-like operation.
|
||||
* @returns Repository-relative sidecar paths resolved and staged.
|
||||
*/
|
||||
export function resolveTranslationPairingConflicts(root: string): string[] {
|
||||
export function resolveTranslationPairingConflicts(
|
||||
root: string,
|
||||
isTranslationPairSource: (sourcePath: string) => boolean,
|
||||
): string[] {
|
||||
const resolutions: { path: string; record: string }[] = []
|
||||
const failures: { path: string; reason: string }[] = []
|
||||
for (const [metaPath, stages] of [...unmergedSidecars(root)].sort(([left], [right]) => left.localeCompare(right))) {
|
||||
@@ -307,6 +372,7 @@ export function resolveTranslationPairingConflicts(root: string): string[] {
|
||||
ancestorRecord,
|
||||
currentRecord,
|
||||
otherRecord,
|
||||
isTranslationPairSource,
|
||||
)
|
||||
const paths = translationPairPathsFromMeta(metaPath)
|
||||
if (readGitIndexBlob(root, paths.source)?.objectId !== result.sourceHash) {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
/** Regression tests for bilingual snapshots, corpus scope, and structure. */
|
||||
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { gitBlobHash, readGitIndexBlob, storeGitBlob } from './translation-pairing-git.ts'
|
||||
import {
|
||||
gitBlobHash,
|
||||
gitIndexPaths,
|
||||
readGitIndexBlob,
|
||||
storeGitBlob,
|
||||
} from './translation-pairing-git.ts'
|
||||
import {
|
||||
parseTranslationPairingRecord,
|
||||
renderTranslationPairingRecord,
|
||||
@@ -13,21 +18,44 @@ import {
|
||||
} from './translation-pairing-record.ts'
|
||||
import {
|
||||
blobHash,
|
||||
isTranslationPairingManifestExcluded,
|
||||
isTranslationScopeFile,
|
||||
languageSwitcherTargets,
|
||||
linksTo,
|
||||
pairAnchorOfArgument,
|
||||
parseTranslationMarkdown,
|
||||
parseTranslationPairingCliArgs,
|
||||
parseTranslationPairingManifest,
|
||||
partitionGeneratedRegions,
|
||||
requiresSourceLanguageSwitcher,
|
||||
translationPairSourcePredicate,
|
||||
translationStructureDiff,
|
||||
translationStructureSignature,
|
||||
} from './translation-pairing.ts'
|
||||
|
||||
const fixturePairSource = (): boolean => true
|
||||
|
||||
function signature(markdown: string) {
|
||||
return translationStructureSignature(parseTranslationMarkdown(markdown), 'counterpart.zh.md')
|
||||
return translationStructureSignature(
|
||||
parseTranslationMarkdown(markdown),
|
||||
'counterpart.zh.md',
|
||||
{
|
||||
repoRoot: process.cwd(), sourcePath: 'counterpart.md',
|
||||
isTranslationPairSource: fixturePairSource, markdown,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
function fixtureSignature(
|
||||
root: string,
|
||||
sourcePath: string,
|
||||
markdown: string,
|
||||
switcherTarget: string,
|
||||
) {
|
||||
return translationStructureSignature(
|
||||
parseTranslationMarkdown(markdown),
|
||||
switcherTarget,
|
||||
{ repoRoot: root, sourcePath, isTranslationPairSource: fixturePairSource, markdown },
|
||||
)
|
||||
}
|
||||
|
||||
function gitSupportsObjectFormat(format: 'sha256'): boolean {
|
||||
@@ -106,6 +134,26 @@ describe('translation pairing snapshots', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('lists exact index files without treating a directory prefix as one entry', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-translation-pairing-index-'))
|
||||
try {
|
||||
execFileSync('git', ['init', '--quiet', root], {
|
||||
env: { ...process.env, GIT_DEFAULT_HASH: 'sha1' },
|
||||
})
|
||||
mkdirSync(join(root, 'docs'), { recursive: true })
|
||||
writeFileSync(join(root, 'docs/reference.md'), '# Reference\n')
|
||||
writeFileSync(join(root, 'docs/reference.zh.md'), '# 参考\n')
|
||||
execFileSync('git', ['-C', root, 'add', 'docs'])
|
||||
|
||||
expect(gitIndexPaths(root)).toEqual(new Set([
|
||||
'docs/reference.md',
|
||||
'docs/reference.zh.md',
|
||||
]))
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it.skipIf(!supportsSha256ObjectFormat)('rejects an object format that pairing records cannot represent', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-translation-pairing-'))
|
||||
try {
|
||||
@@ -119,11 +167,16 @@ describe('translation pairing snapshots', () => {
|
||||
|
||||
describe('translation pairing manifest', () => {
|
||||
it('accepts an exclusions-only manifest', () => {
|
||||
expect(parseTranslationPairingManifest(JSON.stringify({
|
||||
const manifest = parseTranslationPairingManifest(JSON.stringify({
|
||||
excluded: ['docs/generated/'],
|
||||
}))).toEqual({
|
||||
}))
|
||||
expect(manifest).toEqual({
|
||||
excluded: ['docs/generated/'],
|
||||
})
|
||||
expect(isTranslationPairingManifestExcluded('docs/generated/page.md', manifest)).toBe(true)
|
||||
expect(translationPairSourcePredicate(manifest)('docs/generated/page.md')).toBe(false)
|
||||
expect(translationPairSourcePredicate(manifest)('docs/guide.md')).toBe(true)
|
||||
expect(translationPairSourcePredicate(manifest)('packages/example/guide.md')).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
@@ -156,16 +209,44 @@ describe('translation pairing switchers', () => {
|
||||
|
||||
it('accepts only the canonical public URL for an absolute switcher', () => {
|
||||
const targets = languageSwitcherTargets('python/sdk/README.zh.md')
|
||||
const canonical = parseTranslationMarkdown(
|
||||
'[中文](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.zh.md)',
|
||||
)
|
||||
const wrongPath = parseTranslationMarkdown(
|
||||
'[中文](https://github.com/deepseek-ai/deepseek-harness/blob/master/other/README.zh.md)',
|
||||
)
|
||||
const canonicalMarkdown = '# README\n\nEnglish | [中文](https://github.com/deepseek-ai/deepseek-harness/blob/master/python/sdk/README.zh.md)\n'
|
||||
const canonical = parseTranslationMarkdown(canonicalMarkdown)
|
||||
const wrongMarkdown = '# README\n\nEnglish | [中文](https://github.com/deepseek-ai/deepseek-harness/blob/master/other/README.zh.md)\n'
|
||||
const wrongPath = parseTranslationMarkdown(wrongMarkdown)
|
||||
|
||||
expect(linksTo(canonical, targets)).toBe(true)
|
||||
expect(translationStructureSignature(canonical, targets).links).toEqual([])
|
||||
expect(linksTo(wrongPath, targets)).toBe(false)
|
||||
expect(translationStructureSignature(canonical, targets, {
|
||||
repoRoot: process.cwd(),
|
||||
sourcePath: 'python/sdk/README.md',
|
||||
isTranslationPairSource: fixturePairSource,
|
||||
markdown: canonicalMarkdown,
|
||||
}).links).toEqual([])
|
||||
expect(translationStructureSignature(wrongPath, targets, {
|
||||
repoRoot: process.cwd(),
|
||||
sourcePath: 'python/sdk/README.md',
|
||||
isTranslationPairSource: fixturePairSource,
|
||||
markdown: wrongMarkdown,
|
||||
}).links).toEqual([
|
||||
'https://github.com/deepseek-ai/deepseek-harness/blob/master/other/README.zh.md',
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes only the header switcher from the structural links', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-translation-switcher-'))
|
||||
try {
|
||||
writeFileSync(join(root, 'guide.md'), '# Guide\n')
|
||||
writeFileSync(join(root, 'guide.zh.md'), '# 指南\n')
|
||||
const markdown = '# 指南\n\n[English](guide.md) | 中文\n\n[正文](guide.md)\n'
|
||||
expect(translationStructureSignature(
|
||||
parseTranslationMarkdown(markdown),
|
||||
languageSwitcherTargets('guide.md'),
|
||||
{
|
||||
repoRoot: root, sourcePath: 'guide.zh.md',
|
||||
isTranslationPairSource: fixturePairSource, markdown,
|
||||
},
|
||||
).links).toEqual(['dsh-translation-target:guide.md'])
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -201,6 +282,12 @@ describe('translation scope discovery', () => {
|
||||
'CONTRIBUTING.md',
|
||||
'CONTRIBUTING.zh.md',
|
||||
'CONTRIBUTING.i18n.yaml',
|
||||
'BRAND_GUIDELINES.md',
|
||||
'BRAND_GUIDELINES.zh.md',
|
||||
'BRAND_GUIDELINES.i18n.yaml',
|
||||
'SAFETY.md',
|
||||
'SAFETY.zh.md',
|
||||
'SAFETY.i18n.yaml',
|
||||
'apps/cli/README.md',
|
||||
'future/subtree/readme.md',
|
||||
'packages/example/README.zh.md',
|
||||
@@ -215,6 +302,7 @@ describe('translation scope discovery', () => {
|
||||
it.each([
|
||||
'packages/example/guide.md',
|
||||
'packages/example/CONTRIBUTING.md',
|
||||
'packages/example/BRAND_GUIDELINES.md',
|
||||
'examples/tutorial.md',
|
||||
'website/reference.md',
|
||||
'packages/example/README.txt',
|
||||
@@ -230,6 +318,81 @@ describe('translation scope discovery', () => {
|
||||
})
|
||||
|
||||
describe('translation structural signature', () => {
|
||||
it('retains external GFM autolinks without parsing inline-link syntax', () => {
|
||||
const markdown = '<https://example.com/reference.md>\n'
|
||||
expect(signature(markdown).links).toEqual(['https://example.com/reference.md'])
|
||||
})
|
||||
|
||||
it('retains exact authored bytes for ordinary external link targets', () => {
|
||||
const escaped = signature('[External](https://example.com/?x=1&y=2)\n')
|
||||
const literal = signature('[External](https://example.com/?x=1&y=2)\n')
|
||||
expect(escaped.links).toEqual(['https://example.com/?x=1&y=2'])
|
||||
expect(translationStructureDiff(escaped, literal)).toEqual([
|
||||
'link target #1 diverges between the pair: "https://example.com/?x=1&y=2" vs "https://example.com/?x=1&y=2"',
|
||||
])
|
||||
})
|
||||
|
||||
it('treats target-locale siblings as one semantic link target', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-translation-structure-'))
|
||||
try {
|
||||
writeFileSync(join(root, 'reference.md'), '# Reference\n')
|
||||
writeFileSync(join(root, 'reference.zh.md'), '# 参考\n')
|
||||
const sourceMarkdown = '[Reference](reference.md?view=full#section)\n'
|
||||
const counterpartMarkdown = '[参考](reference.zh.md?view=full#section)\n'
|
||||
const source = fixtureSignature(root, 'guide.md', sourceMarkdown, 'guide.zh.md')
|
||||
const counterpart = fixtureSignature(root, 'guide.zh.md', counterpartMarkdown, 'guide.md')
|
||||
expect(translationStructureDiff(source, counterpart)).toEqual([])
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('includes reference-style document links but excludes image-only definitions', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-translation-structure-'))
|
||||
try {
|
||||
writeFileSync(join(root, 'reference.md'), '# Reference\n')
|
||||
writeFileSync(join(root, 'reference.zh.md'), '# 参考\n')
|
||||
const markdown = [
|
||||
'[Reference][doc]',
|
||||
'',
|
||||
'![Preview][asset]',
|
||||
'',
|
||||
'[doc]: reference.md',
|
||||
'[asset]: reference.zh.md',
|
||||
'',
|
||||
].join('\n')
|
||||
expect(translationStructureSignature(
|
||||
parseTranslationMarkdown(markdown),
|
||||
'guide.zh.md',
|
||||
{
|
||||
repoRoot: root, sourcePath: 'guide.md',
|
||||
isTranslationPairSource: fixturePairSource, markdown,
|
||||
},
|
||||
).links).toEqual(['dsh-translation-target:reference.md'])
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('compares the first duplicate reference definition that CommonMark resolves', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-translation-structure-'))
|
||||
try {
|
||||
for (const name of ['reference', 'different', 'other']) {
|
||||
writeFileSync(join(root, `${name}.md`), `# ${name}\n`)
|
||||
writeFileSync(join(root, `${name}.zh.md`), `# ${name} zh\n`)
|
||||
}
|
||||
const sourceMarkdown = '[Reference][ref]\n\n[ref]: reference.md\n[ref]: other.md\n'
|
||||
const counterpartMarkdown = '[参考][ref]\n\n[ref]: different.zh.md\n[ref]: other.zh.md\n'
|
||||
const source = fixtureSignature(root, 'guide.md', sourceMarkdown, 'guide.zh.md')
|
||||
const counterpart = fixtureSignature(root, 'guide.zh.md', counterpartMarkdown, 'guide.md')
|
||||
expect(translationStructureDiff(source, counterpart)).toEqual([
|
||||
'link target #1 diverges between the pair: "dsh-translation-target:reference.md" vs "dsh-translation-target:different.md"',
|
||||
])
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('accepts matching list kinds, starts, and item counts', () => {
|
||||
const source = signature('3. One\n4. Two\n\n- A\n- B\n')
|
||||
const counterpart = signature('3. 一\n4. 二\n\n- 甲\n- 乙\n')
|
||||
|
||||
@@ -12,6 +12,11 @@ import { fromMarkdown } from 'mdast-util-from-markdown'
|
||||
import { gfmFromMarkdown } from 'mdast-util-gfm'
|
||||
import { gfm } from 'micromark-extension-gfm'
|
||||
import type { Nodes } from 'mdast'
|
||||
import {
|
||||
languageSwitcherLinkOffset,
|
||||
semanticTranslationLinkNodeTarget,
|
||||
type TranslationLinkContext,
|
||||
} from './translation-links.ts'
|
||||
|
||||
/** Complete opening marker line: `<!-- BEGIN GENERATED <slug> … -->` (slug captured). */
|
||||
const GENERATED_REGION_BEGIN_LINE = /^<!-- BEGIN GENERATED (\S+)(?: [^>]*)? -->$/
|
||||
@@ -125,7 +130,7 @@ export interface TranslationPairingManifest {
|
||||
}
|
||||
|
||||
const README_ARTIFACT = /(?:^|\/)readme(?:\.md|\.zh\.md|\.i18n\.yaml)$/i
|
||||
const ROOT_CONTRIBUTING_ARTIFACT = /^contributing(?:\.md|\.zh\.md|\.i18n\.yaml)$/i
|
||||
const ROOT_PAIRED_DOCUMENT_ARTIFACT = /^(?:brand_guidelines|contributing|safety)(?:\.md|\.zh\.md|\.i18n\.yaml)$/i
|
||||
const NON_SOURCE_DIRECTORIES = new Set([
|
||||
'node_modules',
|
||||
'lib',
|
||||
@@ -180,7 +185,7 @@ function isTranslationSourceExcluded(file: string): boolean {
|
||||
export function isTranslationScopeFile(file: string): boolean {
|
||||
return !file.startsWith('.agents/notes/archived/')
|
||||
&& !isTranslationSourceExcluded(file) && (README_ARTIFACT.test(file)
|
||||
|| ROOT_CONTRIBUTING_ARTIFACT.test(file)
|
||||
|| ROOT_PAIRED_DOCUMENT_ARTIFACT.test(file)
|
||||
|| file.startsWith('.agents/notes/')
|
||||
|| file.startsWith('docs/')
|
||||
|| file.startsWith('python/'))
|
||||
@@ -213,6 +218,22 @@ export function parseTranslationPairingManifest(content: string): TranslationPai
|
||||
return { excluded: excludedField(record) }
|
||||
}
|
||||
|
||||
/** Whether a manifest entry excludes one exact file or a directory subtree. */
|
||||
export function isTranslationPairingManifestExcluded(
|
||||
file: string,
|
||||
manifest: TranslationPairingManifest,
|
||||
): boolean {
|
||||
return manifest.excluded.some(entry => (entry.endsWith('/') ? file.startsWith(entry) : file === entry))
|
||||
}
|
||||
|
||||
/** Build the active bilingual-source predicate shared by every link consumer. */
|
||||
export function translationPairSourcePredicate(
|
||||
manifest: TranslationPairingManifest,
|
||||
): (sourcePath: string) => boolean {
|
||||
return sourcePath => isTranslationScopeFile(sourcePath)
|
||||
&& !isTranslationPairingManifestExcluded(sourcePath, manifest)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one CLI pair argument to its English anchor path: any of the
|
||||
* pair's three files (`foo.md`, `foo.zh.md`, `foo.i18n.yaml`) or the bare
|
||||
@@ -309,18 +330,6 @@ export function languageSwitcherTargets(counterpart: string): string[] {
|
||||
return [basename(counterpart), `${PUBLIC_REPOSITORY_BLOB_ROOT}${counterpart}`]
|
||||
}
|
||||
|
||||
/** Whether the tree contains a link to any accepted target. */
|
||||
export function linksTo(tree: Nodes, targets: string | readonly string[]): boolean {
|
||||
const accepted = new Set(typeof targets === 'string' ? [targets] : targets)
|
||||
let found = false
|
||||
const visit = (node: Nodes): void => {
|
||||
if (node.type === 'link' && accepted.has(node.url)) found = true
|
||||
if ('children' in node) for (const child of node.children) visit(child)
|
||||
}
|
||||
visit(tree)
|
||||
return found
|
||||
}
|
||||
|
||||
/** Generated English sources cannot carry a switcher without making their generator stale. */
|
||||
export function requiresSourceLanguageSwitcher(source: string): boolean {
|
||||
return ![
|
||||
@@ -347,11 +356,21 @@ export function requiresSourceLanguageSwitcher(source: string): boolean {
|
||||
export function translationStructureSignature(
|
||||
tree: Nodes,
|
||||
switcherTargets: string | readonly string[],
|
||||
linkContext: TranslationLinkContext & { markdown: string },
|
||||
): TranslationStructureSignature {
|
||||
const acceptedSwitchers = new Set(
|
||||
typeof switcherTargets === 'string' ? [switcherTargets] : switcherTargets,
|
||||
)
|
||||
const switcherOffset = languageSwitcherLinkOffset(tree, linkContext.markdown, switcherTargets)
|
||||
const sig: TranslationStructureSignature = { headings: [], code: [], tables: [], lists: [], links: [] }
|
||||
const definitions = new Map<string, Extract<Nodes, { type: 'definition' }>>()
|
||||
const collectDefinitions = (node: Nodes): void => {
|
||||
if (node.type === 'definition' && !definitions.has(node.identifier)) {
|
||||
definitions.set(node.identifier, node)
|
||||
}
|
||||
if ('children' in node) for (const child of node.children) collectDefinitions(child)
|
||||
}
|
||||
collectDefinitions(tree)
|
||||
const linkTarget = (node: Extract<Nodes, { type: 'link' | 'definition' }>): string => (
|
||||
semanticTranslationLinkNodeTarget(node, linkContext.markdown, linkContext)
|
||||
)
|
||||
const visit = (node: Nodes): void => {
|
||||
switch (node.type) {
|
||||
case 'heading':
|
||||
@@ -369,8 +388,17 @@ export function translationStructureSignature(
|
||||
: `bullet:items=${node.children.length}`)
|
||||
break
|
||||
case 'link':
|
||||
if (!acceptedSwitchers.has(node.url)) sig.links.push(node.url)
|
||||
if (node.position?.start.offset !== switcherOffset) {
|
||||
sig.links.push(linkTarget(node))
|
||||
}
|
||||
break
|
||||
case 'linkReference': {
|
||||
const definition = definitions.get(node.identifier)
|
||||
if (definition !== undefined) {
|
||||
sig.links.push(linkTarget(definition))
|
||||
}
|
||||
break
|
||||
}
|
||||
default:
|
||||
// Every other node kind is prose or a container, not part of the signature.
|
||||
break
|
||||
|
||||
@@ -58,6 +58,10 @@ describe('translation prompt rendering', () => {
|
||||
expect(rendered).toContain('Markdown emphasis markers do not create a word boundary')
|
||||
expect(rendered).toContain('Never invent responsibility merely to avoid a passive construction')
|
||||
expect(rendered).toContain('Never vary a terminology-table form, defined concept, or contract verb merely for stylistic variety')
|
||||
expect(rendered).toContain('Chinese output uses its `.zh.md` path')
|
||||
expect(rendered).toContain('belongs to the active bilingual corpus')
|
||||
expect(rendered).toContain('a missing counterpart in that corpus is an error')
|
||||
expect(rendered).toContain('exact query/fragment suffix')
|
||||
expect(rendered).toContain('Return exactly three raw XML sections')
|
||||
})
|
||||
|
||||
|
||||
+15
-5
@@ -11,6 +11,12 @@ interface ProjectGraph {
|
||||
options: ts.CompilerOptions
|
||||
}
|
||||
|
||||
/**
|
||||
* A compiler face: the two aggregates a repository-wide program may seed from.
|
||||
* The root solution is never one of them.
|
||||
*/
|
||||
export type CompilerFace = 'host' | 'client'
|
||||
|
||||
/** TypeScript config host shared by repository scripts. */
|
||||
export const repositoryConfigHost: ts.ParseConfigFileHost = {
|
||||
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
|
||||
@@ -24,12 +30,12 @@ export const repositoryConfigHost: ts.ParseConfigFileHost = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse the host aggregate tsconfig and flatten all referenced projects into one
|
||||
* Parse one face aggregate tsconfig and flatten all referenced projects into one
|
||||
* semantic graph. Never seed the root solution: flattening host+client into one
|
||||
* program collides the cordis Context merges.
|
||||
*/
|
||||
function loadProjectGraph(projectRoot: string): ProjectGraph {
|
||||
const rootConfigPath = resolve(projectRoot, 'tsconfig.host.json')
|
||||
function loadProjectGraph(projectRoot: string, face: CompilerFace): ProjectGraph {
|
||||
const rootConfigPath = resolve(projectRoot, `tsconfig.${face}.json`)
|
||||
const rootConfig = parseConfig(rootConfigPath)
|
||||
const rootNames = new Set<string>()
|
||||
const visited = new Set<string>()
|
||||
@@ -81,8 +87,12 @@ export class TypeScriptProject {
|
||||
/** The checker shared by every semantic query in this project. */
|
||||
readonly checker: ts.TypeChecker
|
||||
|
||||
constructor(private readonly projectRoot: string) {
|
||||
const graph = loadProjectGraph(projectRoot)
|
||||
/**
|
||||
* @param projectRoot - repository root the program is seeded and reported from.
|
||||
* @param face - which compiler face aggregate to flatten.
|
||||
*/
|
||||
constructor(readonly projectRoot: string, face: CompilerFace = 'host') {
|
||||
const graph = loadProjectGraph(projectRoot, face)
|
||||
this.program = ts.createProgram(graph.rootNames, semanticCompilerOptions(graph.options))
|
||||
this.checker = this.program.getTypeChecker()
|
||||
}
|
||||
|
||||
@@ -301,6 +301,26 @@
|
||||
"symbol": "ScheduleView",
|
||||
"source": "packages/schedule/schedule/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/agent-team.md",
|
||||
"symbol": "TeamMemberSnapshot",
|
||||
"source": "packages/experimental/agent-team/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/agent-team.md",
|
||||
"symbol": "TeamMessageSnapshot",
|
||||
"source": "packages/experimental/agent-team/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/agent-team.md",
|
||||
"symbol": "TeamMessageSource",
|
||||
"source": "packages/experimental/agent-team/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/agent-team.md",
|
||||
"symbol": "TeamTaskSnapshot",
|
||||
"source": "packages/experimental/agent-team/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/commands.md",
|
||||
"symbol": "CommandInputDescriptor",
|
||||
@@ -351,6 +371,11 @@
|
||||
"symbol": "ToolProviderResult",
|
||||
"source": "packages/core/system-prompt/src/index.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/llm-streaming.md",
|
||||
"symbol": "ReplayEnvelope",
|
||||
"source": "packages/llm/llm/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/llm-streaming.md",
|
||||
"symbol": "StreamChunk",
|
||||
@@ -424,9 +449,9 @@
|
||||
"source": "packages/core/session/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/session.md",
|
||||
"doc": "docs/subsystems/todo.md",
|
||||
"symbol": "TodoItem",
|
||||
"source": "packages/core/session/src/types.ts"
|
||||
"source": "packages/todo/tool-todo/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/session.md",
|
||||
@@ -660,11 +685,21 @@
|
||||
"symbol": "SessionReferenceInput",
|
||||
"source": "packages/context/session-reference/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/session-reference.md",
|
||||
"symbol": "FileReferenceCandidate",
|
||||
"source": "packages/context/file-reference/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/session-reference.md",
|
||||
"symbol": "SessionReferenceCandidate",
|
||||
"source": "packages/context/session-reference/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/session-reference.md",
|
||||
"symbol": "SessionReferenceMentionCandidate",
|
||||
"source": "packages/context/session-reference/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/session-reference.md",
|
||||
"symbol": "PreparedReferencedMessage",
|
||||
@@ -880,6 +915,11 @@
|
||||
"symbol": "ImageAttachmentLimits",
|
||||
"source": "packages/attachment/attachment/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/attachment.md",
|
||||
"symbol": "EncodedImageAttachment",
|
||||
"source": "packages/attachment/attachment/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/attachment.md",
|
||||
"symbol": "SaveImageAttachment",
|
||||
@@ -890,6 +930,16 @@
|
||||
"symbol": "StoredImageAttachment",
|
||||
"source": "packages/attachment/attachment/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/attachment.md",
|
||||
"symbol": "ImageRequestPolicy",
|
||||
"source": "packages/attachment/attachment/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/attachment.md",
|
||||
"symbol": "RequestImageAttachment",
|
||||
"source": "packages/attachment/attachment/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/shell.md",
|
||||
"symbol": "ShellExecRequest",
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/** Build-time values that bundlers replace before client code reaches a browser. */
|
||||
declare const process: {
|
||||
readonly env: {
|
||||
readonly NODE_ENV?: string
|
||||
readonly [name: `DSH_CLIENT_${string}`]: string | undefined
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/** Application-entrypoint classification and dsh-launch enforcement. */
|
||||
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { applicationEntrypointViolations } from './verify-application-entrypoints.ts'
|
||||
|
||||
const cleanups: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const path of cleanups.splice(0)) rmSync(path, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function fixture(): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-application-entrypoints-'))
|
||||
cleanups.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
function write(root: string, path: string, content: string): void {
|
||||
const target = resolve(root, path)
|
||||
mkdirSync(dirname(target), { recursive: true })
|
||||
writeFileSync(target, content)
|
||||
}
|
||||
|
||||
describe('application entrypoints', () => {
|
||||
it('accepts the repository launcher inventory', () => {
|
||||
expect(applicationEntrypointViolations(resolve(import.meta.dirname, '..'))).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a package-level application bin', () => {
|
||||
const root = fixture()
|
||||
write(root, 'packages/example/app/package.json', JSON.stringify({ bin: { app: 'lib/bin.js' } }))
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([
|
||||
'packages/example/app/package.json: package bin bypasses the dsh launcher; applications use apps/cli profiles',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects an unclassified executable source', () => {
|
||||
const root = fixture()
|
||||
write(root, 'packages/example/app/src/bin.ts', '#!/usr/bin/env node\n')
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([
|
||||
'packages/example/app/src/bin.ts: executable source has no application/build/test classification',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects an executable at an application package root', () => {
|
||||
const root = fixture()
|
||||
write(root, 'apps/example/rogue.mjs', '#!/usr/bin/env node\n')
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([
|
||||
'apps/example/rogue.mjs: executable source has no application/build/test classification',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects an executable at the repository root', () => {
|
||||
const root = fixture()
|
||||
write(root, 'rogue.mjs', '#!/usr/bin/env node\n')
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([
|
||||
'rogue.mjs: executable source has no application/build/test classification',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects an unclassified executable in an example workspace', () => {
|
||||
const root = fixture()
|
||||
write(root, 'examples/rogue/src/bin.ts', '#!/usr/bin/env node\n')
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([
|
||||
'examples/rogue/src/bin.ts: executable source has no application/build/test classification',
|
||||
])
|
||||
})
|
||||
|
||||
it('accepts the temporary private Python carrier source without an npm bin', () => {
|
||||
const root = fixture()
|
||||
write(root, 'packages/sdk/python-runtime/package.json', JSON.stringify({ private: true }))
|
||||
write(root, 'packages/sdk/python-runtime/src/packaged-bin.ts', '#!/usr/bin/env node\n')
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a classified demo wrapper that launches a package entry', () => {
|
||||
const root = fixture()
|
||||
write(root, 'package.json', JSON.stringify({ scripts: { 'demo:code-mode': 'node scripts/demo-code-mode.mjs' } }))
|
||||
write(root, 'scripts/demo-code-mode.mjs', "spawn('node', ['packages/example/app/src/bin.ts'])\n")
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([
|
||||
'scripts/demo-code-mode.mjs: application demo wrapper must launch apps/cli/src/bin.ts',
|
||||
'scripts/demo-code-mode.mjs: application demo wrapper must not launch a package entry directly',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects a new root demo until its launch role is classified', () => {
|
||||
const root = fixture()
|
||||
write(root, 'package.json', JSON.stringify({ scripts: { 'demo:new-app': 'dsh --profile new-app' } }))
|
||||
|
||||
expect(applicationEntrypointViolations(root)).toEqual([
|
||||
'package.json scripts.demo:new-app: demo launcher has no explicit dsh or in-process classification',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* Enforce dsh profiles as the only supported Node application launcher.
|
||||
* Vendor CLIs, build tools, test tools, and the temporary private Python
|
||||
* runtime carrier are explicit classifications rather than implicit holes.
|
||||
*/
|
||||
|
||||
import { existsSync, globSync, readFileSync } from 'node:fs'
|
||||
import { resolve, sep } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
type ManifestBin = string | Record<string, string>
|
||||
|
||||
interface PackageManifest {
|
||||
readonly bin?: unknown
|
||||
}
|
||||
|
||||
interface RootManifest {
|
||||
readonly scripts?: Record<string, unknown>
|
||||
}
|
||||
|
||||
interface DemoPolicy {
|
||||
readonly kind: 'dsh-direct' | 'dsh-wrapper'
|
||||
readonly wrapper?: string
|
||||
}
|
||||
|
||||
/** Public product launcher plus the private build-only WebWorker packer. */
|
||||
const MANIFEST_BIN_ALLOWLIST = new Map<string, ManifestBin>([
|
||||
['apps/cli/package.json', { dsh: 'lib/bin.js' }],
|
||||
['packages/experimental/webworker-packer/package.json', { 'dsh-pack-vfs-image': './bin.js' }],
|
||||
])
|
||||
|
||||
/** Every executable in a Node application workspace has one explicit role. */
|
||||
const EXECUTABLE_SOURCE_ALLOWLIST = new Map<string, string>([
|
||||
['apps/cli/src/bin.ts', 'supported dsh application launcher'],
|
||||
['examples/acp-agent/tests/fixtures/shell/tool-pwsh/driver.ts', 'test-only subprocess driver'],
|
||||
['examples/acp-agent/tests/fixtures/subagent/subagent-acp/driver.ts', 'test-only subprocess driver'],
|
||||
['examples/acp-agent/tests/fixtures/subagent/subagent-claude-code/driver.ts', 'test-only subprocess driver'],
|
||||
['examples/acp-agent/tests/fixtures/subagent/subagent-codex/driver.ts', 'test-only subprocess driver'],
|
||||
['examples/headless-agent/tests/fixtures/headless-driver.ts', 'test-only subprocess driver'],
|
||||
['examples/headless-agent/tests/fixtures/session-telemetry-otel-driver.ts', 'test-only subprocess driver'],
|
||||
['examples/headless-agent/tests/fixtures/time-context-driver.ts', 'test-only subprocess driver'],
|
||||
['examples/python-sdk-agent/tests/fixtures/subagent/subagent-dsh-sdk/driver.ts', 'test-only subprocess driver'],
|
||||
['packages/experimental/webworker-packer/bin.js', 'private build-only wrapper'],
|
||||
['packages/experimental/webworker-packer/src/bin.ts', 'private build-only implementation'],
|
||||
['packages/sdk/client/tests/fake-runtime.ts', 'test-only SDK runtime peer'],
|
||||
['packages/sdk/python-runtime/src/packaged-bin.ts', 'temporary private Python runtime carrier'],
|
||||
['packages/test-support/llm-mock-server/src/bin.ts', 'test-only model server'],
|
||||
])
|
||||
|
||||
/** Root demos are application wrappers and therefore must visibly select dsh. */
|
||||
const ROOT_DEMO_POLICIES = new Map<string, DemoPolicy>([
|
||||
['demo:acp', { kind: 'dsh-direct' }],
|
||||
['demo:code-mode', { kind: 'dsh-wrapper', wrapper: 'scripts/demo-code-mode.mjs' }],
|
||||
['demo:cordis', { kind: 'dsh-wrapper', wrapper: 'scripts/demo-cordis.mjs' }],
|
||||
])
|
||||
|
||||
const SOURCE_PATTERNS = [
|
||||
'*.ts',
|
||||
'*.js',
|
||||
'*.mjs',
|
||||
'*.cjs',
|
||||
'apps/**/*.ts',
|
||||
'apps/**/*.js',
|
||||
'apps/**/*.mjs',
|
||||
'apps/**/*.cjs',
|
||||
'examples/**/*.ts',
|
||||
'examples/**/*.js',
|
||||
'examples/**/*.mjs',
|
||||
'examples/**/*.cjs',
|
||||
'packages/**/*.ts',
|
||||
'packages/**/*.js',
|
||||
'packages/**/*.mjs',
|
||||
'packages/**/*.cjs',
|
||||
]
|
||||
|
||||
const SOURCE_EXCLUDES = [
|
||||
'**/node_modules/**',
|
||||
'**/lib/**',
|
||||
'**/dist/**',
|
||||
'**/coverage/**',
|
||||
]
|
||||
|
||||
/** Convert a host path from glob output to the repository's slash form. */
|
||||
function repositoryPath(path: string): string {
|
||||
return path.split(sep).join('/')
|
||||
}
|
||||
|
||||
/** Stable comparison for string and object npm `bin` declarations. */
|
||||
function normalizedBin(value: unknown): string | undefined {
|
||||
if (typeof value === 'string') return JSON.stringify(value)
|
||||
if (!isRecord(value)) return undefined
|
||||
const entries = Object.entries(value)
|
||||
if (!entries.every(([, target]) => typeof target === 'string')) return undefined
|
||||
return JSON.stringify(Object.fromEntries(entries.sort(([left], [right]) => left.localeCompare(right))))
|
||||
}
|
||||
|
||||
function manifestBinViolations(root: string): string[] {
|
||||
const failures: string[] = []
|
||||
const manifests = globSync(['apps/*/package.json', 'packages/*/*/package.json'], { cwd: root }).sort()
|
||||
for (const rawPath of manifests) {
|
||||
const path = repositoryPath(rawPath)
|
||||
const manifest = JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest
|
||||
if (manifest.bin === undefined) continue
|
||||
const expected = MANIFEST_BIN_ALLOWLIST.get(path)
|
||||
if (expected === undefined) {
|
||||
failures.push(`${path}: package bin bypasses the dsh launcher; applications use apps/cli profiles`)
|
||||
continue
|
||||
}
|
||||
if (normalizedBin(manifest.bin) !== normalizedBin(expected)) {
|
||||
failures.push(`${path}: classified bin must remain ${JSON.stringify(expected)}, got ${JSON.stringify(manifest.bin)}`)
|
||||
}
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
function executableSourceViolations(root: string): string[] {
|
||||
const failures: string[] = []
|
||||
for (const rawPath of globSync(SOURCE_PATTERNS, { cwd: root, exclude: SOURCE_EXCLUDES }).sort()) {
|
||||
const path = repositoryPath(rawPath)
|
||||
const source = readFileSync(resolve(root, path), 'utf8')
|
||||
if (!source.startsWith('#!')) continue
|
||||
if (!EXECUTABLE_SOURCE_ALLOWLIST.has(path)) {
|
||||
failures.push(`${path}: executable source has no application/build/test classification`)
|
||||
}
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
function referencesDshCli(source: string): boolean {
|
||||
return source.includes('apps/cli/src/bin.ts')
|
||||
}
|
||||
|
||||
function referencesPackageEntry(source: string): boolean {
|
||||
return /packages\/[^/\s'"`]+\/[^/\s'"`]+\/(?:src|lib)\/[^\s'"`]+/.test(source)
|
||||
}
|
||||
|
||||
function rootDemoViolations(root: string): string[] {
|
||||
const manifestPath = resolve(root, 'package.json')
|
||||
if (!existsSync(manifestPath)) return []
|
||||
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as RootManifest
|
||||
const failures: string[] = []
|
||||
for (const [name, commandValue] of Object.entries(manifest.scripts ?? {}).sort(([left], [right]) => left.localeCompare(right))) {
|
||||
if (!name.startsWith('demo:')) continue
|
||||
const command = typeof commandValue === 'string' ? commandValue : ''
|
||||
const policy = ROOT_DEMO_POLICIES.get(name)
|
||||
if (policy === undefined) {
|
||||
failures.push(`package.json scripts.${name}: demo launcher has no explicit dsh or in-process classification`)
|
||||
continue
|
||||
}
|
||||
if (policy.kind === 'dsh-direct') {
|
||||
if (!referencesDshCli(command)) failures.push(`package.json scripts.${name}: application demo must launch apps/cli/src/bin.ts`)
|
||||
if (referencesPackageEntry(command)) failures.push(`package.json scripts.${name}: application demo must not launch a package entry directly`)
|
||||
continue
|
||||
}
|
||||
const wrapper = policy.wrapper
|
||||
if (wrapper === undefined || !command.includes(wrapper)) {
|
||||
failures.push(`package.json scripts.${name}: classified wrapper must be ${String(wrapper)}`)
|
||||
continue
|
||||
}
|
||||
const wrapperPath = resolve(root, wrapper)
|
||||
if (!existsSync(wrapperPath)) {
|
||||
failures.push(`${wrapper}: classified demo wrapper is missing`)
|
||||
continue
|
||||
}
|
||||
const source = readFileSync(wrapperPath, 'utf8')
|
||||
if (!referencesDshCli(source)) failures.push(`${wrapper}: application demo wrapper must launch apps/cli/src/bin.ts`)
|
||||
if (referencesPackageEntry(source)) failures.push(`${wrapper}: application demo wrapper must not launch a package entry directly`)
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
/**
|
||||
* Find unsupported application entrypoints below a repository root.
|
||||
* @param root - repository or test-fixture root.
|
||||
* @returns deterministic path-qualified violations.
|
||||
*/
|
||||
export function applicationEntrypointViolations(root: string): string[] {
|
||||
return [
|
||||
...manifestBinViolations(root),
|
||||
...executableSourceViolations(root),
|
||||
...rootDemoViolations(root),
|
||||
]
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const failures = applicationEntrypointViolations(root)
|
||||
if (failures.length > 0) {
|
||||
console.error('verify-application-entrypoints: unsupported launcher(s):')
|
||||
for (const failure of failures) console.error(` ${failure}`)
|
||||
process.exitCode = 1
|
||||
} else {
|
||||
console.log('verify-application-entrypoints: dsh is the only supported Node application launcher; the private Python carrier remains the temporary exception.')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveClientImport } from './verify-client-domain-graph.ts'
|
||||
|
||||
describe('client domain import resolution', () => {
|
||||
it('preserves imports that leave src/client from a top-level file', () => {
|
||||
expect(resolveClientImport('styles.ts', '../styles/base.css?inline'))
|
||||
.toBe('../styles/base.css?inline')
|
||||
})
|
||||
|
||||
it('normalizes imports between domains inside src/client', () => {
|
||||
expect(resolveClientImport('input/hub.ts', '../queue/store.ts'))
|
||||
.toBe('queue/store.ts')
|
||||
})
|
||||
})
|
||||
@@ -15,7 +15,7 @@
|
||||
*/
|
||||
|
||||
import { globSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
||||
import { join, resolve, sep } from 'node:path'
|
||||
import { join, posix, resolve, sep } from 'node:path'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const CLIENT_DIR = join(root, 'packages/client')
|
||||
@@ -41,6 +41,16 @@ function domainOf(rel: string): string {
|
||||
return ix === -1 ? '' : rel.slice(0, ix)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve one relative import to a client-directory-relative path.
|
||||
* @param file - Importing file relative to `src/client`.
|
||||
* @param specifier - Relative module specifier from that file.
|
||||
* @returns Normalized path, preserving leading `..` segments outside `src/client`.
|
||||
*/
|
||||
export function resolveClientImport(file: string, specifier: string): string {
|
||||
return posix.normalize(posix.join(posix.dirname(file), specifier))
|
||||
}
|
||||
|
||||
function checkPackage(pkgName: string, clientDir: string): Violation[] {
|
||||
const violations: Violation[] = []
|
||||
const files = listSources(clientDir)
|
||||
@@ -52,17 +62,8 @@ function checkPackage(pkgName: string, clientDir: string): Violation[] {
|
||||
for (const match of source.matchAll(/from\s+['"](\.[^'"]+)['"]/g)) {
|
||||
const spec = match[1]
|
||||
if (spec === undefined) continue
|
||||
// Resolve the relative specifier against the importing file's directory
|
||||
// to a client-dir-relative path.
|
||||
const fromDir = rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : ''
|
||||
const parts = (fromDir ? fromDir.split('/') : [])
|
||||
for (const seg of spec.split('/')) {
|
||||
if (seg === '.') continue
|
||||
if (seg === '..') parts.pop()
|
||||
else parts.push(seg)
|
||||
}
|
||||
const target = parts.join('/')
|
||||
if (target.startsWith('..')) continue // out of client dir (package root) — package-level rules govern
|
||||
const target = resolveClientImport(rel, spec)
|
||||
if (target === '..' || target.startsWith('../')) continue // package-level rules govern
|
||||
const toDomain = domainOf(target)
|
||||
if (toDomain === '' || CONTRACT_DIRS.has(toDomain)) continue // top-level shared file or contract layer
|
||||
if (fromDomain === toDomain) continue // inside one domain
|
||||
@@ -78,21 +79,26 @@ function checkPackage(pkgName: string, clientDir: string): Violation[] {
|
||||
return violations
|
||||
}
|
||||
|
||||
const violations: Violation[] = []
|
||||
for (const pkg of readdirSync(CLIENT_DIR)) {
|
||||
const clientDir = join(CLIENT_DIR, pkg, 'src/client')
|
||||
try {
|
||||
if (!statSync(clientDir).isDirectory()) continue
|
||||
} catch {
|
||||
// No client half in this package — nothing to layer-check.
|
||||
continue
|
||||
function main(): void {
|
||||
const violations: Violation[] = []
|
||||
for (const pkg of readdirSync(CLIENT_DIR)) {
|
||||
const clientDir = join(CLIENT_DIR, pkg, 'src/client')
|
||||
try {
|
||||
if (!statSync(clientDir).isDirectory()) continue
|
||||
} catch {
|
||||
// No client half in this package — nothing to layer-check.
|
||||
continue
|
||||
}
|
||||
violations.push(...checkPackage(pkg, clientDir))
|
||||
}
|
||||
violations.push(...checkPackage(pkg, clientDir))
|
||||
|
||||
if (violations.length > 0) {
|
||||
console.error(`verify-client-domain-graph: ${violations.length} violation(s):`)
|
||||
for (const v of violations) console.error(` ${v.file} -> ${v.imported}\n ${v.reason}`)
|
||||
process.exitCode = 1
|
||||
return
|
||||
}
|
||||
console.log('verify-client-domain-graph: client domain layering clean.')
|
||||
}
|
||||
|
||||
if (violations.length > 0) {
|
||||
console.error(`verify-client-domain-graph: ${violations.length} violation(s):`)
|
||||
for (const v of violations) console.error(` ${v.file} -> ${v.imported}\n ${v.reason}`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log('verify-client-domain-graph: client domain layering clean.')
|
||||
if (import.meta.filename === resolve(process.argv[1] ?? '')) main()
|
||||
@@ -0,0 +1,402 @@
|
||||
/** Tests for client package modes, dependency sections, and module requests. */
|
||||
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
collectClientPackageViolations,
|
||||
collectRuntimeSourcePackageUses,
|
||||
collectSourcePackageUses,
|
||||
fixClientPackageManifests,
|
||||
readClientDeclarations,
|
||||
type ClientDeclaration,
|
||||
type ClientPackage,
|
||||
type ClientPackageFacts,
|
||||
} from './verify-client-packages.ts'
|
||||
|
||||
const CORDIS = '@deepseek-ai/cordis'
|
||||
const roots: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function declaration(
|
||||
short: string,
|
||||
fields: Partial<Omit<ClientDeclaration, 'name' | 'manifest'>> = {},
|
||||
): ClientDeclaration {
|
||||
return {
|
||||
name: short.startsWith('@') ? short : '@deepseek-ai/dsh-client-' + short,
|
||||
manifest: 'packages/client/' + short.replace(/^.*\//, '') + '/package.json',
|
||||
dynamic: true,
|
||||
external: [],
|
||||
inject: [],
|
||||
...fields,
|
||||
}
|
||||
}
|
||||
|
||||
function pkg(
|
||||
short: string,
|
||||
fields: Partial<Omit<ClientPackage, 'name' | 'manifest'>> = {},
|
||||
): ClientPackage {
|
||||
return {
|
||||
...declaration(short),
|
||||
staticLinked: false,
|
||||
sourceUses: {},
|
||||
runtimeSourceUses: {},
|
||||
dependencies: {},
|
||||
peerDependencies: { [CORDIS]: 'workspace:^' },
|
||||
devDependencies: { [CORDIS]: 'workspace:^' },
|
||||
...fields,
|
||||
}
|
||||
}
|
||||
|
||||
function facts(
|
||||
packages: readonly ClientPackage[],
|
||||
options: Partial<Omit<ClientPackageFacts, 'packages'>> = {},
|
||||
): ClientPackageFacts {
|
||||
return {
|
||||
packages,
|
||||
declarations: options.declarations ?? packages,
|
||||
staticLinkedPackages: options.staticLinkedPackages ?? new Set(
|
||||
packages.filter(item => item.staticLinked).map(item => item.name),
|
||||
),
|
||||
platformModules: options.platformModules ?? [],
|
||||
preloadedExternals: options.preloadedExternals ?? [],
|
||||
parserPreloadIds: options.parserPreloadIds
|
||||
?? (options.preloadedExternals ?? []).map(value => value.replace(/\/client$/, '')),
|
||||
malformed: options.malformed ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
describe('source package uses', () => {
|
||||
it('counts type imports, module augmentations, dynamic imports, and JSX', () => {
|
||||
const uses = collectSourcePackageUses('feature.tsx', [
|
||||
"import type { A } from '@deepseek-ai/dsh-a/subpath'",
|
||||
"declare module '@deepseek-ai/dsh-client-ui-slots' {}",
|
||||
"const load = () => import('@deepseek-ai/dsh-b')",
|
||||
'export const view = <div />',
|
||||
"export type { Local } from './local.ts'",
|
||||
].join('\n'))
|
||||
|
||||
expect([...uses].sort()).toEqual([
|
||||
'@deepseek-ai/dsh-a',
|
||||
'@deepseek-ai/dsh-b',
|
||||
'@deepseek-ai/dsh-client-ui-slots',
|
||||
'react',
|
||||
])
|
||||
expect([...collectRuntimeSourcePackageUses('feature.tsx', [
|
||||
"import type { A } from '@deepseek-ai/dsh-a/subpath'",
|
||||
"declare module '@deepseek-ai/dsh-client-ui-slots' {}",
|
||||
"const load = () => import('@deepseek-ai/dsh-b')",
|
||||
'export const view = <div />',
|
||||
].join('\n'))].sort()).toEqual([
|
||||
'@deepseek-ai/dsh-b',
|
||||
'react',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('package modes', () => {
|
||||
it('accepts one dynamic package and one statically linked package', () => {
|
||||
const dynamic = pkg('runtime')
|
||||
const shell = pkg('ui-slots', { dynamic: false, staticLinked: true })
|
||||
expect(collectClientPackageViolations(facts([dynamic, shell]))).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a package with both modes or neither mode', () => {
|
||||
const both = pkg('both', { staticLinked: true })
|
||||
const neither = pkg('neither', { dynamic: false })
|
||||
const found = collectClientPackageViolations(facts([both, neither]))
|
||||
expect(found).toHaveLength(2)
|
||||
expect(found.join('\n')).toContain('must be dynamic or statically linked, not both')
|
||||
expect(found.join('\n')).toContain('has no supported client package mode')
|
||||
})
|
||||
|
||||
it('requires seeded workspace packages to use staticLinked and preloads to name dynamic rows', () => {
|
||||
const slots = declaration('ui-slots', { dynamic: false })
|
||||
const runtime = declaration('runtime', { dynamic: false })
|
||||
const found = collectClientPackageViolations(facts([], {
|
||||
declarations: [slots, runtime],
|
||||
platformModules: [slots.name],
|
||||
preloadedExternals: [runtime.name + '/client'],
|
||||
}))
|
||||
expect(found).toHaveLength(2)
|
||||
expect(found.join('\n')).toContain('does not use the staticLinked preset')
|
||||
expect(found.join('\n')).toContain('has no dynamic dsh.client row')
|
||||
})
|
||||
|
||||
it('requires every preloaded external to have a parser preload row', () => {
|
||||
const runtime = declaration('runtime')
|
||||
expect(collectClientPackageViolations(facts([], {
|
||||
declarations: [runtime],
|
||||
preloadedExternals: [runtime.name + '/client'],
|
||||
parserPreloadIds: [],
|
||||
}))).toEqual([
|
||||
'packages/client/web/src/platform.ts: parser-preloaded external '
|
||||
+ '"@deepseek-ai/dsh-client-runtime/client" has no matching PARSER_PRELOAD_IDS row in '
|
||||
+ 'packages/client/modules/src/index.ts',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('dependency sections', () => {
|
||||
it('accepts dynamic peer plus dev relationships, static dev inputs, and private dependencies', () => {
|
||||
const slots = pkg('ui-slots', { dynamic: false, staticLinked: true })
|
||||
const runtime = pkg('runtime', {
|
||||
inject: ['@deepseek-ai/dsh-client-feature'],
|
||||
sourceUses: {
|
||||
'@deepseek-ai/dsh-agent': ['packages/client/runtime/src/index.ts'],
|
||||
'@deepseek-ai/dsh-client-ui-slots': ['packages/client/runtime/src/client/slots.ts'],
|
||||
react: ['packages/client/runtime/src/client/view.tsx'],
|
||||
},
|
||||
dependencies: { immer: '^10.1.1' },
|
||||
peerDependencies: {
|
||||
[CORDIS]: 'workspace:^',
|
||||
'@deepseek-ai/dsh-agent': 'workspace:^',
|
||||
'@deepseek-ai/dsh-client-feature': 'workspace:^',
|
||||
},
|
||||
devDependencies: {
|
||||
[CORDIS]: 'workspace:^',
|
||||
'@deepseek-ai/dsh-agent': 'workspace:^',
|
||||
'@deepseek-ai/dsh-client-feature': 'workspace:^',
|
||||
'@deepseek-ai/dsh-client-ui-slots': 'workspace:^',
|
||||
react: '^18.2.0',
|
||||
},
|
||||
})
|
||||
expect(collectClientPackageViolations(facts([slots, runtime], {
|
||||
platformModules: ['react', slots.name],
|
||||
}))).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects internal dependencies, static peers, and mismatched peer development ranges', () => {
|
||||
const slots = pkg('ui-slots', { dynamic: false, staticLinked: true })
|
||||
const subject = pkg('feature', {
|
||||
sourceUses: {
|
||||
'@deepseek-ai/dsh-agent': ['packages/client/feature/src/index.ts'],
|
||||
[slots.name]: ['packages/client/feature/src/view.tsx'],
|
||||
},
|
||||
dependencies: { '@deepseek-ai/dsh-agent': 'workspace:^' },
|
||||
peerDependencies: { [CORDIS]: 'workspace:^', [slots.name]: 'workspace:^' },
|
||||
devDependencies: { [CORDIS]: 'workspace:^', [slots.name]: 'workspace:*' },
|
||||
})
|
||||
const found = collectClientPackageViolations(facts([slots, subject]))
|
||||
expect(found).toHaveLength(2)
|
||||
expect(found.join('\n')).toContain('peer-installed DSH relationship')
|
||||
expect(found.join('\n')).toContain('static client input')
|
||||
})
|
||||
|
||||
it('requires every peer to have the same development range', () => {
|
||||
const subject = pkg('feature', {
|
||||
peerDependencies: { [CORDIS]: 'workspace:^', '@deepseek-ai/cordis-plugin-loader': 'workspace:^' },
|
||||
})
|
||||
expect(collectClientPackageViolations(facts([subject]))).toEqual([
|
||||
'packages/client/feature/package.json: peerDependencies.@deepseek-ai/cordis-plugin-loader'
|
||||
+ ' is workspace:^, so devDependencies.@deepseek-ai/cordis-plugin-loader must use the same range;'
|
||||
+ ' found no declaration',
|
||||
])
|
||||
})
|
||||
|
||||
it('requires statically linked third-party runtime imports in dependencies', () => {
|
||||
const primitives = pkg('ui-primitives', {
|
||||
dynamic: false,
|
||||
staticLinked: true,
|
||||
runtimeSourceUses: { shiki: ['packages/client/ui-primitives/src/highlight.ts'] },
|
||||
devDependencies: { [CORDIS]: 'workspace:^', shiki: '^4.3.1' },
|
||||
})
|
||||
const found = collectClientPackageViolations(facts([primitives]))
|
||||
expect(found).toHaveLength(1)
|
||||
expect(found[0]).toContain('runtime import retained by a statically linked artifact')
|
||||
expect(found[0]).toContain('declare it only in dependencies')
|
||||
|
||||
const valid = { ...primitives, dependencies: { shiki: '^4.3.1' }, devDependencies: { [CORDIS]: 'workspace:^' } }
|
||||
expect(collectClientPackageViolations(facts([valid]))).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the web shell runtime inputs development-only', () => {
|
||||
const web = pkg('web', {
|
||||
dynamic: false,
|
||||
staticLinked: true,
|
||||
runtimeSourceUses: {
|
||||
'@deepseek-ai/cordis-plugin-loader': ['packages/client/web/src/boot.ts'],
|
||||
react: ['packages/client/web/src/seed.ts'],
|
||||
},
|
||||
devDependencies: {
|
||||
[CORDIS]: 'workspace:^',
|
||||
'@deepseek-ai/cordis-plugin-loader': 'workspace:^',
|
||||
react: '^18.2.0',
|
||||
},
|
||||
})
|
||||
expect(collectClientPackageViolations(facts([web]))).toEqual([])
|
||||
})
|
||||
|
||||
it('allows npm dependency cycles', () => {
|
||||
const a = pkg('a', {
|
||||
peerDependencies: { [CORDIS]: 'workspace:^', '@deepseek-ai/dsh-client-b': 'workspace:^' },
|
||||
devDependencies: { [CORDIS]: 'workspace:^', '@deepseek-ai/dsh-client-b': 'workspace:^' },
|
||||
})
|
||||
const b = pkg('b', {
|
||||
peerDependencies: { [CORDIS]: 'workspace:^', '@deepseek-ai/dsh-client-a': 'workspace:^' },
|
||||
devDependencies: { [CORDIS]: 'workspace:^', '@deepseek-ai/dsh-client-a': 'workspace:^' },
|
||||
})
|
||||
expect(collectClientPackageViolations(facts([a, b]))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('module requests', () => {
|
||||
it('accepts a dynamic row supplier and its client subpath', () => {
|
||||
const ui = declaration('ui', { external: ['@deepseek-ai/dsh-client-slots/client'] })
|
||||
const slots = declaration('slots')
|
||||
expect(collectClientPackageViolations(facts([], { declarations: [ui, slots] }))).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects an explicit baseline request', () => {
|
||||
const ui = declaration('ui', { external: ['react'] })
|
||||
expect(collectClientPackageViolations(facts([], {
|
||||
declarations: [ui],
|
||||
platformModules: ['react'],
|
||||
}))).toEqual([
|
||||
ui.manifest + ': dsh.client.external repeats baseline module "react"; remove the explicit declaration',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects duplicates, empty values, self-requests, and missing suppliers', () => {
|
||||
const ui = declaration('ui', {
|
||||
external: ['', '@deepseek-ai/dsh-client-ui', '@deepseek-ai/dsh-missing', '@deepseek-ai/dsh-missing'],
|
||||
inject: ['', '@deepseek-ai/dsh-a', '@deepseek-ai/dsh-a'],
|
||||
})
|
||||
const found = collectClientPackageViolations(facts([], { declarations: [ui] }))
|
||||
expect(found).toHaveLength(6)
|
||||
expect(found.join('\n')).toContain('dsh.client.external contains an empty value')
|
||||
expect(found.join('\n')).toContain('dsh.client.inject contains an empty value')
|
||||
expect(found.join('\n')).toContain('names its own row')
|
||||
expect(found.join('\n')).toContain('has no supplier')
|
||||
})
|
||||
|
||||
it('rejects synchronous module-request cycles but ignores inject cycles', () => {
|
||||
const a = declaration('a', {
|
||||
external: ['@deepseek-ai/dsh-client-b'],
|
||||
inject: ['@deepseek-ai/dsh-client-b'],
|
||||
})
|
||||
const b = declaration('b', {
|
||||
external: ['@deepseek-ai/dsh-client-a'],
|
||||
inject: ['@deepseek-ai/dsh-client-a'],
|
||||
})
|
||||
const found = collectClientPackageViolations(facts([], { declarations: [a, b] }))
|
||||
expect(found).toHaveLength(1)
|
||||
expect(found[0]).toContain('synchronous dsh.client.external cycle')
|
||||
})
|
||||
})
|
||||
|
||||
describe('manifest declarations', () => {
|
||||
it('reports malformed arrays without hiding other packages', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'client-packages-'))
|
||||
roots.push(root)
|
||||
const files: Record<string, unknown> = {
|
||||
'packages/g/a/package.json': {
|
||||
name: '@f/a', dsh: { client: { external: 'react', inject: ['@f/b', 1] } },
|
||||
},
|
||||
'packages/g/b/package.json': { name: '@f/b', dsh: { client: {} } },
|
||||
}
|
||||
for (const [path, value] of Object.entries(files)) {
|
||||
mkdirSync(dirname(join(root, path)), { recursive: true })
|
||||
writeFileSync(join(root, path), JSON.stringify(value))
|
||||
}
|
||||
|
||||
const result = readClientDeclarations(root)
|
||||
expect(result.declarations).toHaveLength(2)
|
||||
expect(result.malformed).toEqual([
|
||||
'packages/g/a/package.json: @f/a dsh.client.external must be a string array',
|
||||
'packages/g/a/package.json: @f/a dsh.client.inject must be a string array',
|
||||
])
|
||||
})
|
||||
|
||||
it('fixes unambiguous dependency sections and declaration entries', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'client-packages-fix-'))
|
||||
roots.push(root)
|
||||
const subject = pkg('feature', {
|
||||
external: ['', 'react', '@deepseek-ai/dsh-client-feature', '@deepseek-ai/dsh-missing'],
|
||||
inject: ['', '@deepseek-ai/dsh-agent', '@deepseek-ai/dsh-agent'],
|
||||
sourceUses: {
|
||||
'@deepseek-ai/dsh-agent': ['packages/client/feature/src/index.ts'],
|
||||
'@deepseek-ai/dsh-client-ui-slots': ['packages/client/feature/src/view.tsx'],
|
||||
},
|
||||
dependencies: {
|
||||
[CORDIS]: 'workspace:^',
|
||||
'@deepseek-ai/dsh-agent': 'workspace:*',
|
||||
},
|
||||
peerDependencies: {
|
||||
'@deepseek-ai/dsh-client-ui-slots': 'workspace:^',
|
||||
'@deepseek-ai/cordis-plugin-loader': 'workspace:^',
|
||||
},
|
||||
devDependencies: {},
|
||||
})
|
||||
const slots = declaration('ui-slots', { dynamic: false })
|
||||
const manifest = {
|
||||
name: subject.name,
|
||||
dsh: { client: { external: subject.external, inject: subject.inject, platform: 'web' } },
|
||||
dependencies: subject.dependencies,
|
||||
peerDependencies: subject.peerDependencies,
|
||||
devDependencies: subject.devDependencies,
|
||||
}
|
||||
mkdirSync(dirname(join(root, subject.manifest)), { recursive: true })
|
||||
writeFileSync(join(root, subject.manifest), JSON.stringify(manifest))
|
||||
writeFileSync(join(root, 'package.json'), JSON.stringify({ private: true }))
|
||||
|
||||
expect(fixClientPackageManifests(root, facts([subject], {
|
||||
declarations: [subject, slots],
|
||||
staticLinkedPackages: new Set([slots.name]),
|
||||
platformModules: ['react', slots.name],
|
||||
}))).toEqual([subject.manifest])
|
||||
|
||||
const fixed = JSON.parse(readFileSync(join(root, subject.manifest), 'utf8')) as {
|
||||
dsh: { client: { external: string[]; inject: string[] } }
|
||||
dependencies?: Record<string, string>
|
||||
peerDependencies: Record<string, string>
|
||||
devDependencies: Record<string, string>
|
||||
}
|
||||
expect(fixed.dsh.client).toMatchObject({
|
||||
external: ['@deepseek-ai/dsh-missing'],
|
||||
inject: ['@deepseek-ai/dsh-agent'],
|
||||
})
|
||||
expect(fixed.dependencies).toBeUndefined()
|
||||
expect(fixed.peerDependencies).toEqual({
|
||||
'@deepseek-ai/cordis-plugin-loader': 'workspace:^',
|
||||
[CORDIS]: 'workspace:^',
|
||||
'@deepseek-ai/dsh-agent': 'workspace:*',
|
||||
})
|
||||
expect(fixed.devDependencies).toEqual({
|
||||
'@deepseek-ai/dsh-client-ui-slots': 'workspace:^',
|
||||
[CORDIS]: 'workspace:^',
|
||||
'@deepseek-ai/dsh-agent': 'workspace:*',
|
||||
'@deepseek-ai/cordis-plugin-loader': 'workspace:^',
|
||||
})
|
||||
})
|
||||
|
||||
it('fixes a statically linked runtime import into dependencies', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'client-packages-static-fix-'))
|
||||
roots.push(root)
|
||||
const subject = pkg('ui-primitives', {
|
||||
dynamic: false,
|
||||
staticLinked: true,
|
||||
runtimeSourceUses: { shiki: ['packages/client/ui-primitives/src/highlight.ts'] },
|
||||
devDependencies: { [CORDIS]: 'workspace:^', shiki: '^4.3.1' },
|
||||
})
|
||||
mkdirSync(dirname(join(root, subject.manifest)), { recursive: true })
|
||||
writeFileSync(join(root, subject.manifest), JSON.stringify({
|
||||
name: subject.name,
|
||||
peerDependencies: subject.peerDependencies,
|
||||
devDependencies: subject.devDependencies,
|
||||
}))
|
||||
writeFileSync(join(root, 'package.json'), JSON.stringify({ private: true }))
|
||||
|
||||
expect(fixClientPackageManifests(root, facts([subject]))).toEqual([subject.manifest])
|
||||
const fixed = JSON.parse(readFileSync(join(root, subject.manifest), 'utf8')) as {
|
||||
dependencies: Record<string, string>
|
||||
devDependencies: Record<string, string>
|
||||
}
|
||||
expect(fixed.dependencies).toEqual({ shiki: '^4.3.1' })
|
||||
expect(fixed.devDependencies).toEqual({ [CORDIS]: 'workspace:^' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,895 @@
|
||||
/**
|
||||
* Verify client package modes, npm dependency sections, and the synchronous
|
||||
* browser module-request graph.
|
||||
*/
|
||||
|
||||
import { globSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { dirname, resolve, sep } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import ts from 'typescript'
|
||||
import { TypeScriptProject } from './ts-project.ts'
|
||||
|
||||
const GATE = 'verify-client-packages'
|
||||
const CLIENT_MANIFEST_GLOB = 'packages/client/*/package.json'
|
||||
const MANIFEST_GLOBS = ['packages/*/*/package.json', 'apps/*/package.json', 'vendor/*/package.json']
|
||||
const CONFIG_GLOB = 'packages/*/*/tsdown.config.ts'
|
||||
const PLATFORM_SOURCE = 'packages/client/web/src/platform.ts'
|
||||
const PARSER_PRELOAD_SOURCE = 'packages/client/modules/src/index.ts'
|
||||
const STATIC_PRESET_SOURCE = 'packages/client/tsdown.client.ts'
|
||||
const CORDIS = '@deepseek-ai/cordis'
|
||||
const DSH_PREFIX = '@deepseek-ai/dsh-'
|
||||
const CLIENT_WEB = '@deepseek-ai/dsh-client-web'
|
||||
|
||||
/** One workspace package's browser-module declaration. */
|
||||
export interface ClientDeclaration {
|
||||
readonly name: string
|
||||
readonly manifest: string
|
||||
readonly dynamic: boolean
|
||||
readonly external: readonly string[]
|
||||
/** Informational package dependencies declared by the row. */
|
||||
readonly inject: readonly string[]
|
||||
}
|
||||
|
||||
/** One package directly under packages/client. */
|
||||
export interface ClientPackage extends ClientDeclaration {
|
||||
readonly staticLinked: boolean
|
||||
readonly sourceUses: Readonly<Record<string, readonly string[]>>
|
||||
readonly runtimeSourceUses: Readonly<Record<string, readonly string[]>>
|
||||
readonly dependencies: Readonly<Record<string, string>>
|
||||
readonly peerDependencies: Readonly<Record<string, string>>
|
||||
readonly devDependencies: Readonly<Record<string, string>>
|
||||
}
|
||||
|
||||
/** Complete source-plane input to the client package verifier. */
|
||||
export interface ClientPackageFacts {
|
||||
readonly packages: readonly ClientPackage[]
|
||||
readonly declarations: readonly ClientDeclaration[]
|
||||
readonly staticLinkedPackages: ReadonlySet<string>
|
||||
readonly platformModules: readonly string[]
|
||||
readonly preloadedExternals: readonly string[]
|
||||
readonly parserPreloadIds: readonly string[]
|
||||
readonly malformed: readonly string[]
|
||||
}
|
||||
|
||||
/** Result of reading every workspace browser-module declaration. */
|
||||
export interface ClientDeclarations {
|
||||
readonly declarations: ClientDeclaration[]
|
||||
readonly malformed: string[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect bare packages referenced by one production source file.
|
||||
* @param path - File path used to select TypeScript's parser mode.
|
||||
* @param source - Source text to inspect.
|
||||
* @returns Bare package names referenced by imports, declarations, or JSX.
|
||||
*/
|
||||
export function collectSourcePackageUses(path: string, source: string): Set<string> {
|
||||
const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
|
||||
return collectSourceFilePackageUses(sourceFile, false)
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect bare packages whose values one production source file reaches at runtime.
|
||||
* @param path - File path used to select TypeScript's parser mode.
|
||||
* @param source - Source text to inspect.
|
||||
* @returns Bare package names retained by runtime imports, exports, requires, or JSX.
|
||||
*/
|
||||
export function collectRuntimeSourcePackageUses(path: string, source: string): Set<string> {
|
||||
const sourceFile = ts.createSourceFile(path, source, ts.ScriptTarget.Latest, true)
|
||||
return collectSourceFilePackageUses(sourceFile, true)
|
||||
}
|
||||
|
||||
function importCarriesRuntimeValue(node: ts.ImportDeclaration): boolean {
|
||||
const clause = node.importClause
|
||||
if (clause === undefined) return true
|
||||
if (clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return false
|
||||
const bindings = clause.namedBindings
|
||||
return clause.name !== undefined
|
||||
|| bindings === undefined
|
||||
|| ts.isNamespaceImport(bindings)
|
||||
|| bindings.elements.length === 0
|
||||
|| bindings.elements.some(element => !element.isTypeOnly)
|
||||
}
|
||||
|
||||
function exportCarriesRuntimeValue(node: ts.ExportDeclaration): boolean {
|
||||
if (node.isTypeOnly) return false
|
||||
const clause = node.exportClause
|
||||
if (clause === undefined || ts.isNamespaceExport(clause)) return true
|
||||
return clause.elements.length === 0 || clause.elements.some(element => !element.isTypeOnly)
|
||||
}
|
||||
|
||||
function collectSourceFilePackageUses(sourceFile: ts.SourceFile, runtimeOnly: boolean): Set<string> {
|
||||
const uses = new Set<string>()
|
||||
|
||||
const add = (specifier: ts.Expression | undefined): void => {
|
||||
if (specifier === undefined || !ts.isStringLiteral(specifier) || !isBareSpecifier(specifier.text)) return
|
||||
uses.add(packageNameOf(specifier.text))
|
||||
}
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (ts.isImportDeclaration(node)) {
|
||||
if (!runtimeOnly || importCarriesRuntimeValue(node)) add(node.moduleSpecifier)
|
||||
} else if (ts.isExportDeclaration(node)) {
|
||||
if (!runtimeOnly || exportCarriesRuntimeValue(node)) add(node.moduleSpecifier)
|
||||
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
||||
if (!runtimeOnly || !node.isTypeOnly) add(node.moduleReference.expression)
|
||||
} else if (!runtimeOnly && ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument)) {
|
||||
add(node.argument.literal)
|
||||
} else if (ts.isCallExpression(node)
|
||||
&& (node.expression.kind === ts.SyntaxKind.ImportKeyword
|
||||
|| ts.isIdentifier(node.expression) && node.expression.text === 'require')) {
|
||||
add(node.arguments[0])
|
||||
} else if (!runtimeOnly && ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name)) {
|
||||
add(node.name)
|
||||
} else if (ts.isJsxElement(node) || ts.isJsxSelfClosingElement(node) || ts.isJsxFragment(node)) {
|
||||
uses.add('react')
|
||||
}
|
||||
ts.forEachChild(node, visit)
|
||||
}
|
||||
|
||||
visit(sourceFile)
|
||||
return uses
|
||||
}
|
||||
|
||||
/**
|
||||
* Read browser-module declarations from workspace manifests.
|
||||
* @param root - Absolute repository root.
|
||||
* @returns Declarations and malformed dsh.client fields.
|
||||
*/
|
||||
export function readClientDeclarations(root: string): ClientDeclarations {
|
||||
const malformed: string[] = []
|
||||
const declarations = globSync(MANIFEST_GLOBS, { cwd: root })
|
||||
.map(normalizePath)
|
||||
.sort()
|
||||
.flatMap(path => readDeclaration(root, path, malformed) ?? [])
|
||||
return { declarations, malformed }
|
||||
}
|
||||
|
||||
/**
|
||||
* Return every client package policy violation.
|
||||
* @param facts - Package modes, manifests, source uses, and platform module lists.
|
||||
* @returns Stable self-contained diagnostics.
|
||||
*/
|
||||
export function collectClientPackageViolations(facts: ClientPackageFacts): string[] {
|
||||
return [
|
||||
...facts.malformed,
|
||||
...collectModeViolations(facts),
|
||||
...collectDependencyViolations(facts),
|
||||
...collectModuleViolations(facts),
|
||||
].sort((left, right) => left.localeCompare(right))
|
||||
}
|
||||
|
||||
interface ManifestDocument {
|
||||
readonly path: string
|
||||
readonly manifest: Manifest
|
||||
changed: boolean
|
||||
}
|
||||
|
||||
type DependencySection = 'dependencies' | 'peerDependencies' | 'devDependencies'
|
||||
|
||||
/**
|
||||
* Repair manifest declarations whose intended result follows uniquely from the policy.
|
||||
* @param root - Absolute repository root.
|
||||
* @param facts - Facts used by the verification pass.
|
||||
* @returns Repository-relative manifests written by the fixer.
|
||||
*/
|
||||
export function fixClientPackageManifests(root: string, facts: ClientPackageFacts): string[] {
|
||||
const documents = new Map<string, ManifestDocument>()
|
||||
const document = (path: string): ManifestDocument => {
|
||||
const cached = documents.get(path)
|
||||
if (cached !== undefined) return cached
|
||||
const loaded: ManifestDocument = {
|
||||
path,
|
||||
manifest: JSON.parse(readFileSync(resolve(root, path), 'utf8')) as Manifest,
|
||||
changed: false,
|
||||
}
|
||||
documents.set(path, loaded)
|
||||
return loaded
|
||||
}
|
||||
|
||||
const baseline = new Set([...facts.platformModules, ...facts.preloadedExternals])
|
||||
for (const declaration of facts.declarations.filter(entry => entry.dynamic)) {
|
||||
const target = document(declaration.manifest)
|
||||
const dsh = isRecord(target.manifest.dsh) ? target.manifest.dsh : undefined
|
||||
const client = isRecord(dsh?.client) ? dsh.client : undefined
|
||||
if (client === undefined) continue
|
||||
target.changed = normalizeClientArray(client, 'inject', () => false) || target.changed
|
||||
target.changed = normalizeClientArray(
|
||||
client,
|
||||
'external',
|
||||
value => baseline.has(value) || rowPackageOf(value, new Set([declaration.name])) === declaration.name,
|
||||
) || target.changed
|
||||
}
|
||||
|
||||
const staticInputs = new Set([
|
||||
...facts.staticLinkedPackages,
|
||||
...facts.platformModules.map(packageNameOf),
|
||||
])
|
||||
staticInputs.delete(CORDIS)
|
||||
const inferredRanges = dependencyRangeCandidates(root)
|
||||
for (const pkg of facts.packages) {
|
||||
const target = document(pkg.manifest)
|
||||
const expected = expectedSections(pkg, staticInputs)
|
||||
for (const [name, rule] of expected) {
|
||||
const range = preferredRange(target.manifest, name, rule.kind, inferredRanges)
|
||||
if (range === undefined) continue
|
||||
target.changed = rule.kind === 'dependency'
|
||||
? ensureDependencyOnly(target.manifest, name, range) || target.changed
|
||||
: rule.kind === 'dev'
|
||||
? ensureDevOnly(target.manifest, name, range) || target.changed
|
||||
: ensurePeerDev(target.manifest, name, range) || target.changed
|
||||
}
|
||||
|
||||
if (pkg.dynamic) {
|
||||
const productionNames = new Set([
|
||||
...Object.keys(section(target.manifest, 'dependencies')),
|
||||
...Object.keys(section(target.manifest, 'peerDependencies')),
|
||||
])
|
||||
for (const name of productionNames) {
|
||||
if (expected.has(name)) continue
|
||||
const range = preferredRange(
|
||||
target.manifest,
|
||||
name,
|
||||
staticInputs.has(name) ? 'dev' : 'peer-dev',
|
||||
inferredRanges,
|
||||
)
|
||||
if (range === undefined) continue
|
||||
if (staticInputs.has(name)) {
|
||||
target.changed = ensureDevOnly(target.manifest, name, range) || target.changed
|
||||
} else if (section(target.manifest, 'dependencies')[name] !== undefined && isInternalDsh(name)) {
|
||||
target.changed = ensurePeerDev(target.manifest, name, range) || target.changed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [name, range] of Object.entries(section(target.manifest, 'peerDependencies'))) {
|
||||
target.changed = setDependency(target.manifest, 'devDependencies', name, range) || target.changed
|
||||
}
|
||||
target.changed = deleteEmptySections(target.manifest) || target.changed
|
||||
}
|
||||
|
||||
const changed = [...documents.values()].filter(target => target.changed).sort((left, right) =>
|
||||
left.path.localeCompare(right.path))
|
||||
for (const target of changed) {
|
||||
writeFileSync(resolve(root, target.path), JSON.stringify(target.manifest, null, 2) + '\n')
|
||||
}
|
||||
return changed.map(target => target.path)
|
||||
}
|
||||
|
||||
function normalizeClientArray(
|
||||
client: Record<string, unknown>,
|
||||
field: 'external' | 'inject',
|
||||
remove: (value: string) => boolean,
|
||||
): boolean {
|
||||
const value = client[field]
|
||||
if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string')) return false
|
||||
const seen = new Set<string>()
|
||||
const normalized = value.filter((entry: string) => {
|
||||
if (entry === '' || seen.has(entry) || remove(entry)) return false
|
||||
seen.add(entry)
|
||||
return true
|
||||
})
|
||||
if (normalized.length === value.length && normalized.every((entry, index) => entry === value[index])) return false
|
||||
if (normalized.length === 0) {
|
||||
if (field === 'external') delete client.external
|
||||
else delete client.inject
|
||||
} else {
|
||||
client[field] = normalized
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function ensureDevOnly(manifest: Manifest, name: string, range: string): boolean {
|
||||
let changed = deleteDependency(manifest, 'dependencies', name)
|
||||
changed = deleteDependency(manifest, 'peerDependencies', name) || changed
|
||||
return setDependency(manifest, 'devDependencies', name, range) || changed
|
||||
}
|
||||
|
||||
function ensureDependencyOnly(manifest: Manifest, name: string, range: string): boolean {
|
||||
let changed = deleteDependency(manifest, 'peerDependencies', name)
|
||||
changed = deleteDependency(manifest, 'devDependencies', name) || changed
|
||||
return setDependency(manifest, 'dependencies', name, range) || changed
|
||||
}
|
||||
|
||||
function ensurePeerDev(manifest: Manifest, name: string, range: string): boolean {
|
||||
let changed = deleteDependency(manifest, 'dependencies', name)
|
||||
changed = setDependency(manifest, 'peerDependencies', name, range) || changed
|
||||
return setDependency(manifest, 'devDependencies', name, range) || changed
|
||||
}
|
||||
|
||||
function setDependency(manifest: Manifest, field: DependencySection, name: string, range: string): boolean {
|
||||
const dependencies = mutableSection(manifest, field)
|
||||
if (dependencies[name] === range) return false
|
||||
dependencies[name] = range
|
||||
return true
|
||||
}
|
||||
|
||||
function deleteDependency(manifest: Manifest, field: DependencySection, name: string): boolean {
|
||||
const dependencies = section(manifest, field)
|
||||
if (dependencies[name] === undefined) return false
|
||||
manifest[field] = Object.fromEntries(Object.entries(dependencies).filter(([key]) => key !== name))
|
||||
return true
|
||||
}
|
||||
|
||||
function deleteEmptySections(manifest: Manifest): boolean {
|
||||
let changed = false
|
||||
for (const field of ['dependencies', 'peerDependencies', 'devDependencies'] as const) {
|
||||
if (manifest[field] === undefined || Object.keys(section(manifest, field)).length > 0) continue
|
||||
if (field === 'dependencies') delete manifest.dependencies
|
||||
else if (field === 'peerDependencies') delete manifest.peerDependencies
|
||||
else delete manifest.devDependencies
|
||||
changed = true
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
function preferredRange(
|
||||
manifest: Manifest,
|
||||
name: string,
|
||||
kind: ExpectedRule['kind'],
|
||||
inferred: ReadonlyMap<string, ReadonlySet<string>>,
|
||||
): string | undefined {
|
||||
const order: readonly DependencySection[] = kind === 'dependency'
|
||||
? ['dependencies', 'devDependencies', 'peerDependencies']
|
||||
: kind === 'dev'
|
||||
? ['devDependencies', 'peerDependencies', 'dependencies']
|
||||
: ['peerDependencies', 'devDependencies', 'dependencies']
|
||||
for (const field of order) {
|
||||
const range = section(manifest, field)[name]
|
||||
if (range !== undefined) return range
|
||||
}
|
||||
if (isInternalDsh(name)) return 'workspace:^'
|
||||
const candidates = inferred.get(name)
|
||||
return candidates?.size === 1 ? [...candidates][0] : undefined
|
||||
}
|
||||
|
||||
function dependencyRangeCandidates(root: string): Map<string, Set<string>> {
|
||||
const candidates = new Map<string, Set<string>>()
|
||||
const paths = globSync([
|
||||
'package.json',
|
||||
...MANIFEST_GLOBS,
|
||||
'website/package.json',
|
||||
], { cwd: root }).map(normalizePath)
|
||||
for (const path of new Set(paths)) {
|
||||
const manifest = JSON.parse(readFileSync(resolve(root, path), 'utf8')) as Manifest
|
||||
for (const field of ['dependencies', 'peerDependencies', 'devDependencies'] as const) {
|
||||
for (const [name, range] of Object.entries(section(manifest, field))) {
|
||||
const ranges = candidates.get(name) ?? new Set<string>()
|
||||
ranges.add(range)
|
||||
candidates.set(name, ranges)
|
||||
}
|
||||
}
|
||||
}
|
||||
return candidates
|
||||
}
|
||||
|
||||
function section(manifest: Manifest, field: DependencySection): Record<string, string> {
|
||||
return manifest[field] ?? {}
|
||||
}
|
||||
|
||||
function mutableSection(manifest: Manifest, field: DependencySection): Record<string, string> {
|
||||
const value = manifest[field]
|
||||
if (value !== undefined) return value
|
||||
const created: Record<string, string> = {}
|
||||
manifest[field] = created
|
||||
return created
|
||||
}
|
||||
|
||||
function collectModeViolations(facts: ClientPackageFacts): string[] {
|
||||
const violations: string[] = []
|
||||
for (const pkg of facts.packages) {
|
||||
if (pkg.dynamic && pkg.staticLinked) {
|
||||
violations.push(
|
||||
pkg.manifest + ': ' + pkg.name + ' declares dsh.client and uses the staticLinked preset;'
|
||||
+ ' a client package must be dynamic or statically linked, not both',
|
||||
)
|
||||
} else if (!pkg.dynamic && !pkg.staticLinked) {
|
||||
violations.push(
|
||||
pkg.manifest + ': ' + pkg.name + ' has no supported client package mode;'
|
||||
+ ' declare dsh.client or use the staticLinked preset',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const workspaceNames = new Set(facts.declarations.map(entry => entry.name))
|
||||
for (const specifier of facts.platformModules) {
|
||||
const owner = packageNameOf(specifier)
|
||||
if (!workspaceNames.has(owner) || owner === CORDIS || facts.staticLinkedPackages.has(owner)) continue
|
||||
violations.push(
|
||||
PLATFORM_SOURCE + ': seeded workspace module ' + JSON.stringify(specifier)
|
||||
+ ' belongs to ' + owner + ', whose build does not use the staticLinked preset',
|
||||
)
|
||||
}
|
||||
|
||||
const rows = rowNames(facts.declarations)
|
||||
for (const specifier of facts.preloadedExternals) {
|
||||
if (rowPackageOf(specifier, rows) === undefined) {
|
||||
violations.push(
|
||||
PLATFORM_SOURCE + ': parser-preloaded external ' + JSON.stringify(specifier)
|
||||
+ ' has no dynamic dsh.client row',
|
||||
)
|
||||
}
|
||||
if (!facts.parserPreloadIds.includes(stripClientSuffix(specifier))) {
|
||||
violations.push(
|
||||
PLATFORM_SOURCE + ': parser-preloaded external ' + JSON.stringify(specifier)
|
||||
+ ' has no matching PARSER_PRELOAD_IDS row in ' + PARSER_PRELOAD_SOURCE,
|
||||
)
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
interface ExpectedRule {
|
||||
readonly kind: 'dependency' | 'dev' | 'peer-dev'
|
||||
readonly origins: Set<string>
|
||||
}
|
||||
|
||||
function collectDependencyViolations(facts: ClientPackageFacts): string[] {
|
||||
const violations: string[] = []
|
||||
const staticInputs = new Set([
|
||||
...facts.staticLinkedPackages,
|
||||
...facts.platformModules.map(packageNameOf),
|
||||
])
|
||||
staticInputs.delete(CORDIS)
|
||||
|
||||
for (const pkg of [...facts.packages].sort((left, right) => left.manifest.localeCompare(right.manifest))) {
|
||||
const expected = expectedSections(pkg, staticInputs)
|
||||
for (const [name, rule] of [...expected].sort(([left], [right]) => left.localeCompare(right))) {
|
||||
const actual = declaredSections(pkg, name)
|
||||
if (rule.kind === 'dependency') {
|
||||
if (actual.length === 1 && actual[0] === 'dependencies') continue
|
||||
violations.push(
|
||||
pkg.manifest + ': ' + name + ' (' + describeOrigins(rule.origins) + ') is a runtime import'
|
||||
+ ' retained by a statically linked artifact; declare it only in dependencies, found '
|
||||
+ describeSections(actual),
|
||||
)
|
||||
continue
|
||||
}
|
||||
if (rule.kind === 'dev') {
|
||||
if (actual.length === 1 && actual[0] === 'devDependencies') continue
|
||||
violations.push(
|
||||
pkg.manifest + ': ' + name + ' (' + describeOrigins(rule.origins) + ') is a static client input;'
|
||||
+ ' declare it only in devDependencies, found ' + describeSections(actual),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const peerRange = pkg.peerDependencies[name]
|
||||
const devRange = pkg.devDependencies[name]
|
||||
if (actual.length === 2
|
||||
&& actual.includes('peerDependencies')
|
||||
&& actual.includes('devDependencies')
|
||||
&& peerRange === devRange) continue
|
||||
violations.push(
|
||||
pkg.manifest + ': ' + name + ' (' + describeOrigins(rule.origins) + ')'
|
||||
+ ' is a peer-installed DSH relationship; declare it in peerDependencies and devDependencies'
|
||||
+ ' with matching ranges, not dependencies; found ' + describeSections(actual)
|
||||
+ describeRangeMismatch(peerRange, devRange),
|
||||
)
|
||||
}
|
||||
|
||||
for (const [name, peerRange] of Object.entries(pkg.peerDependencies).sort(([left], [right]) => left.localeCompare(right))) {
|
||||
if (expected.has(name)) continue
|
||||
const devRange = pkg.devDependencies[name]
|
||||
if (devRange === peerRange) continue
|
||||
violations.push(
|
||||
pkg.manifest + ': peerDependencies.' + name + ' is ' + peerRange + ', so devDependencies.' + name
|
||||
+ ' must use the same range; found ' + (devRange ?? 'no declaration'),
|
||||
)
|
||||
}
|
||||
|
||||
if (!pkg.dynamic) continue
|
||||
for (const section of ['dependencies', 'peerDependencies'] as const) {
|
||||
for (const name of Object.keys(pkg[section]).sort()) {
|
||||
if (expected.has(name)) continue
|
||||
if (staticInputs.has(name)) {
|
||||
violations.push(
|
||||
pkg.manifest + ': dynamic package declares static input ' + name + ' in ' + section + ';'
|
||||
+ ' move it to devDependencies or delete the stale declaration',
|
||||
)
|
||||
} else if (section === 'dependencies' && isInternalDsh(name)) {
|
||||
violations.push(
|
||||
pkg.manifest + ': dynamic package declares ' + name + ' in dependencies;'
|
||||
+ ' dynamic DSH relationships are peer plus dev, and static client inputs are dev-only',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
function expectedSections(pkg: ClientPackage, staticInputs: ReadonlySet<string>): Map<string, ExpectedRule> {
|
||||
const expected = new Map<string, ExpectedRule>([
|
||||
[CORDIS, { kind: 'peer-dev', origins: new Set(['client package baseline']) }],
|
||||
])
|
||||
if (!pkg.dynamic) {
|
||||
if (pkg.name === CLIENT_WEB) return expected
|
||||
for (const [name, locations] of Object.entries(pkg.runtimeSourceUses)) {
|
||||
if (name === pkg.name || name === CORDIS || isInternalDsh(name)) continue
|
||||
expected.set(name, { kind: 'dependency', origins: new Set(locations) })
|
||||
}
|
||||
return expected
|
||||
}
|
||||
|
||||
const add = (name: string, origin: string): void => {
|
||||
if (name === pkg.name) return
|
||||
const kind = staticInputs.has(name) ? 'dev' : isInternalDsh(name) ? 'peer-dev' : undefined
|
||||
if (kind === undefined) return
|
||||
const current = expected.get(name)
|
||||
if (current !== undefined) current.origins.add(origin)
|
||||
else expected.set(name, { kind, origins: new Set([origin]) })
|
||||
}
|
||||
for (const [name, locations] of Object.entries(pkg.sourceUses)) {
|
||||
for (const location of locations) add(name, location)
|
||||
}
|
||||
for (const name of pkg.inject) add(name, 'dsh.client.inject')
|
||||
return expected
|
||||
}
|
||||
|
||||
interface ModuleEdge {
|
||||
readonly from: string
|
||||
readonly to: string
|
||||
readonly specifier: string
|
||||
}
|
||||
|
||||
function collectModuleViolations(facts: ClientPackageFacts): string[] {
|
||||
const violations: string[] = []
|
||||
const baseline = new Set([...facts.platformModules, ...facts.preloadedExternals])
|
||||
const rows = rowNames(facts.declarations)
|
||||
const byName = new Map(facts.declarations.map(entry => [entry.name, entry]))
|
||||
const edges: ModuleEdge[] = []
|
||||
|
||||
for (const pkg of facts.declarations.filter(entry => entry.dynamic)) {
|
||||
for (const field of ['external', 'inject'] as const) {
|
||||
const seen = new Set<string>()
|
||||
for (const value of pkg[field]) {
|
||||
if (value === '') violations.push(pkg.manifest + ': dsh.client.' + field + ' contains an empty value')
|
||||
else if (seen.has(value)) {
|
||||
violations.push(pkg.manifest + ': dsh.client.' + field + ' lists ' + JSON.stringify(value) + ' twice')
|
||||
}
|
||||
seen.add(value)
|
||||
}
|
||||
}
|
||||
|
||||
for (const specifier of new Set(pkg.external)) {
|
||||
if (specifier === '') continue
|
||||
if (baseline.has(specifier)) {
|
||||
violations.push(
|
||||
pkg.manifest + ': dsh.client.external repeats baseline module ' + JSON.stringify(specifier)
|
||||
+ '; remove the explicit declaration',
|
||||
)
|
||||
continue
|
||||
}
|
||||
const supplier = rowPackageOf(specifier, rows)
|
||||
if (supplier === pkg.name) {
|
||||
violations.push(pkg.manifest + ': dsh.client.external names its own row ' + JSON.stringify(specifier))
|
||||
} else if (supplier !== undefined) {
|
||||
edges.push({ from: pkg.name, to: supplier, specifier })
|
||||
} else {
|
||||
const owner = stripClientSuffix(specifier)
|
||||
violations.push(
|
||||
pkg.manifest + ': dsh.client.external ' + JSON.stringify(specifier) + ' has no supplier;'
|
||||
+ (byName.has(owner)
|
||||
? ' workspace package ' + owner
|
||||
+ ' declares no dynamic dsh.client row and the shell does not seed this specifier'
|
||||
: ' no dynamic row or PLATFORM_MODULES entry answers it'),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
violations.push(...collectModuleCycles(edges, byName))
|
||||
return violations
|
||||
}
|
||||
|
||||
function collectModuleCycles(
|
||||
edges: readonly ModuleEdge[],
|
||||
byName: ReadonlyMap<string, ClientDeclaration>,
|
||||
): string[] {
|
||||
const outgoing = new Map<string, ModuleEdge[]>()
|
||||
for (const edge of [...edges].sort((left, right) => left.specifier.localeCompare(right.specifier))) {
|
||||
outgoing.set(edge.from, [...outgoing.get(edge.from) ?? [], edge])
|
||||
}
|
||||
const finished = new Set<string>()
|
||||
const onPath = new Set<string>()
|
||||
const path: ModuleEdge[] = []
|
||||
const reported = new Map<string, string>()
|
||||
|
||||
const walk = (name: string): void => {
|
||||
onPath.add(name)
|
||||
for (const edge of outgoing.get(name) ?? []) {
|
||||
if (onPath.has(edge.to)) {
|
||||
const start = path.findIndex(entry => entry.from === edge.to)
|
||||
const cycle = start === -1 ? [edge] : [...path.slice(start), edge]
|
||||
const key = cycleKey(cycle)
|
||||
if (!reported.has(key)) reported.set(key, formatCycle(cycle, byName))
|
||||
} else if (!finished.has(edge.to)) {
|
||||
path.push(edge)
|
||||
walk(edge.to)
|
||||
path.pop()
|
||||
}
|
||||
}
|
||||
onPath.delete(name)
|
||||
finished.add(name)
|
||||
}
|
||||
|
||||
for (const name of [...outgoing.keys()].sort()) {
|
||||
if (!finished.has(name)) walk(name)
|
||||
}
|
||||
return [...reported.values()]
|
||||
}
|
||||
|
||||
function cycleKey(cycle: readonly ModuleEdge[]): string {
|
||||
const labels = cycle.map(edge => edge.from + ' ' + edge.specifier)
|
||||
const first = [...labels].sort()[0]
|
||||
const offset = first === undefined ? 0 : labels.indexOf(first)
|
||||
return [...labels.slice(offset), ...labels.slice(0, offset)].join(' -> ')
|
||||
}
|
||||
|
||||
function formatCycle(
|
||||
cycle: readonly ModuleEdge[],
|
||||
byName: ReadonlyMap<string, ClientDeclaration>,
|
||||
): string {
|
||||
const entry = cycle[0]
|
||||
const chain = cycle.map(edge => edge.from + ' --(' + edge.specifier + ')-->').join(' ')
|
||||
const manifest = entry === undefined ? 'packages/client' : byName.get(entry.from)?.manifest ?? entry.from
|
||||
return manifest + ': synchronous dsh.client.external cycle: ' + chain + ' ' + (entry?.from ?? '')
|
||||
}
|
||||
|
||||
interface Manifest {
|
||||
name?: unknown
|
||||
dsh?: unknown
|
||||
dependencies?: Record<string, string>
|
||||
peerDependencies?: Record<string, string>
|
||||
devDependencies?: Record<string, string>
|
||||
}
|
||||
|
||||
function readDeclaration(
|
||||
root: string,
|
||||
manifestPath: string,
|
||||
malformed: string[],
|
||||
): ClientDeclaration | undefined {
|
||||
const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) as Manifest
|
||||
if (typeof manifest.name !== 'string') return undefined
|
||||
const dsh = isRecord(manifest.dsh) ? manifest.dsh : undefined
|
||||
const rawClient = dsh?.client
|
||||
if (rawClient === undefined) {
|
||||
return { name: manifest.name, manifest: manifestPath, dynamic: false, external: [], inject: [] }
|
||||
}
|
||||
if (!isRecord(rawClient)) {
|
||||
malformed.push(manifestPath + ': ' + manifest.name + ' dsh.client must be an object')
|
||||
return { name: manifest.name, manifest: manifestPath, dynamic: false, external: [], inject: [] }
|
||||
}
|
||||
return {
|
||||
name: manifest.name,
|
||||
manifest: manifestPath,
|
||||
dynamic: true,
|
||||
external: stringArray(rawClient.external, manifest.name, manifestPath, 'external', malformed),
|
||||
inject: stringArray(rawClient.inject, manifest.name, manifestPath, 'inject', malformed),
|
||||
}
|
||||
}
|
||||
|
||||
function stringArray(
|
||||
value: unknown,
|
||||
packageName: string,
|
||||
manifestPath: string,
|
||||
field: string,
|
||||
malformed: string[],
|
||||
): readonly string[] {
|
||||
if (value === undefined) return []
|
||||
if (!Array.isArray(value) || value.some(entry => typeof entry !== 'string')) {
|
||||
malformed.push(manifestPath + ': ' + packageName + ' dsh.client.' + field + ' must be a string array')
|
||||
return []
|
||||
}
|
||||
return value as string[]
|
||||
}
|
||||
|
||||
async function readStaticLinkedRoster(root: string): Promise<Set<string>> {
|
||||
const presetUrl = pathToFileURL(resolve(import.meta.dirname, '..', STATIC_PRESET_SOURCE)).href
|
||||
const preset = await import(presetUrl) as { isStaticLinkedConfig?: unknown }
|
||||
if (typeof preset.isStaticLinkedConfig !== 'function') {
|
||||
throw new Error(GATE + ': ' + STATIC_PRESET_SOURCE + ' exports no isStaticLinkedConfig')
|
||||
}
|
||||
const predicate = preset.isStaticLinkedConfig as (configs: readonly unknown[]) => boolean
|
||||
const roster = new Set<string>()
|
||||
for (const configPath of globSync(CONFIG_GLOB, { cwd: root }).map(normalizePath).sort()) {
|
||||
const loaded = await import(pathToFileURL(resolve(root, configPath)).href) as { default?: unknown }
|
||||
if (typeof loaded.default !== 'function') continue
|
||||
const configs = (loaded.default as (input: { env: Record<string, string> }) => unknown)({
|
||||
env: { DSH_BUILD_FACE: 'client' },
|
||||
})
|
||||
if (!Array.isArray(configs) || !predicate(configs)) continue
|
||||
const manifest = JSON.parse(
|
||||
readFileSync(resolve(root, configPath.replace(/tsdown\.config\.ts$/, 'package.json')), 'utf8'),
|
||||
) as Manifest
|
||||
if (typeof manifest.name === 'string') roster.add(manifest.name)
|
||||
}
|
||||
return roster
|
||||
}
|
||||
|
||||
function unwrapExpression(expression: ts.Expression): ts.Expression {
|
||||
let current = expression
|
||||
while (ts.isAsExpression(current) || ts.isSatisfiesExpression(current) || ts.isParenthesizedExpression(current)) {
|
||||
current = current.expression
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
function readStringLiteralArray(root: string, sourcePath: string, name: string): string[] {
|
||||
const path = resolve(root, sourcePath)
|
||||
const source = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, false, ts.ScriptKind.TS)
|
||||
const constants = new Map<string, string>()
|
||||
for (const statement of source.statements) {
|
||||
if (!ts.isVariableStatement(statement)) continue
|
||||
for (const declaration of statement.declarationList.declarations) {
|
||||
if (!ts.isIdentifier(declaration.name) || declaration.initializer === undefined) continue
|
||||
const initializer = unwrapExpression(declaration.initializer)
|
||||
if (ts.isStringLiteral(initializer)) constants.set(declaration.name.text, initializer.text)
|
||||
}
|
||||
}
|
||||
for (const statement of source.statements) {
|
||||
if (!ts.isVariableStatement(statement)) continue
|
||||
for (const declaration of statement.declarationList.declarations) {
|
||||
if (!ts.isIdentifier(declaration.name) || declaration.name.text !== name) continue
|
||||
const expression = declaration.initializer === undefined ? undefined : unwrapExpression(declaration.initializer)
|
||||
if (expression === undefined || !ts.isArrayLiteralExpression(expression)) {
|
||||
throw new Error(GATE + ': ' + name + ' in ' + sourcePath + ' must be an array literal')
|
||||
}
|
||||
return expression.elements.map((element) => {
|
||||
const value = unwrapExpression(element)
|
||||
if (ts.isStringLiteral(value)) return value.text
|
||||
if (ts.isIdentifier(value) && constants.has(value.text)) return constants.get(value.text) as string
|
||||
throw new Error(GATE + ': ' + name + ' in ' + sourcePath + ' must contain only string constants')
|
||||
})
|
||||
}
|
||||
}
|
||||
throw new Error(GATE + ': ' + sourcePath + ' declares no ' + name)
|
||||
}
|
||||
|
||||
async function readFacts(root: string): Promise<ClientPackageFacts> {
|
||||
const { declarations, malformed } = readClientDeclarations(root)
|
||||
const byManifest = new Map(declarations.map(entry => [entry.manifest, entry]))
|
||||
const staticLinkedPackages = await readStaticLinkedRoster(root)
|
||||
const project = new TypeScriptProject(root, 'client')
|
||||
const packages: ClientPackage[] = []
|
||||
|
||||
for (const manifestPath of globSync(CLIENT_MANIFEST_GLOB, { cwd: root }).map(normalizePath).sort()) {
|
||||
const declaration = byManifest.get(manifestPath)
|
||||
if (declaration === undefined) throw new Error(GATE + ': no declaration facts for ' + manifestPath)
|
||||
const manifest = JSON.parse(readFileSync(resolve(root, manifestPath), 'utf8')) as Manifest
|
||||
if (typeof manifest.name !== 'string') throw new Error(GATE + ': ' + manifestPath + ' has no package name')
|
||||
const sourceUses = new Map<string, Set<string>>()
|
||||
const runtimeSourceUses = new Map<string, Set<string>>()
|
||||
const packageDirectory = dirname(manifestPath)
|
||||
const sourcePrefix = packageDirectory + '/src/'
|
||||
for (const sourceFile of project.sourceFiles()) {
|
||||
if (sourceFile.isDeclarationFile) continue
|
||||
const file = project.relativePath(sourceFile)
|
||||
if (!file.startsWith(sourcePrefix)) continue
|
||||
for (const name of collectSourceFilePackageUses(sourceFile, false)) {
|
||||
const locations = sourceUses.get(name) ?? new Set<string>()
|
||||
locations.add(file)
|
||||
sourceUses.set(name, locations)
|
||||
}
|
||||
for (const name of collectSourceFilePackageUses(sourceFile, true)) {
|
||||
const locations = runtimeSourceUses.get(name) ?? new Set<string>()
|
||||
locations.add(file)
|
||||
runtimeSourceUses.set(name, locations)
|
||||
}
|
||||
}
|
||||
packages.push({
|
||||
...declaration,
|
||||
staticLinked: staticLinkedPackages.has(declaration.name),
|
||||
sourceUses: Object.fromEntries(
|
||||
[...sourceUses].sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([name, locations]) => [name, [...locations].sort()]),
|
||||
),
|
||||
runtimeSourceUses: Object.fromEntries(
|
||||
[...runtimeSourceUses].sort(([left], [right]) => left.localeCompare(right))
|
||||
.map(([name, locations]) => [name, [...locations].sort()]),
|
||||
),
|
||||
dependencies: manifest.dependencies ?? {},
|
||||
peerDependencies: manifest.peerDependencies ?? {},
|
||||
devDependencies: manifest.devDependencies ?? {},
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
packages,
|
||||
declarations,
|
||||
staticLinkedPackages,
|
||||
platformModules: readStringLiteralArray(root, PLATFORM_SOURCE, 'PLATFORM_MODULES'),
|
||||
preloadedExternals: readStringLiteralArray(root, PLATFORM_SOURCE, 'PRELOADED_CLIENT_EXTERNALS'),
|
||||
parserPreloadIds: readStringLiteralArray(root, PARSER_PRELOAD_SOURCE, 'PARSER_PRELOAD_IDS'),
|
||||
malformed,
|
||||
}
|
||||
}
|
||||
|
||||
function packageNameOf(specifier: string): string {
|
||||
const segments = specifier.split('/')
|
||||
return segments.slice(0, specifier.startsWith('@') ? 2 : 1).join('/')
|
||||
}
|
||||
|
||||
function stripClientSuffix(specifier: string): string {
|
||||
return specifier.endsWith('/client') ? specifier.slice(0, -'/client'.length) : specifier
|
||||
}
|
||||
|
||||
function rowNames(declarations: readonly ClientDeclaration[]): Set<string> {
|
||||
return new Set(declarations.filter(entry => entry.dynamic).map(entry => entry.name))
|
||||
}
|
||||
|
||||
function rowPackageOf(specifier: string, rows: ReadonlySet<string>): string | undefined {
|
||||
if (rows.has(specifier)) return specifier
|
||||
const stripped = stripClientSuffix(specifier)
|
||||
return rows.has(stripped) ? stripped : undefined
|
||||
}
|
||||
|
||||
function declaredSections(pkg: ClientPackage, name: string): string[] {
|
||||
return (['dependencies', 'peerDependencies', 'devDependencies'] as const)
|
||||
.filter(section => pkg[section][name] !== undefined)
|
||||
}
|
||||
|
||||
function describeSections(sections: readonly string[]): string {
|
||||
return sections.length === 0 ? 'no dependency declaration' : sections.join(' + ')
|
||||
}
|
||||
|
||||
function describeRangeMismatch(peer: string | undefined, dev: string | undefined): string {
|
||||
if (peer === undefined || dev === undefined || peer === dev) return ''
|
||||
return ' (peer ' + peer + ', dev ' + dev + ')'
|
||||
}
|
||||
|
||||
function describeOrigins(origins: ReadonlySet<string>): string {
|
||||
const sorted = [...origins].sort()
|
||||
const [first, second, ...rest] = sorted
|
||||
if (first === undefined) return 'production use'
|
||||
if (second === undefined) return first
|
||||
return rest.length === 0 ? first + ', ' + second : first + ', ' + second + ', and ' + String(rest.length) + ' more'
|
||||
}
|
||||
|
||||
function isInternalDsh(name: string): boolean {
|
||||
return name === CORDIS || name.startsWith(DSH_PREFIX)
|
||||
}
|
||||
|
||||
function isBareSpecifier(specifier: string): boolean {
|
||||
return !specifier.startsWith('.') && !specifier.startsWith('/') && !specifier.startsWith('#')
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function normalizePath(path: string): string {
|
||||
return path.split(sep).join('/')
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
let facts = await readFacts(root)
|
||||
if (process.argv.includes('--fix')) {
|
||||
const changed = fixClientPackageManifests(root, facts)
|
||||
console.log(
|
||||
changed.length === 0
|
||||
? GATE + ': no mechanically fixable manifest changes.'
|
||||
: GATE + ': fixed ' + String(changed.length) + ' manifest(s): ' + changed.join(', '),
|
||||
)
|
||||
facts = await readFacts(root)
|
||||
}
|
||||
const violations = collectClientPackageViolations(facts)
|
||||
if (violations.length > 0) {
|
||||
console.error(GATE + ': ' + String(violations.length) + ' violation(s):')
|
||||
for (const violation of violations) console.error(' ' + violation)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const dynamic = facts.packages.filter(pkg => pkg.dynamic).length
|
||||
const requests = facts.declarations.reduce((total, pkg) => total + pkg.external.length, 0)
|
||||
console.log(
|
||||
GATE + ': ' + String(facts.packages.length) + ' client packages (' + String(dynamic) + ' dynamic, '
|
||||
+ String(facts.packages.length - dynamic) + ' statically linked) satisfy dependency and module-request rules; '
|
||||
+ String(requests) + ' explicit external request(s).',
|
||||
)
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) {
|
||||
await main()
|
||||
}
|
||||
@@ -14,7 +14,7 @@ describe('configuration source ownership gate', () => {
|
||||
it('rejects inline endpoints in shipped bundle patches', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-config-source-ownership-'))
|
||||
roots.push(root)
|
||||
const directory = join(root, 'packages/bundle/base')
|
||||
const directory = join(root, 'packages/subagent/subagent-claude-code')
|
||||
mkdirSync(directory, { recursive: true })
|
||||
writeFileSync(
|
||||
join(directory, 'cordis.patch.yml'),
|
||||
@@ -22,7 +22,7 @@ describe('configuration source ownership gate', () => {
|
||||
)
|
||||
|
||||
expect(collectConfigSourceOwnershipViolations(root)).toEqual([
|
||||
'packages/bundle/base/cordis.patch.yml:2: inlines a credential or endpoint from the environment.'
|
||||
'packages/subagent/subagent-claude-code/cordis.patch.yml:2: inlines a credential or endpoint from the environment.'
|
||||
+ ' The adapter resolves apiKeyEnv through ctx.credentials and the endpoint through the'
|
||||
+ ' environment snapshot; inlining here bypasses both ladders.',
|
||||
])
|
||||
|
||||
@@ -14,7 +14,8 @@ const SHIPPED_CONFIG_GLOBS = [
|
||||
'apps/*/config/*.yml',
|
||||
'examples/*/*.cordis.yml',
|
||||
'examples/*/cordis.yml',
|
||||
'packages/bundle/*/cordis.patch.yml',
|
||||
// Bundle identity comes from the package manifest, not the domain directory.
|
||||
'packages/*/*/cordis.patch.yml',
|
||||
// The Python runtime ships its own default composition inside the wheel.
|
||||
'python/*/src/**/cordis.yml',
|
||||
]
|
||||
|
||||
@@ -4,8 +4,15 @@
|
||||
* metadata field must stay static, and a disabled expression must parse.
|
||||
*/
|
||||
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { metadataExpressionErrors } from './verify-cordis-config.ts'
|
||||
import {
|
||||
bundleManifestPaths,
|
||||
bundlePluginDependencyErrors,
|
||||
metadataExpressionErrors,
|
||||
} from './verify-cordis-config.ts'
|
||||
|
||||
describe('verify-cordis-config metadata expressions', () => {
|
||||
it('accepts a disabled !!js expression', () => {
|
||||
@@ -37,3 +44,45 @@ describe('verify-cordis-config metadata expressions', () => {
|
||||
expect(problems.some(problem => problem.includes('[0].disabled: disabled expression does not parse'))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspace Bundle discovery and product dependency closures', () => {
|
||||
it('discovers a Bundle outside packages/bundle from its manifest declaration', () => {
|
||||
const fixture = mkdtempSync(join(tmpdir(), 'dsh-bundle-discovery-'))
|
||||
try {
|
||||
const bundleDir = join(fixture, 'packages/subagent/example')
|
||||
const plainDir = join(fixture, 'packages/bundle/plain')
|
||||
mkdirSync(bundleDir, { recursive: true })
|
||||
mkdirSync(plainDir, { recursive: true })
|
||||
writeFileSync(join(bundleDir, 'package.json'), JSON.stringify({
|
||||
name: '@deepseek-ai/dsh-subagent-example',
|
||||
dsh: { bundle: { patch: './cordis.patch.yml' } },
|
||||
}))
|
||||
writeFileSync(join(plainDir, 'package.json'), JSON.stringify({
|
||||
name: '@deepseek-ai/dsh-plain',
|
||||
}))
|
||||
|
||||
expect(bundleManifestPaths(fixture)).toEqual([
|
||||
'packages/subagent/example/package.json',
|
||||
])
|
||||
} finally {
|
||||
rmSync(fixture, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('allows a Bundle to mount itself but rejects an undeclared plugin package', () => {
|
||||
const manifestPath = 'packages/subagent/example/package.json'
|
||||
const file = 'packages/subagent/example/cordis.patch.yml'
|
||||
const manifest = {
|
||||
name: '@deepseek-ai/dsh-subagent-example',
|
||||
dependencies: {},
|
||||
}
|
||||
const self = { file, name: '@deepseek-ai/dsh-subagent-example' }
|
||||
expect(bundlePluginDependencyErrors(manifestPath, manifest, [self])).toEqual([])
|
||||
expect(bundlePluginDependencyErrors(manifestPath, manifest, [
|
||||
self,
|
||||
{ file, name: '@deepseek-ai/dsh-missing-plugin' },
|
||||
])).toEqual([
|
||||
`${file}: @deepseek-ai/dsh-missing-plugin must be declared in ${manifestPath} dependencies`,
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -12,20 +12,19 @@
|
||||
|
||||
import { globSync, readFileSync } from 'node:fs'
|
||||
import { dirname, relative, resolve } from 'node:path'
|
||||
import * as yaml from 'js-yaml'
|
||||
import { Script } from 'node:vm'
|
||||
import ts from 'typescript'
|
||||
import { cordisConfigFiles } from './cordis-config-files.ts'
|
||||
import { isCordisGroupEntry, isJsExpr, loadCordisYaml } from './cordis-yaml.ts'
|
||||
|
||||
interface JsExpr {
|
||||
__jsExpr: string
|
||||
}
|
||||
|
||||
interface PackageManifest {
|
||||
export interface PackageManifest {
|
||||
name?: string
|
||||
dependencies?: Record<string, string>
|
||||
optionalDependencies?: Record<string, string>
|
||||
dsh?: { bundle?: { patch?: string } }
|
||||
}
|
||||
|
||||
interface PluginReference {
|
||||
export interface PluginReference {
|
||||
file: string
|
||||
name: string
|
||||
}
|
||||
@@ -34,7 +33,9 @@ const root = resolve(import.meta.dirname, '..')
|
||||
// These example files are overlays consumed by the built dsh app, so their bare
|
||||
// specifiers resolve from apps/cli rather than the examples workspace.
|
||||
const appOverlayFiles = new Set([
|
||||
'examples/web-github-review/tests/fixtures/real-cli/cordis.yml',
|
||||
'examples/web-cordis/cordis.yml',
|
||||
'examples/web-github-review/cordis.yml',
|
||||
'examples/web-schedule/cordis.yml',
|
||||
...globSync('examples/mcp-memory/*.cordis.yml', { cwd: root }),
|
||||
])
|
||||
@@ -56,16 +57,6 @@ const CHOOSER_BACKEND_PACKAGES = [
|
||||
'@deepseek-ai/dsh-client-ui-directory-picker-browse',
|
||||
'@deepseek-ai/dsh-client-ui-directory-picker-native',
|
||||
]
|
||||
const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
|
||||
kind: 'scalar',
|
||||
resolve: data => typeof data === 'string',
|
||||
construct: (data: unknown): JsExpr => {
|
||||
if (typeof data !== 'string') throw new TypeError('!!js requires a scalar string')
|
||||
return { __jsExpr: data }
|
||||
},
|
||||
})
|
||||
const schema = yaml.JSON_SCHEMA.extend(jsExprType)
|
||||
|
||||
const errors: string[] = []
|
||||
const pluginReferences: PluginReference[] = []
|
||||
|
||||
@@ -73,7 +64,7 @@ if (import.meta.main) {
|
||||
const files = cordisConfigFiles(root)
|
||||
|
||||
for (const file of files) {
|
||||
const document: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'), { schema })
|
||||
const document = loadCordisYaml(readFileSync(resolve(root, file), 'utf8'))
|
||||
if (!isUnknownArray(document)) {
|
||||
errors.push(`${file}: root must be a Loader entry array`)
|
||||
continue
|
||||
@@ -172,7 +163,7 @@ function validatePresetPlaneSeparation(): string[] {
|
||||
|
||||
/** Every entry of one config file, or an empty list when it is not an entry array. */
|
||||
function loadEntries(file: string): unknown[] {
|
||||
const document: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'), { schema })
|
||||
const document = loadCordisYaml(readFileSync(resolve(root, file), 'utf8'))
|
||||
return isUnknownArray(document) ? document : []
|
||||
}
|
||||
|
||||
@@ -204,7 +195,7 @@ function validateEntry(value: unknown, file: string, path: string): void {
|
||||
}
|
||||
recordPlugin(value, file)
|
||||
validateMetadata(value, file, path)
|
||||
if ((value.group === true || value.name === '@deepseek-ai/cordis-plugin-group') && isUnknownArray(value.config)) {
|
||||
if (isCordisGroupEntry(value)) {
|
||||
for (let index = 0; index < value.config.length; index++) {
|
||||
validateEntry(value.config[index], file, `${path}.config[${index}]`)
|
||||
}
|
||||
@@ -260,11 +251,14 @@ function validateExampleResolution(): string[] {
|
||||
|
||||
function validateAppResolution(): string[] {
|
||||
const violations: string[] = []
|
||||
const bundleManifests = bundleManifestPaths()
|
||||
// App overlays (and any config left under apps/cli/config) resolve from the
|
||||
// dsh app's own dependency surface — the profile module fallback mirrors it.
|
||||
const appDependencies = {
|
||||
...readManifest('apps/cli/package.json').dependencies,
|
||||
// The fallback also links every bundle's own dependencies (healProfilesModuleFallback).
|
||||
// The fallback also links every in-box bundle's own dependencies
|
||||
// (healProfilesModuleFallback). Optional Profile bundles stay outside the
|
||||
// app installation until that Profile installs them.
|
||||
...Object.fromEntries(globSync('packages/bundle/*/package.json', { cwd: root })
|
||||
.flatMap(file => Object.entries(readManifest(file).dependencies ?? {}))),
|
||||
}
|
||||
@@ -274,20 +268,50 @@ function validateAppResolution(): string[] {
|
||||
violations.push(...missingPluginDependencies(appReferences, appDependencies, 'apps/cli/package.json or a bundle manifest'))
|
||||
// Each bundle's patch rows must resolve from that bundle's own dependencies:
|
||||
// per-layer resolution anchors on the bundle package directory.
|
||||
for (const manifestPath of globSync('packages/bundle/*/package.json', { cwd: root })) {
|
||||
for (const manifestPath of bundleManifests) {
|
||||
const bundleDir = manifestPath.replace(/\/package\.json$/, '')
|
||||
const manifest = readManifest(manifestPath)
|
||||
const references = pluginReferences.filter(reference => reference.file.startsWith(`${bundleDir}/`))
|
||||
violations.push(...missingPluginDependencies(
|
||||
// A bundle may mount its own package (the web-app runtime row).
|
||||
references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name),
|
||||
manifest.dependencies ?? {},
|
||||
manifestPath,
|
||||
))
|
||||
const patch = manifest.dsh?.bundle?.patch
|
||||
if (typeof patch !== 'string') continue
|
||||
const patchFile = relative(root, resolve(root, bundleDir, patch)).replaceAll('\\', '/')
|
||||
const references = pluginReferences.filter(reference => reference.file === patchFile)
|
||||
violations.push(...bundlePluginDependencyErrors(manifestPath, manifest, references))
|
||||
}
|
||||
return violations
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover workspace Bundle packages from their manifest declaration.
|
||||
* @param repoRoot Repository root to scan.
|
||||
* @returns Sorted slash-normalized repository-relative package manifest paths.
|
||||
*/
|
||||
export function bundleManifestPaths(repoRoot: string = root): string[] {
|
||||
return globSync('packages/*/*/package.json', { cwd: repoRoot })
|
||||
.filter(path => typeof readManifest(path, repoRoot).dsh?.bundle?.patch === 'string')
|
||||
.map(path => path.replaceAll('\\', '/'))
|
||||
.sort()
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate plugin packages referenced by one Bundle patch.
|
||||
* @param manifestPath Repository-relative Bundle manifest path.
|
||||
* @param manifest Parsed Bundle manifest.
|
||||
* @param references Plugin rows read from the Bundle package directory.
|
||||
* @returns Missing production dependency diagnostics.
|
||||
*/
|
||||
export function bundlePluginDependencyErrors(
|
||||
manifestPath: string,
|
||||
manifest: PackageManifest,
|
||||
references: readonly PluginReference[],
|
||||
): string[] {
|
||||
return missingPluginDependencies(
|
||||
// A Bundle may mount its own package (for example, its provider or runtime row).
|
||||
references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name),
|
||||
manifest.dependencies ?? {},
|
||||
manifestPath,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Every configured specifier of a local workspace package must resolve through
|
||||
* the tsconfig `paths` facade to a `.ts`/`.tsx` source file. The `dsh` source
|
||||
@@ -363,8 +387,8 @@ function missingPluginDependencies(
|
||||
: `${[...locations].join(', ')}: ${packageName} must be declared in ${manifestPath} dependencies`)
|
||||
}
|
||||
|
||||
function readManifest(path: string): PackageManifest {
|
||||
return JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest
|
||||
function readManifest(path: string, repoRoot: string = root): PackageManifest {
|
||||
return JSON.parse(readFileSync(resolve(repoRoot, path), 'utf8')) as PackageManifest
|
||||
}
|
||||
|
||||
function localPackageDirectories(): Map<string, string> {
|
||||
@@ -461,9 +485,8 @@ export function metadataExpressionErrors(entry: Record<string, unknown>, path: s
|
||||
*/
|
||||
function disabledExpressionProblem(expression: string): string | undefined {
|
||||
try {
|
||||
// Compilation only — the constructor never executes the body.
|
||||
// oxlint-disable-next-line typescript/no-implied-eval
|
||||
new Function(`return (${expression})`)
|
||||
// Compilation only — constructing a Script does not execute its source.
|
||||
new Script(`(${expression})`)
|
||||
return undefined
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
@@ -484,10 +507,6 @@ function collectExpressionPaths(value: unknown, path: string, output: string[]):
|
||||
for (const [key, child] of Object.entries(value)) collectExpressionPaths(child, `${path}.${key}`, output)
|
||||
}
|
||||
|
||||
function isJsExpr(value: unknown): value is JsExpr {
|
||||
return isRecord(value) && typeof value.__jsExpr === 'string'
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object'
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { inspectSiteFragments } from './verify-doc-site-fragments.ts'
|
||||
import { inspectSiteFragments, missingSiteFiles } from './verify-doc-site-fragments.ts'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
@@ -85,3 +85,13 @@ describe('inspectSiteFragments', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('missingSiteFiles', () => {
|
||||
it('reports the expected files a build did not emit', () => {
|
||||
const root = fixture()
|
||||
writeFileSync(join(root, 'guide/start.md'), '# Ready\n')
|
||||
|
||||
expect(missingSiteFiles(root, ['guide/start.md', 'guide/absent.md', 'llms.txt']))
|
||||
.toEqual(['guide/absent.md', 'llms.txt'])
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,17 @@
|
||||
/**
|
||||
* Verify fragment links against the HTML emitted by VitePress. Markdown and
|
||||
* VitePress use different heading-slug algorithms, so source-link validation
|
||||
* alone cannot prove that a published fragment exists.
|
||||
* Verify fragment links against the HTML emitted by VitePress, and that the
|
||||
* build carries the raw-Markdown twin of every route plus llms.txt. Markdown
|
||||
* and VitePress use different heading-slug algorithms, so source-link
|
||||
* validation alone cannot prove that a published fragment exists.
|
||||
*
|
||||
* This runs as part of `docs:build` and can also run directly after a build
|
||||
* with `tsx scripts/verify-doc-site-fragments.ts`.
|
||||
*/
|
||||
|
||||
import { globSync, readFileSync } from 'node:fs'
|
||||
import { existsSync, globSync, readFileSync } from 'node:fs'
|
||||
import { resolve, sep } from 'node:path'
|
||||
import { JSDOM } from 'jsdom'
|
||||
import { rawMarkdownFiles } from './project-doc-site.ts'
|
||||
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
|
||||
@@ -138,18 +140,40 @@ export function inspectSiteFragments(distRoot: string): SiteFragmentReport {
|
||||
return { checked, broken }
|
||||
}
|
||||
|
||||
/**
|
||||
* Expected files a build did not emit.
|
||||
*
|
||||
* @param distRoot - Directory containing the built site.
|
||||
* @param expected - Site-relative files the build must carry.
|
||||
* @returns The absent files, in the given order.
|
||||
*/
|
||||
export function missingSiteFiles(distRoot: string, expected: readonly string[]): string[] {
|
||||
return expected.filter(file => !existsSync(resolve(distRoot, file)))
|
||||
}
|
||||
|
||||
function main(): number {
|
||||
const distRoot = resolve(root, 'website/.dist')
|
||||
const report = inspectSiteFragments(distRoot)
|
||||
if (report.broken.length === 0) {
|
||||
console.log(`verify-doc-site-fragments: ${report.checked} internal fragment reference(s) resolve.`)
|
||||
const expected = rawMarkdownFiles()
|
||||
const missing = missingSiteFiles(distRoot, [...expected, 'llms.txt'])
|
||||
if (report.broken.length === 0 && missing.length === 0) {
|
||||
console.log(
|
||||
`verify-doc-site-fragments: ${report.checked} internal fragment reference(s) resolve;`
|
||||
+ ` ${expected.length} raw-Markdown file(s) and llms.txt emitted.`,
|
||||
)
|
||||
return 0
|
||||
}
|
||||
|
||||
console.error(`verify-doc-site-fragments: ${report.broken.length} broken fragment reference(s):`)
|
||||
for (const item of report.broken) {
|
||||
const target = item.target === undefined ? 'target route was not built' : `${item.target} has no id ${JSON.stringify(item.fragment)}`
|
||||
console.error(` ${item.source}: ${JSON.stringify(item.href)} (${target})`)
|
||||
if (report.broken.length > 0) {
|
||||
console.error(`verify-doc-site-fragments: ${report.broken.length} broken fragment reference(s):`)
|
||||
for (const item of report.broken) {
|
||||
const target = item.target === undefined ? 'target route was not built' : `${item.target} has no id ${JSON.stringify(item.fragment)}`
|
||||
console.error(` ${item.source}: ${JSON.stringify(item.href)} (${target})`)
|
||||
}
|
||||
}
|
||||
if (missing.length > 0) {
|
||||
console.error(`verify-doc-site-fragments: ${missing.length} expected raw-Markdown file(s) missing from the build:`)
|
||||
for (const file of missing) console.error(` ${file}`)
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -22,37 +22,28 @@ const PROTOCOL_EXPORTS = new Set(['Config', 'inject', 'name', 'reusable', 'apply
|
||||
|
||||
/** Per-file walk state threaded through the scope recursion. */
|
||||
interface Walk {
|
||||
/** Repo-relative path of the file being walked. */
|
||||
rel: string
|
||||
/** The parsed source file. */
|
||||
sf: ts.SourceFile
|
||||
/** Raw file text (rawJsDoc reads comment ranges out of it). */
|
||||
text: string
|
||||
/** The program's checker, consulted only for heritage-member lookups. */
|
||||
checker: ts.TypeChecker
|
||||
/** The aggregate violation list, appended in place. */
|
||||
violations: string[]
|
||||
}
|
||||
|
||||
/** True when a statement carries the `export` modifier. */
|
||||
function isExported(stmt: ts.Statement): boolean {
|
||||
return ts.canHaveModifiers(stmt) && (ts.getModifiers(stmt)?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)
|
||||
}
|
||||
|
||||
/** True for a class member a consumer cannot reach: `private`/`protected`/`#name`. */
|
||||
function isNonPublic(member: ts.ClassElement): boolean {
|
||||
const mods = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
|
||||
return (mods?.some(m => m.kind === ts.SyntaxKind.PrivateKeyword || m.kind === ts.SyntaxKind.ProtectedKeyword) ?? false)
|
||||
|| ('name' in member && ts.isPrivateIdentifier(member.name))
|
||||
}
|
||||
|
||||
/** True when a class member carries the `static` modifier. */
|
||||
function isStatic(member: ts.ClassElement): boolean {
|
||||
const mods = ts.canHaveModifiers(member) ? ts.getModifiers(member) : undefined
|
||||
return mods?.some(m => m.kind === ts.SyntaxKind.StaticKeyword) ?? false
|
||||
}
|
||||
|
||||
/** The `this`-receiver exemption every function-like check shares. */
|
||||
function thisReceiver(p: ts.ParameterDeclaration): boolean {
|
||||
return ts.isIdentifier(p.name) && p.name.text === 'this'
|
||||
}
|
||||
@@ -611,7 +602,6 @@ function main(): void {
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// Run only when invoked as a script, not when imported by a test.
|
||||
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
|
||||
main()
|
||||
}
|
||||
Loaded 100 of 4342 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user