Merge branch 'feat/mcp-tool-loading' into feat/linear-plugin

# Conflicts:
#	packages/README.i18n.yaml
This commit is contained in:
gengruilin committed 2026-11-06 04:00:40 +08:00
commit 3aa66f4898
2816 files changed
+66728 -15714

No files matched your search

@@ -26,5 +26,7 @@ describe('Python runtime executable assets', () => {
expect(result.stdout).not.toContain('skill-badge/assets/**/*')
expect(result.stdout).toContain('node_modules/@deepseek-ai/dsh-sandbox-windows-acl/assets/**/*')
expect(result.stdout).not.toContain('node_modules/**/*.py')
// skill-office reads its SKILL.md files from the package's assets directory.
expect(result.stdout).toContain('"node_modules/**/*.md"')
})
})
+2 -1
View File
@@ -179,7 +179,8 @@ describe('Python runtime executable builder CLI', () => {
expect(result.stdout).toContain('exec pkg')
expect(result.stdout).toContain('--sea --compress Brotli --targets node24-macos-x64')
expect(result.stdout).toContain('keep only node-pty prebuilds darwin-x64')
expect(result.stdout).toContain('lock optional resource downloads and copy Office skills')
expect(result.stdout).toContain(`lock optional resource downloads in ${join(root, 'dist-exe', 'macos-x64')}`)
expect(result.stdout).not.toContain('office-skills')
expect(result.stdout).toContain(join(root, 'dist-exe', 'macos-x64'))
})
+9 -3
View File
@@ -19,7 +19,6 @@ import { resolveLinuxNodePtyAddon, resolveWindowsNodePtyAddons } from './executa
import { officeSidecarArchives, runtimeNpmArchive, OFFICE_ASSET_IGNORES } from './build-exe-for-python-sdk-office.ts'
import { syncPythonRuntimeProduct } from './build-exe-for-python-sdk-resources.ts'
import { deduplicateStagedWorkspacePackages, materializeStagedLinks } from './build-exe-for-python-sdk-staging.ts'
import { prepareOfficeSkillAssets } from './primary-runtime/prepare.ts'
import primaryLock from './primary-runtime/lock.json' with { type: 'json' }
const root = resolve(import.meta.dirname, '..')
@@ -71,6 +70,13 @@ const ASSET_GLOBS = [
'node_modules/@deepseek-ai/dsh-sandbox-windows-acl/assets/**/*',
]
/** Published source and documentation: types and maps already describe the runtime, so no load path needs them. */
const PUBLISHED_PAYLOAD_IGNORES = [
'**/node_modules/@deepseek-ai/dsh/src/**',
'**/node_modules/@deepseek-ai/dsh-*/src/**',
'**/node_modules/@deepseek-ai/dsh/docs/**',
]
const PLATFORMS = ['linux', 'macos', 'win'] as const
const ARCHES = ['x64', 'arm64'] as const
type Platform = (typeof PLATFORMS)[number]
@@ -342,6 +348,7 @@ class SingleExeBuild {
const sourceModules = join(root, 'node_modules').replaceAll('\\', '/')
const patch = { bin: ENTRY_BIN, pkg: { assets: ASSET_GLOBS, ignore: [
...OFFICE_ASSET_IGNORES,
...PUBLISHED_PAYLOAD_IGNORES,
`${sourceModules}/**`, `${sourceModules}/.pnpm/**`,
...['packages', 'apps', 'vendor', 'native', 'scripts'].map(directory => `${join(root, directory).replaceAll('\\', '/')}/**`),
`${root.replaceAll('\\', '/')}/tsconfig*.json`,
@@ -412,7 +419,7 @@ class SingleExeBuild {
const ripgrep = await this.copyRipgrepSidecar(target, product)
const resources = join(this.outDir, `${target.platform}-${target.arch}`)
if (this.cli.dryRun) {
console.log(`build-exe-for-python-sdk: [dry-run] lock optional resource downloads and copy Office skills to ${resources}`)
console.log(`build-exe-for-python-sdk: [dry-run] lock optional resource downloads in ${resources}`)
} else {
await rm(resources, { recursive: true, force: true })
await mkdir(resources, { recursive: true })
@@ -422,7 +429,6 @@ class SingleExeBuild {
const inputs = { version, target: `${target.platform === 'macos' ? 'mac' : target.platform}-${target.arch}`, office, pnpm }
const identity = createHash('sha256').update(JSON.stringify({ ...inputs, primaryLock })).digest('hex')
await writeFile(join(resources, 'downloads.json'), JSON.stringify({ ...inputs, identity }, undefined, 2) + '\n')
await prepareOfficeSkillAssets(join(this.staging, 'node_modules/@deepseek-ai/dsh-skill-office/assets'), join(resources, 'office-skills'))
}
if (target.platform !== 'macos') return [product, ripgrep, resources]
const spawnHelper = `${product}-spawn-helper`
+47 -21
View File
@@ -8,6 +8,7 @@ import {
isPublicExperimentalPackageDirectory,
PRIVATE_EXPERIMENTAL_PACKAGE_DIRECTORIES,
EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS,
LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES,
} from './experimental-package-policy.ts'
import {
checkDshFamilyVersion,
@@ -22,8 +23,11 @@ import {
type WorkspaceManifest,
} from './check-workspace-constraints.ts'
const legacyManifests = LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES
.map(dir => ({ dir, manifest: { name: dir.replace('packages/experimental/', '@deepseek-ai/dsh-experimental-') } }))
const experimental = {
dir: 'packages/experimental/prototype',
dir: LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES[0]!,
manifest: {
name: '@deepseek-ai/dsh-experimental-prototype',
publishConfig: { access: 'public' },
@@ -118,36 +122,51 @@ describe('workspace manifest discovery', () => {
})
describe('experimental workspace constraints', () => {
it('requires the experimental package-name prefix', () => {
it('requires an unprefixed name to have a directory entry', () => {
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-" or match its declared directory exception',
'@deepseek-ai/dsh-prototype: experimental package name must be declared for this directory in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)',
])
})
it.each(Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('retains %s only at its declared directory', (dir, name) => {
expect(checkExperimentalManifest({ dir, manifest: { name, publishConfig: { access: 'public' } } })).toEqual([])
expect(checkExperimentalManifest({ ...experimental, manifest: { ...experimental.manifest, name } }))
.toEqual([expect.stringContaining('declared directory exception')])
.toEqual([expect.stringContaining('declared for this directory')])
})
it('rejects a missing manifest name even when the directory has no exception', () => {
expect(checkExperimentalManifest({ ...experimental, manifest: { publishConfig: { access: 'public' } } }))
.toEqual([expect.stringContaining('experimental package name must start')])
it('rejects the legacy prefix outside the legacy directory list', () => {
expect(checkExperimentalManifest({ ...experimental, dir: 'packages/experimental/prototype' })).toEqual([
'@deepseek-ai/dsh-experimental-prototype: new experimental packages must not use the "@deepseek-ai/dsh-experimental-" prefix; name it @deepseek-ai/dsh-<name> and declare it in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)',
])
})
it('rejects stale, moved and duplicated retained-name declarations', () => {
it('rejects a missing manifest name', () => {
expect(checkExperimentalManifest({ dir: 'packages/experimental/prototype', manifest: { publishConfig: { access: 'public' } } }))
.toEqual(['packages/experimental/prototype: experimental package must declare a name'])
})
it('rejects stale, moved and duplicated unprefixed-name declarations', () => {
const manifests = Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS).map(([dir, name]) => ({ dir, manifest: { name } }))
expect(checkExperimentalNameExceptions(manifests)).toEqual([])
expect(checkExperimentalNameExceptions([...manifests, ...legacyManifests])).toEqual([])
const [first, ...rest] = manifests
for (const invalid of [
rest,
[{ ...first!, manifest: { name: '@deepseek-ai/dsh-experimental-replacement' } }, ...rest],
[{ ...first!, dir: 'packages/core/replacement' }, ...rest],
[...manifests, { ...first!, dir: 'packages/experimental/duplicate' }],
]) expect(checkExperimentalNameExceptions(invalid)).toEqual([expect.stringContaining(first!.manifest.name)])
]) expect(checkExperimentalNameExceptions([...invalid, ...legacyManifests])).toEqual([expect.stringContaining(first!.manifest.name)])
})
it('rejects a legacy directory without a prefixed package', () => {
const unprefixed = Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS).map(([dir, name]) => ({ dir, manifest: { name } }))
const others = legacyManifests.filter(entry => entry.dir !== experimental.dir)
for (const invalid of [others, [...others, { dir: experimental.dir, manifest: { name: '@deepseek-ai/dsh-renamed' } }]]) {
expect(checkExperimentalNameExceptions([...unprefixed, ...invalid]))
.toEqual([`${experimental.dir}: remove this directory from LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES; no package with the legacy prefix lives here`])
}
})
it.each(Object.values(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('rejects retained runtime names and aliases: %s', (name) => {
@@ -294,16 +313,16 @@ describe('package payload constraints', () => {
[{ import: './art/icon.svg', default: './art/fallback.svg' }, ['art/icon.svg', 'art/fallback.svg']],
[['./art/icon.svg', './art/icon.svg'], ['art/icon.svg']],
] as const)('includes exported icon targets in the canonical payload: %j', (icon, expected) => {
expect(expectedDshPackageFiles({ exports: { './icon': icon } })).toEqual([...expected, 'lib/index.js', 'lib/types/**/*.d.ts'])
expect(expectedDshPackageFiles({ exports: { './icon': icon } })).toEqual([...expected, 'lib/index.js', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src'])
})
it.each(['icon.svg', './icon.svg'])('includes and deduplicates manifest icon %s', (icon) => {
expect(expectedDshPackageFiles({ icon, exports: { './icon': './icon.svg' } })).toEqual(['icon.svg', 'lib/index.js', 'lib/types/**/*.d.ts'])
expect(expectedDshPackageFiles({ icon, exports: { './icon': './icon.svg' } })).toEqual(['icon.svg', 'lib/index.js', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src'])
})
it('includes manifest, root, and subpath icon targets', () => {
expect(expectedDshPackageFiles({ icon: './legacy.svg', exports: { './icon': './fallback.svg', './search/icon': './search.svg' } })).toEqual([
'legacy.svg', 'fallback.svg', 'search.svg', 'lib/index.js', 'lib/types/**/*.d.ts',
'legacy.svg', 'fallback.svg', 'search.svg', 'lib/index.js', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src',
])
})
@@ -324,7 +343,7 @@ describe('package payload constraints', () => {
{ exports: { './search/locale/*.json': './z/*.json', './locale/*.json': './a/*.json' }, resources: ['a/*.json', 'z/*.json'] },
])('includes declared locale resources in the canonical payload: $exports', ({ exports, resources }) => {
expect(expectedDshPackageFiles({ name: '@deepseek-ai/dsh-localized', exports })).toEqual([
...resources, 'lib/index.js', 'lib/types/**/*.d.ts',
...resources, 'lib/index.js', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src',
])
})
@@ -362,7 +381,7 @@ describe('package payload constraints', () => {
const detailFiles = detailDocumentFiles(dir)
expect(detailFiles).toEqual(['docs'])
expect(expectedDshPackageFiles({ exports: { './locale/*.json': './locale/*.json' } }, detailFiles)).toEqual([
'locale/*.json', 'docs', 'lib/index.js', 'lib/types/**/*.d.ts',
'locale/*.json', 'docs', 'lib/index.js', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src',
])
})
@@ -403,7 +422,7 @@ describe('package payload constraints', () => {
'./locale/zh.json': null,
'./locale/fr.json': { types: './locale/fr.d.ts' },
},
})).toEqual(['lib/index.js', 'lib/types/**/*.d.ts'])
})).toEqual(['lib/index.js', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src'])
})
it.each(['team/agent-team', 'experimental/voice-input-bundle', 'experimental/auto-review', 'client/ui-agent-team', 'team/tool-agent-team'])(
@@ -441,6 +460,9 @@ describe('package payload constraints', () => {
'lib/index.js',
'cordis.patch.yml',
'lib/types/**/*.d.ts',
'lib/types/**/*.d.ts.map',
'lib/**/*.js.map',
'src',
])
expect(expectedDshPackageFiles({
name: '@deepseek-ai/dsh-private-profile',
@@ -450,6 +472,9 @@ describe('package payload constraints', () => {
'cordis.patch.yml',
'layers/web.patch.yml',
'lib/types/**/*.d.ts',
'lib/types/**/*.d.ts.map',
'lib/**/*.js.map',
'src',
])
})
@@ -473,6 +498,7 @@ describe('package payload constraints', () => {
},
})).toEqual([
'lib/index.js', 'lib/client.js', 'lib/client.node.js', 'lib/assets', 'lib/loader.js', 'lib/types/**/*.d.ts',
'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src',
])
})
@@ -483,7 +509,7 @@ describe('package payload constraints', () => {
{ './assets/extra': './lib/assets/*' },
])('does not publish package assets without the exact asset export target: %j', (assets) => {
expect(expectedDshPackageFiles({ exports: { './client': './lib/client.js', ...assets } }))
.toEqual(['lib/index.js', 'lib/client.js', 'lib/types/**/*.d.ts'])
.toEqual(['lib/index.js', 'lib/client.js', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src'])
})
it('rejects a package-asset export whose payload omits the built assets', () => {
@@ -498,7 +524,7 @@ describe('package payload constraints', () => {
'./client': { types: './lib/types/client/index.d.ts', default: './lib/client.js' },
'./assets/*': './lib/assets/*',
},
files: ['lib/index.js', 'lib/client.js', 'lib/assets', 'lib/types/**/*.d.ts'],
files: ['lib/index.js', 'lib/client.js', 'lib/assets', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src'],
peerDependencies: { '@deepseek-ai/cordis': 'workspace:~' },
devDependencies: { '@deepseek-ai/cordis': 'workspace:~' },
} satisfies WorkspaceManifest['manifest']
@@ -507,7 +533,7 @@ describe('package payload constraints', () => {
expect(payloadErrors(manifest)).toEqual([])
expect(payloadErrors({ ...manifest, files: manifest.files.filter(file => file !== 'lib/assets') })).toEqual([
expect.stringContaining('@deepseek-ai/dsh-client-probe: package.json files must be '
+ '["lib/index.js","lib/client.js","lib/assets","lib/types/**/*.d.ts"]'),
+ '["lib/index.js","lib/client.js","lib/assets","lib/types/**/*.d.ts","lib/types/**/*.d.ts.map","lib/**/*.js.map","src"]'),
])
})
@@ -527,7 +553,7 @@ it('publishes CLI runtime declarations and rejects a payload that omits them', (
const manifest = JSON.parse(readFileSync(new URL('../apps/cli/package.json', import.meta.url), 'utf8')) as WorkspaceManifest['manifest']
expect(checkWorkspaceManifest({ dir: 'apps/cli', manifest })).toEqual([])
expect(checkWorkspaceManifest({ dir: 'apps/cli', manifest: { ...manifest, files: ['lib/*.js'] } }))
.toEqual([expect.stringContaining('@deepseek-ai/dsh: package.json files must be ["lib/*.js","lib/types/*.d.ts"]')])
.toEqual([expect.stringContaining('@deepseek-ai/dsh: package.json files must be ["lib/*.js","lib/*.js.map","lib/types/*.d.ts","lib/types/*.d.ts.map","docs","src"]')])
})
it('requires the shared Web injection entry in the published payload', () => {
@@ -607,7 +633,7 @@ it('requires the OAR license while rejecting unrelated payload files', () => {
const manifest = JSON.parse(readFileSync(new URL(`../${dir}/package.json`, import.meta.url), 'utf8')) as WorkspaceManifest['manifest']
const files = [
'icon.svg', 'locale/*.json', 'lib/index.js',
'LICENSE-OAR', 'lib/types/**/*.d.ts',
'LICENSE-OAR', 'lib/types/**/*.d.ts', 'lib/types/**/*.d.ts.map', 'lib/**/*.js.map', 'src',
]
expect(expectedDshPackageFiles(manifest)).toEqual(files)
expect(checkWorkspaceManifest({ dir, manifest })).toEqual([])
+34 -25
View File
@@ -15,9 +15,10 @@ import {
hasExperimentalPackageReference,
EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS,
EXPERIMENTAL_PACKAGE_NAME_PREFIX,
LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES,
PRIVATE_EXPERIMENTAL_PACKAGE_DIRECTORIES,
} from './experimental-package-policy.ts'
import { hasTypertRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
import { hasTypertRemoteNavigation } from './publication-payload.ts'
import type { DshBundleManifest } from '../packages/util/package-manifest/src/types.ts'
import { detailPath } from '../packages/util/plugin-detail/src/document.ts'
import { bundlePatchFiles } from '../packages/boot/app-boot/src/profile.ts'
@@ -56,10 +57,6 @@ const publicNativePackages = new Set([
'@deepseek-ai/node-addon-system-linux-arm64',
'@deepseek-ai/node-addon-system-linux-x64',
])
/** Deliberate source payloads whose exact bytes are part of the package's audit surface. */
const publicationSourceAllowlist: Readonly<Record<string, readonly string[]>> = {
'@deepseek-ai/node-addon-system': ['src/main.c', 'src/flock.c'],
}
/** Public source home recorded in maintained package manifests. */
const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harness.git'
/** Packages that participate in the experimental policy. */
@@ -78,14 +75,15 @@ const standardReleaseMemberDirectory = new RegExp(
const desktopApplicationDirectory = 'apps/desktop'
const localArtifactDirs = new Set(['node_modules'])
const appPackageFiles: Readonly<Record<string, readonly string[]>> = {
'@deepseek-ai/dsh': ['lib/*.js', 'lib/types/*.d.ts'],
// Only `prepack` stages `docs`; every other reader of this directory sees
// whatever the checkout holds.
'@deepseek-ai/dsh': ['lib/*.js', 'lib/*.js.map', 'lib/types/*.d.ts', 'lib/types/*.d.ts.map', 'docs', 'src'],
'@deepseek-ai/dsh-desktop-host': [
'lib/index.js', 'lib/cli.js',
],
// Sourcemaps stay out by payload policy; the worker-preview surface
// (dist/preview.html and dist/preview/) backs opt-in experimental
// packages and is not published.
'@deepseek-ai/dsh-web-frontend': ['dist', '!dist/**/*.map', '!dist/preview.html', '!dist/preview'],
// The worker-preview surface (dist/preview.html and dist/preview/) backs
// opt-in experimental packages and is not published.
'@deepseek-ai/dsh-web-frontend': ['dist', '!dist/preview.html', '!dist/preview', 'src'],
}
/** The subset of package.json fields this constraint check cares about. */
@@ -363,6 +361,13 @@ export function expectedDshPackageFiles(manifest: PackageManifest, detailFiles:
// declarations.
...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
'lib/types/**/*.d.ts',
// A published declaration map plus `src` lets a consumer editor open the
// implementation behind an exported declaration, and lets a plugin author
// read it without a repository checkout.
'lib/types/**/*.d.ts.map',
// Every emitted map ships beside the JavaScript it describes, so a stack
// frame or a debugger session resolves into the published `src`.
'lib/**/*.js.map',
...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
? ['lib/typert.host.js', 'lib/typert.host.d.ts']
: [],
@@ -370,8 +375,11 @@ export function expectedDshPackageFiles(manifest: PackageManifest, detailFiles:
? ['lib/typert.client.js', 'lib/typert.client.d.ts']
: [],
...hasTypertRemoteNavigation(manifest)
? ['lib/typert.remote-client.js', 'lib/typert.remote-client.d.ts']
// The generated Remote declaration carries a `sourceMappingURL` its map
// resolves, and that map resolves the Host method through `src`.
? ['lib/typert.remote-client.js', 'lib/typert.remote-client.d.ts', 'lib/typert.remote-client.d.ts.map']
: [],
'src',
]
}
@@ -423,9 +431,14 @@ export function checkExperimentalManifest(
if (!experimentalPackageDirectory.test(dir)) return []
const label = manifest.name ?? dir
const errors: string[] = []
if (manifest.name === undefined || !manifest.name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX)
&& manifest.name !== EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS[dir]) {
errors.push(`${label}: experimental package name must start with ${JSON.stringify(EXPERIMENTAL_PACKAGE_NAME_PREFIX)} or match its declared directory exception`)
if (manifest.name === undefined) {
errors.push(`${label}: experimental package must declare a name`)
} else if (manifest.name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX)) {
if (!LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES.includes(dir)) {
errors.push(`${label}: new experimental packages must not use the ${JSON.stringify(EXPERIMENTAL_PACKAGE_NAME_PREFIX)} prefix; name it @deepseek-ai/dsh-<name> and declare it in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)`)
}
} else if (manifest.name !== EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS[dir]) {
errors.push(`${label}: experimental package name must be declared for this directory in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)`)
}
if (isPublicExperimentalPackageDirectory(dir, privateDirectories)) {
if (manifest.private === true) errors.push(`${label}: public experimental package must not set "private": true`)
@@ -440,7 +453,7 @@ export function checkExperimentalManifest(
}
/**
* Reject missing, renamed, moved, or duplicated retained-name exceptions.
* Reject missing, renamed, moved, or duplicated unprefixed-name declarations and stale legacy prefixed directories.
* @param manifests - every workspace manifest, with repository-relative directories.
* @returns Violations of the exact directory/name ownership declarations.
*/
@@ -449,7 +462,12 @@ export function checkExperimentalNameExceptions(manifests: readonly WorkspaceMan
for (const [dir, name] of Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS)) {
const owners = manifests.filter(entry => entry.manifest.name === name)
if (owners.length !== 1 || owners[0]?.dir !== dir) {
errors.push(`${dir}: retained experimental name ${name} must have exactly one workspace owner at this directory`)
errors.push(`${dir}: unprefixed experimental name ${name} must have exactly one workspace owner at this directory`)
}
}
for (const dir of LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES) {
if (!manifests.some(entry => entry.dir === dir && entry.manifest.name?.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX) === true)) {
errors.push(`${dir}: remove this directory from LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES; no package with the legacy prefix lives here`)
}
}
return errors
@@ -540,15 +558,6 @@ export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): st
return errors
}
if (manifest.name?.startsWith('@deepseek-ai/')) {
const allowedSources = publicationSourceAllowlist[manifest.name] ?? []
for (const file of manifest.files ?? []) {
if (isForbiddenPublicationFile(file) && !allowedSources.includes(file)) {
errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
}
}
}
if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && manifest.name?.startsWith('@deepseek-ai/')) {
const expectedFiles = appPackageFiles[manifest.name]
if (expectedFiles === undefined) {
+2
View File
@@ -106,6 +106,8 @@ export class RepositoryCleaner {
await this.addIfPresent(targets, join(this.root, '.dsh-build'), canonicalRoot)
await this.addIfPresent(targets, join(this.root, 'apps/desktop/.desktop-build'), canonicalRoot)
// The CLI package's documentation copy: `prepack` writes it, `postpack` removes it.
await this.addIfPresent(targets, join(this.root, 'apps/cli/docs'), canonicalRoot)
// These checks cover legacy root-level incremental state emitted by older configs.
await this.addIfPresent(targets, join(this.root, '.typecheck'), canonicalRoot)
+3 -2
View File
@@ -260,9 +260,10 @@ describe('client bundle package asset imports', () => {
})
const output = builds.flatMap(bundle => bundle.chunks).find(chunk => chunk.type === 'chunk' && chunk.fileName === 'client.js')
const code = output?.type === 'chunk' ? output.code : ''
expect(code).toContain(`require.asset(${JSON.stringify(WHALE_URL)})`)
// The minifier may print either string quote.
expect(code).toMatch(new RegExp(`require\\.asset\\(["\`]${WHALE_URL.replaceAll('.', '\\.')}["\`]\\)`))
expect(code).not.toContain('__dshPackageAsset_')
expect(code).toContain('"__dshPackageAsset("')
expect(code).toMatch(/["`]__dshPackageAsset\(["`]/)
} finally {
for (const bundle of builds) await bundle[Symbol.asyncDispose]()
}
+4 -3
View File
@@ -206,8 +206,9 @@ describe('client bundle dynamic imports', () => {
if (config === undefined) throw new Error('client config missing')
const output = await clientChunkOutput(root, config, 'client.js')
expect(output).toContain('require.async("./client.terminal.js")')
expect(output).not.toContain('Promise.resolve().then(() => require("./client.terminal.js"))')
// The compressor rewrites string literals, so the quotes are not part of the contract.
expect(output).toMatch(/require\.async\((["'`])\.\/client\.terminal\.js\1\)/)
expect(output).not.toMatch(/Promise\.resolve\(\)\.then\(\(\)\s*=>\s*require\((["'`])\.\/client\.terminal\.js\1\)\)/)
})
})
@@ -626,7 +627,7 @@ describe('client bundle debug artifacts', () => {
const resolved = new URL(workspaceSource, 'https://dsh.test/plugins/@deepseek-ai/dsh-client-connection/client.js.map')
expect(resolved.pathname).toBe('/packages/client/connection/src/rpc.ts')
const dependencySource = '../../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/index.js'
const dependencySource = '../../../../node_modules/.pnpm/zod@4.6.6/node_modules/zod/index.js'
expect(transform(dependencySource, sourceMapPath)).toBe(dependencySource)
})
})
+5
View File
@@ -48,6 +48,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' },
// Repository compiler scans measure scripts/ sources only. The epoch-header
// suite also calls the v3-to-v4 admission guard, covered by its package tests.
{ filter: 'scripts/persistence-schema.spec.ts', exclude: 'scripts/persistence-schema.spec.ts' },
{ filter: 'scripts/persistence-epoch-header.spec.ts', exclude: 'scripts/persistence-epoch-header.spec.ts' },
{ filter: 'scripts/gen-client-catalog.spec.ts', exclude: 'scripts/gen-client-catalog.spec.ts' },
// Built-artifact proof. Packer/runtime src is threshold-excluded, and the
// suite self-skips on unbuilt checkouts; the serial-windows complete
// reference still starts this uninstrumented gate after its build gate, so
+295
View File
@@ -0,0 +1,295 @@
/** Byte-level source reuse survives unrelated releases and invalidates changed build inputs. */
import { execFileSync, spawnSync } from 'node:child_process'
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { expect, it, onTestFinished } from 'vitest'
import { loadDesktopPackageEnvironment } from '../../apps/desktop/scripts/desktop-package-environment.mjs'
import { cuaHelperBuildKey, cuaHelperSourceDigest, cuaHelperSourceMatches, readCuaSigningSettings } from './build-inputs.ts'
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'cua-inputs-'))
onTestFinished(() => { rmSync(root, { recursive: true, force: true }) })
const git = (...args: string[]): void => { execFileSync('git', args, { cwd: root, stdio: 'pipe' }) }
const files = {
'package.json': JSON.stringify({ version: '1.0.0', packageManager: '[email protected]' }),
'pnpm-lock.yaml': 'lockfileVersion: 9.0\n',
'packages/experimental/cua-macos/native/Package.swift': '// swift package\n',
'packages/experimental/cua-macos/native/Sources/Main.swift': 'print("one")\n',
'packages/experimental/cua-macos/native/Info.plist': 'application identity',
'scripts/cua-helper/package.ts': 'build helper',
'apps/desktop/scripts/notarize-macos.mjs': 'notarize helper',
'.github/workflows/cua-helper-package.yml': 'build configuration',
'.github/workflows/release-publish.yml': 'publish configuration',
'packages/client/unrelated/src/index.ts': 'unrelated feature',
}
for (const [path, bytes] of Object.entries(files)) {
mkdirSync(dirname(join(root, path)), { recursive: true })
writeFileSync(join(root, path), bytes)
}
git('init', '--quiet')
git('add', '.')
return { root, git, source: join(root, 'packages/experimental/cua-macos/native/Sources/Main.swift') }
}
function copyHelperScripts(root: string): void {
for (const file of ['scripts/cua-helper/build-inputs.ts', 'scripts/cua-helper/select-artifact.ts',
'apps/desktop/scripts/desktop-file-settings.mjs', 'apps/desktop/scripts/desktop-release-environment.mjs', 'scripts/release/process.ts']) {
mkdirSync(dirname(join(root, file)), { recursive: true })
copyFileSync(resolve(file), join(root, file))
}
}
it('keeps identical source bytes across product versions and unrelated package edits', () => {
const f = fixture()
const before = cuaHelperSourceDigest(f.root)
writeFileSync(join(f.root, 'package.json'), JSON.stringify({ version: '2.0.0', packageManager: '[email protected]' }))
writeFileSync(join(f.root, 'packages/client/unrelated/src/index.ts'), 'another unrelated feature')
utimesSync(f.source, new Date('2001-01-01'), new Date('2001-01-01'))
expect(cuaHelperSourceDigest(f.root)).toBe(before)
writeFileSync(f.source, readFileSync(f.source).toString().replace('one', 'two'))
utimesSync(f.source, new Date('2001-01-01'), new Date('2001-01-01'))
expect(cuaHelperSourceDigest(f.root)).not.toBe(before)
})
it.each(['add', 'delete', 'rename', 'resource', 'dependency', 'script', 'workflow', 'package manager'])(
'invalidates %s changes', (change) => {
const f = fixture()
const before = cuaHelperSourceDigest(f.root)
if (change === 'add') writeFileSync(join(dirname(f.source), 'Added.swift'), 'new source')
if (change === 'delete') rmSync(f.source)
if (change === 'rename') renameSync(f.source, join(dirname(f.source), 'Renamed.swift'))
if (change === 'resource') writeFileSync(join(f.root, 'packages/experimental/cua-macos/native/Info.plist'), 'changed identity')
if (change === 'dependency') writeFileSync(join(f.root, 'pnpm-lock.yaml'), 'changed dependency')
if (change === 'script') writeFileSync(join(f.root, 'apps/desktop/scripts/notarize-macos.mjs'), 'changed notarization')
if (change === 'workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package.yml'), 'changed build configuration')
if (change === 'package manager') writeFileSync(join(f.root, 'package.json'), JSON.stringify({ packageManager: '[email protected]' }))
f.git('add', '-A')
expect(cuaHelperSourceDigest(f.root)).not.toBe(before)
},
)
it.skipIf(process.platform === 'win32')('includes executable mode and rejects source links', () => {
const f = fixture()
const before = cuaHelperSourceDigest(f.root)
chmodSync(f.source, 0o755)
expect(cuaHelperSourceDigest(f.root)).not.toBe(before)
rmSync(f.source)
symlinkSync(join(f.root, 'pnpm-lock.yaml'), f.source)
expect(() => cuaHelperSourceDigest(f.root)).toThrow('regular file')
})
it('fails on missing required tracked build inputs', () => {
const f = fixture()
f.git('rm', '--cached', 'scripts/cua-helper/package.ts')
expect(() => cuaHelperSourceDigest(f.root)).toThrow('missing tracked build input')
})
it.each(['preset', 'identity', 'team', 'certificate', 'toolchain', 'source'])(
'invalidates changed %s while credentials stay outside the build key', (change) => {
const f = fixture()
const certificate = join(f.root, 'signing.p12')
writeFileSync(certificate, 'fixture encrypted certificate')
const environment = { CSC_LINK: certificate, DSH_PACKAGING_PRESET: 'production',
DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Fixture (ABCDEFGHIJ)', DSH_DESKTOP_MACOS_TEAM_ID: 'ABCDEFGHIJ',
APPLE_APP_SPECIFIC_PASSWORD: 'private-password' }
const source = cuaHelperSourceDigest(f.root)
const run = (_command: string, args: string[]): string => args.join(' ')
const before = cuaHelperBuildKey(source, environment, run)
environment.APPLE_APP_SPECIFIC_PASSWORD = 'new-private-password'
expect(cuaHelperBuildKey(source, environment, run)).toBe(before)
if (change === 'preset') environment.DSH_PACKAGING_PRESET = 'test'
if (change === 'identity') environment.DSH_DESKTOP_MACOS_SIGNING_IDENTITY = 'Other (ABCDEFGHIJ)'
if (change === 'team') environment.DSH_DESKTOP_MACOS_TEAM_ID = '1234567890'
if (change === 'certificate') writeFileSync(certificate, 'another certificate')
const after = cuaHelperBuildKey(change === 'source' ? 'b'.repeat(64) : source, environment,
change === 'toolchain' ? () => 'another toolchain' : run)
expect(after).not.toBe(before)
},
)
it('resolves the configured signing file without installing desktop dependencies or exposing parser errors', () => {
const f = fixture()
const config = join(f.root, 'config')
mkdirSync(join(config, 'secrets'), { recursive: true })
writeFileSync(join(config, 'secrets/macos-signing.env'), 'CSC_LINK=./signing.p12\nDSH_DESKTOP_MACOS_TEAM_ID=ABCDEFGHIJ\n')
const environment = { DSH_PACKAGING_CONFIG_DIR: config, DSH_PACKAGING_PRESET: 'production' }
expect(readCuaSigningSettings(environment)).toMatchObject({ CSC_LINK: join(config, 'secrets/signing.p12'), DSH_PACKAGING_PRESET: 'production' })
expect(() => readCuaSigningSettings({ ...environment, DSH_PACKAGING_PRESET: 'invalid' })).toThrow('preset')
expect(() => readCuaSigningSettings({ ...environment, DSH_PACKAGING_CONFIG_DIR: 'relative' })).toThrow('CONFIG_DIR')
})
it('loads fingerprinting and selection under plain Node with no node_modules directory', () => {
const f = fixture()
copyHelperScripts(f.root)
const output = execFileSync(process.execPath, ['--input-type=module', '-e',
"const a = await import('./scripts/cua-helper/select-artifact.ts'); const b = await import('./scripts/cua-helper/build-inputs.ts'); console.log(typeof a.selectCuaHelperArtifact, typeof b.cuaHelperSourceDigest)"],
{ cwd: f.root, encoding: 'utf8', timeout: 30_000, stdio: 'pipe' })
expect(output.trim()).toBe('function function')
})
const repository = 'deepseek-harness/deepseek-harness'
function producerSnapshot(root: string) {
const git = (...args: string[]): string => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: 'pipe' })
git('add', '-A')
git('-c', `core.hooksPath=${join(root, 'no-hooks')}`, '-c', 'commit.gpgsign=false', '-c', 'user.name=Fixture',
'-c', '[email protected]', 'commit', '--quiet', '-m', 'fixture')
const commit = git('rev-parse', 'HEAD').trim()
const tree = git('ls-tree', '-r', '-z', 'HEAD').split('\0').filter(Boolean).map((entry) => {
const [metadata, path] = entry.split('\t')
const [mode, type, sha] = (metadata ?? '').split(' ')
if (!path || !mode || !type || !sha) throw new Error('Invalid Git fixture tree entry')
return { path, mode, type, sha }
})
const response = { truncated: false, tree }
const responses: Record<string, unknown> = { [`repos/${repository}/git/trees/${commit}?recursive=1`]: response }
for (const entry of tree.filter(entry => entry.path === 'package.json')) {
const bytes = execFileSync('git', ['cat-file', 'blob', entry.sha], { cwd: root, stdio: 'pipe' })
responses[`repos/${repository}/git/blobs/${entry.sha}`] = { sha: entry.sha, encoding: 'base64', content: bytes.toString('base64') }
}
return { commit, response, responses, api: async (path: string): Promise<unknown> => {
if (!(path in responses)) throw new Error(`Unexpected GitHub fixture request ${path}`)
return responses[path]
} }
}
it('compares GitHub commit objects independently of artifact claims while allowing a root version bump', async () => {
const f = fixture()
const previous = producerSnapshot(f.root)
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(true)
writeFileSync(join(f.root, 'package.json'), JSON.stringify({ version: '2.0.0', packageManager: '[email protected]' }))
writeFileSync(join(f.root, 'packages/client/unrelated/src/index.ts'), 'another unrelated feature')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(true)
writeFileSync(f.source, 'changed native code')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(false)
})
it.each(['helper workflow', 'publish workflow', 'packaging script', 'manifest lifecycle', 'npm config', 'patch', 'tracked dependency', 'deleted file'])(
'rejects independent producer source proof after a changed %s', async (change) => {
const f = fixture()
const previous = producerSnapshot(f.root)
const digest = cuaHelperSourceDigest(f.root)
if (change === 'helper workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package.yml'), 'forged uploader')
if (change === 'publish workflow') writeFileSync(join(f.root, '.github/workflows/release-publish.yml'), 'forged caller')
if (change === 'packaging script') writeFileSync(join(f.root, 'scripts/cua-helper/package.ts'), 'forged metadata')
if (change === 'manifest lifecycle') writeFileSync(join(f.root, 'package.json'), JSON.stringify({
version: '1.0.0', packageManager: '[email protected]', scripts: { postinstall: 'unexpected code' },
}))
if (change === 'npm config') writeFileSync(join(f.root, '.npmrc'), 'node-options=--require=./unexpected.cjs')
if (change === 'patch') {
mkdirSync(join(f.root, 'patches'))
writeFileSync(join(f.root, 'patches/dependency.patch'), 'changed package code')
}
if (change === 'tracked dependency') {
mkdirSync(join(f.root, 'apps/desktop/node_modules/unexpected'), { recursive: true })
writeFileSync(join(f.root, 'apps/desktop/node_modules/unexpected/index.js'), 'unexpected dependency code')
f.git('add', '--force', 'apps/desktop/node_modules')
}
if (change === 'deleted file') rmSync(f.source)
f.git('add', '-A')
expect(cuaHelperSourceDigest(f.root)).not.toBe(digest)
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(false)
},
)
it('stops source comparison when GitHub returns an incomplete tree', async () => {
const f = fixture()
const previous = producerSnapshot(f.root)
previous.response.truncated = true
await expect(cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).rejects.toThrow('incomplete commit tree')
})
it.each(['test', 'production'])('computes the same %s build key through selection and packaging configuration readers', (preset) => {
const f = fixture()
const config = join(f.root, 'config')
mkdirSync(join(config, 'presets'), { recursive: true })
mkdirSync(join(config, 'secrets'))
writeFileSync(join(config, 'presets', `${preset}.env`), `DSH_DESKTOP_AUTO_UPDATE_ENV=${preset}\n`)
writeFileSync(join(config, 'secrets/signing.p12'), 'fixture certificate')
writeFileSync(join(config, 'secrets/macos-signing.env'), [
'CSC_LINK=./signing.p12', 'CSC_KEY_PASSWORD=fixture-password', 'DSH_DESKTOP_MACOS_TEAM_ID=ABCDEFGHIJ',
'DSH_DESKTOP_MACOS_SIGNING_IDENTITY=Fixture (ABCDEFGHIJ)',
].join('\n'))
const environment = { DSH_PACKAGING_CONFIG_DIR: config, DSH_PACKAGING_PRESET: preset }
const source = cuaHelperSourceDigest(f.root)
const run = (_command: string, args: string[]): string => args.join(' ')
expect(cuaHelperBuildKey(source, readCuaSigningSettings(environment), run))
.toBe(cuaHelperBuildKey(source, loadDesktopPackageEnvironment('darwin', environment), run))
})
// A private POSIX PATH exposes only Git, so successful CLI execution cannot depend on gh.
it.skipIf(process.platform === 'win32').each(['match', 'miss', 'api failure', 'missing token'])(
'runs the plain-Node selector entry with %s and without gh or node_modules', (scenario) => {
const f = fixture()
copyHelperScripts(f.root)
const snapshot = producerSnapshot(f.root)
const key = 'a'.repeat(64)
const base = `repos/${repository}/actions/runs/123`
Object.assign(snapshot.responses, {
[base]: { run_attempt: 2 },
[`${base}/attempts/2`]: { id: 123, run_attempt: 2, status: 'completed', conclusion: 'success',
event: 'workflow_dispatch', path: '.github/workflows/cua-helper-package.yml', head_sha: snapshot.commit,
repository: { full_name: repository }, head_repository: { full_name: repository } },
[`${base}/jobs?filter=all&per_page=100`]: { jobs: [{ name: 'package', conclusion: 'success', run_attempt: 2 }] },
[`${base}/artifacts?per_page=100`]: { artifacts: scenario === 'match'
? [{ id: 456, name: `cua-helper-123-2-${key}`, expired: false, size_in_bytes: 4096 }] : [] },
})
const data = join(f.root, 'responses.json')
writeFileSync(data, JSON.stringify(snapshot.responses))
const bin = join(f.root, 'git-only-bin')
mkdirSync(bin)
const git = execFileSync('/usr/bin/which', ['git'], { encoding: 'utf8' }).trim()
symlinkSync(git, join(bin, 'git'))
const preload = join(f.root, 'mock-github.mjs')
writeFileSync(preload, `import { readFileSync } from 'node:fs';
const data = JSON.parse(readFileSync(process.env.FIXTURE_API_DATA, 'utf8'));
globalThis.fetch = async (input, options) => {
const url = new URL(input);
if (url.origin !== 'https://api.github.com' || new Headers(options.headers).get('authorization') !== 'Bearer fixture-token') {
throw new Error('unexpected GitHub request');
}
if (process.env.FIXTURE_API_FAILURE === '1') return new Response('fixture API failure', { status: 503 });
const path = url.pathname.slice(1) + url.search;
if (path.includes('/workflows/')) return Response.json({ workflow_runs: path.includes('cua-helper-package.yml') ? [{ id: 123 }] : [] });
if (!(path in data)) throw new Error('unexpected GitHub path');
return Response.json(data[path]);
};
`)
const output = join(f.root, 'outputs')
const summary = join(f.root, 'summary')
const result = spawnSync(process.execPath, ['--import', preload, join(f.root, 'scripts/cua-helper/select-artifact.ts')], {
cwd: f.root, encoding: 'utf8', timeout: 60_000,
env: { ...process.env, NODE_OPTIONS: '', PATH: bin, GH_TOKEN: scenario === 'missing token' ? '' : 'fixture-token',
GITHUB_API_URL: 'https://api.github.com', GITHUB_REPOSITORY: repository, GITHUB_OUTPUT: output,
GITHUB_STEP_SUMMARY: summary, CUA_RUN_ID: '', CUA_BUILD_KEY: key,
FIXTURE_API_DATA: data, FIXTURE_API_FAILURE: scenario === 'api failure' ? '1' : '0' },
})
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(existsSync(join(bin, 'gh'))).toBe(false)
expect(existsSync(join(f.root, 'node_modules'))).toBe(false)
if (scenario === 'api failure' || scenario === 'missing token') {
expect(result.status).toBe(1)
expect(result.stderr).toContain(scenario === 'missing token' ? 'GH_TOKEN is required' : 'HTTP 503')
expect(existsSync(output)).toBe(false)
expect(existsSync(summary)).toBe(false)
} else {
expect(result.status, result.stderr).toBe(0)
expect(readFileSync(output, 'utf8')).toBe(scenario === 'match' ? 'artifact-id=456\nrun-id=123\n' : 'artifact-id=\nrun-id=\n')
expect(readFileSync(summary, 'utf8')).toContain(scenario === 'match' ? '跳过依赖安装' : '未找到')
}
},
)
it('matches Git blobs when tracked attributes require CRLF checkout bytes', async () => {
const f = fixture()
const path = join(f.root, 'apps/desktop/scripts/fixture.cmd')
writeFileSync(join(f.root, '.gitattributes'), '*.cmd text eol=crlf\n')
writeFileSync(path, '@echo off\necho fixture\n')
const previous = producerSnapshot(f.root)
writeFileSync(path, '@echo off\r\necho fixture\r\n')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(true)
writeFileSync(join(f.root, '.gitattributes'), '*.cmd text eol=lf\n')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(false)
})
+169
View File
@@ -0,0 +1,169 @@
/** Content and machine identity for reusing a signed helper before installing dependencies. */
import assert from 'node:assert/strict'
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { appendFileSync, lstatSync, readFileSync } from 'node:fs'
import { isAbsolute, join, resolve } from 'node:path'
import { isEntry } from '../release/process.ts'
import { readDesktopPackageSettings } from '../../apps/desktop/scripts/desktop-file-settings.mjs'
import { resolveMacOSSigningEnvironment } from '../../apps/desktop/scripts/desktop-release-environment.mjs'
const sourceDirectories = [
'packages/experimental/cua-macos/native', 'scripts/cua-helper', 'apps/desktop/scripts', 'patches',
]
const sourceFiles = new Set([
'.github/workflows/cua-helper-package.yml', '.github/workflows/release-publish.yml',
'package.json', 'scripts/package.json', 'apps/package.json', 'apps/desktop/package.json', 'scripts/release/process.ts',
'pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc', '.pnpmfile.cjs', '.pnpmfile.mjs',
])
function isSourceFile(path: string): boolean {
return sourceFiles.has(path) || path === '.gitattributes' || path.endsWith('/.gitattributes') || /^(?:(?:apps|apps\/desktop|scripts)\/)?tsconfig[^/]*\.json$/u.test(path)
|| path.split('/').includes('node_modules')
|| sourceDirectories.some(directory => path.startsWith(`${directory}/`))
}
function trackedSources(root: string): string[] {
const files = execFileSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })
.split('\0').filter(isSourceFile).sort()
for (const required of ['packages/experimental/cua-macos/native/Package.swift', 'scripts/cua-helper/package.ts',
'package.json', 'pnpm-lock.yaml']) {
if (!files.includes(required)) throw new Error(`CUA source: missing tracked build input ${required}`)
}
return files
}
function manifestConfiguration(bytes: Buffer, root: boolean): Buffer {
const manifest: unknown = JSON.parse(bytes.toString('utf8'))
assert(manifest && typeof manifest === 'object' && !Array.isArray(manifest), 'CUA source: invalid package manifest')
assert(!root || ('packageManager' in manifest && typeof manifest.packageManager === 'string'),
'CUA source: package.json must declare packageManager')
return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(manifest).filter(([name]) => name !== 'version'))))
}
function sourceFile(root: string, file: string): { bytes: Buffer; executable: boolean } {
const path = join(root, file)
const stat = lstatSync(path)
if (!stat.isFile()) throw new Error(`CUA source: build input must be a regular file: ${file}`)
return { bytes: readFileSync(path), executable: (stat.mode & 0o111) !== 0 }
}
function gitBlobHash(bytes: Buffer): string {
return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex')
}
/**
* Hash tracked build inputs by path, bytes and executable mode; only package manifest version fields is excluded.
* Missing tracked files and links fail; build outputs and untracked files never enter the digest.
* @param root - Clean repository root containing all helper build inputs.
* @returns SHA-256 of sources, resources, workflows, package configuration, patches and locked dependencies.
*/
export function cuaHelperSourceDigest(root: string): string {
const hash = createHash('sha256')
for (const file of trackedSources(root)) {
const { bytes, executable } = sourceFile(root, file)
const input = file === 'package.json' || file.endsWith('/package.json') ? manifestConfiguration(bytes, file === 'package.json') : bytes
hash.update(`${file}\0`).update(createHash('sha256').update(input).digest()).update(Buffer.from([Number(executable)]))
}
return hash.digest('hex')
}
/**
* Compare a producer's immutable GitHub commit tree with local build inputs independently of artifact metadata.
* Incomplete trees, unreadable blobs and API failures stop selection; content differences return false.
* @param root - Consumer repository root, before dependency installation.
* @param repository - GitHub repository containing the authenticated producer run.
* @param commit - Producer head SHA returned by GitHub, never an artifact-supplied revision.
* @param api - Read-only GitHub JSON reader.
* @returns Resolves to whether selected paths, bytes and executable modes match, excluding package manifest version fields.
*/
export async function cuaHelperSourceMatches(root: string, repository: string, commit: string,
api: (path: string) => Promise<unknown>): Promise<boolean> {
assert(/^[a-f0-9]{40}$/u.test(commit), 'CUA source: invalid producer commit')
const response = await api(`repos/${repository}/git/trees/${commit}?recursive=1`)
assert(response && typeof response === 'object' && 'truncated' in response && response.truncated === false
&& 'tree' in response && Array.isArray(response.tree), 'CUA source: GitHub returned an incomplete commit tree')
const tree = new Map<string, { sha: string; mode: string }>()
const entries: unknown[] = response.tree
for (const value of entries) {
assert(value && typeof value === 'object' && 'path' in value && typeof value.path === 'string', 'CUA source: invalid tree entry')
if (!isSourceFile(value.path) || ('type' in value && value.type === 'tree')) continue
assert('sha' in value && typeof value.sha === 'string' && /^[a-f0-9]{40}$/u.test(value.sha)
&& 'mode' in value && typeof value.mode === 'string' && 'type' in value, 'CUA source: invalid source entry')
if (value.type !== 'blob' || !['100644', '100755'].includes(value.mode)) return false
assert(!tree.has(value.path), 'CUA source: duplicate source entry')
tree.set(value.path, { sha: value.sha, mode: value.mode })
}
const files = trackedSources(root)
if (tree.size !== files.length) return false
for (const file of files) {
const remote = tree.get(file)
if (!remote) return false
const local = sourceFile(root, file)
if (remote.mode !== (local.executable ? '100755' : '100644')) return false
if (gitBlobHash(local.bytes) === remote.sha) continue
const canonical = execFileSync('git', ['hash-object', `--path=${file}`, '--stdin'],
{ cwd: root, input: local.bytes, encoding: 'utf8' }).trim()
if (canonical === remote.sha) continue
if (file !== 'package.json' && !file.endsWith('/package.json')) return false
const blob = await api(`repos/${repository}/git/blobs/${remote.sha}`)
assert(blob && typeof blob === 'object' && 'sha' in blob && blob.sha === remote.sha
&& 'encoding' in blob && blob.encoding === 'base64' && 'content' in blob && typeof blob.content === 'string',
'CUA source: invalid package manifest blob')
const bytes = Buffer.from(blob.content, 'base64')
assert(gitBlobHash(bytes) === remote.sha, 'CUA source: package manifest blob digest mismatch')
if (!manifestConfiguration(local.bytes, file === 'package.json').equals(manifestConfiguration(bytes, file === 'package.json'))) return false
}
return true
}
/**
* Read the signing preset's public identity and certificate location without installing desktop dependencies.
* @param environment - Actions environment with the machine configuration directory and selected preset.
* @returns File-owned signing settings and the selected preset; no values are logged.
*/
export function readCuaSigningSettings(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const root = environment.DSH_PACKAGING_CONFIG_DIR
const preset = environment.DSH_PACKAGING_PRESET
if (!root || !isAbsolute(root) || !['test', 'production'].includes(preset ?? '')) {
throw new Error('CUA reuse: DSH_PACKAGING_CONFIG_DIR and a test or production preset are required')
}
const settings = readDesktopPackageSettings(join(root, 'secrets/macos-signing.env'), () => true)
return { ...settings, DSH_PACKAGING_PRESET: preset }
}
/**
* Bind source bytes to the active toolchain, preset and signing certificate container.
* @param source - Current source digest.
* @param environment - File-owned signing settings including CSC_LINK and the selected preset.
* @param run - Synchronous query returning the active compiler, SDK and Python version strings.
* @returns SHA-256 build key; credential values and certificate bytes are not recorded.
*/
export function cuaHelperBuildKey(source: string, environment: NodeJS.ProcessEnv,
run: (command: string, args: string[]) => string = (command, args) =>
execFileSync(command, args, { encoding: 'utf8', timeout: 60_000, stdio: 'pipe' }).trim()): string {
const signing = resolveMacOSSigningEnvironment(environment)
const certificate = environment.CSC_LINK
if (!certificate || !isAbsolute(certificate)) throw new Error('CUA reuse: CSC_LINK must identify the signing certificate file')
const configuration = {
source, preset: environment.DSH_PACKAGING_PRESET ?? 'local', ...signing,
certificate: createHash('sha256').update(readFileSync(certificate)).digest('hex'),
node: process.version,
swift: run('/usr/bin/xcrun', ['swift', '--version']),
clang: run('/usr/bin/xcrun', ['clang', '--version']),
sdk: run('/usr/bin/xcrun', ['--sdk', 'macosx', '--show-sdk-build-version']),
python: run('/usr/bin/xcrun', ['python3', '--version']),
}
return createHash('sha256').update(JSON.stringify(configuration)).digest('hex')
}
if (isEntry(import.meta.url)) {
const env = process.env
if (!env.GITHUB_OUTPUT || !env.GITHUB_STEP_SUMMARY) throw new Error('CUA build inputs: Actions context required')
const root = resolve(import.meta.dirname, '../..')
const sourceDigest = cuaHelperSourceDigest(root)
const buildKey = cuaHelperBuildKey(sourceDigest, readCuaSigningSettings(env))
appendFileSync(env.GITHUB_OUTPUT, `build-key=${buildKey}\n`)
appendFileSync(env.GITHUB_STEP_SUMMARY, `CUA helper 源码摘要:\`${sourceDigest}\`。\n\n`)
console.log(`CUA helper source digest: ${sourceDigest}`)
}
+1
View File
@@ -48,6 +48,7 @@ vi.mock('tar', () => ({
create: async ({ file }: { file: string }) => writeFile(file, 'fixture archive'),
extract: async () => {},
}))
vi.mock('./build-inputs.ts', () => ({ cuaHelperSourceDigest: () => 'a'.repeat(64), cuaHelperBuildKey: () => 'b'.repeat(64) }))
vi.mock('./payload.ts', async importOriginal => ({
...await importOriginal<typeof import('./payload.ts')>(),
readCuaApplication: (directory: string) => ({ application: join(directory, 'fixture/DSH Computer Use.app') }),
+11 -4
View File
@@ -3,6 +3,7 @@ import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join, resolve } from 'node:path'
import { isEntry } from '../release/process.ts'
import { parseArgs } from 'node:util'
import { execa } from 'execa'
import { create, extract } from 'tar'
@@ -15,6 +16,7 @@ import { notarizeMacOS } from '../../apps/desktop/scripts/notarize-macos.mjs'
import { createPackagingRun } from '../../apps/desktop/scripts/packaging-run.mjs'
import { packagingErrorDetails, packagingStep } from '../../apps/desktop/scripts/packaging-step.mjs'
import { verifyMacOSRuntimeCode } from '../../apps/desktop/scripts/verify-macos-signature.mjs'
import { cuaHelperBuildKey, cuaHelperSourceDigest } from './build-inputs.ts'
import { CUA_APPLICATION, CUA_ARCHITECTURES, CUA_MANIFEST, readCuaApplication, sealCuaApplication, verifyCuaHelperPayload, type CuaHelperManifest } from './payload.ts'
async function main(): Promise<void> {
@@ -23,6 +25,11 @@ async function main(): Promise<void> {
const root = resolve(import.meta.dirname, '../..')
const output = resolve(values.out)
const environment = loadDesktopPackageEnvironment('darwin')
const sourceDigest = cuaHelperSourceDigest(root)
const buildKey = cuaHelperBuildKey(sourceDigest, environment)
if (process.env.CUA_EXPECTED_BUILD_KEY !== undefined && process.env.CUA_EXPECTED_BUILD_KEY !== buildKey) {
throw new Error('CUA build inputs changed after artifact selection; restart the helper workflow')
}
const signing = resolveMacOSSigningEnvironment(environment)
const notary = resolveMacOSNotarizationEnvironment(environment)
const settings = resolveMacOSPackageSettings(environment)
@@ -68,15 +75,15 @@ async function main(): Promise<void> {
applications.push({ architecture, bundle: sealCuaApplication(directory, application) })
}
})
const manifest: CuaHelperManifest = { schemaVersion: 1, version, commit, teamId: signing.teamId, applications }
const manifest: CuaHelperManifest = { schemaVersion: 2, sourceDigest, buildKey, version, commit, teamId: signing.teamId, applications }
writeFileSync(join(payload, CUA_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`)
verifyCuaHelperPayload(payload, { version, commit })
verifyCuaHelperPayload(payload, { sourceDigest, buildKey })
const archive = join(output, 'cua-helper.tgz')
await create({ cwd: payload, file: archive, gzip: true, portable: true }, [CUA_MANIFEST, 'native'])
const extracted = join(scratch, 'extracted')
mkdirSync(extracted)
await extract({ cwd: extracted, file: archive, strict: true })
verifyCuaHelperPayload(extracted, { version, commit })
verifyCuaHelperPayload(extracted, { sourceDigest, buildKey })
for (const { architecture, bundle } of applications) {
const application = join(extracted, 'native/bin', `darwin-${architecture}`, bundle, CUA_APPLICATION)
await verify(application, architecture)
@@ -98,4 +105,4 @@ async function main(): Promise<void> {
journal.finish(true)
}
await main()
if (isEntry(import.meta.url)) await main()
+16 -6
View File
@@ -10,7 +10,7 @@ import { expect, it, onTestFinished } from 'vitest'
import { CUA_APPLICATION, CUA_ARCHITECTURES, CUA_MANIFEST, cuaApplicationDigest, readCuaApplication, sealCuaApplication, stageCuaHelperPayload, verifyCuaHelperPayload } from './payload.ts'
import { verifyCuaHelperTarball } from './verify-tarball.ts'
const identity = { version: '1.0.0', commit: 'a'.repeat(40) }
const identity = { sourceDigest: 'a'.repeat(64), buildKey: 'b'.repeat(64) }
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'cua-payload-test-'))
onTestFinished(() => { rmSync(root, { recursive: true, force: true }) })
@@ -28,7 +28,7 @@ function fixture() {
chmodSync(join(application, 'Contents/MacOS/dsh-cua-native'), 0o755)
return { architecture, bundle: sealCuaApplication(directory, application) }
})
const manifest = { schemaVersion: 1, ...identity, teamId: 'ABCDEFGHIJ', applications }
const manifest = { schemaVersion: 2, ...identity, version: '1.0.0', commit: 'a'.repeat(40), teamId: 'ABCDEFGHIJ', applications }
writeFileSync(join(payload, CUA_MANIFEST), JSON.stringify(manifest))
return { root, payload, manifest, directory: join(payload, 'native/bin/darwin-arm64') }
}
@@ -72,7 +72,7 @@ it.skipIf(process.platform === 'win32')('keeps npm tarball bytes when reusing a
mkdirSync(output)
stageCuaHelperPayload(f.payload, packageRoot, identity)
writeFileSync(join(packageRoot, 'package.json'), JSON.stringify({
name: '@deepseek-ai/dsh-experimental-cua-macos', version: identity.version, type: 'module',
name: '@deepseek-ai/dsh-experimental-cua-macos', version: f.manifest.version, type: 'module',
files: ['lib/index.js', 'native/bin', CUA_MANIFEST],
}))
writeFileSync(join(packageRoot, 'lib/index.js'), 'export const provider = "fixture";\n')
@@ -103,11 +103,11 @@ it.skipIf(process.platform === 'win32')('keeps npm tarball bytes when reusing a
expect(rebuilt.equals(first)).toBe(false)
})
it.skipIf(process.platform === 'win32').each(['version', 'commit', 'architecture', 'missing', 'extra', 'permissions', 'symlink'] as const)('rejects %s damage before staging', (damage) => {
it.skipIf(process.platform === 'win32').each(['source', 'configuration', 'architecture', 'missing', 'extra', 'permissions', 'symlink'] as const)('rejects %s damage before staging', (damage) => {
const f = fixture()
const before = readCuaApplication(f.directory)
if (damage === 'version') f.manifest.version = '2.0.0'
if (damage === 'commit') f.manifest.commit = 'b'.repeat(40)
if (damage === 'source') f.manifest.sourceDigest = 'c'.repeat(64)
if (damage === 'configuration') f.manifest.buildKey = 'd'.repeat(64)
if (damage === 'architecture') f.manifest.applications[1] = f.manifest.applications[0]!
if (damage === 'missing') rmSync(join(before.application, 'Contents/Info.plist'))
if (damage === 'extra') cpSync(before.application, join(f.directory, 'old-generation', CUA_APPLICATION), { recursive: true })
@@ -128,3 +128,13 @@ it('keeps company signing outside pull-request release rehearsals', () => {
expect(release).toContain('scripts/cua-helper/stage.ts')
expect(readFileSync(resolve('.github/workflows/release.yml'), 'utf8')).not.toContain('cua-helper-package.yml')
})
it.skipIf(process.platform === 'win32')('retains the original build commit and version when consuming identical helper sources', () => {
const f = fixture()
f.manifest.version = '0.9.0'
f.manifest.commit = 'c'.repeat(40)
writeFileSync(join(f.payload, CUA_MANIFEST), JSON.stringify(f.manifest))
const consumer = join(f.root, 'consumer')
stageCuaHelperPayload(f.payload, consumer, identity)
expect(JSON.parse(readFileSync(join(consumer, CUA_MANIFEST), 'utf8'))).toEqual(f.manifest)
})
+7 -5
View File
@@ -12,7 +12,8 @@ export const CUA_APPLICATION = 'DSH Computer Use.app'
export const CUA_MANIFEST = 'cua-helper.json'
const Digest = z.string().regex(/^[a-f0-9]{64}$/u)
const Manifest = z.object({
schemaVersion: z.literal(1), version: z.string().min(1), commit: z.string().regex(/^[a-f0-9]{40}$/u),
schemaVersion: z.literal(2), sourceDigest: Digest, buildKey: Digest,
version: z.string().min(1), commit: z.string().regex(/^[a-f0-9]{40}$/u),
teamId: z.string().regex(/^[A-Z0-9]{10}$/u),
applications: z.array(z.object({ architecture: z.enum(CUA_ARCHITECTURES), bundle: Digest }).strict()).length(2),
}).strict()
@@ -90,12 +91,13 @@ export function sealCuaApplication(directory: string, application: string): stri
/**
* Verify the producer record and every final application before copying or packing.
* @param root - Extracted helper artifact containing native/bin and cua-helper.json.
* @param expected - Source commit and product version of the consuming checkout.
* @param expected - Source digest and, on the Mac-to-pack transfer, the selected build key.
* @returns Validated producer metadata.
*/
export function verifyCuaHelperPayload(root: string, expected: { version: string; commit: string }): CuaHelperManifest {
export function verifyCuaHelperPayload(root: string, expected: { sourceDigest: string; buildKey?: string }): CuaHelperManifest {
const manifest = Manifest.parse(JSON.parse(readFileSync(join(root, CUA_MANIFEST), 'utf8')))
if (manifest.version !== expected.version || manifest.commit !== expected.commit) throw new Error('CUA artifact does not match the release source and version')
if (manifest.sourceDigest !== expected.sourceDigest) throw new Error('CUA artifact does not match the current helper source bytes')
if (expected.buildKey !== undefined && manifest.buildKey !== expected.buildKey) throw new Error('CUA artifact does not match the selected build configuration')
if (new Set(manifest.applications.map(entry => entry.architecture)).size !== 2) throw new Error('CUA artifact must contain arm64 and x64')
const bin = join(root, 'native/bin')
if (readdirSync(bin).sort().join(',') !== 'darwin-arm64,darwin-x64') throw new Error('CUA artifact has unexpected architecture directories')
@@ -112,7 +114,7 @@ export function verifyCuaHelperPayload(root: string, expected: { version: string
* @param packageRoot - Provider package to receive native/bin.
* @param expected - Source identity required by the release.
*/
export function stageCuaHelperPayload(root: string, packageRoot: string, expected: { version: string; commit: string }): void {
export function stageCuaHelperPayload(root: string, packageRoot: string, expected: { sourceDigest: string; buildKey?: string }): void {
verifyCuaHelperPayload(root, expected)
const destination = join(packageRoot, 'native/bin')
if (existsSync(destination)) throw new Error('CUA staging requires an empty native/bin; use a clean release checkout')
+248 -52
View File
@@ -1,94 +1,290 @@
/** Retained CUA selection stays within one producer, attempt and immutable artifact. */
import { expect, it, vi } from 'vitest'
import { selectCuaHelperArtifact } from './select-artifact.ts'
/** Discovery and explicit selection require matching inputs and successful producer evidence. */
import { expect, it, onTestFinished, vi } from 'vitest'
import { createGitHubJsonReader, selectCuaHelperArtifact } from './select-artifact.ts'
const repository = 'deepseek-harness/deepseek-harness'
const base = `repos/${repository}/actions/runs/123`
const key = 'a'.repeat(64)
function fixture() {
const run = { id: 123, run_attempt: 2, status: 'completed', conclusion: 'success', event: 'workflow_dispatch',
path: '.github/workflows/cua-helper-package.yml', repository: { full_name: repository } }
const jobs = [{ jobs: [{ name: 'package', conclusion: 'success' }] }]
const artifact = { id: 456, name: 'cua-helper-123-2', expired: false, size_in_bytes: 4096 }
const artifacts = [{ artifacts: [{ ...artifact, id: 455, name: 'cua-helper-123-1' }] }, { artifacts: [artifact] }]
const api = vi.fn((path: string, paginate?: boolean) => {
path: '.github/workflows/cua-helper-package.yml', head_sha: 'c'.repeat(40), repository: { full_name: repository }, head_repository: { full_name: repository } }
const jobs = [{ jobs: [{ name: 'package', conclusion: 'success', run_attempt: 2 }] }]
const matchesSource = vi.fn(async (_commit: string) => true)
const artifact = { id: 456, name: `cua-helper-123-2-${key}`, expired: false, size_in_bytes: 4096 }
const artifacts = [{ artifacts: [{ ...artifact, id: 455, name: `cua-helper-123-1-${key}` }] }, { artifacts: [artifact] }]
const api = vi.fn(async (path: string, paginate?: boolean) => {
if (path === base) { expect(paginate).toBeUndefined(); return { run_attempt: 2 } }
if (path === `${base}/attempts/2`) { expect(paginate).toBeUndefined(); return run }
expect(paginate).toBe(true)
if (path === `${base}/attempts/2/jobs?per_page=100`) return jobs
if (path.includes('/workflows/cua-helper-package.yml/runs?')) return [{ workflow_runs: [{ id: 123 }] }]
if (path.includes('/workflows/release-publish.yml/runs?')) return [{ workflow_runs: [] }]
if (path === `${base}/jobs?filter=all&per_page=100`) return jobs
if (path === `${base}/artifacts?per_page=100`) return artifacts
throw new Error(`Unexpected GitHub request ${path}`)
})
return { run, jobs, artifact, artifacts, api }
return { run, jobs, artifact, artifacts, api, matchesSource }
}
it.each([undefined, '', '2'])('pins attempt %s and finds its artifact across pages', (attempt) => {
it.each(['123', ''])('selects a matching artifact with run ID %j and pins the latest attempt', async (runId) => {
const f = fixture()
expect(selectCuaHelperArtifact(repository, { cua_run_id: '123', cua_run_attempt: attempt }, f.api))
expect(await selectCuaHelperArtifact(repository, runId, key, f.api, f.matchesSource))
.toEqual({ runId: '123', attempt: '2', artifactId: '456' })
expect(f.api.mock.calls.some(([path]) => path === base)).toBe(attempt !== '2')
expect(f.api.mock.calls.filter(([path]) => path === base)).toHaveLength(1)
expect(f.api.mock.calls.some(([path]) => path.includes('/workflows/'))).toBe(runId === '')
})
it('allows successful CUA packaging when later publication jobs failed', () => {
it('allows successful helper packaging when later npm publication failed', async () => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.run.conclusion = 'failure'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success' }, { name: 'Publish to npm', conclusion: 'failure' }]
expect(selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api).artifactId).toBe('456')
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }, { name: 'Publish to npm', conclusion: 'failure', run_attempt: 2 }]
expect((await selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource))?.artifactId).toBe('456')
})
it.each([
{}, { cua_run_attempt: '2' }, { cua_run_id: '' }, { cua_run_id: '123/other' }, { cua_run_id: ' 123' },
{ cua_run_id: '0' }, { cua_run_id: '123', cua_run_attempt: '-1' }, { cua_run_id: '123', cua_run_attempt: '2\nartifact-id=9' },
])('rejects invalid selection fields before reading GitHub: %j', (inputs) => {
it.each(['123/other', ' 123', '0', '-1', '2\nartifact-id=9', 'https://github.com/owner/repo/actions/runs/123'])(
'rejects invalid run ID %j before reading GitHub', async (runId) => {
const f = fixture()
await expect(selectCuaHelperArtifact(repository, runId, key, f.api, f.matchesSource)).rejects.toThrow('numeric run ID')
expect(f.api).not.toHaveBeenCalled()
},
)
it.each(['wrong/repo/extra', '../repo', 'owner/..', 'owner/.'])('rejects invalid repository %s before reading GitHub', async (repo) => {
const f = fixture()
expect(() => selectCuaHelperArtifact(repository, inputs, f.api)).toThrow()
await expect(selectCuaHelperArtifact(repo, '123', key, f.api, f.matchesSource)).rejects.toThrow('invalid repository')
expect(f.api).not.toHaveBeenCalled()
})
it.each(['wrong/repo/extra', '../repo', 'owner/..', 'owner/.'])('rejects invalid repository %s before reading GitHub', (repo) => {
const f = fixture()
expect(() => selectCuaHelperArtifact(repo, { cua_run_id: '123' }, f.api)).toThrow('invalid repository')
expect(f.api).not.toHaveBeenCalled()
})
it.each(['workflow', 'event', 'repository', 'id', 'attempt', 'running', 'failed'] as const)('rejects %s run evidence', (change) => {
const f = fixture()
if (change === 'workflow') f.run.path = '.github/workflows/ci.yml'
if (change === 'event') f.run.event = 'pull_request'
if (change === 'repository') f.run.repository.full_name = 'outsider/fork'
if (change === 'id') f.run.id = 124
if (change === 'attempt') f.run.run_attempt = 1
if (change === 'running') f.run.status = 'in_progress'
if (change === 'failed') f.run.conclusion = 'failure'
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api)).toThrow()
expect(f.api.mock.calls.some(([path]) => path.includes('/artifacts'))).toBe(false)
})
it.each(['workflow', 'event', 'repository', 'head_repository', 'id', 'attempt', 'running', 'failed'] as const)(
'rejects explicit %s run evidence', async (change) => {
const f = fixture()
if (change === 'workflow') f.run.path = '.github/workflows/ci.yml'
if (change === 'event') f.run.event = 'pull_request'
if (change === 'repository') f.run.repository.full_name = 'outsider/fork'
if (change === 'head_repository') f.run.head_repository.full_name = 'outsider/fork'
if (change === 'id') f.run.id = 124
if (change === 'attempt') f.run.run_attempt = 1
if (change === 'running') f.run.status = 'in_progress'
if (change === 'failed') f.run.conclusion = 'failure'
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow()
expect(f.api.mock.calls.some(([path]) => path.includes('/artifacts'))).toBe(false)
},
)
it.each(['failure', 'cancelled', 'skipped', 'missing', 'duplicate'])(
'rejects %s helper jobs without falling back to attempt 1', (status) => {
'rejects %s helper jobs without falling back to attempt 1', async (status) => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.run.conclusion = 'failure'
f.jobs[0]!.jobs = status === 'missing' ? [] : status === 'duplicate'
? [{ name: 'cua-helper / package', conclusion: 'success' }, { name: 'cua-helper / package', conclusion: 'success' }]
: [{ name: 'cua-helper / package', conclusion: status }]
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api)).toThrow('successful cua-helper / package job')
? [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }, { name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }]
: [{ name: 'cua-helper / package', conclusion: status, run_attempt: 2 }]
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('last executed cua-helper / package job did not succeed')
expect(f.api.mock.calls.some(([path]) => path.includes('/attempts/1') || path.includes('/artifacts'))).toBe(false)
},
)
it.each(['missing', 'expired', 'empty', 'duplicate'] as const)('rejects %s artifacts instead of another attempt', (change) => {
it.each(['missing', 'expired', 'empty', 'mismatch', 'legacy'] as const)(
'rebuilds on automatic %s but rejects the same explicit selection', async (change) => {
const f = fixture()
if (change === 'missing') f.artifacts.pop()
if (change === 'expired') f.artifact.expired = true
if (change === 'empty') f.artifact.size_in_bytes = 0
if (change === 'mismatch') f.artifact.name = `cua-helper-123-2-${'b'.repeat(64)}`
if (change === 'legacy') f.artifact.name = 'cua-helper-123-2'
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('CUA reuse: run 123:')
},
)
it('selects a match across workflows and pages after a newer failed producer', async () => {
const f = fixture()
if (change === 'missing') f.artifacts.pop()
if (change === 'expired') f.artifact.expired = true
if (change === 'empty') f.artifact.size_in_bytes = 0
if (change === 'duplicate') f.artifacts.push({ artifacts: [{ ...f.artifact, id: 457 }] })
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api)).toThrow('select an available build or rebuild')
const api = vi.fn(async (path: string, paginate?: boolean): Promise<unknown> => {
if (path.includes('/workflows/cua-helper-package.yml/runs?')) return [{ workflow_runs: [] }]
if (path.includes('/workflows/release-publish.yml/runs?')) return [{ workflow_runs: [{ id: 124 }] }, { workflow_runs: [{ id: 123 }] }]
if (path.endsWith('/runs/124/artifacts?per_page=100')) return [{ artifacts: [{ ...f.artifact, name: `cua-helper-124-1-${key}` }] }]
if (path.endsWith('/runs/124')) return { run_attempt: 1 }
if (path.endsWith('/runs/124/attempts/1')) return { ...f.run, id: 124, run_attempt: 1, conclusion: 'failure' }
return f.api(path, paginate)
})
expect((await selectCuaHelperArtifact(repository, '', key, api, f.matchesSource, new Date('2026-11-03T00:00:00Z')))?.runId).toBe('123')
const paths = api.mock.calls.map(([path]) => path)
expect(paths.find(path => path.includes('/workflows/'))).toContain(encodeURIComponent('>=2026-10-20T00:00:00.000Z'))
expect(paths.indexOf(`${base.replace('123', '124')}/attempts/1`)).toBeLessThan(paths.indexOf(base))
})
it('propagates unavailable GitHub evidence without returning a selection', () => {
const api = vi.fn(() => { throw new Error('HTTP 404') })
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, api)).toThrow('HTTP 404')
it.each(['duplicate', 'invalid metadata'] as const)('stops automatic discovery on %s evidence', async (change) => {
const f = fixture()
if (change === 'duplicate') f.artifacts.push({ artifacts: [{ ...f.artifact, id: 457 }] })
const api = async (path: string, paginate?: boolean): Promise<unknown> => change === 'invalid metadata' && path.endsWith('/artifacts?per_page=100')
? [{ artifacts: [{ ...f.artifact, expired: 'false' }] }] : f.api(path, paginate)
await expect(selectCuaHelperArtifact(repository, '', key, api, f.matchesSource)).rejects.toThrow()
})
it.each(['', '123'])('propagates unavailable GitHub evidence with selection %j', async (runId) => {
const api = vi.fn(async () => { throw new Error('HTTP 403') })
await expect(selectCuaHelperArtifact(repository, runId, key, api, async () => true)).rejects.toThrow('HTTP 403')
expect(api).toHaveBeenCalledTimes(1)
})
it('does not query job or attempt details when artifact names exclude the requested build key', async () => {
const f = fixture()
f.artifact.name = 'cua-helper-123-2-legacy'
f.artifacts.shift()
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
expect(f.api.mock.calls.map(([path]) => path).filter(path => !path.includes('/workflows/')))
.toEqual([`${base}/artifacts?per_page=100`])
})
it.each(['123', ''])('retains the original helper after a publish-only rerun with selection %j', async (runId) => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 1 },
{ name: 'Publish to npm', conclusion: 'success', run_attempt: 2 }]
f.artifacts.pop()
expect(await selectCuaHelperArtifact(repository, runId, key, f.api, f.matchesSource))
.toEqual({ runId: '123', attempt: '1', artifactId: '455' })
expect(f.matchesSource).toHaveBeenCalledExactlyOnceWith(f.run.head_sha)
})
it('does not reuse an older successful helper after a newer helper execution failed', async () => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 1 },
{ name: 'cua-helper / package', conclusion: 'failure', run_attempt: 2 }]
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('did not succeed')
expect(f.matchesSource).not.toHaveBeenCalled()
})
it('rejects forged artifact keys when independent producer source evidence differs', async () => {
const f = fixture()
f.matchesSource.mockResolvedValue(false)
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('producer commit')
})
it('stops when a new attempt appears during selection', async () => {
const f = fixture()
f.jobs[0]!.jobs[0]!.run_attempt = 3
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('run advanced')
})
it('authenticates native HTTP requests and follows canonical GitHub pagination links', async () => {
const request = vi.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ jobs: [{ id: 1 }] }, {
headers: { link: '<https://api.github.com/repositories/42/actions/jobs?page=2>; rel="next"' },
}))
.mockResolvedValueOnce(Response.json({ jobs: [{ id: 2 }] }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
await expect(api('repos/owner/repo/actions/jobs?page=1', true)).resolves.toEqual([
{ jobs: [{ id: 1 }] }, { jobs: [{ id: 2 }] },
])
expect(request).toHaveBeenCalledTimes(2)
expect(request.mock.calls[1]![1]?.signal).toBe(request.mock.calls[0]![1]?.signal)
expect(request.mock.calls[1]![0]).toHaveProperty('href', 'https://api.github.com/repositories/42/actions/jobs?page=2')
for (const [, options] of request.mock.calls) {
const headers = new Headers(options?.headers)
expect(headers.get('authorization')).toBe('Bearer fixture-token')
expect(headers.get('accept')).toBe('application/vnd.github+json')
expect(options?.signal).toBeInstanceOf(AbortSignal)
expect(options?.redirect).toBe('error')
}
})
it('uses the configured GitHub API base path and leaves non-paginated JSON unwrapped', async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ run_attempt: 2 }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token', GITHUB_API_URL: 'https://github.example.test/api/v3' }, request)
await expect(api('repos/owner/repo/actions/runs/123')).resolves.toEqual({ run_attempt: 2 })
expect(request.mock.calls[0]![0]).toHaveProperty('href', 'https://github.example.test/api/v3/repos/owner/repo/actions/runs/123')
})
it.each([401, 403, 429, 500, 503])('rejects HTTP %s without returning a partial page list or response credentials', async (status) => {
const request = vi.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ jobs: [{ id: 1 }] }, {
headers: { link: '<https://api.github.com/repos/owner/repo/jobs?page=2>; rel="next"' },
}))
.mockResolvedValueOnce(new Response('private-response-value', { status }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
const result = api('repos/owner/repo/jobs?page=1', true)
await expect(result).rejects.toThrow(`HTTP ${status}`)
await expect(result).rejects.not.toThrow('private-response-value')
await expect(result).rejects.not.toThrow('fixture-token')
})
it.each(['connection reset', 'request timeout'])('reports %s as a failed query', async (failure) => {
const request = vi.fn<typeof fetch>().mockRejectedValue(new Error(failure))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
await expect(api('repos/owner/repo')).rejects.toThrow('failed or timed out')
})
it('rejects invalid JSON without exposing its content', async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response('private-response-value'))
const result = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo')
await expect(result).rejects.toThrow('invalid JSON')
await expect(result).rejects.not.toThrow('private-response-value')
})
it.each([
'https://outside.example.test/page/2',
'https://[email protected]/repos/owner/repo/jobs?page=2',
'https://api.github.com/repos/owner/repo/jobs?page=1',
])('rejects unsafe or cyclic pagination %s before sending another request', async (next) => {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ jobs: [] }, { headers: { link: `<${next}>; rel="next"` } }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
await expect(api('repos/owner/repo/jobs?page=1', true)).rejects.toThrow('CUA reuse: GitHub')
expect(request).toHaveBeenCalledTimes(1)
})
it('rejects a malformed next-page header', async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({}, { headers: { link: 'missing-url; rel="next"' } }))
await expect(createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo/jobs', true))
.rejects.toThrow('invalid pagination link')
})
it('stops reading an oversized response and cancels its stream', async () => {
let cancelled = false
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)) },
cancel() { cancelled = true },
})
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response(body))
await expect(createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo/git/trees/fixture'))
.rejects.toThrow('exceeds 32 MiB')
expect(cancelled).toBe(true)
})
it.each(['', 'not-a-url', 'http://api.github.com', 'https://user:[email protected]', 'https://api.github.com?token=private'])(
'rejects invalid API configuration %j before requesting data', (url) => {
const request = vi.fn<typeof fetch>()
expect(() => createGitHubJsonReader({ GH_TOKEN: 'fixture-token', GITHUB_API_URL: url }, request)).toThrow('GITHUB_API_URL')
expect(request).not.toHaveBeenCalled()
},
)
it('requires an explicit Actions token instead of relying on gh credentials', () => {
const request = vi.fn<typeof fetch>()
expect(() => createGitHubJsonReader({}, request)).toThrow('GH_TOKEN is required')
expect(request).not.toHaveBeenCalled()
})
it('propagates an asynchronous source verification failure', async () => {
const f = fixture()
f.matchesSource.mockRejectedValue(new Error('source evidence unavailable'))
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('source evidence unavailable')
})
it('passes the 60-second abort signal to the HTTP transport', async () => {
const controller = new AbortController()
const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal)
onTestFinished(() => { timeout.mockRestore() })
const request: typeof fetch = async (_url, options) => {
expect(options?.signal).toBe(controller.signal)
controller.abort(new DOMException('fixture timeout', 'TimeoutError'))
options?.signal?.throwIfAborted()
throw new Error('Expected an aborted request')
}
await expect(createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo')).rejects.toThrow('timed out')
expect(timeout).toHaveBeenCalledExactlyOnceWith(60_000)
})
+197 -61
View File
@@ -1,74 +1,210 @@
/** Select one retained, successful CUA packaging attempt without contacting the Mac runner. */
import { execFileSync } from 'node:child_process'
import { appendFileSync, readFileSync } from 'node:fs'
/** Find a matching retained helper on the Mac runner before installing dependencies. */
import assert from 'node:assert/strict'
import { appendFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { z } from 'zod'
import { isEntry } from '../release/process.ts'
import { cuaHelperSourceMatches } from './build-inputs.ts'
const positiveId = z.string().regex(/^[1-9]\d*$/u)
const inputsSchema = z.object({
cua_run_id: positiveId,
cua_run_attempt: z.union([positiveId, z.literal('')]).optional(),
})
const runSchema = z.object({
id: z.number().int().positive(), run_attempt: z.number().int().positive(),
status: z.literal('completed'), conclusion: z.string().nullable(), event: z.literal('workflow_dispatch'),
path: z.enum(['.github/workflows/cua-helper-package.yml', '.github/workflows/release-publish.yml']),
repository: z.object({ full_name: z.string() }),
})
const jobsSchema = z.array(z.object({ jobs: z.array(z.object({ name: z.string(), conclusion: z.string().nullable() })) }))
const artifactsSchema = z.array(z.object({ artifacts: z.array(z.object({
id: z.number().int().positive(), name: z.string(), expired: z.boolean(), size_in_bytes: z.number().int().nonnegative(),
})) }))
const workflows = ['cua-helper-package.yml', 'release-publish.yml'] as const
function record(value: unknown): Record<string, unknown> {
assert(value !== null && typeof value === 'object' && !Array.isArray(value), 'CUA reuse: invalid GitHub object')
return value as Record<string, unknown>
}
function id(value: unknown): string {
assert(typeof value === 'number' && Number.isSafeInteger(value) && value > 0, 'CUA reuse: invalid GitHub identifier')
return String(value)
}
function rows(value: unknown, key: string): Record<string, unknown>[] {
assert(Array.isArray(value), 'CUA reuse: expected paginated GitHub response')
return value.flatMap((page: unknown) => {
const entries = record(page)[key]
assert(Array.isArray(entries), `CUA reuse: invalid GitHub ${key}`)
return entries.map(record)
})
}
/** Exact producer attempt and immutable artifact selected by the Mac workflow. */
export interface CuaHelperSelection {
readonly runId: string
readonly attempt: string
readonly artifactId: string
}
/**
* Pin an explicit attempt or the latest attempt once, then select its immutable artifact ID.
* A successful helper job in a completed publication run is reusable even if later npm jobs failed.
* Failure returns no selection; there is no fallback to another attempt. Payload validation remains with stage.ts.
* @param repository - Repository containing the producer and consuming release.
* @param inputsValue - Untrusted dispatch fields cua_run_id and optional cua_run_attempt.
* @param api - Read-only GitHub JSON reader; paginated responses must be arrays of pages.
* @returns Exact run, attempt and artifact to download before source/version and application validation.
* Select the last executed helper job, preserving its producer attempt across pack/publish-only reruns.
* Automatic misses rebuild; explicit misses and unreadable GitHub evidence fail without selecting another run.
* @param repository - Same repository that owns the producer and consumer.
* @param runId - Optional decimal run ID; empty selects automatic discovery.
* @param buildKey - Source and machine configuration digest required by the consumer.
* @param api - Read-only GitHub JSON reader; paginated responses are arrays of pages.
* @param matchesSource - Independent comparison of the producer head SHA with the consuming build inputs.
* @param now - Discovery time; automatic search covers the artifact's 14-day retention window.
* @returns Resolves to the matching producer artifact, or undefined when automatic discovery has no match.
*/
export function selectCuaHelperArtifact(repository: string, inputsValue: unknown,
api: (path: string, paginate?: boolean) => unknown): { runId: string; attempt: string; artifactId: string } {
if (!/^[\w.-]+\/[\w.-]+$/u.test(repository) || repository.split('/').some(part => part === '.' || part === '..')) {
throw new Error('CUA reuse: invalid repository')
export async function selectCuaHelperArtifact(repository: string, runId: string, buildKey: string,
api: (path: string, paginate?: boolean) => Promise<unknown>, matchesSource: (commit: string) => Promise<boolean>,
now = new Date()): Promise<CuaHelperSelection | undefined> {
assert(/^[\w.-]+\/[\w.-]+$/u.test(repository) && !repository.split('/').some(part => part === '.' || part === '..'),
'CUA reuse: invalid repository')
assert(runId === '' || /^[1-9]\d*$/u.test(runId), 'CUA reuse: enter the numeric run ID after /actions/runs/ in the run URL')
assert(/^[a-f0-9]{64}$/u.test(buildKey), 'CUA reuse: invalid build key')
const base = `repos/${repository}/actions`
const selectRun = async (candidate: string, retained?: Record<string, unknown>[]): Promise<CuaHelperSelection | string> => {
const attempt = id(record(await api(`${base}/runs/${candidate}`)).run_attempt)
const run = record(await api(`${base}/runs/${candidate}/attempts/${attempt}`))
assert(id(run.id) === candidate && id(run.run_attempt) === attempt
&& record(run.repository).full_name === repository && record(run.head_repository).full_name === repository,
'CUA reuse: selected run, attempt or repository does not match GitHub evidence')
const workflow = workflows.find(name => run.path === `.github/workflows/${name}`)
assert(workflow && run.event === 'workflow_dispatch', 'CUA reuse: select a supported repository packaging or release run')
if (run.status !== 'completed') return 'the latest attempt has not completed'
if (workflow === 'cua-helper-package.yml' && run.conclusion !== 'success') return 'the latest packaging attempt did not succeed'
const jobName = workflow === 'cua-helper-package.yml' ? 'package' : 'cua-helper / package'
const jobs = rows(await api(`${base}/runs/${candidate}/jobs?filter=all&per_page=100`, true), 'jobs')
.filter(job => job.name === jobName)
const attempts = jobs.map(job => Number(id(job.run_attempt)))
assert(attempts.every(value => value <= Number(attempt)), 'CUA reuse: run advanced during selection; retry with the same run ID')
const producerAttempt = Math.max(0, ...attempts)
const producers = jobs.filter(job => job.run_attempt === producerAttempt)
if (producers.length !== 1 || producers[0]?.conclusion !== 'success') return `the last executed ${jobName} job did not succeed`
const name = `cua-helper-${candidate}-${producerAttempt}-${buildKey}`
const artifacts = (retained ?? rows(await api(`${base}/runs/${candidate}/artifacts?per_page=100`, true), 'artifacts'))
.filter(artifact => artifact.name === name)
if (artifacts.length === 0) return 'no artifact matches the current source bytes and build configuration; use the producer run linked in its summary or rebuild'
const [artifact] = artifacts
assert(artifacts.length === 1 && artifact !== undefined, 'CUA reuse: matching artifact is ambiguous')
assert(typeof artifact.expired === 'boolean' && typeof artifact.size_in_bytes === 'number', 'CUA reuse: invalid artifact metadata')
if (artifact.expired || artifact.size_in_bytes <= 0) return 'the matching artifact is expired or empty'
assert(typeof run.head_sha === 'string' && /^[a-f0-9]{40}$/u.test(run.head_sha), 'CUA reuse: invalid producer head SHA')
if (!await matchesSource(run.head_sha)) return 'the producer commit has different helper build inputs'
return { runId: candidate, attempt: String(producerAttempt), artifactId: id(artifact.id) }
}
const inputs = inputsSchema.parse(inputsValue)
const base = `repos/${repository}/actions/runs/${inputs.cua_run_id}`
const attempt = inputs.cua_run_attempt
|| String(z.object({ run_attempt: z.number().int().positive() }).parse(api(base)).run_attempt)
const run = runSchema.parse(api(`${base}/attempts/${attempt}`))
if (String(run.id) !== inputs.cua_run_id || String(run.run_attempt) !== attempt || run.repository.full_name !== repository) {
throw new Error('CUA reuse: selected run, attempt or repository does not match GitHub evidence')
if (runId !== '') {
const selected = await selectRun(runId)
if (typeof selected === 'string') throw new Error(`CUA reuse: run ${runId}: ${selected}`)
return selected
}
const jobName = run.path === '.github/workflows/cua-helper-package.yml' ? 'package' : 'cua-helper / package'
if (jobName === 'package' && run.conclusion !== 'success') {
throw new Error('CUA reuse: standalone packaging did not succeed; select a successful attempt')
const since = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString()
const candidates: Record<string, unknown>[] = []
for (const workflow of workflows) {
candidates.push(...rows(await api(
`${base}/workflows/${workflow}/runs?event=workflow_dispatch&status=completed&created=${encodeURIComponent(`>=${since}`)}&per_page=100`,
true), 'workflow_runs'))
}
const jobs = jobsSchema.parse(api(`${base}/attempts/${attempt}/jobs?per_page=100`, true))
.flatMap(page => page.jobs).filter(job => job.name === jobName)
if (jobs.length !== 1 || jobs[0]?.conclusion !== 'success') {
throw new Error(`CUA reuse: run ${inputs.cua_run_id}, attempt ${attempt} requires one successful ${jobName} job;`
+ ' select a successful attempt')
candidates.sort((left, right) => Number(id(right.id)) - Number(id(left.id)))
for (const candidate of candidates) {
const candidateId = id(candidate.id)
const artifacts = rows(await api(`${base}/runs/${candidateId}/artifacts?per_page=100`, true), 'artifacts')
if (!artifacts.some(artifact => typeof artifact.name === 'string'
&& artifact.name.startsWith(`cua-helper-${candidateId}-`) && artifact.name.endsWith(`-${buildKey}`))) continue
const selected = await selectRun(candidateId, artifacts)
if (typeof selected !== 'string') return selected
}
const name = `cua-helper-${inputs.cua_run_id}-${attempt}`
const artifacts = artifactsSchema.parse(api(`${base}/artifacts?per_page=100`, true))
.flatMap(page => page.artifacts).filter(artifact => artifact.name === name)
const [artifact] = artifacts
if (artifacts.length !== 1 || artifact === undefined || artifact.expired || artifact.size_in_bytes === 0) {
throw new Error(`CUA reuse: ${name} is missing, expired, empty or ambiguous; select an available build or rebuild`)
}
return { runId: inputs.cua_run_id, attempt, artifactId: String(artifact.id) }
return undefined
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
/**
* Create authenticated, read-only GitHub requests using Node's built-in fetch.
* Each call, including pagination, has a 60-second deadline and a 32 MiB response limit.
* Pagination stays on the configured API origin. Request or parsing failures never return partial pages.
* @param environment - GH_TOKEN and optional GITHUB_API_URL supplied by Actions.
* @param request - HTTP transport receiving the authenticated URL and request options.
* @returns JSON reader; paginated calls resolve to an array of page objects.
*/
export function createGitHubJsonReader(environment: NodeJS.ProcessEnv, request: typeof fetch = fetch):
(path: string, paginate?: boolean) => Promise<unknown> {
const token = environment.GH_TOKEN?.trim()
if (!token) throw new Error('CUA reuse: GH_TOKEN is required for GitHub API access')
const configured = environment.GITHUB_API_URL ?? 'https://api.github.com'
let base: URL
try { base = new URL(configured.endsWith('/') ? configured : `${configured}/`) } catch (_error) {
// URL parser errors may include credential-bearing configuration.
throw new Error('CUA reuse: GITHUB_API_URL must be a valid HTTPS API URL')
}
assert(base.protocol === 'https:' && !base.username && !base.password && !base.search && !base.hash,
'CUA reuse: GITHUB_API_URL must be HTTPS without credentials, query or fragment')
return async (path, paginate = false) => {
let target = new URL(path, base)
const visited = new Set<string>()
const pages: unknown[] = []
let bytes = 0
const signal = AbortSignal.timeout(60_000)
while (true) {
assert(target.origin === base.origin && target.pathname.startsWith(base.pathname)
&& !target.username && !target.password && !target.hash, 'CUA reuse: GitHub pagination left the configured API')
assert(!visited.has(target.href), 'CUA reuse: GitHub returned a pagination cycle')
visited.add(target.href)
let response: Response
try {
response = await request(target, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2026-03-10', 'User-Agent': 'deepseek-harness-cua-helper' },
redirect: 'error', signal,
})
} catch (error) {
throw new Error('CUA reuse: GitHub request failed or timed out; check connectivity and retry this workflow', { cause: error })
}
if (!response.ok) {
try { await response.body?.cancel() } catch (_error) {
// A failed body stream must not hide the HTTP failure already received.
}
throw new Error(`CUA reuse: GitHub request failed (HTTP ${response.status}); check token permissions, rate limits or service availability, then retry`)
}
const reader = response.body?.getReader()
if (!reader) throw new Error('CUA reuse: GitHub returned an empty response')
const chunks: Uint8Array[] = []
try {
while (true) {
const chunk = await reader.read()
if (chunk.done) break
bytes += chunk.value.byteLength
if (bytes > 32 * 1024 * 1024) {
await reader.cancel()
throw new Error('CUA reuse: GitHub response exceeds 32 MiB')
}
chunks.push(chunk.value)
}
} finally { reader.releaseLock() }
let value: unknown
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch (_error) {
// JSON parser errors may include response bytes.
throw new Error('CUA reuse: GitHub returned invalid JSON; retry this workflow')
}
if (!paginate) return value
pages.push(value)
const link = response.headers.get('link') ?? ''
const next = /<([^>]+)>\s*;\s*rel="next"/u.exec(link)?.[1]
assert(next || !link.includes('rel="next"'), 'CUA reuse: GitHub returned an invalid pagination link')
if (!next) return pages
target = new URL(next, target)
}
}
}
if (isEntry(import.meta.url)) {
const env = process.env
if (!env.GITHUB_EVENT_PATH || !env.GITHUB_REPOSITORY || !env.GITHUB_OUTPUT) throw new Error('CUA reuse: Actions context required')
const event = z.object({ inputs: inputsSchema }).parse(JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8')))
const selection = selectCuaHelperArtifact(env.GITHUB_REPOSITORY, event.inputs, (path, paginate) =>
JSON.parse(execFileSync('gh', ['api', ...(paginate ? ['--paginate', '--slurp'] : []), path],
{ encoding: 'utf8', timeout: 60_000, maxBuffer: 8 * 1024 * 1024 })))
appendFileSync(env.GITHUB_OUTPUT, `artifact-id=${selection.artifactId}\nattempt=${selection.attempt}\n`)
console.log(`CUA helper: run ${selection.runId}, attempt ${selection.attempt}, artifact ${selection.artifactId}`)
if (!env.GITHUB_REPOSITORY || !env.GITHUB_OUTPUT || !env.GITHUB_STEP_SUMMARY || !env.CUA_BUILD_KEY) {
throw new Error('CUA reuse: Actions context and CUA_BUILD_KEY are required')
}
const githubJson = createGitHubJsonReader(env)
const repository = env.GITHUB_REPOSITORY
const root = resolve(import.meta.dirname, '../..')
const sourceMatches = new Map<string, boolean>()
const selection = await selectCuaHelperArtifact(repository, env.CUA_RUN_ID ?? '', env.CUA_BUILD_KEY, githubJson, async (commit) => {
let matches = sourceMatches.get(commit)
if (matches === undefined) {
matches = await cuaHelperSourceMatches(root, repository, commit, githubJson)
sourceMatches.set(commit, matches)
}
return matches
})
appendFileSync(env.GITHUB_OUTPUT, `artifact-id=${selection?.artifactId ?? ''}\nrun-id=${selection?.runId ?? ''}\n`)
const summary = selection
? `复用 [CUA helper 构建](https://github.com/${repository}/actions/runs/${selection.runId}/attempts/${selection.attempt}),run ID \`${selection.runId}\`,artifact ID \`${selection.artifactId}\`。跳过依赖安装、编译、签名和公证。`
: '未找到源码逐字节一致且构建配置匹配的可用 CUA helper 产物,执行依赖安装和重新构建。'
appendFileSync(env.GITHUB_STEP_SUMMARY, `${summary}\n`)
console.log(summary)
}
+5 -6
View File
@@ -1,14 +1,13 @@
/** Stage the signed helper artifact selected by the credential-free npm pack job. */
import { execFileSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { parseArgs } from 'node:util'
import { cuaHelperSourceDigest } from './build-inputs.ts'
import { stageCuaHelperPayload } from './payload.ts'
const { values } = parseArgs({ options: { from: { type: 'string' } }, allowPositionals: false })
if (!values.from) throw new Error('Usage: stage.ts --from <extracted-helper-artifact>')
const root = resolve(import.meta.dirname, '../..')
const { version } = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as { version: string }
const commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim()
stageCuaHelperPayload(resolve(values.from), resolve(root, 'packages/experimental/cua-macos'), { version, commit })
console.log(`CUA helper staged for ${version} (${commit})`)
const expected = { sourceDigest: cuaHelperSourceDigest(root),
...(process.env.CUA_EXPECTED_BUILD_KEY === undefined ? {} : { buildKey: process.env.CUA_EXPECTED_BUILD_KEY }) }
stageCuaHelperPayload(resolve(values.from), resolve(root, 'packages/experimental/cua-macos'), expected)
console.log(`CUA helper staged for source digest ${expected.sourceDigest}`)
+2 -2
View File
@@ -8,10 +8,10 @@ import { verifyCuaHelperPayload } from './payload.ts'
/**
* Verify both helper applications in the exact provider tarball being published.
* @param tarball - pnpm-produced provider package archive.
* @param expected - Product version and source commit of the publishing checkout.
* @param expected - Helper source digest of the publishing checkout.
* @returns Resolves only when the archive has complete, digest-verified application generations.
*/
export async function verifyCuaHelperTarball(tarball: string, expected: { version: string; commit: string }): Promise<void> {
export async function verifyCuaHelperTarball(tarball: string, expected: { sourceDigest: string }): Promise<void> {
const root = mkdtempSync(join(tmpdir(), 'cua-publish-verify-'))
try {
await extract({ file: tarball, cwd: root, strict: true, filter: (path, entry) => {
+28
View File
@@ -0,0 +1,28 @@
/** Shared assertions for original-build routing and artifact identity in packaging workflows. */
import { expect } from 'vitest'
/**
* Require archival steps to retain the original machine, directory and build identity.
* @param job Parsed archival job from a packaging workflow.
* @param count Expected number of artifact upload steps.
* @returns The checked upload steps, preserving platform-specific fields.
*/
export function expectDesktopArchive<S extends { uses?: string; with?: Record<string, unknown> }>(
job: { 'runs-on': string | string[]; env: Record<string, string>; steps: S[] }, count: number,
): S[] {
expect(job['runs-on']).toEqual(['self-hosted', '${{ needs.package.outputs.runner }}'])
expect(job.env).toMatchObject({
DESKTOP_RETAINED_DIRECTORY: '${{ needs.package.outputs.directory }}',
DESKTOP_PACKAGE_ATTEMPT: '${{ needs.package.outputs.attempt }}',
DESKTOP_PACKAGE_RUNNER: '${{ needs.package.outputs.runner-name }}',
})
const uploads = job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(count)
for (const step of uploads) {
expect(step.with?.name).toBe('${{ env.DESKTOP_ARCHIVE_NAME }}')
expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.version }}')
expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.attempt }}')
expect(job.env.DESKTOP_ARCHIVE_NAME).not.toContain('github.run_attempt')
}
return uploads
}
+4
View File
@@ -23,6 +23,7 @@ it.each(['macos', 'windows'])('%s packaging accepts test branches but preserves
mkdirSync(join(root, 'apps/desktop/scripts'), { recursive: true })
writeFileSync(join(root, 'package.json'), '{"version":"1.0.0"}')
writeFileSync(join(root, 'apps/desktop/scripts/desktop-ci-version.mjs'), 'PACKAGE_VERSION_MODE')
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), '--check-runner')
git('add', '.')
git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-m', 'fixture')
const sha = git('rev-parse', 'HEAD')
@@ -51,6 +52,9 @@ it.each(['macos', 'windows'])('%s packaging accepts test branches but preserves
}
for (const preset of ['test', 'production']) expect(run(preset, 'dsh-v1.0.0').status).toBe(0)
expect(run('test', 'dsh-v2.0.0').status).not.toBe(0)
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), 'old archival adapter')
expect(run('test', 'dsh-v1.0.0').stderr).toContain('independent Desktop artifact archival support')
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), '--check-runner')
writeFileSync(join(root, 'apps/desktop/scripts/desktop-ci-version.mjs'), 'old adapter')
expect(run('test', 'dsh-v1.0.0').status).not.toBe(0)
} finally { rmSync(root, { recursive: true, force: true, maxRetries: 3 }) }
+23
View File
@@ -9,6 +9,7 @@ const workflow = yaml.load(readFileSync(resolve(import.meta.dirname, '../.github
permissions: Record<string, string>
jobs: Record<string, {
defaults?: unknown
concurrency?: { group: string; 'cancel-in-progress': boolean }
needs?: string | string[]
env?: Record<string, string>
if?: string
@@ -78,3 +79,25 @@ it('rejects non-master dispatch before scheduling a self-hosted job', () => {
if (result.status !== 0) expect(result.stderr).toContain('must be dispatched from master')
}
})
it('defaults to production website upload and separates cache-only recovery', () => {
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { upload_website: { type: 'boolean', default: true } } })
expect(workflow.jobs.prepare!.env?.DESKTOP_UPLOAD_WEBSITE).toBe('${{ inputs.upload_website }}')
expect(workflow.jobs.prepare!.env?.DOWNLOAD_PROD_EO_ZONE_ID).toBe('${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}')
const upload = workflow.jobs['upload-website-installer']!
const purge = workflow.jobs['purge-website-installer']!
expect(purge.needs).toEqual(['route', 'prepare', 'upload-website-installer'])
expect(upload.concurrency).toEqual({ group: 'desktop-website-upload-${{ needs.prepare.outputs.website-destination }}', 'cancel-in-progress': false })
expect(purge.concurrency).toEqual({ group: 'desktop-website-purge-${{ needs.prepare.outputs.website-destination }}', 'cancel-in-progress': false })
for (const job of [upload, purge]) {
expect(job.if).toBe("inputs.upload_website && needs.prepare.outputs.preset != 'test'")
expect(job.environment).toBe('desktop-production')
const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop/scripts/preflight-desktop-publish-local.mjs')
expect(preflight).toBeGreaterThan(-1)
expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile'))
expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}')
}
expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts upload')
expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts purge')
expect(purge.steps.some(step => step.run?.includes('publish-desktop-ci.ts'))).toBe(false)
})
+22 -21
View File
@@ -1,6 +1,6 @@
/**
* Quick comprehensive documentation-standard tests: the reference example
* stays valid, the consolidated `dsh-doc` skill carries no stale copied
* stays valid, the consolidated `dsh-doc-writing` skill carries no stale copied
* website values or prototype-era language, and the kind system maps each
* label to exactly one skill template. Session release records match the
* writer bound, bilingual counterpart, and evidence links. These run in `pnpm run test` and
@@ -38,14 +38,14 @@ function packageReadmes(): string[] {
* or a document whose kind does not match its position fails here.
*/
const KIND_TEMPLATES: Readonly<Record<string, string>> = {
'package-group': '.agents/skills/dsh-doc/templates/package-group.md',
'package-reference': '.agents/skills/dsh-doc/templates/package-reference.md',
'package-library': '.agents/skills/dsh-doc/templates/package-library.md',
'package-bundle': '.agents/skills/dsh-doc/templates/package-bundle.md',
'persistence-change': '.agents/skills/dsh-doc/templates/persistence-change.md',
'persistence-release': '.agents/skills/dsh-doc/templates/persistence-release.md',
'persistence-format': '.agents/skills/dsh-doc/templates/persistence-format.md',
'upgrade-guide': '.agents/skills/dsh-doc/templates/upgrade-guide.md',
'package-group': '.agents/skills/dsh-doc-writing/templates/package-group.md',
'package-reference': '.agents/skills/dsh-doc-writing/templates/package-reference.md',
'package-library': '.agents/skills/dsh-doc-writing/templates/package-library.md',
'package-bundle': '.agents/skills/dsh-doc-writing/templates/package-bundle.md',
'persistence-change': '.agents/skills/dsh-doc-writing/templates/persistence-change.md',
'persistence-release': '.agents/skills/dsh-doc-writing/templates/persistence-release.md',
'persistence-format': '.agents/skills/dsh-doc-writing/templates/persistence-format.md',
'upgrade-guide': '.agents/skills/dsh-doc-writing/templates/upgrade-guide.md',
}
/**
@@ -85,6 +85,7 @@ const PACKAGE_LIBRARIES: Readonly<Record<string, string>> = {
'packages/test-support/session-snapshot': 'Test infrastructure; mounts nothing into a product composition.',
'packages/test-support/agent-loop-testkit': 'Test helper library; mounts nothing into a product composition.',
'packages/test-support/tool-testkit': 'Tool fixture library; exports helpers without a plugin entry.',
'packages/test-support/mcp-testkit': 'MCP OAuth and manager profile fixture library; exports helpers without a plugin entry.',
'packages/test-support/client-runtime': 'Browser-side test infrastructure.',
'packages/test-support/llm-mock-server': 'Test server library; substitutes provider wire behavior.',
'packages/test-support/loader-smoke': 'Test harness library; mounts nothing into a product composition.',
@@ -304,15 +305,15 @@ describe('Session format release authority', () => {
})
})
describe('dsh-doc skill consolidation', () => {
describe('dsh-doc-writing skill consolidation', () => {
it('carries no prototype-era language', () => {
const files = [
'.agents/skills/dsh-doc/SKILL.md',
'.agents/skills/dsh-doc/references/metadata-links-i18n.md',
'.agents/skills/dsh-doc/references/structure-hierarchy.md',
'.agents/skills/dsh-doc/references/style.md',
'.agents/skills/dsh-doc/references/review.md',
'.agents/skills/dsh-doc/references/website-sync.md',
'.agents/skills/dsh-doc-writing/SKILL.md',
'.agents/skills/dsh-doc-writing/references/metadata-links-i18n.md',
'.agents/skills/dsh-doc-writing/references/structure-hierarchy.md',
'.agents/skills/dsh-doc-writing/references/style.md',
'.agents/skills/dsh-doc-writing/references/review.md',
'.agents/skills/dsh-doc-writing/references/website-sync.md',
]
for (const file of files) {
const source = readFileSync(resolve(root, file), 'utf8')
@@ -321,20 +322,20 @@ describe('dsh-doc skill consolidation', () => {
})
it('copies no stale website sidebar or section-owner values', () => {
const source = readFileSync(resolve(root, '.agents/skills/dsh-doc/references/website-sync.md'), 'utf8')
const source = readFileSync(resolve(root, '.agents/skills/dsh-doc-writing/references/website-sync.md'), 'utf8')
expect(source).not.toContain('en-docs')
expect(source).not.toContain('sectionOrder')
})
it('keeps the reference example linked from the skill', () => {
const skill = readFileSync(resolve(root, '.agents/skills/dsh-doc/SKILL.md'), 'utf8')
const skill = readFileSync(resolve(root, '.agents/skills/dsh-doc-writing/SKILL.md'), 'utf8')
expect(skill).toContain('session-persistence-jsonl/README.md')
expect(skill).toContain('session-persistence-jsonl/README.zh.md')
})
it('defines controlled English as a precision-preserving review discipline', () => {
const skill = readFileSync(resolve(root, '.agents/skills/dsh-doc/SKILL.md'), 'utf8')
const style = readFileSync(resolve(root, '.agents/skills/dsh-doc/references/style.md'), 'utf8')
const skill = readFileSync(resolve(root, '.agents/skills/dsh-doc-writing/SKILL.md'), 'utf8')
const style = readFileSync(resolve(root, '.agents/skills/dsh-doc-writing/references/style.md'), 'utf8')
expect(skill).toContain('references/style.md#controlled-technical-english')
expect(style).toContain('not certified ASD-STE100 compliance')
expect(style).toContain('review prompts, not mechanical gates')
@@ -342,7 +343,7 @@ describe('dsh-doc skill consolidation', () => {
})
it('maps every kind label to exactly one skill template that exists', () => {
const templateFiles = globSync('.agents/skills/dsh-doc/templates/*.md', { cwd: root }).map(path => path.split(sep).join('/')).sort()
const templateFiles = globSync('.agents/skills/dsh-doc-writing/templates/*.md', { cwd: root }).map(path => path.split(sep).join('/')).sort()
const registered = Object.values(KIND_TEMPLATES).sort()
expect(templateFiles).toEqual(registered)
for (const [kind, template] of Object.entries(KIND_TEMPLATES)) {
+4 -4
View File
@@ -1,4 +1,4 @@
/** Retained package names keep experimental isolation and persisted record namespaces. */
/** Unprefixed and legacy prefixed package names keep experimental isolation and persisted record namespaces. */
import { describe, expect, it } from 'vitest'
import {
@@ -19,7 +19,7 @@ describe('experimental package identities', () => {
}
})
it.each(names)('does not extend the retained-name exception %s to another package', (name) => {
it.each(names)('does not extend the unprefixed name %s to another package', (name) => {
for (const reference of [`${name}-unrelated`, `other-${name}`, name.replace('@deepseek-ai/', '@other/')]) {
expect(isExperimentalPackageName(reference)).toBe(false)
expect(hasExperimentalPackageReference(reference)).toBe(false)
@@ -27,12 +27,12 @@ describe('experimental package identities', () => {
}
})
it('keeps new experimental packages under their prefixed namespaces', () => {
it('derives the record namespace from a legacy prefixed name', () => {
expect(experimentalPackageRecordNamespace('@deepseek-ai/dsh-experimental-bridge')).toBe('bridge')
expect(hasExperimentalPackageReference('@deepseek-ai/dsh-core')).toBe(false)
})
it.each(Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('keeps %s record names independent of the retained npm name', (directory, name) => {
it.each(Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('keeps %s record names independent of the unprefixed npm name', (directory, name) => {
expect(experimentalPackageRecordNamespace(name)).toBe(directory.split('/').at(-1))
})
})
+55 -8
View File
@@ -1,9 +1,9 @@
/** Experimental package identities, publication policy, and retained npm names. */
/** Experimental package identities, publication policy, and npm names. */
/**
* Experimental packages whose npm names omit the experimental prefix, by directory: identities retained across
* experimental classification and package-role moves, and packages named without the prefix so that leaving
* experimental status keeps their names.
* Experimental packages whose npm names omit the experimental prefix, by directory. Every new experimental package
* belongs here so that promotion keeps its name; isolation checks and plugin-record ownership recognize an unprefixed
* experimental name only through this map.
*/
export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly<Record<string, string>> = {
'packages/experimental/cua': '@deepseek-ai/dsh-cua',
@@ -11,6 +11,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly<Record<string, strin
'packages/experimental/tool-session-query': '@deepseek-ai/dsh-tool-session-query',
'packages/experimental/session-title-all-prompts-llm': '@deepseek-ai/dsh-session-title-all-prompts-llm',
'packages/experimental/tool-terminal': '@deepseek-ai/dsh-tool-terminal',
'packages/experimental/terminal-panel': '@deepseek-ai/dsh-terminal-panel',
'packages/experimental/tool-ralph': '@deepseek-ai/dsh-tool-ralph',
'packages/experimental/skill-badge': '@deepseek-ai/dsh-skill-badge',
'packages/experimental/hook-protocol': '@deepseek-ai/dsh-hook-protocol',
@@ -27,17 +28,63 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly<Record<string, strin
'packages/experimental/personalized-recommendations': '@deepseek-ai/dsh-personalized-recommendations',
} satisfies Record<`packages/experimental/${string}`, `@deepseek-ai/dsh-${string}`>
/** npm namespace for experimental packages without retained-name exceptions. */
/** Legacy npm namespace, allowed only in `LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES`. */
export const EXPERIMENTAL_PACKAGE_NAME_PREFIX = '@deepseek-ai/dsh-experimental-'
const retainedNames = new Set(Object.values(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))
/** Existing experimental packages that keep the legacy prefix until a rename; this list must not grow. */
export const LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES: readonly string[] = [
'packages/experimental/api-speech-to-text',
'packages/experimental/auto-review',
'packages/experimental/badge-skill-bundle',
'packages/experimental/browser-use-chrome-devtools-mcp',
'packages/experimental/browser-use-playwright-mcp',
'packages/experimental/browser-use-runtime',
'packages/experimental/browser-use-stagehand-native',
'packages/experimental/claude-code-mods',
'packages/experimental/client-ui-claude-code-mods',
'packages/experimental/client-ui-cot-translation',
'packages/experimental/client-ui-forge',
'packages/experimental/client-ui-stats',
'packages/experimental/client-ui-voice-input',
'packages/experimental/computer-use-cua-driver-mcp',
'packages/experimental/computer-use-cua-driver-native',
'packages/experimental/cot-translation-bundle',
'packages/experimental/cua-macos',
'packages/experimental/forge',
'packages/experimental/forge-bundle',
'packages/experimental/forge-github',
'packages/experimental/forge-session',
'packages/experimental/inspector',
'packages/experimental/inspector-profile',
'packages/experimental/liveshare',
'packages/experimental/liveshare-protocol',
'packages/experimental/plugin-market-bundle',
'packages/experimental/ptc-runtime-python',
'packages/experimental/ralph-bundle',
'packages/experimental/session-inspector',
'packages/experimental/session-search',
'packages/experimental/session-titles-bundle',
'packages/experimental/speech-to-text',
'packages/experimental/speech-to-text-sensevoice',
'packages/experimental/subagent-oar',
'packages/experimental/terminal-bundle',
'packages/experimental/tool-subagent-oar',
'packages/experimental/tool-worktree',
'packages/experimental/translator',
'packages/experimental/voice-input-bundle',
'packages/experimental/webworker-packer',
'packages/experimental/webworker-runtime',
'packages/experimental/worktree',
]
const unprefixedNames = new Set(Object.values(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))
/**
* Identify an experimental npm package independently of its installed directory.
* @param name - complete npm package name, without a version or subpath.
* @returns Whether the name uses the experimental prefix or a retained name.
* @returns Whether the name uses the legacy prefix or appears in `EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS`.
*/
export function isExperimentalPackageName(name: string): boolean {
return name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX) || retainedNames.has(name)
return name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX) || unprefixedNames.has(name)
}
/**
+12 -17
View File
@@ -1,29 +1,24 @@
/** Exercise the wheel's Office API and model-shell commands from a shipped profile. */
import { readFile, writeFile } from 'node:fs/promises'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
/** Exercise the downloaded sidecar's Kit through the Host Office kit and directly from a shipped profile. */
import { copyFile, readFile, writeFile } from 'node:fs/promises'
import { createConverter } from '@deepseek-ai/libreoffice-kit'
export const name = 'python-sdk-office-smoke'
export async function apply(ctx, config) {
const skill = await ctx.skills.get('office-export-pdf')
const json = skill?.content.match(/\n(\{\n[\s\S]+)$/u)?.[1]
if (json === undefined) throw new Error('Office skill did not supply CLI paths')
const { libreofficeKit: { node, cli: entry } } = JSON.parse(json)
async function cli(args) {
const result = await promisify(execFile)(node, [entry, ...args], { timeout: 120_000, env: { ...process.env, PATH: '' } })
return JSON.parse(result.stdout)
}
const capabilities = await cli(['capabilities', '--json'])
await cli(['convert', '--input', config.input, '--output', config.output + '.cli.pdf'])
const pdf = await readFile(config.output + '.cli.pdf')
if (pdf.subarray(0, 5).toString() !== '%PDF-') throw new Error('Office shell command did not create a PDF')
const bytes = await readFile(config.input)
const converted = await ctx.officeKit.convertTo({
extension: 'docx', format: 'pdf', priority: 'foreground',
source: { key: 'python-sdk-office-smoke', version: 'fixture', bytes: bytes.length, async read() { return { bytes, version: 'fixture' } } },
output: { owner: 'python-sdk-office-smoke', name: 'service.pdf' },
})
await copyFile(converted.path, config.output + '.service.pdf')
const pdf = await readFile(config.output + '.service.pdf')
if (pdf.subarray(0, 5).toString() !== '%PDF-') throw new Error('Office kit service did not create a PDF')
const converter = await createConverter({ timeoutMs: 120_000 })
try {
const result = await converter.render({ inputPath: config.input, outputPath: config.output })
const images = await converter.renderImages({ inputPath: config.imageInput, outputDir: config.imageOutput, pages: [1], dpi: 72 })
await writeFile(config.result, JSON.stringify({ ...result, images, capabilities, moduleUrl: import.meta.resolve('@deepseek-ai/libreoffice-kit') }))
await writeFile(config.result, JSON.stringify({ ...result, images, moduleUrl: import.meta.resolve('@deepseek-ai/libreoffice-kit') }))
} finally {
await converter.dispose()
}
+5 -1
View File
@@ -241,13 +241,17 @@ describe('the real workspace surface', () => {
expect(entries.length).toBeGreaterThan(30)
for (const entry of entries) {
expect(entry.summary, `${entry.key} has no summary`).not.toBe('')
expect(['single', 'list', 'keyed', 'chain']).toContain(entry.kind)
expect(['single', 'list', 'keyed', 'chain', 'hoc']).toContain(entry.kind)
expect(['root', 'session', 'session-maybe']).toContain(entry.scope)
}
// The frame root is the canonical trap: occupied by the shipped app frame,
// so a dynamic package registering there replaces the whole UI.
const root = entries.find(entry => entry.key === 'root')
expect(root?.replaceRisk).toBe('shadows-shipped-ui')
// A hoc layer wraps the owner content; its example must keep rendering it.
const frame = entries.find(entry => entry.key === 'conversation.hero.frame')
expect(frame?.replaceRisk).toBe('wraps-owner-content')
expect(frame?.example).toContain('({ children }) => React.createElement(\'div\', null, children)')
expect(root?.occupants.join(' ')).toContain('AppFrame')
expect(entries.find(entry => entry.key === 'conversation.session')?.declaredBy)
.toContain("factory 'conversation.content' (client-ui-conversation)")
+28 -11
View File
@@ -33,7 +33,7 @@ const OUT = 'packages/extensions/cordis-client-runner/src/client/slot-catalog.ts
const SOURCE_GLOBS = ['packages/*/*/src/**/*.ts', 'packages/*/*/src/**/*.tsx']
/** Slot cardinalities the contract allows. */
const KINDS = ['single', 'list', 'keyed', 'chain'] as const
const KINDS = ['single', 'list', 'keyed', 'chain', 'hoc'] as const
/** Slot data scopes the contract allows. */
const SCOPES = ['root', 'session', 'session-maybe'] as const
@@ -48,9 +48,9 @@ const MAX_DECL_CHARS = 1200
* share that hands down a subsystem instead of a share, and prose that grew
* into a manual. Every report also lists one line per standard prop seat of its
* scope, so the widest Session-scope slot (`tool.call.toolview`, with the
* global and Session access seats) sets the current 125.
* global and Session access seats and one occupant line per keyed tool view) sets the current 127.
*/
const MAX_ENTRY_LINES = 125
const MAX_ENTRY_LINES = 127
/** One register-call option as the catalog teaches it. */
interface OptionDoc {
@@ -82,6 +82,11 @@ const REGISTER_OPTIONS: Readonly<Record<(typeof KINDS)[number], readonly OptionD
chain: [
{ name: 'select', requirement: 'required', type: '(owner) => unknown | null', doc: 'Pure routing selector. Entries are tried in ascending order; the first non-null result wins and arrives as the component\'s `matched` prop. All-null falls through to the owner\'s fallback.' },
],
hoc: [
{ name: 'id', requirement: 'required', type: 'string', doc: 'Your layer key. A fresh id adds a layer; reusing a shipped id replaces that layer. Your component may omit `children`, which replaces everything inside the layer.' },
{ name: 'key', requirement: 'optional', type: 'string', doc: 'Dispatch key this layer serves; omitted, it serves every dispatch. Within one id, an exact-key layer replaces the wildcard layer for that key.' },
{ name: 'order', requirement: 'optional', type: 'number', doc: 'Nesting position, ascending (default 0); the lowest order is the outermost layer. Render the `children` prop at most once.' },
],
}
/** The one register option a dynamic package must NOT pass, and why. */
@@ -301,9 +306,11 @@ function entryOf(
...occupant.id === undefined ? [] : [`id '${occupant.id}'`],
...occupant.entryKey === undefined ? [] : [`key '${occupant.entryKey}'`],
].join(' ')),
replaceRisk: cellOccupied && (declaration.kind === 'single' || declaration.kind === 'keyed')
? 'shadows-shipped-ui'
: 'none',
replaceRisk: declaration.kind === 'hoc'
? 'wraps-owner-content'
: cellOccupied && (declaration.kind === 'single' || declaration.kind === 'keyed')
? 'shadows-shipped-ui'
: 'none',
example: exampleOf(declaration),
source: declaration.source,
}
@@ -344,10 +351,13 @@ function ownerCompositionNames(type: ts.TypeNode): string[] {
return []
}
/** How a keyed slot's key domain is constrained, '' for the other kinds. */
/** How a keyed slot's key domain, or a hoc slot's layer dispatch keys, is constrained; '' for the other kinds. */
function keyDomainOf(declaration: SlotDeclaration, occupants: readonly SlotRegistration[]): string {
if (declaration.kind !== 'keyed') return ''
const taken = [...new Set(occupants.flatMap(occupant => occupant.entryKey === undefined ? [] : [occupant.entryKey]))].sort()
if (declaration.kind === 'hoc') {
return taken.length === 0 ? '' : `open: any entryKey the owner dispatches; a layer without key serves every dispatch, already taken: ${taken.join(', ')}`
}
if (declaration.kind !== 'keyed') return ''
const shipped = taken.length === 0 ? 'none are taken yet' : `already taken: ${taken.join(', ')}`
return declaration.keyProps === undefined
? `open: any string the owner dispatches (no compile-time key set), ${shipped}`
@@ -365,7 +375,9 @@ function exampleOf(declaration: SlotDeclaration): string {
' apply(ctx) {',
` ctx.slots.inject('${declaration.key}', () => ctx.slots.register(`,
` { ${options} },`,
" () => React.createElement('div', null, 'hello'),",
declaration.kind === 'hoc'
? " ({ children }) => React.createElement('div', null, children),"
: " () => React.createElement('div', null, 'hello'),",
' ))',
' },',
'}',
@@ -393,6 +405,7 @@ const KIND_EXAMPLE: Readonly<Record<string, readonly string[]>> = {
list: ["id: 'my-entry'", 'order: 100', "label: 'My entry'"],
keyed: ["key: '<one key the owner dispatches>'"],
chain: ['select: owner => null'],
hoc: ["id: 'my-layer'", 'order: 100'],
}
/** Drop the `@deepseek-ai/dsh-` prefix so rows stay readable. */
@@ -476,7 +489,7 @@ export function renderClientCatalog(entries: readonly SlotEntry[]): string {
'export interface ClientSlotEntry {',
' /** SlotMap key passed as the register call\'s `name`. */',
' key: string',
' /** Cardinality: `single`, `list`, `keyed`, or `chain`. */',
' /** Cardinality: `single`, `list`, `keyed`, `chain`, or `hoc`. */',
' kind: string',
' /** Data scope: `root`, `session`, or `session-maybe`. */',
' scope: string',
@@ -502,7 +515,11 @@ export function renderClientCatalog(entries: readonly SlotEntry[]): string {
' declaredBy: string',
' /** Entries the shipped composition already registered here. */',
' occupants: readonly string[]',
' /** `shadows-shipped-ui` when registering here replaces shipped UI; `none` when additive. */',
' /**',
' * `shadows-shipped-ui` when registering here replaces shipped UI; `wraps-owner-content` when your',
' * component wraps the owner content and renders `children` at most once, omitting it to replace',
' * that content; `none` when additive.',
' */',
' replaceRisk: string',
' /** A minimal browser half that registers into this slot. */',
' example: string',
+33 -6
View File
@@ -71,11 +71,12 @@ export const SERVICE_PAGE: Record<string, string> = {
mcpResources: 'mcp.md',
agentLoop: 'core.md',
mcpManager: 'mcp.md',
mcpClientHost: 'mcp.md',
agentDefaultModel: 'core.md',
agentPresets: 'core.md',
agents: 'core.md',
approval: 'approval.md',
officeToPdf: 'office-to-pdf.md',
officeKit: 'office-kit.md',
attachments: 'attachment.md',
shell: 'shell.md',
shellEnv: 'shell.md',
@@ -271,6 +272,8 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
'webserver': 'web-server.md',
'workflow': 'workflow.md',
'workspace': 'workspace.md',
'working-directory': 'working-directory.md',
'worktree': 'worktrees.md',
}
/**
@@ -284,6 +287,9 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
* exemption cannot mask another declaration in that scope.
*/
export const EVENT_WALK_EXEMPTIONS: Record<string, string> = {
'workspace/archive-notice': 'client-face archive follow-up copy — packages/client/ui-workspace/README.md owns the API',
'workspace/archive-followup-failed': 'client-face archive follow-up failure — packages/client/ui-workspace/README.md owns the API',
'workspace/archive-followup-settled': 'client-face archive follow-up settlement — packages/client/ui-workspace/README.md owns the API',
'agent/request': 'deprecated compatibility hook — packages/core/agent/README.md documents migration',
'command/executed': 'client-face local command acknowledgment — packages/client/ui-commands/README.md owns the API',
'connection/reset': 'client-face transport signal — packages/api/session-controller/README.md owns the API',
@@ -357,13 +363,20 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
CuaApplicationState: 'computer-use.md',
CuaSystemPermission: 'computer-use.md',
CuaSystemPermissionState: 'computer-use.md',
RenderedDocumentBytes: 'office-to-pdf.md',
OfficeToPdfRequest: 'office-to-pdf.md',
OfficeToPdfResult: 'office-to-pdf.md',
OfficeToPdfPriority: 'office-to-pdf.md',
OfficeToPdfGeneration: 'office-to-pdf.md',
RenderedDocumentBytes: 'office-kit.md',
OfficeKitRequest: 'office-kit.md',
OfficeKitResult: 'office-kit.md',
OfficeImagesRequest: 'office-kit.md',
OfficeImagesResult: 'office-kit.md',
OfficeConversionRequest: 'office-kit.md',
OfficeRecalculationRequest: 'office-kit.md',
OfficeFileResult: 'office-kit.md',
OfficeKitPriority: 'office-kit.md',
OfficeKitGeneration: 'office-kit.md',
AddShareSessionsRequest: 'liveshare.md',
CreatedShare: 'liveshare.md',
CreateShareRequest: 'liveshare.md',
ShareSessions: 'liveshare.md',
OwnerIdentityRequest: 'liveshare.md',
OwnerIdentityStatus: 'liveshare.md',
OwnerRelayState: 'liveshare.md',
@@ -398,6 +411,8 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
CreatedWorktree: 'worktrees.md',
CreateWorktreePhase: 'worktrees.md',
RestoreWorktreeRequest: 'worktrees.md',
WorktreeCleanup: 'worktrees.md',
WorktreeCreation: 'worktrees.md',
RestoredWorktree: 'worktrees.md',
ChangeRequestListener: 'forge.md',
ChangeRequestRef: 'forge.md',
@@ -407,6 +422,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
ForgeLineComment: 'forge.md',
ForgeReviewRequest: 'forge.md',
ForgeReviewResult: 'forge.md',
ForgeBaseBranches: 'forge.md',
ForgeBranches: 'forge.md',
ForgeChangeRequestDiff: 'forge.md',
ForgeChangeRequestStatesFrame: 'forge.md',
@@ -743,6 +759,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
SubagentInterruptAuthority: 'subagent.md',
SubagentInterruptReceipt: 'subagent.md',
SubagentListEntry: 'subagent.md',
SubagentMemberNames: 'subagent.md',
SubagentPromptReceipt: 'subagent.md',
SubagentPromptRequest: 'subagent.md',
SubagentProvider: 'subagent.md',
@@ -1023,6 +1040,12 @@ export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
McpServerRegistration: 'plugin-registered server entry is owned by packages/mcp/mcp-manager/README.md',
McpProbeOptions: 'probe options are owned by packages/mcp/mcp-client/README.md',
McpProbeResult: 'probe outcome union is owned by packages/mcp/mcp-client/README.md',
ServerConfig: 'server configuration union is owned by packages/mcp/mcp-client/README.md',
ServerConfigInput: 'server configuration before defaults is owned by packages/mcp/mcp-client/README.md',
StreamableHttpConfig: 'Streamable HTTP server configuration is owned by packages/mcp/mcp-client/README.md',
McpOAuthConfig: 'per-server OAuth configuration is owned by packages/mcp/mcp-client/README.md#oauth',
McpServerInstance: 'server instance mounted by the host is owned by packages/mcp/mcp-client/README.md',
McpOAuthAuthorization: 'explicit authorization owner is owned by packages/mcp/mcp-client/README.md#oauth',
McpOAuthAttemptId: 'authorization attempt identity is owned by packages/mcp/mcp-client/README.md#oauth',
McpOAuthAttemptView: 'authorization progress is owned by packages/mcp/mcp-manager/README.md#oauth-authorization',
AgentPreset: 'discovered preset record is owned by packages/preset/agent-preset-registry/README.md',
@@ -1114,6 +1137,10 @@ export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
TerminalFrame: 'Browser terminal stream frames are owned by packages/api/terminal-controller/README.md',
TerminalRetentionFrame: 'Browser terminal window holds are owned by packages/api/terminal-controller/README.md',
WebTerminalId: 'Browser terminal identity is owned by packages/api/terminal-controller/README.md',
AgentTerminal: 'Agent terminal handles are owned by packages/api/terminal-controller/README.md',
AgentTerminalRequest: 'Agent terminal allocation fields are owned by packages/api/terminal-controller/README.md',
TerminalScreenRequest: 'Browser terminal screen reads are owned by packages/api/terminal-controller/README.md',
TerminalScreenPage: 'Browser terminal screen reads are owned by packages/api/terminal-controller/README.md',
}
/** Repository data policy consumed by the Cordis catalog projector. */
+14 -6
View File
@@ -269,9 +269,9 @@ const SERVICE_ROLES: ServiceRole[] = [
note: 'The native provider owns application consent and cancellation; the optional Client page queries and changes those decisions through its Remote.',
},
{
key: 'officeToPdf', pkg: 'office-to-pdf', title: 'Office to PDF conversion',
mode: 'core', consumers: ['client-ui-sidebar-documentpreview'],
note: 'Authorized Office bytes are converted on the Host using the declared native target engine, or Node WASM when no native target is declared.',
key: 'officeKit', pkg: 'office-kit', title: 'Office rendering, conversion, and recalculation',
mode: 'core', consumers: ['client-ui-sidebar-documentpreview', 'tool-office'],
note: 'Authorized Office bytes are rendered as PDFs or images, converted, or recalculated on the Host using the declared native target engine, or Node WASM when no native target is declared.',
},
{
key: 'attachments',
@@ -712,6 +712,14 @@ const SERVICE_ROLES: ServiceRole[] = [
mode: 'core',
note: 'Reconciles mcp-client instances against its volatile servers configuration, aggregates their connection statuses, and serves restart and probe to management surfaces.',
},
{
key: 'mcpClientHost',
pkg: 'mcp-client',
title: 'MCP client host for a server manager',
mode: 'service',
consumers: ['mcp-manager'],
note: 'An mcp-client entry loaded with host: true validates, mounts, probes, and authorizes servers for the manager, which reaches no other mcp-client value; its servers run below it, so a reload of the MCP client restarts the manager.',
},
{
key: 'mcpAccounts',
pkg: 'client-ui-mcp-account',
@@ -772,7 +780,7 @@ const SERVICE_ROLES: ServiceRole[] = [
pkg: 'terminal',
title: 'Persistent PTY session registry',
mode: 'seam',
implementations: ['terminal-bash'],
implementations: ['terminal-bash', 'terminal-panel'],
consumers: ['tool-terminal'],
note: 'The registry owns exact-Agent session identity and cleanup; backends own terminal mechanics, while tool-terminal exposes the owner-scoped model tools.',
},
@@ -782,7 +790,7 @@ const SERVICE_ROLES: ServiceRole[] = [
title: 'Process-sandbox seam',
mode: 'seam',
implementations: ['sandbox-local', 'sandbox-ssh'],
consumers: ['bash-sandbox', 'terminal-bash'],
consumers: ['bash-sandbox', 'terminal-bash', 'api-terminal-controller'],
note: 'Consumers hand over the exact argv they are about to spawn; same-world backends wrap it under a per-call policy and report enforcement.',
},
{
@@ -791,7 +799,7 @@ const SERVICE_ROLES: ServiceRole[] = [
title: 'Sandbox policy home',
mode: 'core',
implementations: [],
consumers: ['bash-sandbox', 'fs-sandbox', 'terminal-bash'],
consumers: ['bash-sandbox', 'fs-sandbox', 'terminal-bash', 'terminal-panel'],
note: 'The one home for the deployment default mode + workspace root; only the sandboxed executor and provider read the service (the tool layers use the pure `sandbox/mode` fold it also exports). Both enforcing families read it so bash and fs cannot confine to different roots.',
},
{
+3 -3
View File
@@ -1,6 +1,6 @@
/**
* Generate the loadable-plugin package list shipped inside the
* `cordis-composition-reference` skill from the workspace manifests and the
* `dsh-doc` skill from the workspace manifests and the
* config-catalog classification. `--check` exits 1 when the committed file is stale.
*/
@@ -9,7 +9,7 @@ import { resolve } from 'node:path'
import { collectConfigCatalog, type CatalogEntry } from './gen-config-catalog.ts'
const root = resolve(import.meta.dirname, '..')
const OUT = 'packages/preset/agent-preset/skills/cordis-composition-reference/references/packages.md'
const OUT = 'packages/preset/agent-preset/skills/dsh-doc/references/packages.md'
interface Row {
pkg: string
@@ -42,7 +42,7 @@ export function render(entries: readonly CatalogEntry[]): string {
'',
'This file is GENERATED from workspace manifests (`scripts/gen-plugin-packages.ts`) and verified fresh by `pnpm run verify-plugin-packages` (part of `doc-sync`); do not edit it by hand.',
'',
'Every package below exports a Cordis plugin that a bundle patch can name in a Loader row. `Config` marks packages whose row accepts a `config` mapping; query `Config.listConfigs` through `cordis_inspect_query` (filter by `name`, then query the `entry` id) for the mounted schema. Packages under `experimental` are pre-stable.',
'Every package below exports a Cordis plugin that a bundle patch can name in a Loader row. `Config` marks packages whose row accepts a `config` mapping; read the mounted schema from `Config.listConfigs` through `cordis_inspect_query` (filter by `name`, then query the `entry` id) when available, otherwise from the package README. Packages under `experimental` are pre-stable.',
'',
]
let group = ''
+35 -2
View File
@@ -13,6 +13,7 @@ import LlmRuntime from '@deepseek-ai/dsh-llm'
import type { ToolSchema } from '@deepseek-ai/dsh-llm'
import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type OfficeKit from '@deepseek-ai/dsh-office-kit'
import { createScope } from '@deepseek-ai/dsh-scope'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import SessionPersistence from '@deepseek-ai/dsh-session-persistence'
@@ -56,11 +57,13 @@ 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 ToolPresent from '@deepseek-ai/dsh-tool-present'
import * as ToolOffice from '@deepseek-ai/dsh-tool-office'
import * as ToolFs from '@deepseek-ai/dsh-tool-fs'
import * as ToolFsSearch from '@deepseek-ai/dsh-tool-fs-search'
import * as ToolStrReplaceEditor from '@deepseek-ai/dsh-tool-str-replace-editor'
import TerminalSessionService from '@deepseek-ai/dsh-terminal'
import * as ToolPty from '@deepseek-ai/dsh-tool-terminal'
import * as TerminalPanel from '@deepseek-ai/dsh-terminal-panel'
import * as ToolGoal from '@deepseek-ai/dsh-tool-goal'
import * as ToolSchedule from '@deepseek-ai/dsh-tool-schedule'
import ScheduleService from '@deepseek-ai/dsh-schedule'
@@ -296,7 +299,7 @@ const TOOL_PACKAGES: ToolPackage[] = [
await ctx.plugin(NodePtcRuntime)
},
note:
'The PTC executor exposes only run_code to the model and declares other visible capabilities in a generated SDK in the runtime’s language. Program bindings enter the shared guarded tool pipeline in submission order; concurrency-safe bodies overlap up to maxParallelSubCalls, and nested results remain linked to the outer program.',
'The PTC executor exposes only run_code to the model and declares other visible capabilities in a generated SDK in the runtime’s language. Program bindings enter the shared guarded tool pipeline in submission order; concurrency-safe bodies overlap up to maxParallelSubCalls, and nested results remain linked to the outer program. The resolved timeout and maxSubCallsPerMinute set the total call allowance; exceeding it terminates the program.',
},
{
pkg: '@deepseek-ai/dsh-plan-mode',
@@ -329,6 +332,20 @@ const TOOL_PACKAGES: ToolPackage[] = [
note:
'The bash tool is the model-facing consumer of the bash executor seam. With a job registry composed every call registers with the generic `ctx.jobs` runtime as it starts, collected/stopped through the `job_*` tools from `@deepseek-ai/dsh-tool-jobs`; without one, or with `enableRunInBackground: false`, the tool registers a foreground-only schema without the `run_in_background` parameter.',
},
{
pkg: '@deepseek-ai/dsh-tool-office',
dir: 'tool-office',
source: 'packages/document/tool-office/src/index.ts',
requires: ['ctx.workingDirectory', 'ctx.tools', 'ctx.fs', 'ctx.agents', 'ctx.officeKit', 'ctx.attachments and ctx.llm for office_render'],
writes: ['tool/call', 'tool/result with rendered image attachments', 'temporary converted files in the Office kit output store'],
async mount(ctx) {
// Schema harvest never renders or converts a document.
ctx.provide('officeKit', {} as OfficeKit)
await ctx.plugin(AgentRegistry)
await ctx.plugin(ToolOffice)
},
note: 'Declared to an Agent from the step after it successfully loads an Office skill, and kept while the previous request header declares an Office tool. Admitted calls fail with the Office service\'s unavailable error when LibreOffice Kit is not installed.',
},
{
pkg: '@deepseek-ai/dsh-tool-present',
dir: 'tool-present',
@@ -458,6 +475,22 @@ const TOOL_PACKAGES: ToolPackage[] = [
note:
'The six terminal tools are opt-in and complement one-shot shell/filesystem tools. `terminal_send(run_in_background: true)` registers with `ctx.jobs`; TUI, named key sequences, BEL, resize, auto-start, and cross-agent sharing are absent from the schema.',
},
{
pkg: '@deepseek-ai/dsh-terminal-panel',
dir: 'terminal-panel',
source: 'packages/experimental/terminal-panel/src/tools.ts',
requires: ['ctx.tools', 'ctx.systemPrompt', 'ctx.terminals', 'ctx.terminalController', 'ctx.sandboxPolicy', 'a calling Agent'],
writes: ['tool/call', 'tool/result'],
async mount(ctx) {
// Schema harvest never opens or reads a terminal.
ctx.provide('terminalController', {} as Context['terminalController'])
await ctx.plugin(SandboxPolicy)
await ctx.plugin(TerminalSessionService)
await ctx.plugin(TerminalPanel, TerminalPanel.Config({}))
},
note:
'The package also serves the six `terminal_*` tools from Web sidebar terminals. `user_terminal_list` and `user_terminal_read` only read terminals the user controls; `readUserTerminals: false` removes both.',
},
{
pkg: '@deepseek-ai/dsh-tool-goal',
dir: 'tool-goal',
@@ -583,7 +616,7 @@ const TOOL_PACKAGES: ToolPackage[] = [
await ctx.plugin(ToolSubagent, { provider: 'mock', modelDiscovery: true })
},
note:
'The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns a child id promptly; local children accept follow-ups, while external backends report their single execution automatically.',
'The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns the child\'s name promptly; local children accept follow-ups, while external backends report their single execution automatically.',
},
{
pkg: '@deepseek-ai/dsh-tool-subagent-control',
+19 -6
View File
@@ -1,3 +1,4 @@
import { expectDesktopArchive } from './desktop-archive-workflow-test.ts'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import yaml from 'js-yaml'
@@ -24,8 +25,16 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
}>
}
it('archives using the same persistent pnpm store as packaging', () => {
const cache = (job: string) => workflow.jobs[job]!.steps.find(step => step.name === 'Configure persistent package caches')
expect(cache('upload-artifact')).toEqual(cache('package'))
expect(cache('upload-artifact')?.run).toContain('PNPM_CONFIG_STORE_DIR=')
})
it('confines signed Mac packaging to manual dispatch and a dedicated Apple Silicon runner', () => {
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
expect(workflow.jobs.package!.env.PACKAGE_VERSION_MODE).toBe("${{ inputs.version_mode == 'follow-dsh' && 'product' || inputs.version_mode == 'build-number' && 'auto' || inputs.version_mode }}")
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { version_mode: { default: 'default', options: ['default', 'follow-dsh', 'build-number', 'manual'] } } })
expect(workflow.jobs.package).not.toHaveProperty('name')
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { test_release_id: { type: 'string', default: '', required: false } } })
expect(workflow.on.workflow_dispatch).not.toHaveProperty('inputs.publish')
@@ -36,11 +45,14 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
expect(steps.find(step => step.id === 'checkout')?.with).toMatchObject({ 'persist-credentials': false, clean: true })
for (const step of steps) expect(step.run ?? '').not.toContain('${{ inputs.')
const uploads = steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(2)
expect(uploads).toHaveLength(1)
const archive = workflow.jobs['upload-artifact']!
expect(archive['runs-on']).toEqual(['self-hosted', '${{ needs.package.outputs.runner }}'])
const installer = archive.steps.find(step => step.uses?.startsWith('actions/upload-artifact@'))!
expect(uploads[0]?.if).toBe("always() && steps.checkout.outcome == 'success'")
expect(uploads[1]?.if).toBe('success()')
expect(uploads[1]?.with?.path).toBe('${{ steps.retained.outputs.directory }}/*')
expect(uploads[1]?.with?.['compression-level']).toBe(0)
expect(installer.if).toBe('success()')
expect(installer.with?.path).toBe('${{ steps.archive.outputs.path }}')
expect(installer.with).toMatchObject({ archive: false, overwrite: true, name: '${{ env.DESKTOP_ARCHIVE_NAME }}' })
})
it('defaults to notarization and labels the explicit debugging option', () => {
@@ -50,7 +62,6 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
} } })
const steps = workflow.jobs.package!.steps
expect(steps.filter(step => step.run?.includes('args+=(--skip-notarization)'))).toHaveLength(2)
expect(steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain('${{ steps.settings.outputs.mode }}')
})
it('retains build inputs outside checkout and run-specific pnpm installations', () => {
@@ -85,13 +96,15 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
})
it('passes the same target to preparation, packaging and retention', () => {
const archive = workflow.jobs['upload-artifact']!
expectDesktopArchive(archive, 1)
const job = workflow.jobs.package!
expect(job.env.DSH_DESKTOP_TARGET_PLATFORM).toBe('darwin')
expect(job.env.DSH_DESKTOP_TARGET_ARCH).toBe(arch)
const builds = job.steps.filter(step => step.run?.includes('pnpm run package:desktop:mac:'))
expect(builds).toHaveLength(2)
for (const step of builds) expect(step.run).toContain(`package:desktop:mac:${arch}`)
expect(job.steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain(`macos-${arch}-`)
expect(archive.env.DESKTOP_ARCHIVE_NAME).toBe('macos-' + arch + '-${{ needs.package.outputs.mode }}-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}.zip')
if (arch === 'x64') {
const rosetta = job.steps.findIndex(step => step.run === 'arch -x86_64 /usr/bin/true')
expect(rosetta).toBeGreaterThan(-1)
+2 -8
View File
@@ -20,9 +20,6 @@
"apps/cli/tests/web-auth.e2e.ts": {
"a2b9a35fdf6552ba148d15436c9b3f98ed5763a2b91a95f579b951fd6613e75c": 1
},
"apps/desktop-host/tests/office.spec.ts": {
"3f8653cd87f99ebd70765379dae51ab308ed9c280e831d39e1abd469bfcdc6e3": 1
},
"apps/desktop/scripts/installed-update-qualification.ts": {
"5a8270cf9b1e554ae0cff6eaf7086e44c22f61a08e5f91dc7e1397eccaa726a5": 2
},
@@ -350,7 +347,7 @@
"2e78263d16d54ccfd8d322bcdf1bf738bd8134e15c24063ece9a1d1b52f4ebd9": 1
},
"packages/bundle/web-app/tests/document-conversion.e2e.ts": {
"743a7488a765c578e607d08ba6bdcf6f2f2971f67b05a42d5097aad2458134a1": 1
"95057a87f4a7358284982d7c73febfe26aed9f37a4ceb5b8df724f2b6bc1084c": 1
},
"packages/bundle/web-app/tests/document-preview.spec.ts": {
"154da39139a0074bad3d13a624e5fa62d1f7ce19dc8b9c28a73af3263cd7f10e": 1
@@ -964,7 +961,7 @@
"packages/deliverables/workspace-changes/tests/loader-composition.spec.ts": {
"59c63f734e8bba862325f776e3fcbebd78a84cfb4161f8df41c216950d9bf351": 1
},
"packages/document/office-to-pdf/tests/queue.spec.ts": {
"packages/document/office-kit/tests/queue.spec.ts": {
"bbe31b89b81048bb47c7158e78670deec5f2973286f9abc591290a8fdd851cf1": 1
},
"packages/experimental/browser-use-runtime/src/index.ts": {
@@ -1449,9 +1446,6 @@
"746ebc5aade01a50cc9a74fc07b1023addf021aef80b62c069a437ac140c9e64": 1,
"c920d88f6eb309ef5991608642a1ab0fd972690538b33c34d86c68d07ddd6edf": 1
},
"packages/session-query/session-log-export/tests/dialog.client.spec.tsx": {
"a9b1969d76db0b05f87c862956f8ff45c52f1f4a5b32a206339de0c9fee99a77": 1
},
"packages/session-query/session-log-export/tests/loader-composition.host.spec.ts": {
"59c63f734e8bba862325f776e3fcbebd78a84cfb4161f8df41c216950d9bf351": 1,
"e12d49327a6708ae3ace371e28ed0deb471dc8895c584ba94a86af344c15cec3": 1
+5 -6
View File
@@ -144,7 +144,7 @@ describe('optional bundles', () => {
}
})
it('offers the forge panel and model worktree tool together with their separate worktree services', () => {
it('offers the forge panel and model worktree tool together over one worktree service', () => {
const name = '@deepseek-ai/dsh-experimental-forge-bundle'
expect(OPTIONAL_BUNDLES).toContain(name)
for (const template of Object.values(PROFILE_TEMPLATES)) expect(template.bundles).not.toContain(name)
@@ -159,9 +159,8 @@ describe('optional bundles', () => {
expect(flattenRows(composeEntries(shipped)).some(row => row.name === moduleName)).toBe(false)
expect(rows.filter(row => row.name === moduleName && row.disabled !== true)).toHaveLength(1)
}
const group = composeEntries([...shipped, bundle(name).patches]).find(row => row.id === 'optional-forge-panel')
expect(group?.isolate).toEqual({ worktrees: true })
expect(rows.filter(row => row.name === '@deepseek-ai/dsh-experimental-worktree')).toHaveLength(2)
expect(composeEntries([...shipped, bundle(name).patches]).some(row => row.name === 'cordis:group' && row.id === 'optional-forge-panel')).toBe(false)
expect(rows.filter(row => row.name === '@deepseek-ai/dsh-experimental-worktree')).toHaveLength(1)
})
it('keeps the existing tool and panel row overrides addressable in the unified bundle', () => {
@@ -170,12 +169,12 @@ describe('optional bundles', () => {
const composed = composeEntries([...shipped, bundle('@deepseek-ai/dsh-experimental-forge-bundle').patches, [
{ id: 'worktree', config },
{ id: 'tool-worktree', disabled: true },
{ id: 'optional-forge-panel', disabled: true },
{ id: 'forge-panel', disabled: true },
]], message => warnings.push(message))
expect(warnings).toEqual([])
expect(composed.find(row => row.id === 'worktree')?.config).toEqual(config)
expect(composed.find(row => row.id === 'tool-worktree')?.disabled).toBe(true)
expect(composed.find(row => row.id === 'optional-forge-panel')?.disabled).toBe(true)
expect(composed.find(row => row.id === 'forge-panel')?.disabled).toBe(true)
})
it('ships all five lightweight bundles without selecting them in a default template', () => {
+37 -7
View File
@@ -1,17 +1,46 @@
/**
* Executable lint checks use private copies of repository sources and configuration.
* Process-spawning cases set Vitest's case timeout to 90 seconds, including
* plain local runs without a CI override. Configuration-only cases keep the default.
*/
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 { existsSync, globSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { cp, lstat, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises'
import { basename, join, relative } from 'node:path'
import { fileURLToPath } from 'node:url'
import { flattenDiagnosticMessageText, parseConfigFileTextToJson } from 'typescript'
import { describe, expect, it } from 'vitest'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
const repositoryRoot = fileURLToPath(new URL('..', import.meta.url))
const sourceRepositoryRoot = fileURLToPath(new URL('..', import.meta.url))
let repositoryRoot = ''
// Probes belong to a private copy: repository compiler scans run in other workers and processes.
beforeAll(async () => {
repositoryRoot = await mkdtemp(join(tmpdir(), 'dsh-oxlint-contract-'))
repositoryRoot = await realpath(repositoryRoot)
const files = [
...globSync('tsconfig*.json', { cwd: sourceRepositoryRoot }),
'.oxlintrc.json', '.oxlintrc.staged.json', 'package.json', 'lefthook.yml',
'apps', 'native', 'packages', 'python', 'scripts', 'vendor', 'website',
]
for (const path of files) {
await cp(join(sourceRepositoryRoot, path), join(repositoryRoot, path), {
recursive: true,
async filter(source) {
if (['node_modules', 'lib', '.typecheck'].includes(basename(source))) return false
return (await lstat(source)).isDirectory() || /\.(?:json|[cm]?[jt]sx?)$/u.test(source) || source.endsWith('lefthook.yml')
},
})
}
await symlink(join(sourceRepositoryRoot, 'node_modules'), join(repositoryRoot, 'node_modules'),
process.platform === 'win32' ? 'junction' : 'dir')
}, 90_000)
afterAll(async () => {
if (repositoryRoot !== '') await rm(repositoryRoot, { recursive: true, force: true })
}, 90_000)
const oxlintCli = fileURLToPath(new URL('../node_modules/oxlint/bin/oxlint', import.meta.url))
const tsxCli = fileURLToPath(new URL('../node_modules/tsx/dist/cli.mjs', import.meta.url))
@@ -24,7 +53,7 @@ function isUnknownArray(value: unknown): value is unknown[] {
}
function runRepositoryOxlint(args: readonly string[], env: NodeJS.ProcessEnv = {}) {
return spawnSync(process.execPath, [tsxCli, 'scripts/run-oxlint.ts', ...args], {
return spawnSync(process.execPath, [tsxCli, join(sourceRepositoryRoot, 'scripts/run-oxlint.ts'), ...args], {
cwd: repositoryRoot,
encoding: 'utf8',
env: { ...process.env, NO_COLOR: '1', ...env },
@@ -76,6 +105,7 @@ probePromise()
const path = join(repositoryRoot, parent, `oxlint-contract-${suffix}${extension}`)
await writeFile(path, source)
paths.push([label, relative(repositoryRoot, path), tsconfig])
expect(existsSync(join(sourceRepositoryRoot, relative(repositoryRoot, path)))).toBe(false)
}
const clientScript = 'scripts/client-bundle-purity.spec.ts'
@@ -223,7 +253,7 @@ export const longProbe = 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 +
)
expect(packageJson.devDependencies).not.toHaveProperty('eslint')
expect(packageJson.devDependencies).not.toHaveProperty('@typescript-eslint/parser')
expect(existsSync(join(repositoryRoot, 'eslint.format.config.mjs'))).toBe(false)
expect(existsSync(join(sourceRepositoryRoot, 'eslint.format.config.mjs'))).toBe(false)
const lefthook = await readFile(join(repositoryRoot, 'lefthook.yml'), 'utf8')
expect(lefthook).toContain('scripts/run-oxlint.ts --config .oxlintrc.staged.json --fix')
+1 -1
View File
@@ -84,7 +84,7 @@ const PEER_REQUIRED_HOST_EXPORTS = {
'@deepseek-ai/dsh-experimental-translator': ['TranslationError'],
// Stateless; a safe classification would turn the forge panel's forge and worktree peers into dependencies.
'@deepseek-ai/dsh-experimental-forge': ['changeRequestKey'],
'@deepseek-ai/dsh-experimental-worktree': ['generatedWorktreeName'],
'@deepseek-ai/dsh-experimental-worktree': ['generatedWorktreeName', 'CREATED_RECORD', 'createdWorktreeSchema'],
// The forge panel matches ctx.fs failures with `instanceof FsError`.
'@deepseek-ai/dsh-fs': ['FsError'],
'@deepseek-ai/dsh-scope': ['carrierKeyOf', 'createScope', 'scopeOf', 'scopeTarget'],
+266
View File
@@ -0,0 +1,266 @@
/**
* Value exports that plugin entries already had when verify-plugin-entry-exports started enforcing the plugin entry
* rule in docs/defensive-patterns/package-surface.md. Each line records existing debt, not an approved exception. The
* gate passes a listed export and fails a line when its package has no plugin entry, when its export list is empty or
* repeats a name, or when it names an export the entry no longer reports, so removing an export removes its line in
* the same change. A line added after the gate's introduction is an exception under the rule, and the rule requires
* the domain owner's confirmation for it.
*/
export const EXISTING_PLUGIN_ENTRY_EXPORTS = {
'@deepseek-ai/dsh-acp-app': ['ACP_APP_STARTUP_SERVICE'],
'@deepseek-ai/dsh-action-cards': ['Config', 'isPluginStopping'],
'@deepseek-ai/dsh-agent': [
'AgentModel', 'agentCarrier', 'agentEvents', 'assembleContextFor', 'emitAgentEvent', 'foldConsumedWork',
'installModelSelection', 'modelSelectionProjectionDefinition',
],
'@deepseek-ai/dsh-agent-instructions': [
'discoverBaselineInstructionFiles', 'loadBaselineInstructions', 'renderAgentInstructions',
],
'@deepseek-ai/dsh-agent-loop': ['CONFIGURED_AGENT_IDENTITIES_KEY', 'DEFAULT_MAX_PARALLEL_TOOL_CALLS'],
'@deepseek-ai/dsh-agent-preset-registry': [
'agentPresetProjectionDefinition', 'auditRows', 'entryListProblem', 'leakedServices',
],
'@deepseek-ai/dsh-agent-team': ['TeamId', 'TeamMessageId', 'TeamTaskId'],
'@deepseek-ai/dsh-api-remote-access': ['REMOTE_ACCESS_SNAPSHOT_KEY'],
'@deepseek-ai/dsh-api-remotes': ['API_REMOTE_FORWARDED_EVENTS'],
'@deepseek-ai/dsh-attachment-local': [
'DEFAULT_IMAGE_COMPRESSION_CONCURRENCY', 'DEFAULT_MAX_IMAGES_PER_MESSAGE', 'DEFAULT_MAX_IMAGE_BYTES',
'DEFAULT_MAX_IMAGE_DIMENSION', 'DEFAULT_MAX_IMAGE_PIXELS', 'DEFAULT_MAX_MESSAGE_IMAGE_BYTES',
'DEFAULT_NORMALIZED_IMAGE_MAX_BYTES', 'DEFAULT_NORMALIZED_IMAGE_MAX_DIMENSION',
'DEFAULT_NORMALIZED_IMAGE_MAX_PIXELS', 'MAX_IMAGE_COMPRESSION_CONCURRENCY', 'canPassThroughNormalization',
'commitPreparedImageFile', 'normalizeImage', 'prepareImageFile', 'readImageFile', 'readRequestImageFile',
'requestImageVariantId', 'saveImageFile', 'validateImageFile',
],
'@deepseek-ai/dsh-bash-local': ['ENV_OVERRIDES', 'assertServiceableBashConfig'],
'@deepseek-ai/dsh-client-connection': [
'API_PATH', 'CONNECT_PATH', 'Peer', 'RpcId', 'clientRequestSchema', 'rpcErrorSchema', 'rpcIdSchema',
'rpcMessageSchema', 'rpcResultSchema', 'serverResponseSchema', 'transportError',
],
'@deepseek-ai/dsh-client-hmr': ['EVENTS_ENDPOINT'],
'@deepseek-ai/dsh-client-locale': ['LOCALE_IDS', 'LOCALE_PREFERENCE_FIELD', 'LOCALE_SETTINGS_NAMESPACE'],
'@deepseek-ai/dsh-client-modules': ['bootInjections', 'orderByModuleGraph', 'stripClientSuffix'],
'@deepseek-ai/dsh-client-ui-chat': [
'CHAT_SETTINGS_NAMESPACE', 'DEFAULT_TRANSCRIPT_VIEW_MODE', 'LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE',
'LEGACY_TRANSCRIPT_VIEW_MODE', 'TRANSCRIPT_VIEW_FIELD', 'TRANSCRIPT_VIEW_MODES',
],
'@deepseek-ai/dsh-client-ui-conversation': [
'BUSY_ENTER_BEHAVIORS', 'BUSY_ENTER_FIELD', 'CONVERSATION_SETTINGS_NAMESPACE', 'DEFAULT_BUSY_ENTER_BEHAVIOR',
],
'@deepseek-ai/dsh-client-ui-theme': [
'DEFAULT_FONT_SIZE', 'DEFAULT_PREFERENCE', 'FONT_SIZE_FIELD', 'FONT_SIZE_MAX', 'FONT_SIZE_MIN', 'THEME_PREFERENCES',
'THEME_PREFERENCE_FIELD', 'THEME_SETTINGS_NAMESPACE',
],
'@deepseek-ai/dsh-command-feedback': ['FEEDBACK_CATEGORIES', 'recordFeedback'],
'@deepseek-ai/dsh-commands': ['CommandDefinitionId', 'CommandId', 'name', 'parseCommand'],
'@deepseek-ai/dsh-compaction-tool-result-pruner': ['DEFAULTS', 'PRUNE_MARKER', 'codePointLength', 'resolveConfig'],
'@deepseek-ai/dsh-cordis-host-runner': [
'ApprovalRequestId', 'CordisDynamicPackageId', 'CordisDynamicPluginId', 'CordisDynamicPluginRunId',
],
'@deepseek-ai/dsh-credentials-local': [
'CREDENTIALS_FILENAME', 'DOCUMENT_VERSION', 'parseCredentialsDocument', 'renderFlatLayoutMigration', 'resolveSpec',
],
'@deepseek-ai/dsh-cua': ['CuaConfig', 'installCua'],
'@deepseek-ai/dsh-deepseek-account-platform': ['Config'],
'@deepseek-ai/dsh-experimental-claude-code-mods': [
'DEFAULT_TOOL_ALIASES', 'KNOWN_EVENTS', 'MODS_API_VERSION', 'SERVED_EVENTS', 'defineMod',
],
'@deepseek-ai/dsh-experimental-cua-macos': ['GUIDANCE'],
'@deepseek-ai/dsh-experimental-forge': ['changeRequestKey'],
'@deepseek-ai/dsh-experimental-inspector': ['resolveInspectorOptions', 'startInspector'],
'@deepseek-ai/dsh-experimental-ptc-runtime-python': [
'checkDoneValue', 'detachResidual', 'encodeJsonPlain', 'hasNonLosslessNumber', 'hasUnsafeIntegerToken',
'hostFrameParseCeiling', 'logTruncationMarker', 'readProcessStart', 'resolvePythonBin', 'validateChildFrame',
],
'@deepseek-ai/dsh-experimental-worktree': [
'CREATED_RECORD', 'createdWorktreeSchema', 'generatedWorktreeName', 'worktreeProjection',
],
'@deepseek-ai/dsh-file-reference-local': [
'DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES', 'DEFAULT_FILE_SEARCH_MAX_ENTRIES', 'DEFAULT_FILE_SEARCH_MAX_RESULTS',
'FILE_REFERENCE_PROMPT', 'WorkspaceFileSearch', 'activeAtToken', 'formatFileMention',
],
'@deepseek-ai/dsh-goal': [
'GOAL_CHANGE_VERSION', 'GoalId', 'applyGoalProjection', 'decodeGoalChange', 'foldGoal', 'goalChangeRef',
'goalProjectionDefinition',
],
'@deepseek-ai/dsh-goal-round-driver': ['renderGoalRoundPrompt'],
'@deepseek-ai/dsh-host-directory-picker-auto': [
'BACKEND_PACKAGES', 'SURFACE_PACKAGES', 'canExecute', 'hasLinuxChooserBinary', 'resolveDirectoryPickerBackend',
],
'@deepseek-ai/dsh-host-directory-picker-browse': ['boundedInsert', 'fullyQualified', 'raceAbort'],
'@deepseek-ai/dsh-host-directory-picker-native': ['pickNativeDirectory'],
'@deepseek-ai/dsh-host-plugin-inventory': ['pluginEntryId', 'readPluginInventory'],
'@deepseek-ai/dsh-host-product-telemetry-otel': ['Config'],
'@deepseek-ai/dsh-host-webserver': [
'bindUrlHost', 'isLoopbackHost', 'isWildcardHost', 'normalizeBindAddress', 'renderIndexInjections',
],
'@deepseek-ai/dsh-jobs-local': ['TASK_WAIT_TIMEOUT'],
'@deepseek-ai/dsh-llm': [
'ACCOUNT_QUOTA_EXCEEDED_CODE', 'APP_IDENTITY', 'AssistantStreamAccumulator', 'BlockAssembler',
'CONTEXT_SUMMARY_MAX_CHARS', 'CONTEXT_WINDOW_EXCEEDED_CODE', 'EMPTY_RESPONSE_CODE', 'IMAGE_OFFLOAD_REQUIRED_CODE',
'INVALID_CREDENTIAL_CODE', 'LLM_FAILURE_CODES', 'LlmAdapter', 'LlmAttemptId', 'MessageId', 'ProviderRequestId',
'QUOTA_EXCEEDED_CODE', 'RETRY_CODE_CHOICES', 'ReasoningEffortId', 'RetryPolicySchema', 'ToolCallId',
'assembleAssistantStream', 'assertUsableApiKey', 'assistantStreamChunks', 'assistantStreamFirstTokenTime',
'assistantStreamHasVisibleContent', 'assistantStreamHasVisibleText', 'attributionHeaders', 'boundContextSummary',
'callConfigEquals', 'chunkHasVisibleText', 'contentHasFile', 'contentHasImage', 'createAssistantMessage',
'createDeveloperMessage', 'createMessage', 'createSystemMessage', 'createToolResultMessage', 'createUserMessage',
'errorChain', 'expandAssistantStream', 'fileHandleText', 'freezeMessage', 'isAgentLoopRequest',
'isContextWindowExceededError', 'isHarnessError', 'isQuotaExceededError', 'isTokenDelta', 'isVisibleChunk',
'joinAssistantStreamText', 'lastAssistantStreamChunk', 'markAgentLoopRequest', 'normalizeApiKey',
'offloadedImageText', 'projectFilesToText', 'projectImagesForTextModel', 'projectOffloadedImages',
'projectToolUpdates', 'requestImageHandleText', 'requiredImageOffload', 'resolveImageAttachmentAccess',
'resolveRetryPolicy', 'runFirstTokenTime', 'runFirstVisibleTime', 'textOnlyImageText', 'userAgent',
],
'@deepseek-ai/dsh-llm-deepseek-account': ['plainAccountOptions', 'resolveAccountOptions'],
'@deepseek-ai/dsh-llm-deepseek-api-key': ['plainOptions', 'resolveAdapterOptions'],
'@deepseek-ai/dsh-llm-pi-ai': ['PiAiAdapter', 'recordKeyFor', 'supportedProtocols'],
'@deepseek-ai/dsh-llm-replay': [
'deriveReplayScript', 'installLlmReplay', 'loadReplayScript', 'loadSessionScripts', 'parseSessionHeader',
'parseSessionLog', 'prepareSessionSnapshotFixtureForComparison', 'resolveScriptedEntry',
],
'@deepseek-ai/dsh-llm-retry': ['RetryId'],
'@deepseek-ai/dsh-lsp': ['LspProviderId', 'finalExtension'],
'@deepseek-ai/dsh-lsp-stdio': [
'LspConnection', 'LspInstance', 'MessageDecoder', 'canonicalizeWorkspace', 'encodeMessage',
'negotiatePositionEncoding', 'normalizeHover', 'normalizeLocations', 'readHostSource', 'requestMethod',
'supportsOperation', 'supportsTransientOpen',
],
'@deepseek-ai/dsh-mcp-client': ['createMcpToolDefinition'],
'@deepseek-ai/dsh-office-kit': ['Config', 'OfficeKitGeneration', 'OfficeKitKey', 'OfficeSourceKey'],
'@deepseek-ai/dsh-permission-presets': ['AUTO_PRESET', 'CUSTOM_PRESET'],
'@deepseek-ai/dsh-persona': ['PERSONA_PREFIX_SECTION', 'PERSONA_SUFFIX_SECTION'],
'@deepseek-ai/dsh-plan-mode': ['EXIT_PLAN_MODE', 'planProjectionDefinition', 'resolveConfig'],
'@deepseek-ai/dsh-plugin-manager': ['classifyInstallFailure', 'parseInstallSpec', 'pinnedGitOrigin'],
'@deepseek-ai/dsh-pwsh-local': [
'ENCODING_PREAMBLE', 'ENV_OVERRIDES', 'assertServiceablePwshConfig', 'candidatePwshPaths', 'resolvePwshPath',
],
'@deepseek-ai/dsh-sandbox-policy': ['SANDBOX_MODES', 'setSandboxMode'],
'@deepseek-ai/dsh-schedule': [
'DEFAULT_LIST_LIMIT', 'MAX_LIST_LIMIT', 'MAX_TITLE_LENGTH', 'MIN_EVERY_INTERVAL_SECONDS', 'REQUIRED_TITLE_MESSAGE',
'ScheduleId', 'canonicalizeCronExpression', 'createAfterScheduleRecord', 'createAtScheduleRecord',
'createCronScheduleRecord', 'createDailyScheduleRecord', 'createEveryScheduleRecord', 'createWeeklyScheduleRecord',
'decodeScheduleRecord', 'formatScheduleLocalTime', 'isRecurringScheduleRecord', 'normalizeWeekdays',
'parseCronInput', 'parseWeeklyInput', 'renderRecurringReminderBatchFraming', 'renderReminderFraming',
'resolveCronOccurrence', 'resolveDailyOccurrence', 'resolveEveryOccurrence', 'resolveRecurringOccurrence',
'resolveWeeklyOccurrence', 'scheduleDomain', 'scheduleTitle', 'weeklyTime',
],
'@deepseek-ai/dsh-sdk-app': ['SDK_APP_STARTUP_SERVICE'],
'@deepseek-ai/dsh-sdk-jsonrpc-server': ['HarnessSdkJsonRpcServer'],
'@deepseek-ai/dsh-session': [
'KNOWN_SESSION_EVENT_TYPES', 'SESSION_FORMAT_VERSION', 'Session', 'SessionId', 'SessionLogOffset',
'SessionPreparation', 'SessionSeq', 'TOOL_NOT_STARTED', 'TOOL_OUTCOME_UNKNOWN', 'ToolCallRecovery',
'adoptSessionEvent', 'appendPluginRecord', 'buildForkSeed', 'canonicalHeader', 'decodeSeqRanges',
'deriveEventMessage', 'encodeSeqRanges', 'foldRequestHeader', 'foldSurface', 'headerEquals',
'interruptedTurnClosers', 'isAppendSurfaceEvent', 'isReplacementSurfaceEvent', 'isSurfaceEligibleType',
'isSurfaceEvent', 'pluginRecordOf', 'snapshotSessionEvent',
],
'@deepseek-ai/dsh-session-log-deepseek': ['acceptedThrough'],
'@deepseek-ai/dsh-session-log-export': [
'DEFAULT_SESSION_LOG_COMPRESSION_LEVEL', 'SESSION_LOG_EXPORT_PATH', 'SESSION_LOG_FILENAME', 'flushLiveSessionLog',
'formatSessionMarkdown', 'readSessionLogText', 'serializeSessionLog', 'sessionLogExportDeps',
'sessionLogZipEntries', 'sessionLogZipFilename', 'streamSessionLogZip',
],
'@deepseek-ai/dsh-session-persistence-jsonl': ['JsonlCompressionSchema'],
'@deepseek-ai/dsh-session-projection-cache': [
'Config', 'checkpointIdentity', 'checkpointRecord', 'checkpointRow', 'projectionCacheDomainSpec',
],
'@deepseek-ai/dsh-session-query-sqlite': [
'SESSION_QUERY_SQLITE_APPLICATION_ID', 'SESSION_QUERY_SQLITE_DEFAULT_LIMIT', 'SESSION_QUERY_SQLITE_MAX_LIMIT',
'SESSION_QUERY_SQLITE_PATH_KEY', 'SESSION_QUERY_SQLITE_SCHEMA_VERSION', 'SESSION_QUERY_SQLITE_SNIPPET_CHARS',
],
'@deepseek-ai/dsh-session-reference': [
'DEFAULT_CANDIDATE_LIMIT', 'DEFAULT_MAX_REFERENCE_BYTES', 'MAX_REFERENCES', 'SESSION_REFERENCE_SCHEME',
'decodeSessionReferenceUri', 'encodeSessionReferenceUri', 'formatSessionReferenceMention',
'parseSessionReferenceText',
],
'@deepseek-ai/dsh-session-telemetry-otel': [
'Config', 'DEFAULT_SHUTDOWN_TIMEOUT_MILLIS', 'DEFAULT_TELEMETRY_MODE', 'SessionTelemetryMode',
],
'@deepseek-ai/dsh-session-title': [
'SessionTitleProviderId', 'fallbackSessionTitle', 'foldSessionTitle', 'normalizeSessionTitle',
'titleProjectionDefinition', 'truncateTitleUtf8',
],
'@deepseek-ai/dsh-settings': ['redactSecrets'],
'@deepseek-ai/dsh-skill': [
'BUNDLED_SKILL_RANK', 'escapeText', 'isModelInvocable', 'isSkillName', 'isUserInvocable', 'renderSkillContent',
],
'@deepseek-ai/dsh-skill-filesystem': ['FileSystemSkillProvider'],
'@deepseek-ai/dsh-spill-local': [
'DEFAULT_ROOT_PREFIX', 'discoverDefaultRoots', 'encodeSegment', 'isErrno', 'privateRoot', 'saveTextFile',
'sessionDir', 'sweepSpillRoots',
],
'@deepseek-ai/dsh-storage': ['BackendRegistry', 'UNIT_NAME_RE', 'storageBackendServiceKey'],
'@deepseek-ai/dsh-storage-domain': ['DomainFacility', 'defineDomain', 'descriptorOf', 'domainTable'],
'@deepseek-ai/dsh-storage-json': ['JsonStorageBackend'],
'@deepseek-ai/dsh-storage-sqlite': ['STORAGE_SQLITE_SCHEMA_VERSION', 'SqliteStorageBackend'],
'@deepseek-ai/dsh-subagent': [
'AssistantOutputFold', 'NO_START_CAPABILITIES', 'ROOT_AGENT_NAME', 'STRUCTURED_OUTPUT_TOOL',
'SUBAGENT_DESCRIPTOR_VERSION', 'SubagentRunId', 'appendDelegatedPolicyOverrides', 'applyChildComposition',
'assertPositiveFinite', 'assertSubagentMaxDepth', 'assertUsableCwd', 'captureDelegatedPolicyOverrides',
'childSessionMeta', 'delegationDepthOf', 'finalAssistantOutput', 'foldSubagentDescriptor',
'parentAgentOptionsForDelegation', 'resolveChildAgentOptions', 'resolveChildDepth', 'settleRunResult',
'snapshotSubagentDescriptor', 'subprocessRunHandle',
],
'@deepseek-ai/dsh-system-prompt': [
'PERSONA_PREFIX_SECTION', 'PERSONA_SUFFIX_SECTION', 'TOOL_ORDER_REST', 'joinContextSections',
'renderContextSections', 'renderContextSnapshot', 'renderPrompt',
],
'@deepseek-ai/dsh-terminal': ['TerminalSessionId'],
'@deepseek-ai/dsh-terminal-bash': ['BashTerminalBackend', 'PWSH_PROMPT_SETUP'],
'@deepseek-ai/dsh-terminal-panel': ['GUIDANCE'],
'@deepseek-ai/dsh-tool-call-timeout-policy': ['TOOL_TIMEOUT'],
'@deepseek-ai/dsh-tool-executor-native': ['NativeToolExecutor'],
'@deepseek-ai/dsh-tool-executor-ptc': [
'PtcExecutor', 'jsonSchemaToPy', 'jsonSchemaToTs', 'renderToolsSdk', 'renderToolsSdkPy',
],
'@deepseek-ai/dsh-tool-fs-search': [
'GLOB_MAX_RESULTS', 'GLOB_VCS_EXCLUDES', 'GREP_MAX_LINE_BYTES', 'GREP_MAX_MATCHES', 'RAW_OUTPUT_MAX_BYTES',
'SEARCH_GRACE_MS', 'SEARCH_META_MAX_BYTES', 'SEARCH_STDERR_MAX_BYTES', 'SEARCH_TIMEOUT_MS', 'applyGlobTool',
'applyGrepTool', 'buildGlobCommand', 'buildGrepCommand', 'formatGlobOutput', 'formatGrepMatches',
'formatGrepOutput', 'parseGlobArgs', 'parseGrepArgs', 'parseGrepMatches', 'presentGlobCall', 'presentGlobResult',
'presentGrepCall', 'presentGrepResult', 'previewLine', 'resolveRgPath', 'runRipgrep', 'sampleAcrossTopLevel',
'toWorkdirRelative', 'trySaveFormattedResult',
],
'@deepseek-ai/dsh-tool-lsp': [
'DEFAULT_LSP_TOOL_TIMEOUT_MS', 'DEFAULT_MAX_LOCATIONS', 'DEFAULT_MAX_RESULT_CHARS', 'LSP_OPERATIONS',
'LSP_PROMPT_TEXT', 'formatHover', 'formatLocations', 'parseLspArgs', 'presentLspCall', 'renderUri',
],
'@deepseek-ai/dsh-tool-session-query': ['DEFAULT_MAX_SEARCH_RESULTS', 'DEFAULT_SEARCH_TIMEOUT_MS'],
'@deepseek-ai/dsh-tool-terminal': ['DEFAULT_MAX_RESULT_BYTES', 'MIN_MAX_RESULT_BYTES'],
'@deepseek-ai/dsh-tool-web': [
'DEFAULT_FETCH_MAX_OUTPUT_CHARS', 'DEFAULT_WEB_TOOL_TIMEOUT_MS', 'WEB_SEARCH_MAX_QUERIES', 'WEB_SEARCH_MAX_RESULTS',
'applyWebFetchTool', 'applyWebSearchTool', 'fetchMetaFromResult', 'fetchMetaFromValue', 'formatFetchOutput',
'formatSearchOutput', 'parseFetchArgs', 'presentFetchCall', 'presentFetchResult', 'presentSearchCall',
'presentSearchResult', 'searchMetaFromResult', 'searchMetaFromValue',
],
'@deepseek-ai/dsh-tool-workspace-dependencies': [
'copyPrimaryRuntime', 'installPrimaryRuntime', 'parsePrimaryRuntime', 'primaryRuntimePythonAliases',
'readPrimaryRuntime', 'resolvePrimaryRuntime', 'workspaceDependencyPaths',
],
'@deepseek-ai/dsh-tools': [
'RUN_CODE_NAME', 'TOOL_ABORTED', 'TOOL_ABORTED_BEFORE_DISPATCH', 'assertObjectJsonSchema',
'assertSupportedJsonSchema', 'defineTool', 'isJsonSchemaRecord', 'isPlainJsonArray', 'isPlainJsonRecord',
'parameterSchemaSpecToJsonSchema', 'projectToolSchema', 'validateArgs', 'validateJsonSchemaValue',
'valueSchemaSpecToJsonSchema',
],
'@deepseek-ai/dsh-typert-loader': ['TYPERT_HOST_EXPORT', 'validateTypertManifest'],
'@deepseek-ai/dsh-typert-registry': ['typertEndpoint', 'typertKey', 'typertPackageKey'],
'@deepseek-ai/dsh-user-approval': ['APPROVAL_POLICIES', 'ApprovalRequestId', 'setApprovalPolicy'],
'@deepseek-ai/dsh-user-questions': ['TIMED_WAIT_PARAMETER', 'isTimedAskUserQuestionSchema'],
'@deepseek-ai/dsh-web-app': ['internals'],
'@deepseek-ai/dsh-web-deepseek-api': [
'DEEPSEEK_DEFAULT_COUNT', 'DEEPSEEK_FETCH_API_PROVIDER_ID', 'DEEPSEEK_SEARCH_API_PROVIDER_ID',
'DEEPSEEK_SEARCH_REQUESTS_PER_SECOND', 'DEEPSEEK_WEB_API_BASE_URL', 'DeepSeekFetchApiProvider',
'DeepSeekSearchApiProvider', 'mapSearchResponse',
],
'@deepseek-ai/dsh-web-fetch-http': ['DEFAULT_USER_AGENT', 'HttpFetchProvider', 'LOCAL_FETCH_PROVIDER_ID'],
'@deepseek-ai/dsh-web-search-deepseek': [
'DEEPSEEK_DEFAULT_API_VERSION', 'DEEPSEEK_DEFAULT_BASE_URL', 'DEEPSEEK_DEFAULT_MAX_TOKENS',
'DEEPSEEK_DEFAULT_MAX_USES', 'DEEPSEEK_DEFAULT_MODEL', 'DEEPSEEK_PROVIDER_ID', 'DeepSeekSearchProvider',
'WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE',
],
'@deepseek-ai/dsh-webhook': ['WebhookDeliveryId', 'WebhookRuleId', 'WebhookSourceId'],
'@deepseek-ai/dsh-workflow-ptc': ['materializeFromRealm', 'validateMeta'],
'@deepseek-ai/dsh-workspace': [
'WorkspaceId', 'realpathNormalize', 'workspaceDomainSpec', 'workspaceDomainState', 'workspaceRecord',
],
} as const satisfies Readonly<Record<string, readonly string[]>>
+6 -4
View File
@@ -42,12 +42,14 @@ describe('pre-merge check', () => {
}
})
it('checks the versions before it installs, and installs before the builds', () => {
const steps = preMergeSteps('/repo')
expect(steps.map(step => step.name)).toEqual(['versions', 'install', 'host contracts', 'client'])
it('checks the versions before it installs, and installs before the upgrade guides, which need the merged base commit, and the builds', () => {
expect(preMergeSteps('/repo').map(step => step.name)).toEqual(['versions', 'install', 'host contracts', 'client'])
const steps = preMergeSteps('/repo', 'b'.repeat(40))
expect(steps.map(step => step.name)).toEqual(['versions', 'install', 'upgrade guides', 'host contracts', 'client'])
expect(steps[0]).toEqual({ name: 'versions', command: process.execPath, args: [join('/repo', 'scripts', 'verify-version-sync.ts'), '/repo'] })
expect(steps[1]).toEqual({ name: 'install', command: 'pnpm', args: ['install', '--frozen-lockfile'] })
expect(steps[3]?.args).toEqual(['exec', 'tsx', 'scripts/compile-referenced-projects.ts', 'client'])
expect(steps[2]?.args).toEqual(['run', 'verify-upgrade-guides', '--base', 'b'.repeat(40)])
expect(steps[4]?.args).toEqual(['exec', 'tsx', 'scripts/compile-referenced-projects.ts', 'client'])
})
it('annotates a failure as a warning and passes in report mode', () => {
+12 -3
View File
@@ -1,6 +1,7 @@
/**
* Validate the tree a pull request produces once merged with its base branch: the version
* synchronization of the released manifests, the install, and the Host and Client builds.
* synchronization of the released manifests, the install, the version directories of added upgrade
* guides, and the Host and Client builds.
*
* The `Policy / Pre-Merge Check` job runs this file with `node`, and knows nothing else about the
* merged tree, so what that tree needs changes here without touching the check. The file runs under
@@ -23,13 +24,17 @@ export interface PreMergeStep {
/**
* The steps that check the merged tree, in order. The versions come first because reading the
* manifests needs no install, so a mistyped release stops the check before anything is built.
* The upgrade-guide step compares with the base-branch commit the job merged, so a release published
* after the pull request was written rejects its stale guides; without that commit the step is left out.
* @param root - Repository root.
* @param base - Base-branch commit merged into the pull request; the job sets it as `BASE_SHA`.
* @returns Steps in run order.
*/
export function preMergeSteps(root: string): PreMergeStep[] {
export function preMergeSteps(root: string, base?: string): PreMergeStep[] {
return [
{ name: 'versions', command: process.execPath, args: [join(root, 'scripts', 'verify-version-sync.ts'), root] },
{ name: 'install', command: 'pnpm', args: ['install', '--frozen-lockfile'] },
...base === undefined ? [] : [{ name: 'upgrade guides', command: 'pnpm', args: ['run', 'verify-upgrade-guides', '--base', base] }],
{ name: 'host contracts', command: 'pnpm', args: ['exec', 'tsx', 'scripts/compile-referenced-projects.ts', 'host-contracts'] },
{ name: 'client', command: 'pnpm', args: ['exec', 'tsx', 'scripts/compile-referenced-projects.ts', 'client'] },
]
@@ -120,7 +125,11 @@ export async function preMergeCheck(root: string, options: PreMergeOptions = {})
const invokedPath = process.argv[1]
const isMain = invokedPath !== undefined && import.meta.url === pathToFileURL(resolve(invokedPath)).href
if (isMain) {
const outcome = await preMergeCheck(resolve(import.meta.dirname, '..'))
const root = resolve(import.meta.dirname, '..')
// A job definition older than this file sets no BASE_SHA.
const base = process.env.BASE_SHA || undefined
if (base === undefined) process.stdout.write('pre-merge-check: BASE_SHA is not set, so added upgrade guides are not checked\n')
const outcome = await preMergeCheck(root, { steps: preMergeSteps(root, base) })
if (outcome.ok) {
process.stdout.write('pre-merge-check: passed\n')
} else {
+1 -21
View File
@@ -5,7 +5,7 @@ import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { zipSync } from 'fflate'
import { expect, it } from 'vitest'
import { downloadPrimaryRuntimeAsset, prepareOfficeSkillAssets, primaryRuntimePayloadDigest, prunePnpmForeignNativePackages, smokePrimaryRuntime, unpackPrimaryRuntimeWheel } from './prepare.ts'
import { downloadPrimaryRuntimeAsset, primaryRuntimePayloadDigest, prunePnpmForeignNativePackages, smokePrimaryRuntime, unpackPrimaryRuntimeWheel } from './prepare.ts'
import lock from './lock.json' with { type: 'json' }
it('covers every SDK wheel target with the shared interpreter lock', () => {
@@ -132,26 +132,6 @@ it('rejects library files requiring an unsupported installation scheme', async (
}
})
it('copies complete Office resources outside the application archive and removes obsolete assets', async () => {
const root = await mkdtemp(join(tmpdir(), 'desktop-office-assets-'))
try {
const source = join(root, 'package', 'assets')
const destination = join(root, 'Contents', 'Resources', 'runtime', 'office-skills')
await mkdir(source, { recursive: true })
for (const name of ['office-docx', 'office-pptx', 'office-xlsx']) {
await mkdir(join(source, name))
await writeFile(join(source, name, 'SKILL.md'), `# ${name}\n`)
}
await prepareOfficeSkillAssets(source, destination)
await writeFile(join(destination, 'obsolete.py'), 'old helper')
await prepareOfficeSkillAssets(source, destination)
for (const name of ['office-docx', 'office-pptx', 'office-xlsx']) {
expect(await readFile(join(destination, name, 'SKILL.md'), 'utf8')).toBe(`# ${name}\n`)
}
await expect(readFile(join(destination, 'obsolete.py'))).rejects.toMatchObject({ code: 'ENOENT' })
} finally { await rm(root, { recursive: true, force: true }) }
})
it('gives Python-only payloads a distinct identity', () => {
expect(primaryRuntimePayloadDigest('linux-x64', lock, undefined)).not.toBe(primaryRuntimePayloadDigest('linux-x64', lock, '11.7.0'))
})
+3 -19
View File
@@ -172,17 +172,6 @@ export function prunePnpmForeignNativePackages(pnpm: string, platform: NodeJS.Pl
}
}
/**
* Copy the skill package's complete asset tree to ordinary filesystem resources.
* @param source - The package's assets directory.
* @param destination - External Office skill resource directory.
* @returns Resolves after replacing the external assets with the complete package tree.
*/
export async function prepareOfficeSkillAssets(source: string, destination: string): Promise<void> {
rmSync(destination, { recursive: true, force: true })
await cp(source, destination, { recursive: true, dereference: true })
}
/** A locked interpreter and wheel target. */
export type PrimaryRuntimeTarget = keyof typeof lock.targets
@@ -190,7 +179,7 @@ export type PrimaryRuntimeTarget = keyof typeof lock.targets
export interface PreparePrimaryRuntimeOptions {
/** Target whose archives and wheels are downloaded. */
readonly target: PrimaryRuntimeTarget
/** Resource directory receiving primary-runtime/ and office-skills/. */
/** Resource directory receiving primary-runtime/. */
readonly output: string
/** SHA-256-addressed archive cache. */
readonly cache: string
@@ -198,16 +187,14 @@ export interface PreparePrimaryRuntimeOptions {
readonly version: string
/** Locked npm pnpm tarball for installed carriers; build hosts otherwise copy their installed pnpm. */
readonly pnpmArchive?: RuntimeNpmArchive
/** Ordinary filesystem Office assets; build hosts otherwise resolve the workspace package. */
readonly skillSource?: string
/** Omit Node.js and pnpm for carriers providing only Python. */
readonly pythonOnly?: boolean
}
/**
* Materialize locked interpreters, libraries and Office resources without executing target code.
* Materialize locked interpreters and libraries without executing target code.
* @param options - Explicit target and carrier-owned output locations.
* @returns Resolves after the complete payload and skills have been copied to the output directory.
* @returns Resolves after the complete payload has been copied to the output directory.
*/
export async function preparePrimaryRuntime(options: PreparePrimaryRuntimeOptions): Promise<void> {
const { target } = options
@@ -259,9 +246,6 @@ export async function preparePrimaryRuntime(options: PreparePrimaryRuntimeOption
} finally {
rmSync(staging, { recursive: true, force: true })
}
const assets = options.skillSource ?? join(dirname(createRequire(import.meta.url).resolve('@deepseek-ai/dsh-skill-office/package.json')), 'assets')
await prepareOfficeSkillAssets(assets,
join(paths.runtime, 'office-skills'))
}
/**
+1
View File
@@ -40,6 +40,7 @@ export const PRODUCT_PACKAGE_POLICY: Readonly<Record<string, ProductPackagePolic
'packages/typert/generator': { category: 'build', reason: 'Build-time generation of type metadata.' },
'packages/test-support/agent-loop-testkit': { category: 'test', reason: 'Published agent-loop test harness.' },
'packages/test-support/tool-testkit': { category: 'test', reason: 'Shared tool definition and execution fixtures for tests and benchmarks.' },
'packages/test-support/mcp-testkit': { category: 'test', reason: 'Shared MCP OAuth world and MCP manager profile fixtures for tests.' },
'packages/test-support/client-runtime': { category: 'test', reason: 'Published browser plugin test harness.' },
'packages/test-support/llm-mock-server': { category: 'test', reason: 'Published model-provider test server.' },
'packages/test-support/llm-replay': { category: 'test', reason: 'Published recorded-model replay harness.' },
+4 -67
View File
@@ -1,72 +1,7 @@
import { describe, expect, it } from 'vitest'
import {
hasTypertRemoteNavigation,
isForbiddenPublicationFile,
validateTarballPayload,
} from './publication-payload.ts'
function validateFixtureTarball(files: readonly string[]): () => void {
return () => {
validateTarballPayload(files, 'fixture.tgz')
}
}
describe('publication payload policy', () => {
it.each([
'lib/index.js',
'lib/types/index.d.ts',
'lib/styles/base.css',
])('accepts %s', (file) => {
expect(isForbiddenPublicationFile(file)).toBe(false)
})
it.each([
'src',
'./src',
'src/',
'src/index.ts',
'./src/index.ts',
String.raw`src\index.ts`,
'lib/types/index.d.ts.map',
'./lib/types/index.d.ts.map',
'lib/typert.remote-client.d.ts.map',
'lib/client.js.map',
'./lib/client.js.map',
])('rejects static manifest path %s', (file) => {
expect(isForbiddenPublicationFile(file)).toBe(true)
})
it('rejects source members in packed tarballs', () => {
expect(validateFixtureTarball([
'package/package.json',
'package/src/index.ts',
])).toThrow('fixture.tgz publishes source file package/src/index.ts')
})
it('rejects source maps in packed tarballs', () => {
expect(validateFixtureTarball([
'package/package.json',
'package/lib/types/index.d.ts.map',
])).toThrow('fixture.tgz publishes source map package/lib/types/index.d.ts.map')
expect(validateFixtureTarball([
'package/package.json',
'package/lib/typert.remote-client.d.ts.map',
])).toThrow('fixture.tgz publishes source map package/lib/typert.remote-client.d.ts.map')
expect(validateFixtureTarball([
'package/package.json',
'package/lib/client.js.map',
])).toThrow('fixture.tgz publishes source map package/lib/client.js.map')
})
it('accepts a clean packed tarball', () => {
expect(validateFixtureTarball([
'package/package.json',
'package/lib/index.js',
'package/lib/types/index.d.ts',
'package/lib/styles/base.css',
])).not.toThrow()
})
import { hasTypertRemoteNavigation } from './publication-payload.ts'
describe('publication payload facts', () => {
it('recognizes only the canonical Host-for-Client export pair', () => {
expect(hasTypertRemoteNavigation({
exports: {
@@ -77,5 +12,7 @@ describe('publication payload policy', () => {
},
})).toBe(true)
expect(hasTypertRemoteNavigation({ exports: { './remote': './lib/remote.js' } })).toBe(false)
expect(hasTypertRemoteNavigation({ exports: { './remote': { types: './lib/typert.remote-client.d.ts' } } })).toBe(false)
expect(hasTypertRemoteNavigation(undefined)).toBe(false)
})
})
+1 -39
View File
@@ -1,4 +1,4 @@
/** Publication payload policy shared by static manifests and packed tarballs. */
/** Publication payload facts shared by static manifests and packed tarballs. */
/**
* Whether a package manifest exports generated Host-for-Client metadata.
@@ -15,41 +15,3 @@ export function hasTypertRemoteNavigation(manifest: unknown): boolean {
return entry.types === './lib/typert.remote-client.d.ts'
&& entry.default === './lib/typert.remote-client.js'
}
/** Normalize a package manifest path or npm tarball member to its payload-relative path. */
function payloadPath(file: string): string {
const normalized = file.replaceAll('\\', '/').replace(/^\.\/+/, '').replace(/\/+$/, '')
return normalized.startsWith('package/') ? normalized.slice('package/'.length) : normalized
}
/**
* Whether a package payload path exposes source or map intermediates. Maps
* serve editor navigation during development, where a workspace consumer
* resolves their source through the package link; a published map resolves
* nothing, so no payload publishes one.
* @param file - manifest path or tarball member to classify.
* @returns whether publishing this path is forbidden.
*/
export function isForbiddenPublicationFile(file: string): boolean {
const normalized = payloadPath(file)
return normalized === 'src'
|| normalized.startsWith('src/')
|| normalized.endsWith('.d.ts.map')
|| normalized.endsWith('.js.map')
}
/**
* Reject source and map members in a packed npm tarball.
* @param files - tarball members to validate.
* @param context - tarball identity named in the failure.
*/
export function validateTarballPayload(files: readonly string[], context: string): void {
for (const file of files) {
if (!isForbiddenPublicationFile(file)) continue
const normalized = payloadPath(file)
if (normalized === 'src' || normalized.startsWith('src/')) {
throw new Error(`${context} publishes source file ${file}`)
}
throw new Error(`${context} publishes source map ${file}`)
}
}
-7
View File
@@ -18,7 +18,6 @@ import { createInterface } from 'node:readline/promises'
import { pathToFileURL } from 'node:url'
import { parseArgs } from 'node:util'
import { discoverNpmBaselineManifests } from './npm-baseline-packages.ts'
import { validateTarballPayload } from './publication-payload.ts'
const DEFAULT_REGISTRY = 'https://registry.npm.harnessment.com'
const DEFAULT_OUTPUT_DIRECTORY = '.artifacts/npm-baseline'
@@ -317,9 +316,6 @@ class ReleaseBundle {
if (expected === undefined || !missingNames.delete(artifact.name)) {
throw new Error(`unexpected or duplicate packed package: ${artifact.name}`)
}
if (expected.origin === 'harness') {
validateTarballPayload(artifact.files, tarball)
}
if (artifact.version !== version) {
throw new Error(`${tarball} has version ${artifact.version}; expected ${version}`)
}
@@ -393,9 +389,6 @@ class ReleaseBundle {
throw new Error(`tarball checksum mismatch: ${pkg.tarball}`)
}
const artifact = inspectTarball(path, runner)
if (pkg.origin === 'harness') {
validateTarballPayload(artifact.files, pkg.tarball)
}
if (artifact.name !== pkg.name || artifact.version !== this.manifest.version) {
throw new Error(`tarball identity mismatch: ${pkg.tarball}`)
}
+9 -3
View File
@@ -26,7 +26,9 @@ async function fixture() {
await file(join(root, 'node/node_modules/@deepseek-ai/dsh/lib/bin.js'), `
export async function runCli(options = {}) {
const result = process.argv[2] ? { argv: process.argv.slice(2) }
: { primary: process.env.DSH_BUNDLED_PRIMARY_RUNTIME, office: process.env.DSH_BUNDLED_OFFICE_CLI };
: { primary: process.env.DSH_PRIMARY_RUNTIME };
const office = Object.keys(process.env).filter(name => /^DSH_BUNDLED_OFFICE_(?:CLI|NODE)$/.test(name));
if (office.length > 0) result.office = office;
if (options.packageManager) Object.assign(result, { packageManager: options.packageManager, hostPath: process.env.PATH });
console.log(JSON.stringify(result));
}
@@ -74,8 +76,8 @@ async function fixture() {
`)
function run(resource?: string, extra: NodeJS.ProcessEnv = {}, args: string[] = []) {
const child = spawn(process.execPath, [bootstrap, ...args], {
env: { ...process.env, DSH_RESOURCE_CACHE: cache, DSH_RUNTIME_DOWNLOAD: resource, DSH_BUNDLED_PRIMARY_RUNTIME: undefined,
DSH_PRIMARY_RUNTIME: undefined, DSH_OFFICE_SIDECAR: undefined, DSH_BUNDLED_OFFICE_CLI: undefined, ...extra },
env: { ...process.env, DSH_RESOURCE_CACHE: cache, DSH_RUNTIME_DOWNLOAD: resource,
DSH_PRIMARY_RUNTIME: undefined, DSH_OFFICE_SIDECAR: undefined, ...extra },
stdio: ['pipe', 'pipe', 'pipe'],
})
let stdout = '', stderr = ''
@@ -146,6 +148,10 @@ it('starts without downloading, independently downloads either resource, and reu
const location = JSON.parse(office.stdout) as string
expect(await readFile(join(location, 'node_modules/@deepseek-ai/libreoffice-kit/lib/cli.js'), 'utf8')).toBe('cli')
expect(await run('office', { DSH_FIXTURE_FAIL: '1' }).done).toMatchObject({ code: 0, stdout: office.stdout })
// A cached sidecar only redirects Kit resolution; the CLI process receives no Office executable paths.
const started = await run().done
expect(started.code, started.stderr).toBe(0)
expect(JSON.parse(started.stdout)).toEqual({ primary: join(cache, 'a'.repeat(64), 'primary', 'primary-runtime') })
} finally { await rm(root, { recursive: true, force: true }) }
})
+18 -3
View File
@@ -98,6 +98,7 @@ describe('release families', () => {
'@deepseek-ai/dsh-experimental-speech-to-text',
'@deepseek-ai/dsh-experimental-subagent-oar',
'@deepseek-ai/dsh-experimental-terminal-bundle',
'@deepseek-ai/dsh-terminal-panel',
'@deepseek-ai/dsh-tool-ralph',
'@deepseek-ai/dsh-tool-session-query',
'@deepseek-ai/dsh-experimental-tool-subagent-oar',
@@ -398,18 +399,32 @@ describe('release families', () => {
])
})
it('applies the harness payload policy to dsh and keeps upstream payloads for vendored packages', () => {
it('accepts the harness payload and keeps upstream payloads for vendored packages', () => {
const dsh = releaseFamily('dsh')
const vendor = releaseFamily('vendor')
const harness = member('packages/a/library', '@deepseek-ai/dsh-library')
const vendored = member('vendor/cordis', '@deepseek-ai/cordis')
expect(() => { dsh.validatePayload(harness, ['package/lib/index.js', 'package/src/index.ts']) })
.toThrow(/publishes source file/)
expect(() => { dsh.validatePayload(harness, ['package/lib/index.js', 'package/lib/index.js.map', 'package/src/index.ts']) }).not.toThrow()
expect(() => { vendor.validatePayload(vendored, ['package/lib/index.js', 'package/src/index.ts']) }).not.toThrow()
expect(() => { vendor.validatePayload(vendored, []) }).toThrow(/empty tarball/)
})
it('requires the installed package payload the staging hook supplies', () => {
const dsh = releaseFamily('dsh')
const installed = member('apps/cli', '@deepseek-ai/dsh')
expect(() => { dsh.validatePayload(installed, ['package/lib/index.js', 'package/src/bin.ts']) })
.toThrow(/@deepseek-ai\/dsh packed no documentation/)
expect(() => { dsh.validatePayload(installed, ['package/lib/index.js', 'package/docs/guide.md', 'package/src/bin.ts']) })
.toThrow(/@deepseek-ai\/dsh packed no upgrade guide index/)
const docs = ['package/docs/guide.md', 'package/docs/upgrade-guide/README.md']
expect(() => { dsh.validatePayload(installed, ['package/lib/index.js', ...docs]) })
.toThrow(/@deepseek-ai\/dsh packed no source/)
expect(() => { dsh.validatePayload(installed, ['package/lib/index.js', ...docs, 'package/src/bin.ts']) })
.not.toThrow()
})
it('drives the installed entry only for the family that publishes one', () => {
expect(releaseFamily('dsh').installedEntry).toEqual({ packageName: '@deepseek-ai/dsh', binPath: 'lib/bin.js' })
expect(releaseFamily('vendor').installedEntry).toBeUndefined()
+19 -10
View File
@@ -15,7 +15,6 @@ import {
officialClientBuildEnvironment,
readClientBuildRecord,
} from '../client-build-environment.ts'
import { validateTarballPayload } from '../publication-payload.ts'
import { ON_DEMAND_BUNDLES } from '../../packages/util/official-bundles/src/bundles.ts'
/**
@@ -387,12 +386,24 @@ class DshFamily extends ReleaseFamily {
}
/**
* Reject source and declaration-map members, the repository's publication policy.
* Require the installed package to carry the documentation and source its
* manifest promises. `docs` exists only because `prepack` stages it, and a
* stale tree in the checkout would satisfy a weaker check, so the staged
* copy must be complete for the pack that publishes it.
* @param member - the packed member.
* @param files - every path inside its tarball.
*/
validatePayload(member: ReleaseMember, files: readonly string[]): void {
validateTarballPayload(files, member.name)
if (member.name !== this.installedEntry.packageName) return
if (!files.some(file => file.startsWith('package/docs/') && file.endsWith('.md'))) {
throw new Error(`${member.name} packed no documentation`)
}
if (!files.includes('package/docs/upgrade-guide/README.md')) {
throw new Error(`${member.name} packed no upgrade guide index`)
}
if (!files.some(file => file.startsWith('package/src/') && file.endsWith('.ts'))) {
throw new Error(`${member.name} packed no source`)
}
}
/** Publish every advertised on-demand package before the installation that offers it. */
@@ -446,14 +457,12 @@ class VendorFamily extends ReleaseFamily {
}
/**
* Require the payload the vendored manifest declares, including upstream's
* `src` tree and declaration maps.
* Accept upstream's payload.
*
* The harness policy that rejects both does not apply here: these manifests
* export `./src/*` for source navigation, so dropping `src` would publish a
* package whose export map points at absent files. What must hold instead is
* that every path the manifest selects is present, which `files` already
* decides and `pnpm pack` already enforces.
* Upstream's manifest owns that payload, so this family enforces no shape of
* its own beyond a nonempty tarball. What must hold is that every path the
* manifest selects is present, which `files` already decides and `pnpm pack`
* already enforces.
* @param member - the packed member.
* @param files - every path inside its tarball.
*/
+6 -4
View File
@@ -307,16 +307,18 @@ describe('release pack CLI', () => {
it('validates every parallel tarball before recording the publish order', async () => {
const root = fixture()
packageFixture(root, 'packages/util/alpha', '@deepseek-ai/alpha')
packageFixture(root, 'packages/util/zebra', '@deepseek-ai/zebra', { files: ['lib/index.js', 'src/index.ts'] })
write(join(root, 'packages/util/zebra/src/index.ts'), 'export const source = 1\n')
packageFixture(root, 'apps/cli', '@deepseek-ai/dsh', { files: ['lib/index.js', 'src/bin.ts'] })
packageFixture(root, 'packages/subagent/subagent-claude-code', '@deepseek-ai/dsh-subagent-claude-code')
packageFixture(root, 'packages/subagent/subagent-codex', '@deepseek-ai/dsh-subagent-codex')
write(join(root, 'apps/cli/src/bin.ts'), 'export const bin = 1\n')
write(join(root, 'apps/web/dist/index.html'), '<main></main>')
writeClientBuildRecord(root, officialClientBuildEnvironment(root, { DSH_CLIENT_COMMIT_HASH: commit }))
const result = await runPack(root, ['--family', 'dsh', '--concurrency', '8'])
expect(result.status).not.toBe(0)
expect(result.stderr).toContain('@deepseek-ai/zebra publishes source file package/src/index.ts')
expect(readdirSync(join(root, 'packed')).filter(name => name.endsWith('.tgz'))).toHaveLength(2)
expect(result.stderr).toContain('@deepseek-ai/dsh packed no documentation')
expect(readdirSync(join(root, 'packed')).filter(name => name.endsWith('.tgz'))).toHaveLength(4)
expect(existsSync(join(root, 'packed', PUBLISH_ORDER_FILE))).toBe(false)
})
+20 -1
View File
@@ -3,11 +3,13 @@
import { createHash } from 'node:crypto'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { attempt, attemptEchoed, type CommandResult } from './process.ts'
import { publishRelease } from './publish.ts'
import { cuaHelperSourceDigest } from '../cua-helper/build-inputs.ts'
import { verifyCuaHelperTarball } from '../cua-helper/verify-tarball.ts'
import { packedIdentity, readPublishOrder } from './tarball.ts'
vi.mock('./process.ts', async importOriginal => ({
@@ -23,6 +25,8 @@ vi.mock('./tarball.ts', async importOriginal => ({
readPublishOrder: vi.fn(),
}))
vi.mock('../cua-helper/verify-tarball.ts', () => ({ verifyCuaHelperTarball: vi.fn() }))
vi.mock('node:timers/promises', async importOriginal => ({
...await importOriginal<typeof import('node:timers/promises')>(),
setTimeout: vi.fn(),
@@ -310,3 +314,18 @@ describe('release publication channels', () => {
expect(attemptEchoed).not.toHaveBeenCalled()
})
})
it('verifies helper sources from the repository root when publication is invoked from a subdirectory', async () => {
const fixture = packedRelease(['1.0.0'])
vi.mocked(packedIdentity).mockReturnValue({ name: '@deepseek-ai/dsh-experimental-cua-macos', version: '1.0.0' })
vi.mocked(verifyCuaHelperTarball).mockResolvedValue(undefined)
registry()
const root = resolve(import.meta.dirname, '../..')
const sourceDigest = cuaHelperSourceDigest(root)
const cwd = vi.spyOn(process, 'cwd').mockReturnValue(join(root, 'scripts'))
try {
await publishRelease('dsh', fixture.directory)
expect(verifyCuaHelperTarball).toHaveBeenCalledExactlyOnceWith(fixture.packages[0]!.path, { sourceDigest })
expect(attemptEchoed).toHaveBeenCalledOnce()
} finally { cwd.mockRestore() }
})
+2 -3
View File
@@ -12,7 +12,7 @@
* the same artifact safe.
*/
import { execFileSync } from 'node:child_process'
import { cuaHelperSourceDigest } from '../cua-helper/build-inputs.ts'
import { verifyCuaHelperTarball } from '../cua-helper/verify-tarball.ts'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
@@ -188,8 +188,7 @@ export async function publishRelease(familyId: string, directory: string, distTa
})
for (const member of order) {
if (member.name !== '@deepseek-ai/dsh-experimental-cua-macos') continue
const commit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
await verifyCuaHelperTarball(member.tarball, { version: member.version, commit })
await verifyCuaHelperTarball(member.tarball, { sourceDigest: cuaHelperSourceDigest(resolve(import.meta.dirname, '../..')) })
}
if (distTag !== undefined) {
for (const member of order) verifyDistTag(member, distTag)
+2 -1
View File
@@ -380,7 +380,7 @@ describe('gate graph validation', () => {
'rescope-vendor', 'publint', 'constraints', 'default-product-isolation', 'product-use', 'official-bundle-catalog', 'provider-data', 'package-dependencies', 'application-entrypoints',
'dsh-package-licenses', 'node-next-types',
'optional-dependency-imports', 'client-packages', 'installer-locales', 'locale-metadata', 'client-ui-i18n', 'client-route-resolution', 'no-bare-dispatcher',
'plugin-record-callers', 'no-unknown-casts', 'no-top-level-await',
'plugin-record-callers', 'no-unknown-casts', 'no-top-level-await', 'plugin-entry-exports',
'cordis-config', 'runtime-closure',
])
})
@@ -1004,6 +1004,7 @@ describe('Node 24 lane ownership', () => {
expect.arrayContaining([
'apps/cli/tests/profiles/headless/tests/source-tool.built.e2e.ts',
'apps/desktop/tests/acl-skill.built.e2e.ts',
'apps/desktop/tests/installed-docs-asar.built.e2e.ts',
'packages/subprocess/subprocess-local/tests/spawn-runner-built.e2e.ts',
'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
+2
View File
@@ -421,6 +421,7 @@ function sharedHygieneGates(): Gate[] {
pnpmScript('plugin-record-callers', 'verify-plugin-record-callers', { label: 'plugin record callers' }),
pnpmScript('no-unknown-casts', 'verify-no-unknown-casts', { label: 'no new unknown casts' }),
pnpmScript('no-top-level-await', 'verify-no-top-level-await', { label: 'no module-scope await' }),
pnpmScript('plugin-entry-exports', 'verify-plugin-entry-exports', { label: 'plugin entry exports' }),
]
}
@@ -911,6 +912,7 @@ function builtBinSmokeGate(needs: string[] = ['build']): Gate {
'apps/cli/tests/profiles/headless/tests/source-tool.built.e2e.ts',
'apps/cli/tests/built-bin.e2e.ts',
'apps/desktop/tests/acl-skill.built.e2e.ts',
'apps/desktop/tests/installed-docs-asar.built.e2e.ts',
'packages/host/directory-picker-native/tests/built-worker.e2e.ts',
'packages/sdk/server/tests/built-scope-carrier.e2e.ts',
'packages/deliverables/tool-present/tests/built-errors.e2e.ts',
+1 -1
View File
@@ -24,7 +24,7 @@ const REGISTER_HEAD = /\.(?:register|registerFactory)\(/
export interface SlotDeclaration {
/** SlotMap key, e.g. `settings.section`. */
key: string
/** Cardinality literal (`single` / `list` / `keyed` / `chain`), or '' when not a literal. */
/** Cardinality literal (`single` / `list` / `keyed` / `chain` / `hoc`), or '' when not a literal. */
kind: string
/** Data-scope literal (`root` / `session` / `session-maybe`), or '' when not a literal. */
scope: string
+3 -3
View File
@@ -93,6 +93,7 @@ LEGACY_CUSTOM_DISABLED_ROWS = (
"tool-fs",
"tool-fs-search",
"tool-goal",
"tool-office",
"tool-plugin-manager",
"tool-schedule",
"tool-skill",
@@ -995,9 +996,8 @@ def _smoke_sdk_authoring_cached(base_url: str, executable: Path, update_snapshot
assert len(requests) == 2, requests
prompt = json.dumps(requests[0], ensure_ascii=False)
assert ("- `office`:" in prompt) == (mode != "disabled"), mode
for name in ("office-docx", "office-pptx", "office-xlsx", "office-render", "office-recalculate", "office-export-pdf"):
for name in ("office-docx", "office-pptx", "office-xlsx"):
assert (name in prompt) == (mode != "disabled"), (mode, name)
assert "render --input" not in prompt and "libreofficeKit" not in prompt, mode
assert ("CUSTOM_OFFICE_DOCX" in prompt) == (mode == "replacement"), mode
tool_result = next(block for message in requests[1]["messages"]
for block in message.get("content", [])
@@ -1155,7 +1155,7 @@ def smoke_sdk_office(executable: Path) -> None:
patch = root / f"{mode}.patch.yml"
patch.write_text(json.dumps([{"insert": [{
"id": "python-sdk-office-smoke",
"inject": ["skills"],
"inject": ["officeKit"],
"name": plugin.as_uri(),
"config": {"input": str(document), "output": str(output), "result": str(result_path),
"imageInput": str(documents["pptx"]), "imageOutput": str(root / "node-pptx")},
@@ -134,7 +134,7 @@
"content": [
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
],
"source": {
@@ -1204,7 +1204,7 @@
"content": [
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
],
"source": {
@@ -11,7 +11,7 @@
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"}
{"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":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"image","attachment":{"attachmentId":"sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640","mediaType":"image/png","width":1,"height":1,"bytes":69}}],"source":{"kind":"python-snapshot-image-offload"}},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["run_code"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
@@ -134,7 +134,7 @@
"content": [
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
],
"source": {
@@ -890,11 +890,12 @@
"seq": 37,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-1}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "Check direct child"
"label": "Check direct child",
"name": "agent-1"
}
},
{
@@ -914,7 +915,7 @@
"content": [
{
"type": "text",
"text": "started subagent {{child-1}}"
"text": "started subagent agent-1"
}
],
"isError": false,
@@ -922,7 +923,7 @@
},
"meta": {
"kind": "activation",
"subagentId": "{{child-1}}"
"name": "agent-1"
}
},
"sourceEventSeqs": [
@@ -970,7 +971,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -984,7 +985,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -1144,11 +1145,12 @@
"seq": 46,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-2}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "advanced-exe-snapshot child 1"
"label": "advanced-exe-snapshot child 1",
"name": "agent-2"
}
},
{
@@ -1248,7 +1250,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -1262,7 +1264,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -1682,7 +1684,7 @@
"content": [
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
],
"source": {
@@ -2778,11 +2780,12 @@
"seq": 37,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-1}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "Check direct child"
"label": "Check direct child",
"name": "agent-1"
}
}
}
@@ -2808,7 +2811,7 @@
"content": [
{
"type": "text",
"text": "started subagent {{child-1}}"
"text": "started subagent agent-1"
}
],
"isError": false,
@@ -2816,7 +2819,7 @@
},
"meta": {
"kind": "activation",
"subagentId": "{{child-1}}"
"name": "agent-1"
}
},
"sourceEventSeqs": [
@@ -2982,7 +2985,7 @@
"content": [
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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.\n</system-reminder>"
}
],
"source": {
@@ -3275,7 +3278,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -3289,7 +3292,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -3676,11 +3679,12 @@
"seq": 46,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-2}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "advanced-exe-snapshot child 1"
"label": "advanced-exe-snapshot child 1",
"name": "agent-2"
}
}
}
@@ -3809,7 +3813,7 @@
"content": [
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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.\n</system-reminder>"
}
],
"source": {
@@ -4228,7 +4232,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -4242,7 +4246,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -12,7 +12,7 @@
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"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\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"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":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"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":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[12],"source":{"kind":"fallback"}}}
@@ -12,7 +12,7 @@
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"}
{"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\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"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":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\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.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"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":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[12],"source":{"kind":"fallback"}}}
@@ -11,7 +11,7 @@
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"}
{"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":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"image","attachment":{"attachmentId":"sha256:b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640","mediaType":"image/png","width":1,"height":1,"bytes":69}}],"source":{"kind":"python-snapshot-image-offload"}},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
@@ -36,16 +36,16 @@
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":4,"throughSeq":33}}
{"type":"assistant/message","data":{"turn":1,"step":3,"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","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-direct-child","name":"subagent","args":[""]},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-direct-child","args":["{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"]},{"type":"chunk","time":0,"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":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":3,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}
{"type":"subagent/catalog","data":{"version":0,"childId":"{{child-1}}","childCreatedAt":0,"mode":"continuable","label":"Check direct child"}}
{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-direct-child"},"toolCallId":"advanced-direct-child","content":[{"type":"text","text":"started subagent {{child-1}}"}],"isError":false,"id":"{{messageId}}"},"meta":{"kind":"activation","subagentId":"{{child-1}}"}},"sourceEventSeqs":[36],"surfaceOp":"append"}
{"type":"subagent/catalog","data":{"version":3,"childId":"{{child-1}}","childCreatedAt":0,"mode":"continuable","label":"Check direct child","name":"agent-1"}}
{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-direct-child"},"toolCallId":"advanced-direct-child","content":[{"type":"text","text":"started subagent agent-1"}],"isError":false,"id":"{{messageId}}"},"meta":{"kind":"activation","name":"agent-1"}},"sourceEventSeqs":[36],"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}}","sessionFormatVersion":4,"throughSeq":40}}
{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent {{child-1}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{child-1}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"}]}}
{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent agent-1 finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent agent-1 finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"}]}}
{"type":"assistant/message","data":{"turn":1,"step":4,"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","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-workflow","name":"workflow","args":[""]},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-workflow","args":["{\"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":"chunk","time":0,"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":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":4,"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":"subagent/catalog","data":{"version":0,"childId":"{{child-2}}","childCreatedAt":0,"mode":"continuable","label":"advanced-exe-snapshot child 1"}}
{"type":"subagent/catalog","data":{"version":3,"childId":"{{child-2}}","childCreatedAt":0,"mode":"continuable","label":"advanced-exe-snapshot child 1","name":"agent-2"}}
{"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"}}
@@ -53,7 +53,7 @@
{"type":"step/end","data":{"turn":1,"step":4}}
{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":5}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Background subagent {{child-1}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{child-1}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Background subagent agent-1 finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent agent-1 finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":4,"throughSeq":54}}
{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{message:1}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["ADVANCED_EXECUTABLE_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":5}}
@@ -8,7 +8,7 @@
}
},
"catalogs": [
"Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"authoring\".\n\nTo message other agents, use send_message({ agent_id: \"<agent-id>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids.<system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
"Query the packaged Python environment for Office authoring.<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder><system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
],
"result": {
"python": "{{python}}",
@@ -8,7 +8,7 @@
}
},
"catalogs": [
"Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"authoring\".\n\nTo message other agents, use send_message({ agent_id: \"<agent-id>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids.<system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
"Query the packaged Python environment for Office authoring.<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n</system-reminder><system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
],
"result": {
"python": "{{python}}",
@@ -58,7 +58,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\"."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n</system-reminder>"
}
]
}
@@ -123,7 +123,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\"."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n</system-reminder>"
}
]
},
@@ -207,7 +207,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\"."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n</system-reminder>"
}
]
},
@@ -58,7 +58,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\"."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n</system-reminder>"
}
]
}
@@ -123,7 +123,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\"."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n</system-reminder>"
}
]
},
@@ -207,7 +207,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\"."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n</system-reminder>"
}
]
},
@@ -12,7 +12,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
]
}
@@ -41,7 +41,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
]
}
@@ -8,7 +8,7 @@
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Complete the first isolated Python SDK process turn."}],"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\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","subagent","workflow","working_directory"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session/title","data":{"title":"Complete the first isolated Python","messageSeqs":[8],"source":{"kind":"fallback"}}}
@@ -8,7 +8,7 @@
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Complete the second isolated Python SDK process turn."}],"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\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","subagent","workflow","working_directory"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session/title","data":{"title":"Complete the second isolated Python","messageSeqs":[8],"source":{"kind":"fallback"}}}
@@ -11,7 +11,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically \u2014 do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically \u2014 do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
]
}
@@ -29,7 +29,7 @@
},
{
"type": "text",
"text": "Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically \u2014 do not request sandbox escalation (do not set `sandbox_permissions`)."
"text": "<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically \u2014 do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"
}
]
},
@@ -8,7 +8,7 @@
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Run three todo updates; the scheduler will reject the second call."}],"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\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","subagent","todo_write","workflow","working_directory"]},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}}
{"type":"session/title","data":{"title":"Run three todo updates; the","messageSeqs":[8],"source":{"kind":"fallback"}}}
+137
View File
@@ -0,0 +1,137 @@
import { existsSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { cleanStagedDshDocs, publishedDocuments, stageDshDocs } from './stage-dsh-docs.ts'
const roots: string[] = []
function temporaryRoot(): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-stage-docs-'))
roots.push(root)
return root
}
function write(root: string, path: string, contents = '# fixture\n'): void {
const target = join(root, path)
mkdirSync(join(target, '..'), { recursive: true })
writeFileSync(target, contents)
}
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
describe('documentation staging', () => {
it('copies published pages, assets, and upgrade guides without the internal trees', async () => {
const source = join(temporaryRoot(), 'docs')
const destination = join(temporaryRoot(), 'cli', 'docs')
const published = new Set(['guide/index.md', 'guide/index.zh.md'])
write(source, 'guide/index.md')
write(source, 'guide/index.zh.md')
write(source, 'guide/index.i18n.yaml')
write(source, 'images/diagram.png', 'png')
write(source, 'upgrade-guide/v0.1.0/change/guide.md', '---\ndescription: "Change."\n---\n# Change\n')
write(source, 'upgrade-guide/v0.1.0/change/guide.zh.md', '---\ndescription: "变更。"\n---\n# 变更\n')
write(source, 'upgrade-guide/v0.1.0/change/guide.i18n.yaml')
write(source, 'postmortem/incident.md')
write(source, 'AGENTS.md')
write(source, 'persistence-changes/v1/changes.md')
write(source, 'i18n/terminology.md')
await stageDshDocs(source, destination, published)
for (const copied of [
'guide/index.md', 'guide/index.zh.md', 'images/diagram.png',
'upgrade-guide/v0.1.0/change/guide.md', 'upgrade-guide/v0.1.0/change/guide.zh.md', 'upgrade-guide/README.md',
]) {
expect(existsSync(join(destination, copied)), copied).toBe(true)
}
for (const excluded of [
'guide/index.i18n.yaml', 'upgrade-guide/v0.1.0/change/guide.i18n.yaml',
'postmortem', 'AGENTS.md', 'persistence-changes', 'i18n',
]) {
expect(existsSync(join(destination, excluded)), excluded).toBe(false)
}
})
it('indexes every staged upgrade guide by the release it upgrades from, newest first', async () => {
const source = join(temporaryRoot(), 'docs')
const destination = join(temporaryRoot(), 'cli', 'docs')
const guide = (description: string, title: string): string => `---\nkind: upgrade-guide\ndescription: "${description}"\n---\n# ${title}\n`
write(source, 'upgrade-guide/v0.2.0-rc.1/b-item/guide.md', '---\r\n# note\r\nkind: upgrade-guide\r\ndescription: >\r\n Second | change\r\n across lines.\r\n---\r\n# Second\r\n')
write(source, 'upgrade-guide/v0.2.0-rc.1/b-item/guide.zh.md', guide('第二项。', '第二'))
write(source, 'upgrade-guide/v0.2.0-rc.1/a-item/guide.md', guide('First change.', 'First'))
write(source, 'upgrade-guide/v0.2.0-rc.1/a-item/guide.zh.md', guide('第一项。', '第一'))
write(source, 'upgrade-guide/v0.10.0/c-item/guide.md', guide('Later change.', 'Later'))
write(source, 'upgrade-guide/v0.10.0/c-item/guide.zh.md', guide('后续变更。', '后续'))
await stageDshDocs(source, destination, new Set())
const index = readFileSync(join(destination, 'upgrade-guide/README.md'), 'utf8')
await stageDshDocs(source, destination, new Set())
expect(readFileSync(join(destination, 'upgrade-guide/README.md'), 'utf8')).toBe(index)
expect(index).toContain('upgrading from release vT to the release after it; vT is the release being left, not the target')
const sections = index.split('\n## ').slice(1).map(section => section.split('\n').filter(line => line.startsWith('| ') && !line.startsWith('| Item') && !line.startsWith('| ---')))
expect(index.match(/^## .+$/gmu)).toEqual(['## v0.10.0', '## v0.2.0-rc.1'])
expect(sections).toEqual([
['| Later | Later change. | 后续变更。 | [v0.10.0/c-item/guide.md](v0.10.0/c-item/guide.md) | [v0.10.0/c-item/guide.zh.md](v0.10.0/c-item/guide.zh.md) |'],
[
'| First | First change. | 第一项。 | [v0.2.0-rc.1/a-item/guide.md](v0.2.0-rc.1/a-item/guide.md) | [v0.2.0-rc.1/a-item/guide.zh.md](v0.2.0-rc.1/a-item/guide.zh.md) |',
'| Second | Second \\| change across lines. | 第二项。 | [v0.2.0-rc.1/b-item/guide.md](v0.2.0-rc.1/b-item/guide.md) | [v0.2.0-rc.1/b-item/guide.zh.md](v0.2.0-rc.1/b-item/guide.zh.md) |',
],
])
})
it('writes a preamble-only index without guides and rejects a guide the index cannot describe', async () => {
const source = join(temporaryRoot(), 'docs')
const destination = join(temporaryRoot(), 'cli', 'docs')
write(source, 'kept.md')
await stageDshDocs(source, destination, new Set(['kept.md']))
expect(readFileSync(join(destination, 'upgrade-guide/README.md'), 'utf8')).not.toContain('## ')
write(source, 'upgrade-guide/v0.1.0/change/guide.md', '# Untitled summary\n')
write(source, 'upgrade-guide/v0.1.0/change/guide.zh.md', '# 无摘要\n')
await expect(stageDshDocs(source, destination, new Set())).rejects.toThrow(/needs a frontmatter description and a level-one title/)
})
it('publishes the generated index for the repository guides', async () => {
const destination = join(temporaryRoot(), 'cli', 'docs')
await stageDshDocs(join(import.meta.dirname, '..', 'docs'), destination)
const index = readFileSync(join(destination, 'upgrade-guide/README.md'), 'utf8')
for (const file of readdirSync(join(import.meta.dirname, '..', 'docs/upgrade-guide'), { recursive: true, encoding: 'utf8' })) {
if (file.endsWith('guide.md')) expect(index).toContain(`](${file.split('\\').join('/')})`)
}
})
it('replaces a previous copy instead of merging into it', async () => {
const source = join(temporaryRoot(), 'docs')
const destination = join(temporaryRoot(), 'cli', 'docs')
write(source, 'kept.md')
write(destination, 'removed.md')
await stageDshDocs(source, destination, new Set(['kept.md']))
expect(existsSync(join(destination, 'kept.md'))).toBe(true)
expect(existsSync(join(destination, 'removed.md'))).toBe(false)
})
it('removes a staged copy', async () => {
const destination = join(temporaryRoot(), 'cli', 'docs')
write(destination, 'architecture.md')
await cleanStagedDshDocs(destination)
expect(existsSync(destination)).toBe(false)
})
it('publishes the website manifest pages and no internal document', () => {
const published = publishedDocuments()
expect(published.has('architecture.md')).toBe(true)
expect(published.has('architecture.zh.md')).toBe(true)
for (const excluded of ['AGENTS.md', 'testing.md', 'postmortem/README.md', 'persistence-changes/README.md', 'i18n/README.md']) {
expect(published.has(excluded)).toBe(false)
}
})
})
+185
View File
@@ -0,0 +1,185 @@
/** Stage the published documentation inside the published `dsh` package. */
import { cp, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { JSON_SCHEMA, load as loadYaml } from 'js-yaml'
import { rcompare } from 'semver'
import { docsPages } from '../website/docs.ts'
/** Repository root, resolved from this script rather than the invoking directory. */
const REPOSITORY_ROOT = fileURLToPath(new URL('..', import.meta.url))
/** Directory whose contents are published, and the package directory that receives them. */
const DOCS_DIRECTORY = join(REPOSITORY_ROOT, 'docs')
const STAGED_DIRECTORY = join(REPOSITORY_ROOT, 'apps', 'cli', 'docs')
/** Generated migration records and the translation guidelines: maintainer material no reader in an installed package needs. */
const EXCLUDED_DIRECTORIES = ['persistence-changes', 'i18n'] as const
/** Translation alignment records the documentation gates own. */
const EXCLUDED_SUFFIX = '.i18n.yaml'
/** Upgrade guides reach an installed reader and are not on the website. */
const ALWAYS_PUBLISHED_DIRECTORY = 'upgrade-guide'
/** Generated index of the staged upgrade guides; the repository tree has none. */
const UPGRADE_GUIDE_INDEX = `${ALWAYS_PUBLISHED_DIRECTORY}/README.md`
/**
* Source-relative Markdown paths the documentation website publishes.
*
* The npm payload carries the same pages plus the upgrade guides, so a new
* internal document under `docs/` reaches neither surface until the manifest
* adopts it.
* @returns every manifest source and alias, relative to the documentation root.
*/
export function publishedDocuments(): ReadonlySet<string> {
const published = new Set<string>()
for (const page of docsPages) {
for (const file of [page.source, ...page.sourceAliases ?? []]) {
if (file.startsWith('docs/')) published.add(file.slice('docs/'.length))
}
}
return published
}
/**
* Replace a package's `docs` directory with the documentation a reader needs.
*
* The copy follows the working tree, so a pack publishes the `docs/` contents
* the checkout holds rather than the committed tree. Runs from the `prepack`
* lifecycle of `@deepseek-ai/dsh`, so packing the package and packing the
* release set both publish the same files.
* @param source - Documentation root to copy; defaults to the repository `docs`.
* @param destination - Package directory to replace; defaults to `apps/cli/docs`.
* @param published - Source-relative Markdown paths to keep; defaults to the website manifest.
* @returns Resolves after the destination holds the filtered copy.
*/
export async function stageDshDocs(
source: string = DOCS_DIRECTORY,
destination: string = STAGED_DIRECTORY,
published: ReadonlySet<string> = publishedDocuments(),
): Promise<void> {
await rm(destination, { recursive: true, force: true })
const files = await stagedFiles(source, published)
for (const file of files) {
const target = join(destination, file)
await mkdir(dirname(target), { recursive: true })
await cp(join(source, file), target)
}
await mkdir(join(destination, ALWAYS_PUBLISHED_DIRECTORY), { recursive: true })
await writeFile(join(destination, UPGRADE_GUIDE_INDEX), await upgradeGuideIndex(source, files))
}
/** One upgrade guide pair as the generated index lists it. */
interface IndexedGuide {
readonly item: string
readonly title: string
readonly summary: string
readonly summaryZh: string
}
/**
* Render the index of every staged upgrade guide, grouped by the release it upgrades from.
* @param source - Documentation root holding the guides.
* @param files - Staged source-relative paths.
* @returns the index Markdown; without staged guides it holds only the preamble.
* @throws When a guide lacks its Chinese counterpart, a `description`, or a level-one title.
*/
async function upgradeGuideIndex(source: string, files: readonly string[]): Promise<string> {
const versions = new Map<string, IndexedGuide[]>()
for (const file of files) {
const match = /^upgrade-guide\/v(?<version>[^/]+)\/(?<item>[^/]+)\/guide\.md$/u.exec(file)?.groups
if (match?.version === undefined || match.item === undefined) continue
const { version, item } = match
const english = await guideHeading(join(source, file))
const chinese = await guideHeading(join(source, file.replace(/\.md$/u, '.zh.md')))
const guides = versions.get(version) ?? []
guides.push({ item, title: english.title, summary: english.description, summaryZh: chinese.description })
versions.set(version, guides)
}
const cell = (text: string): string => text.replace(/\s+/gu, ' ').trim().replaceAll('|', '\\|')
const lines = [
'# Upgrade guides',
'',
'Generated when `@deepseek-ai/dsh` is packed. A `v<T>` section lists what to change when upgrading from release vT to the release after it; vT is the release being left, not the target. Paths are relative to this file.',
'',
'打包 `@deepseek-ai/dsh` 时生成。`v<T>` 一节列出从 vT 版本升级到其下一个版本时需要做的修改;vT 是升级前的版本,不是目标版本。路径相对于本文件。',
]
for (const [version, guides] of [...versions].sort(([left], [right]) => rcompare(left, right))) {
lines.push('', `## v${version}`, '', '| Item | Summary | 摘要 | English | 中文 |', '| --- | --- | --- | --- | --- |')
for (const guide of guides) {
const directory = `v${version}/${guide.item}`
lines.push(`| ${cell(guide.title)} | ${cell(guide.summary)} | ${cell(guide.summaryZh)} | [${directory}/guide.md](${directory}/guide.md) | [${directory}/guide.zh.md](${directory}/guide.zh.md) |`)
}
}
return `${lines.join('\n')}\n`
}
/**
* Read the frontmatter description and level-one title of one guide.
* @param path - Absolute guide path.
* @returns the guide's one-sentence description and title.
* @throws When the file is missing or lacks either field.
*/
async function guideHeading(path: string): Promise<{ readonly description: string; readonly title: string }> {
const text = await readFile(path, 'utf8')
// The same frontmatter rules as `verify-upgrade-guides`; the title is the first heading after it.
const frontmatter = /^---\r?\n(?<yaml>[\s\S]*?)\r?\n---\r?\n/u.exec(text)
const yaml = frontmatter?.groups?.yaml
const metadata = yaml === undefined ? undefined : loadYaml(yaml, { schema: JSON_SCHEMA }) as { description?: unknown } | null
const title = frontmatter === null ? undefined : /^# (?<title>.+?)\r?$/mu.exec(text.slice(frontmatter[0].length))?.groups?.title
if (typeof metadata?.description !== 'string' || title === undefined) {
throw new Error(`stage-dsh-docs: ${path} needs a frontmatter description and a level-one title`)
}
return { description: metadata.description, title }
}
/**
* Remove a staged copy, so no pack leaves a stale tree for the next one.
* @param destination - Package directory to remove; defaults to `apps/cli/docs`.
* @returns Resolves after the directory is absent.
*/
export async function cleanStagedDshDocs(destination: string = STAGED_DIRECTORY): Promise<void> {
await rm(destination, { recursive: true, force: true })
}
/**
* List the files one stage publishes, in stable path order.
* @param source - Documentation root to walk.
* @param published - Source-relative Markdown paths to keep.
* @returns source-relative POSIX paths of every published file.
*/
async function stagedFiles(source: string, published: ReadonlySet<string>): Promise<string[]> {
const files: string[] = []
const walk = async (directory: string): Promise<void> => {
for (const entry of await readdir(join(source, directory), { withFileTypes: true })) {
const path = directory === '' ? entry.name : `${directory}/${entry.name}`
if (EXCLUDED_DIRECTORIES.some(excluded => path === excluded || path.startsWith(`${excluded}/`))) continue
if (entry.isDirectory()) {
await walk(path)
continue
}
if (path.endsWith(EXCLUDED_SUFFIX)) continue
if (path.endsWith('.md') && !published.has(path) && !isUpgradeGuide(path)) continue
files.push(path)
}
}
await walk('')
return files.sort()
}
/**
* Whether one path belongs to a shipped upgrade guide.
* @param path - Source-relative documentation path.
* @returns whether the path lives under the upgrade-guide tree.
*/
function isUpgradeGuide(path: string): boolean {
return path.startsWith(`${ALWAYS_PUBLISHED_DIRECTORY}/`)
}
if (import.meta.main) {
if (process.argv.includes('--clean')) await cleanStagedDshDocs()
else await stageDshDocs()
}
+126 -55
View File
@@ -1,9 +1,11 @@
/** Release rehearsal routing and persistent-runner isolation, without executing release builds. */
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { runInNewContext } from 'node:vm'
import { load } from 'js-yaml'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, onTestFinished } from 'vitest'
const root = resolve(import.meta.dirname, '../..')
const repository = 'deepseek-harness/deepseek-harness'
@@ -11,6 +13,7 @@ const selfhosted = ['self-hosted', 'linux', 'x64', 'vm-backup']
const hosted = 'ubuntu-24.04'
interface Step {
env?: Record<string, string>
name?: string
uses?: string
run?: string
@@ -30,6 +33,8 @@ interface Workflow {
with?: Record<string, unknown>
needs?: string
permissions?: Record<string, string>
outputs?: Record<string, string>
env?: Record<string, string>
}>
}
@@ -42,7 +47,7 @@ function workflow(file: string): Workflow {
// Missing context properties use the Actions empty-string value.
function evaluate(expression: string, context: Record<string, string | boolean>): unknown {
const source = expression.trim().replace(/^\$\{\{|\}\}$/g, '')
.replace(/\b(?:github|vars|runner|inputs|needs)(?:\.[a-zA-Z_][a-zA-Z_0-9-]*)+/g,
.replace(/\b(?:github|vars|runner|inputs|needs|steps)(?:\.[a-zA-Z_][a-zA-Z_0-9-]*)+/g,
key => JSON.stringify(context[key] ?? ''))
return runInNewContext(source, {
fromJSON: JSON.parse, startsWith: (value: string, prefix: string) => value.startsWith(prefix),
@@ -180,75 +185,141 @@ it('keeps vendor publication manual and entirely hosted', () => {
expect(Object.keys(publish.on)).toEqual(['workflow_dispatch'])
for (const job of Object.values(publish.jobs)) expect(job['runs-on']).toBe(hosted)
})
it('keeps DSH publication manual with hosted npm jobs and an explicit signed-helper producer', () => {
it('keeps DSH publication manual and delegates all helper selections to the Mac workflow', () => {
const publish = workflow('release-publish.yml')
expect(Object.keys(publish.on)).toEqual(['workflow_dispatch'])
const helper = publish.jobs['cua-helper']!
expect(helper).toEqual({
if: "startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check",
uses: './.github/workflows/cua-helper-package.yml',
with: { reuse: true, preset: 'production', cua_run_id: '${{ inputs.cua_run_id }}' },
})
for (const [name, job] of Object.entries(publish.jobs)) {
if (name === 'cua-helper') {
expect(job).toEqual({
if: "(startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check) && inputs.cua_run_id == '' && inputs.cua_run_attempt == ''",
uses: './.github/workflows/cua-helper-package.yml',
with: { source_ref: '${{ github.ref }}', preset: 'production' },
})
} else expect(job['runs-on']).toBe(hosted)
if (name !== 'cua-helper') expect(job['runs-on']).toBe(hosted)
}
expect(JSON.stringify(publish)).not.toContain('cua_run_attempt')
expect(publish.on['workflow_dispatch']).toMatchObject({ inputs: { 'skip-tag-check': {
description: 'Skip release tag validation for the selected ref; other publication checks still apply.',
} } })
expect(publish.jobs['pack']!.needs).toBe('cua-helper')
expect(publish.jobs['pack']!.if).toBeUndefined()
})
it.each([
['refs/tags/dsh-v0.2.1-rc.4', false, '', '', true],
['refs/heads/master', false, '', '', false],
['refs/heads/master', true, '', '', true],
['refs/tags/dsh-v0.2.1-rc.4', false, '123', '', false],
['refs/heads/master', true, '123', '2', false],
['refs/tags/dsh-v0.2.1-rc.4', false, '', '2', false],
] as const)('selects the helper producer for ref %s, skip=%s, run=%s, attempt=%s', (ref, skip, runId, attempt, expected) => {
['refs/tags/dsh-v0.2.1-rc.4', false, true],
['refs/heads/master', false, false],
['refs/heads/master', true, true],
] as const)('gates helper selection for ref %s, skip=%s', (ref, skip, expected) => {
const expression = workflow('release-publish.yml').jobs['cua-helper']!.if!
expect(evaluate(expression, { 'github.ref': ref, 'inputs.skip-tag-check': skip,
'inputs.cua_run_id': runId, 'inputs.cua_run_attempt': attempt })).toBe(expected)
expect(evaluate(expression, { 'github.ref': ref, 'inputs.skip-tag-check': skip })).toBe(expected)
})
it.each([
['success', '', '', false, true],
['failure', '', '', false, false],
['failure', '123', '', false, false],
['cancelled', '', '', false, false],
['skipped', '', '', false, false],
['skipped', '123', '', false, true],
['skipped', '123', '2', false, true],
['skipped', '', '2', false, true],
['skipped', '123', '2', true, false],
] as const)('gates npm packing with helper=%s, run=%s, attempt=%s, cancelled=%s', (result, runId, attempt, cancelled, expected) => {
const pack = workflow('release-publish.yml').jobs['pack']!
expect(pack.needs).toBe('cua-helper')
expect(evaluate(pack.if!, { 'needs.cua-helper.result': result,
'inputs.cua_run_id': runId, 'inputs.cua_run_attempt': attempt, cancelled })).toBe(expected)
it('skips installation and signing on a helper match and exports the original producer identifiers', () => {
const helper = workflow('cua-helper-package.yml')
expect(helper.permissions).toEqual({ contents: 'read', actions: 'read' })
const job = helper.jobs['package']!
const select = job.steps.find(step => step.name === 'Find reusable CUA helper')!
expect(select.run).toBe('node scripts/cua-helper/select-artifact.ts')
expect(Boolean(evaluate(select.if!, {}))).toBe(false)
expect(evaluate(select.if!, { 'inputs.reuse': true })).toBe(true)
expect(select.env?.['CUA_BUILD_KEY']).toBe('${{ steps.build-inputs.outputs.build-key }}')
const inputs = job.steps.find(step => step.name === 'Record CUA helper build inputs')!
expect(inputs.run).toBe('node scripts/cua-helper/build-inputs.ts')
expect(inputs.if).toBeUndefined()
expect(job.steps.indexOf(inputs)).toBeLessThan(job.steps.indexOf(select))
const expensive = job.steps.filter(step => step.uses === 'pnpm/[email protected]'
|| step.name === 'Install locked dependencies' || step.name === 'Build and verify notarized applications'
|| step.uses === 'actions/[email protected]')
expect(expensive).toHaveLength(4)
expect(job.steps.find(step => step.name === 'Install locked dependencies')?.run)
.toBe('pnpm install --frozen-lockfile --ignore-scripts --ignore-pnpmfile')
const build = job.steps.find(step => step.name === 'Build and verify notarized applications')!
expect(build.run).toContain('node --import tsx/esm scripts/cua-helper/package.ts --out dist/cua-helper')
expect(build.run).not.toContain('pnpm exec')
for (const step of expensive) {
expect(job.steps.indexOf(select)).toBeLessThan(job.steps.indexOf(step))
expect(evaluate(step.if!, { 'steps.retained.outputs.artifact-id': '456' })).toBe(false)
expect(evaluate(step.if!, { 'steps.retained.outputs.artifact-id': '' })).toBe(true)
}
expect(job.outputs).toMatchObject({
'artifact-id': '${{ steps.retained.outputs.artifact-id || steps.upload.outputs.artifact-id }}',
'run-id': '${{ steps.retained.outputs.run-id || github.run_id }}',
'build-key': '${{ steps.build-inputs.outputs.build-key }}',
})
})
it('validates retained attempts before downloading exactly one artifact with read-only Actions access', () => {
it('downloads the selected producer artifact and verifies its build key before packing', () => {
const publish = workflow('release-publish.yml')
expect(publish.permissions).toEqual({ contents: 'read' })
expect(publish.permissions).toEqual({ contents: 'read', actions: 'read' })
const pack = publish.jobs['pack']!
expect(pack.permissions).toEqual({ contents: 'read', actions: 'read' })
const select = pack.steps.find(step => step.name === 'Select retained CUA helper')!
const retained = pack.steps.find(step => step.name === 'Download retained CUA helper')!
const fresh = pack.steps.find(step => step.name === 'Download freshly built CUA helper')!
expect(select.run).toBe('pnpm exec tsx scripts/cua-helper/select-artifact.ts')
expect(pack.steps.indexOf(select)).toBeLessThan(pack.steps.indexOf(retained))
expect(retained).toMatchObject({ uses: 'actions/[email protected]', with: {
'artifact-ids': '${{ steps.retained-cua.outputs.artifact-id }}', 'run-id': '${{ inputs.cua_run_id }}',
const download = pack.steps.find(step => step.name === 'Download selected CUA helper')!
expect(download).toMatchObject({ uses: 'actions/[email protected]', with: {
'artifact-ids': '${{ needs.cua-helper.outputs.artifact-id }}', 'run-id': '${{ needs.cua-helper.outputs.run-id }}',
'github-token': '${{ github.token }}', path: 'dist/cua-helper',
} })
expect(retained.with?.name).toBeUndefined()
expect(fresh.with).toEqual({ name: '${{ needs.cua-helper.outputs.artifact }}', path: 'dist/cua-helper' })
for (const [runId, attempt, reuse] of [['', '', false], ['123', '', true], ['123', '2', true], ['', '2', true]] as const) {
const context = { 'inputs.cua_run_id': runId, 'inputs.cua_run_attempt': attempt }
expect(evaluate(select.if!, context)).toBe(reuse)
expect(evaluate(retained.if!, context)).toBe(reuse)
expect(evaluate(fresh.if!, context)).toBe(!reuse)
}
expect(download.if).toBeUndefined()
expect(download.with?.name).toBeUndefined()
const stage = pack.steps.find(step => step.name === 'Stage verified native helper applications')!
expect(stage.if).toBeUndefined()
expect(stage.env).toEqual({ CUA_EXPECTED_BUILD_KEY: '${{ needs.cua-helper.outputs.build-key }}' })
expect(stage.run).toContain('scripts/cua-helper/stage.ts --from dist/cua-helper/extracted')
expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(retained))
expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(fresh))
expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(download))
expect(pack.steps.indexOf(stage)).toBeLessThan(pack.steps.findIndex(step => step.name === 'Pack release tarballs'))
})
it('checks out the Actions run commit and exposes only the preset on the manual helper form', () => {
const helper = workflow('cua-helper-package.yml')
const dispatch = helper.on['workflow_dispatch'] as { inputs: Record<string, unknown> }
const called = helper.on['workflow_call'] as { inputs: Record<string, unknown> }
expect(Object.keys(dispatch.inputs)).toEqual(['preset'])
expect(called.inputs).toEqual({ reuse: { type: 'boolean', default: false },
cua_run_id: { type: 'string', default: '' }, preset: { type: 'string', default: 'production' } })
const job = helper.jobs['package']!
const checkout = job.steps.find(step => step.uses === 'actions/[email protected]')!
expect(checkout.with).toEqual({ 'persist-credentials': false, clean: true })
expect(job.env).not.toHaveProperty('PACKAGE_SOURCE_REF')
expect(JSON.stringify(helper)).not.toContain('source_ref')
expect(workflow('release-publish.yml').jobs['cua-helper']!.with).not.toHaveProperty('source_ref')
})
it.each([
['refs/heads/release-candidate', 'test', true, ''],
['refs/tags/dsh-v1.2.3', 'production', true, ''],
['refs/tags/dsh-v1.2.4', 'production', false, 'Release tag must match product version'],
['refs/heads/master', 'invalid', false, 'Invalid preset'],
['refs/pull/42/merge', 'test', false, 'Select a trusted repository branch or release tag'],
['', 'test', false, 'Select a trusted repository branch or release tag'],
] as const)('validates the run ref %s and preset %s before dependency installation', (ref, preset, accepted, diagnostic) => {
const directory = mkdtempSync(join(tmpdir(), 'cua-workflow-ref-'))
onTestFinished(() => { rmSync(directory, { recursive: true, force: true }) })
writeFileSync(join(directory, 'package.json'), JSON.stringify({ version: '1.2.3' }))
const job = workflow('cua-helper-package.yml').jobs['package']!
const validation = job.steps.find(step => step.name === 'Validate run ref and preset')!
const source = /^node -e '([\s\S]+)'$/u.exec(validation.run!.trim())?.[1]
expect(source).toBeDefined()
const result = spawnSync(process.execPath, ['-e', source!], {
cwd: directory, encoding: 'utf8', timeout: 60_000,
env: { ...process.env, GITHUB_REF: ref, DSH_PACKAGING_PRESET: preset, PACKAGE_SOURCE_REF: 'refs/tags/dsh-v0.0.0' },
})
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(result.status, result.stderr).toBe(accepted ? 0 : 1)
if (!accepted) expect(result.stderr).toContain(diagnostic)
expect(job.steps.indexOf(validation)).toBeLessThan(job.steps.findIndex(step => step.name === 'Record CUA helper build inputs'))
})
it.each([
[false, '', true],
[true, '', true],
[true, '456', false],
] as const)('builds for reuse=%s and selected artifact=%s only when required', (reuse, artifactId, build) => {
const steps = workflow('cua-helper-package.yml').jobs['package']!.steps
const selection = steps.find(step => step.name === 'Find reusable CUA helper')!
expect(Boolean(evaluate(selection.if!, reuse ? { 'inputs.reuse': true } : {}))).toBe(reuse)
for (const step of steps.filter(step => step.uses === 'pnpm/[email protected]'
|| step.name === 'Install locked dependencies' || step.name === 'Build and verify notarized applications'
|| step.uses === 'actions/[email protected]')) {
expect(evaluate(step.if!, { 'steps.retained.outputs.artifact-id': artifactId })).toBe(build)
}
})
-1
View File
@@ -407,7 +407,6 @@ describe('translation scope discovery', () => {
'coverage/report/README.md',
'python/sdk-runtime/src/deepseek_harness_runtime/runtime/deepseek-harness-sdk-runtime-macos-arm64/README.md',
'python/sdk-runtime/src/deepseek_harness_runtime/runtime/node/README.md',
'python/sdk-runtime/src/deepseek_harness_runtime/runtime/macos-arm64/office-skills/office-docx/SKILL.md',
])('excludes non-source or non-README path %s', (file) => {
expect(isTranslationScopeFile(file)).toBe(false)
})
+2
View File
@@ -142,6 +142,7 @@ export const TRANSLATION_SCOPE_GLOB_EXCLUDES = [
'**/__pycache__/**',
'**/.pytest_cache/**',
'apps/web/dist/**',
'apps/cli/docs/**',
'.artifacts/**',
'python/sdk-runtime/src/deepseek_harness_runtime/runtime/**',
'vendor/**',
@@ -154,6 +155,7 @@ function isTranslationSourceExcluded(file: string): boolean {
|| segment.startsWith('.doc-typecheck-')
|| segment.startsWith('.node-next-types-'))
|| file.startsWith('apps/web/dist/')
|| file.startsWith('apps/cli/docs/')
|| file.startsWith('python/sdk-runtime/src/deepseek_harness_runtime/runtime/')
}
+30
View File
@@ -2382,6 +2382,11 @@
"symbol": "SubagentActivation",
"source": "packages/subagent/subagent/src/types.ts"
},
{
"doc": "docs/subsystems/subagent.md",
"symbol": "SubagentMemberNames",
"source": "packages/subagent/subagent/src/types.ts"
},
{
"doc": "docs/subsystems/product-telemetry.md",
"symbol": "ProductTelemetryScalar",
@@ -2602,6 +2607,16 @@
"symbol": "RestoreWorktreeRequest",
"source": "packages/experimental/worktree/src/types.ts"
},
{
"doc": "docs/subsystems/worktrees.md",
"symbol": "WorktreeCleanup",
"source": "packages/experimental/worktree/src/types.ts"
},
{
"doc": "docs/subsystems/worktrees.md",
"symbol": "WorktreeCreation",
"source": "packages/experimental/worktree/src/types.ts"
},
{
"doc": "docs/subsystems/worktrees.md",
"symbol": "RestoredWorktree",
@@ -2697,6 +2712,21 @@
"symbol": "ForgeBranches",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeBaseBranch",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeAutomaticBase",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeBaseBranches",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeChangeRequestListState",
+1 -1
View File
@@ -250,7 +250,7 @@ describe('package dependency scope', () => {
expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-experimental-forge'])
.toEqual(['changeRequestKey'])
expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-experimental-worktree'])
.toEqual(['generatedWorktreeName'])
.toEqual(['generatedWorktreeName', 'CREATED_RECORD', 'createdWorktreeSchema'])
expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-fs']).toEqual(['FsError'])
expect(PACKAGE_DEPENDENCY_POLICY.peerRequiredHostExports['@deepseek-ai/dsh-session'])
.toEqual(['SESSION_FORMAT_VERSION', 'appendPluginRecord', 'pluginRecordOf'])
@@ -85,7 +85,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/browser-use/browser-use': { kind: 'none', reason: 'The registry only reserves a provider name; providers own browser tools and Session resources.' },
'packages/experimental/browser-use-runtime': { kind: 'indirect', reason: 'Browser providers call the library to own resources and expose upstream MCP tools.' },
'packages/computer-use/computer-use': { kind: 'none', reason: 'The registry only reserves provider names; providers own all model-facing tools and guidance.' },
'packages/document/office-to-pdf': { kind: 'none', reason: 'The provider returns PDF bytes without constructing model input.' },
'packages/document/office-kit': { kind: 'indirect', reason: 'The provider returns rendered and converted bytes; the Office tools own their model-visible results.' },
'packages/credentials/deepseek-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' },
'packages/credentials/deepseek-account-platform': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' },
@@ -148,7 +148,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/client/ui-sidebar-right': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/ui-sidebar': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/ui-brand-official': { kind: 'none', reason: 'Browser-side presentation occupants; registers nothing model-facing.' },
'packages/client/ui-conversation': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/ui-approval': { kind: 'none', reason: 'Browser-side approval presentation; registers nothing model-facing.' },
'packages/client/ui-chat': { kind: 'none', reason: 'Browser-side Chat presentation; registers nothing model-facing.' },
'packages/client/ui-mcp-account': { kind: 'none', reason: 'Plugins page account registry and controls over the MCP manager; the connector and the MCP client document the tools a grant exposes.' },
@@ -244,6 +243,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/test-support/session-snapshot': { kind: 'none', reason: 'The test harness observes and normalizes transcripts without changing live requests.' },
'packages/test-support/agent-loop-testkit': { kind: 'none', reason: 'The test helper mounts services but neither drives nor modifies model requests.' },
'packages/test-support/tool-testkit': { kind: 'none', reason: 'Fixture helpers define and execute test tools without making model requests.' },
'packages/test-support/mcp-testkit': { kind: 'none', reason: 'OAuth and MCP protocol fixtures serve test traffic without making model requests.' },
'packages/test-support/loader-smoke': { kind: 'none', reason: 'The test harness submits an ordinary user task but delegates prompt and tool composition to the loaded tree.' },
'packages/test-support/llm-mock-server': { kind: 'none', reason: 'The test server substitutes provider wire behavior without invoking a real model.' },
'packages/test-support/llm-replay': { kind: 'none', reason: 'The keyless adapter invokes no provider model.' },
@@ -24,7 +24,7 @@ describe('package README Summary limit', () => {
const summary = Array.from({ length: MAX_PACKAGE_README_SUMMARY_WORDS + 1 }, () => 'word').join(' ')
expect(packageReadmeSummaryErrors('packages/example/example/README.md', readme(summary, kind))).toEqual([
`packages/example/example/README.md: Summary has 101 words; the limit is 100. Read .agents/skills/dsh-doc/SKILL.md and .agents/skills/dsh-doc/templates/${kind}.md before rewriting it.`,
`packages/example/example/README.md: Summary has 101 words; the limit is 100. Read .agents/skills/dsh-doc-writing/SKILL.md and .agents/skills/dsh-doc-writing/templates/${kind}.md before rewriting it.`,
])
})
+3 -3
View File
@@ -46,10 +46,10 @@ export function packageReadmeSummaryErrors(file: string, source: string): string
const kind = readKind(source)
const template = kind === undefined
? '.agents/skills/dsh-doc/templates/'
: `.agents/skills/dsh-doc/templates/${kind}.md`
? '.agents/skills/dsh-doc-writing/templates/'
: `.agents/skills/dsh-doc-writing/templates/${kind}.md`
return [
`${file}: Summary has ${String(words)} words; the limit is ${String(MAX_PACKAGE_README_SUMMARY_WORDS)}. Read .agents/skills/dsh-doc/SKILL.md and ${template} before rewriting it.`,
`${file}: Summary has ${String(words)} words; the limit is ${String(MAX_PACKAGE_README_SUMMARY_WORDS)}. Read .agents/skills/dsh-doc-writing/SKILL.md and ${template} before rewriting it.`,
]
}
+346
View File
@@ -0,0 +1,346 @@
/**
* Tests for the plugin entry export gate: which entries it checks, which export forms it reports, how the
* existing-export list is validated, and how it fails when an entry goes unchecked.
*
* The fixture compiles its own `tsconfig.host.json` and `tsconfig.client.json`, with a stand-in Cordis `Service` at
* the path the repository maps `@deepseek-ai/cordis` to.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, describe, expect, it } from 'vitest'
import {
ENTRY_GLOB,
EXISTING_EXPORTS_FILE,
discoverEntries,
scanFailures,
scanRepository,
} from './verify-plugin-entry-exports.ts'
const compilerOptions = {
target: 'es2022',
module: 'esnext',
moduleResolution: 'bundler',
noEmit: true,
skipLibCheck: true,
types: [],
paths: { '@deepseek-ai/cordis': ['./vendor/cordis/src/index.ts'] },
}
const manifest = (name: string): string => JSON.stringify({ name, version: '0.0.1' })
const PLUGIN_ENTRY = [
"import { Service } from '@deepseek-ai/cordis'",
'',
// The Loader fields, with Config as both an interface and a value.
"export const name = 'plugin'",
"export const inject = ['tools']",
'export interface Config { limit: number }',
'export const Config = (config: Config): Config => config',
'export function apply(): void {}',
// Types, in every form the compiler erases.
'export interface Shape { a: number }',
'export type Alias = string',
"export type { Remote as RemoteAlias } from './types.ts'",
"export { type Remote } from './types.ts'",
"export { Remote as RemoteAgain } from './types.ts'",
"export type * from './type-star.ts'",
// Classes judged by what they construct.
'export class DirectError extends Error {}',
'export class IndirectError extends DirectError {}',
'class Detailed<T> extends Error { declare readonly detail?: T }',
'export class GenericError extends Detailed<string> {}',
'export class DirectService extends Service {}',
'export class GenericService extends Service<string> {}',
'export const ExpressionError = class extends Error {}',
'function Tagged<Base extends new (...args: any[]) => object>(base: Base) {',
" return class extends base { readonly tag = 'tagged' }",
'}',
'export class MixedError extends Tagged(Error) {}',
// Values the rule does not allow.
'export function helper(): void {}',
'export const LIMIT = 3',
'export const PATTERN = /x/u',
'export enum Mode { A }',
'export namespace Space { export const inner = 1 }',
'export class Plain {}',
'export const PlainExpression = class {}',
'export class MixedPlain extends Tagged(class {}) {}',
"export type Id = string & { readonly brand: 'Id' }",
'export function Id(value: string): Id { return value as Id }',
"export * from './values.ts'",
"export * as namespaced from './values.ts'",
"export { helperImpl as renamed } from './values.ts'",
"export { missing } from './missing.ts'",
"export * from './gone.ts'",
'',
].join('\n')
const FIXTURE: Record<string, string> = {
'tsconfig.host.json': JSON.stringify({
compilerOptions,
include: ['vendor/**/*.ts', 'packages/**/*.ts'],
exclude: ['packages/f/client-only/**', 'packages/f/orphan/**'],
}),
'tsconfig.client.json': JSON.stringify({ compilerOptions, include: ['packages/f/client-only/**/*.ts'] }),
'vendor/cordis/src/index.ts': 'export abstract class Service<T = never> { declare readonly value?: T }\n',
'packages/f/plugin/package.json': manifest('@f/plugin'),
'packages/f/plugin/src/index.ts': PLUGIN_ENTRY,
'packages/f/plugin/src/types.ts': 'export interface Remote { b: string }\n',
'packages/f/plugin/src/type-star.ts': 'export interface StarShape { c: number }\nexport const hiddenByTypeStar = 1\n',
'packages/f/plugin/src/values.ts': [
'export const starred = 1',
'export interface StarredShape { d: number }',
'export function helperImpl(): void {}',
'',
].join('\n'),
// A value `apply` makes an entry a function plugin, in each form an entry can export it.
'packages/f/const-apply/package.json': manifest('@f/const-apply'),
'packages/f/const-apply/src/index.ts': 'export const apply = (): void => {}\nexport const extra = 1\n',
'packages/f/reexport-apply/package.json': manifest('@f/reexport-apply'),
'packages/f/reexport-apply/src/index.ts': "export { apply } from './apply.ts'\nexport const extra = 1\n",
'packages/f/reexport-apply/src/apply.ts': 'export function apply(): void {}\n',
'packages/f/with-default/package.json': manifest('@f/with-default'),
'packages/f/with-default/src/index.ts': 'export function apply(): void {}\nexport default apply\n',
// A Service class as the default export beside apply: the Loader loads it instead of the namespace.
'packages/f/default-service/package.json': manifest('@f/default-service'),
'packages/f/default-service/src/index.ts': [
"import { Service } from '@deepseek-ai/cordis'",
'export function apply(): void {}',
'export default class Mixed extends Service {}',
'',
].join('\n'),
// Run-time export paths: an erased `export type` does not hide the value `export *` brings in under its name, and a
// name that only a nested `export type *` reaches is a type, including an `apply` that reaches the entry that way.
'packages/f/type-shadow/package.json': manifest('@f/type-shadow'),
'packages/f/type-shadow/src/index.ts': [
'export function apply(): void {}',
"export type { hidden } from './value.ts'",
"export * from './value.ts'",
'',
].join('\n'),
'packages/f/type-shadow/src/value.ts': 'export const hidden = 1\n',
'packages/f/type-barrel/package.json': manifest('@f/type-barrel'),
'packages/f/type-barrel/src/index.ts': "export function apply(): void {}\nexport * from './barrel.ts'\n",
'packages/f/type-barrel/src/barrel.ts': "export type * from './value.ts'\n",
'packages/f/type-barrel/src/value.ts': 'export const hidden = 1\n',
'packages/f/type-apply/package.json': manifest('@f/type-apply'),
'packages/f/type-apply/src/index.ts': "export * from './barrel.ts'\n",
'packages/f/type-apply/src/barrel.ts': "export type * from './impl.ts'\n",
'packages/f/type-apply/src/impl.ts': 'export function apply(): void {}\nexport const extra = 1\n',
// Base classes that only share a name with Error and Service are not the allowed roots.
'packages/f/fake-base/package.json': manifest('@f/fake-base'),
'packages/f/fake-base/src/index.ts': [
'export function apply(): void {}',
'class Error {}',
'class Service {}',
'export class FakeError extends Error {}',
'export class FakeService extends Service {}',
'',
].join('\n'),
// A service plugin entry default-exports a class the Loader constructs. Beside it pass other names for the same class,
// types, and Service or Error classes; `Config` and other values are reported, because the Loader reads the class.
'packages/f/service/package.json': manifest('@f/service'),
'packages/f/service/src/index.ts': [
"import { Service } from '@deepseek-ai/cordis'",
'export default class Store extends Service {}',
'export { Store as NamedStore }',
'export class StoreError extends Error {}',
'export interface StoreShape { a: number }',
'export const helper = 1',
'export const Config = { limit: 1 }',
'',
].join('\n'),
'packages/f/plain-class/package.json': manifest('@f/plain-class'),
'packages/f/plain-class/src/index.ts': [
'export default class Plain {}',
'export { Plain }',
'export function plainHelper(): void {}',
'',
].join('\n'),
// Entries the Loader cannot load as a plugin are not checked: a library, an abstract default class that defines a
// capability seam, and a default export that is not a class.
'packages/f/library/package.json': manifest('@f/library'),
'packages/f/library/src/index.ts': 'export const util = 1\n',
'packages/f/seam/package.json': manifest('@f/seam'),
'packages/f/seam/src/index.ts': [
"import { Service } from '@deepseek-ai/cordis'",
'export default abstract class Definition extends Service {}',
'export const seamHelper = 1',
'',
].join('\n'),
'packages/f/default-function/package.json': manifest('@f/default-function'),
'packages/f/default-function/src/index.ts': 'export default function plugin(): void {}\nexport const fnHelper = 1\n',
// Only the Client face compiles this entry; no face compiles the orphan.
'packages/f/client-only/package.json': manifest('@f/client-only'),
'packages/f/client-only/src/index.ts': 'export function apply(): void {}\nexport const clientValue = 1\n',
'packages/f/orphan/package.json': manifest('@f/orphan'),
'packages/f/orphan/src/index.ts': 'export function apply(): void {}\n',
'packages/f/listed/package.json': manifest('@f/listed'),
'packages/f/listed/src/index.ts': [
'export function apply(): void {}',
'export const kept = 1',
'export const alsoKept = 2',
'export interface Typed { a: number }',
'export class ListedError extends Error {}',
'',
].join('\n'),
}
const EXISTING = {
'@f/listed': ['kept', 'alsoKept', 'kept', 'gone', 'Typed', 'ListedError'],
'@f/library': ['util'],
'@f/unknown': ['value'],
'@f/const-apply': [],
'@f/orphan': ['anything'],
}
function writeFixture(files: Record<string, string>, prefix: string): string {
const fixtureRoot = mkdtempSync(join(tmpdir(), prefix))
for (const [rel, content] of Object.entries(files)) {
mkdirSync(dirname(join(fixtureRoot, rel)), { recursive: true })
writeFileSync(join(fixtureRoot, rel), content)
}
return fixtureRoot
}
function lineOf(text: string, line: string): number {
return text.split('\n').indexOf(line) + 1
}
const root = writeFixture(FIXTURE, 'plugin-entry-exports-')
const emptyRoot = writeFixture({
'tsconfig.host.json': JSON.stringify({ compilerOptions, include: ['packages/**/*.ts'] }),
'packages/f/library/package.json': manifest('@f/library'),
'packages/f/library/src/index.ts': 'export const util = 1\n',
}, 'plugin-entry-exports-empty-')
const namelessRoot = writeFixture({
'packages/f/nameless/package.json': JSON.stringify({ version: '0.0.1' }),
'packages/f/nameless/src/index.ts': 'export function apply(): void {}\n',
}, 'plugin-entry-exports-nameless-')
const result = scanRepository(root, EXISTING)
afterAll(() => {
for (const fixtureRoot of [root, emptyRoot, namelessRoot]) rmSync(fixtureRoot, { recursive: true, force: true })
})
describe('function plugin entry exports', () => {
it('reports every value beyond the Loader fields, types, and Service or Error classes', () => {
expect(result.violations.map(value => `${value.packageName} ${value.exportName}`)).toEqual([
'@f/client-only clientValue',
'@f/const-apply extra',
'@f/default-service default',
'@f/fake-base FakeError',
'@f/fake-base FakeService',
'@f/plain-class plainHelper',
'@f/plugin helper',
'@f/plugin LIMIT',
'@f/plugin PATTERN',
'@f/plugin Mode',
'@f/plugin Space',
'@f/plugin Plain',
'@f/plugin PlainExpression',
'@f/plugin MixedPlain',
'@f/plugin Id',
'@f/plugin helperImpl',
'@f/plugin starred',
'@f/plugin namespaced',
'@f/plugin renamed',
'@f/plugin missing',
'@f/plugin *',
'@f/reexport-apply extra',
'@f/service helper',
'@f/service Config',
'@f/type-shadow hidden',
'@f/with-default default',
])
})
it('follows run-time export paths through type-only exports', () => {
const shadow = result.violations.find(value => value.packageName === '@f/type-shadow')
expect(shadow).toMatchObject({ exportName: 'hidden', line: 3, unresolved: false })
expect(result.violations.some(value => value.packageName === '@f/type-barrel' || value.packageName === '@f/type-apply'))
.toBe(false)
})
it('reports a default export beside apply even when it is a Service class', () => {
expect(result.violations.filter(value => value.exportName === 'default').map(value => value.packageName))
.toEqual(['@f/default-service', '@f/with-default'])
})
it('checks entries that export a value apply or default-export a class the Loader constructs', () => {
expect(result.checkedEntries).toEqual({ function: 10, service: 2 })
const unchecked = new Set(['@f/library', '@f/seam', '@f/default-function', '@f/type-apply'])
expect(result.violations.some(value => unchecked.has(value.packageName))).toBe(false)
})
it('locates a star re-export at its statement and a renamed re-export at its specifier', () => {
const lines = Object.fromEntries(result.violations
.filter(value => value.packageName === '@f/plugin')
.map(value => [value.exportName, value.line]))
expect(lines.starred).toBe(lineOf(PLUGIN_ENTRY, "export * from './values.ts'"))
expect(lines.helperImpl).toBe(lineOf(PLUGIN_ENTRY, "export * from './values.ts'"))
expect(lines.renamed).toBe(lineOf(PLUGIN_ENTRY, "export { helperImpl as renamed } from './values.ts'"))
expect(lines.Id).toBe(lineOf(PLUGIN_ENTRY, 'export function Id(value: string): Id { return value as Id }'))
})
it('names the file, line, package, and export, and marks an export whose target does not resolve', () => {
const failures = scanFailures(result)
expect(failures).toContain('packages/f/const-apply/src/index.ts:2 @f/const-apply exports extra')
expect(failures).toContain(`packages/f/plugin/src/index.ts:${String(lineOf(PLUGIN_ENTRY, "export { missing } from './missing.ts'"))}`
+ ' @f/plugin exports missing, whose target does not resolve')
expect(failures).toContain(`packages/f/plugin/src/index.ts:${String(lineOf(PLUGIN_ENTRY, "export * from './gone.ts'"))}`
+ ' @f/plugin exports *, whose target does not resolve')
})
it('reads the Client face and fails an entry that no face compiles', () => {
expect(result.unloadedEntries).toEqual(['packages/f/orphan/src/index.ts'])
expect(scanFailures(result)).toContain('packages/f/orphan/src/index.ts is compiled by neither'
+ ' tsconfig.host.json nor tsconfig.client.json, so its exports go unchecked')
})
})
describe('existing-export list', () => {
it('passes a listed export', () => {
expect(result.violations.some(value => value.packageName === '@f/listed')).toBe(false)
expect(result.listedExports).toBe(2)
})
it('fails unknown packages, entries that are not plugins, empty lists, repeats, and exports no longer reported', () => {
const entry = 'packages/f/listed/src/index.ts'
expect(result.listProblems).toEqual([
'@f/listed lists kept more than once; keep one',
`@f/listed lists gone, which ${entry} no longer exports beyond the rule; remove it`,
`@f/listed lists Typed, which ${entry} no longer exports beyond the rule; remove it`,
`@f/listed lists ListedError, which ${entry} no longer exports beyond the rule; remove it`,
'@f/library: packages/f/library/src/index.ts is not a plugin entry; remove its line',
`@f/unknown has no ${ENTRY_GLOB} entry; remove its line`,
'@f/const-apply lists no exports; remove its line',
])
expect(scanFailures(result)).toContain(`${EXISTING_EXPORTS_FILE}: @f/const-apply lists no exports; remove its line`)
})
})
describe('entry corpus', () => {
it('fails when no function plugin entry or no service plugin entry is found', () => {
const empty = scanRepository(emptyRoot, {}, ['host'])
expect(empty.checkedEntries).toEqual({ function: 0, service: 0 })
expect(scanFailures(empty)).toEqual([
`no function plugin entry matches ${ENTRY_GLOB}; entry discovery or classification is broken`,
`no service plugin entry matches ${ENTRY_GLOB}; entry discovery or classification is broken`,
])
})
it('rejects an entry whose package manifest has no name', () => {
expect(() => discoverEntries(namelessRoot)).toThrow('packages/f/nameless/package.json has no string name')
})
})
+485
View File
@@ -0,0 +1,485 @@
/**
* Reject a value that a plugin entry exports beyond what the Cordis Loader loads.
*
* The rule lives in docs/defensive-patterns/package-surface.md ("A plugin package exports what the Loader loads"):
* a function plugin's entry exports `name`, `inject`, `Config`, and `apply`, a service plugin's entry default-exports
* its plugin class, and either may add the Service Definition classes and error types that other packages extend or
* throw. The Loader imports the entry when its row activates and reads only what the plugin form provides; any other
* value on the entry is API that another package can import statically, which evaluates the entry module without its
* Loader row.
*
* The corpus is every `packages/<group>/<package>/src/index.ts`. An entry that exports a value named `apply` is a
* function plugin. A default export beside `apply` is always reported, even a class allowed below, because the Loader
* then loads the default export instead of the module namespace. An entry without `apply` whose default export is a
* class the Loader can construct is a service plugin: its default export and other names for the same class pass, and
* `name`, `inject`, and `Config` are reported like any other value because the Loader reads them from the class. Other
* entries are not checked: libraries, a default export that is not a class, and an abstract default class, which
* defines a capability seam that providers extend. Each entry is read through the Host compiler face and then the
* Client face; the first face that compiles it classifies it. An entry that neither face compiles fails the gate,
* because it would otherwise go unchecked, and so does a corpus without a function plugin or without a service plugin.
*
* Value-vs-type follows the names each entry exports at run time, resolved against a bound Program because
* `verbatimModuleSyntax` is off: type-only exports and declarations emit nothing, a re-export emits only a run-time
* export of its target, and `export *` brings in every run-time name of its target except `default` and the names the
* module exports itself. A type-only export therefore does not hide a value that `export *` provides under the same
* name, and a name that only `export type *` reaches, at any depth, is a type. A value passes as a class when every
* construct signature builds an instance whose base types reach Cordis `Service` or the global `Error`; class
* declarations, class expressions, and mixin results are judged by what they construct. An export whose target does
* not resolve is reported, and so is an `export *` whose module does not resolve, under the name `*`.
*
* Exports that predate the gate are listed in scripts/plugin-entry-existing-exports.ts. A listed export passes. A list
* line fails when its package has no entry or its entry is not a plugin, when its export list is empty or repeats a
* name, and when it names an export the entry no longer reports, so removing an export also removes its line.
*/
import { globSync, readFileSync } from 'node:fs'
import { join, posix, resolve } from 'node:path'
import ts from 'typescript'
import { EXISTING_PLUGIN_ENTRY_EXPORTS } from './plugin-entry-existing-exports.ts'
import { TypeScriptProject, type CompilerFace } from './ts-project.ts'
const GATE = 'verify-plugin-entry-exports'
const root = resolve(import.meta.dirname, '..')
/** The corpus glob for the root entry of every workspace package. */
export const ENTRY_GLOB = 'packages/*/*/src/index.ts'
/** Repository-relative path of the list of exports that predate the gate. */
export const EXISTING_EXPORTS_FILE = 'scripts/plugin-entry-existing-exports.ts'
/** The rule this gate enforces, named in its diagnostics. */
const RULE = 'docs/defensive-patterns/package-surface.md#a-plugin-package-exports-what-the-loader-loads'
/** Values the Loader reads from a function plugin's module namespace. */
const LOADER_FIELDS: ReadonlySet<string> = new Set(['name', 'inject', 'Config', 'apply'])
/** The plugin forms the rule names: `apply` on the module namespace, or a default-exported plugin class. */
export type PluginForm = 'function' | 'service'
/** Every plugin form, in report order. */
const PLUGIN_FORMS: readonly PluginForm[] = ['function', 'service']
/** Package name to the value exports its plugin entry may keep while they still exist. */
export type ExistingEntryExports = Readonly<Record<string, readonly string[]>>
/** One package root entry that the corpus glob found. */
export interface PluginEntry {
/** Repository-relative POSIX path of the entry. */
readonly file: string
/** The `name` field of the package manifest that owns the entry. */
readonly packageName: string
}
/** One value a plugin entry exports beyond what its form allows. */
export interface EntryValueExport {
/** Repository-relative POSIX path of the entry. */
readonly file: string
/** One-based line of the declaration, re-export specifier, or `export *` statement in the entry. */
readonly line: number
readonly packageName: string
readonly exportName: string
/** True when the export's target does not resolve, so the value cannot be classified. */
readonly unresolved: boolean
}
/** What one repository scan checked and found. */
export interface ScanResult {
/** Number of entries checked, per plugin form. */
readonly checkedEntries: Readonly<Record<PluginForm, number>>
/** Reported exports that the existing-export list does not name, sorted by file, line, and name. */
readonly violations: readonly EntryValueExport[]
/** Defects in the existing-export list. */
readonly listProblems: readonly string[]
/** Entries that no compiler face compiles. */
readonly unloadedEntries: readonly string[]
/** Number of reported exports that the existing-export list names. */
readonly listedExports: number
}
/** How one compiler face classified one entry. */
interface EntryFacts {
/** Undefined for an entry the Loader cannot load as a plugin. */
readonly form: PluginForm | undefined
readonly valueExports: readonly EntryValueExport[]
}
function lineOf(node: ts.Node, sourceFile: ts.SourceFile): number {
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1
}
function resolveAlias(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol {
return (symbol.flags & ts.SymbolFlags.Alias) === 0 ? symbol : checker.getAliasedSymbol(symbol)
}
/**
* Find every package root entry and the package that owns it.
* @param repositoryRoot - absolute repository root.
* @returns entries sorted by path.
* @throws when an owning manifest has no string `name`.
*/
export function discoverEntries(repositoryRoot: string): PluginEntry[] {
return globSync(ENTRY_GLOB, { cwd: repositoryRoot })
.map(file => file.replaceAll('\\', '/'))
.sort()
.map((file) => {
const manifest = posix.join(posix.dirname(posix.dirname(file)), 'package.json')
const parsed: unknown = JSON.parse(readFileSync(join(repositoryRoot, manifest), 'utf8'))
const name = typeof parsed === 'object' && parsed !== null && 'name' in parsed ? parsed.name : undefined
if (typeof name !== 'string') throw new Error(`${GATE}: ${manifest} has no string name`)
return { file, packageName: name }
})
}
/** The Cordis `Service` class as this program resolves it, or undefined when the program does not load Cordis. */
function cordisService(project: TypeScriptProject): ts.Symbol | undefined {
const { checker, program } = project
const resolved = ts.resolveModuleName(
'@deepseek-ai/cordis', join(project.projectRoot, 'package.json'), program.getCompilerOptions(), ts.sys,
).resolvedModule
const sourceFile = resolved === undefined ? undefined : program.getSourceFile(resolved.resolvedFileName)
const moduleSymbol = sourceFile === undefined ? undefined : checker.getSymbolAtLocation(sourceFile)
if (moduleSymbol === undefined) return undefined
const service = checker.getExportsOfModule(moduleSymbol).find(symbol => ts.symbolName(symbol) === 'Service')
return service === undefined ? undefined : resolveAlias(service, checker)
}
/** Whether any hop of an export's alias chain is a type-only import or export. */
function isTypeOnlyAlias(symbol: ts.Symbol, checker: ts.TypeChecker): boolean {
const seen = new Set<ts.Symbol>()
for (let current: ts.Symbol | undefined = symbol; current !== undefined && !seen.has(current);) {
seen.add(current)
if (current.declarations?.some(declaration => ts.isTypeOnlyImportOrExportDeclaration(declaration)) === true) {
return true
}
if ((current.flags & ts.SymbolFlags.Alias) === 0) return false
current = checker.getImmediateAliasedSymbol(current)
}
return false
}
/** One name a module exports at run time: the node that introduces it there, and the value it carries. */
interface RuntimeExport {
/** Undefined for a name a declaration file provides, which has no emit to locate. */
readonly node: ts.Node | undefined
/** Undefined when the export's target does not resolve. */
readonly symbol: ts.Symbol | undefined
}
/** Run-time exports per module, shared by every entry that one Program classifies. */
type RuntimeExportCache = Map<ts.Symbol, ReadonlyMap<string, RuntimeExport>>
function hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean {
return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some(modifier => modifier.kind === kind) ?? false)
}
function bindingNames(name: ts.BindingName): string[] {
if (ts.isIdentifier(name)) return [name.text]
return name.elements.flatMap(element => ts.isOmittedExpression(element) ? [] : bindingNames(element.name))
}
/** The symbol an alias resolves to, or undefined when it reaches no declaration. */
function resolvedTarget(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol | undefined {
const target = resolveAlias(symbol, checker)
return (target.declarations ?? []).length === 0 ? undefined : target
}
/** Run-time exports of the module a specifier names, or undefined when the specifier does not resolve. */
function moduleRuntimeExports(
specifier: ts.Expression, checker: ts.TypeChecker, cache: RuntimeExportCache,
): ReadonlyMap<string, RuntimeExport> | undefined {
const moduleSymbol = checker.getSymbolAtLocation(specifier)
return moduleSymbol === undefined ? undefined : runtimeExports(moduleSymbol, checker, cache)
}
/** Run-time exports of a declaration file or ambient module: its values that no type-only alias reaches. */
function declaredRuntimeExports(moduleSymbol: ts.Symbol, checker: ts.TypeChecker, result: Map<string, RuntimeExport>): void {
for (const exported of checker.getExportsOfModule(moduleSymbol)) {
if (isTypeOnlyAlias(exported, checker)) continue
const target = resolvedTarget(exported, checker)
if (target === undefined || (target.flags & ts.SymbolFlags.Value) !== 0) {
result.set(ts.symbolName(exported), { node: undefined, symbol: target })
}
}
}
/**
* Names a module exports at run time with `verbatimModuleSyntax` off, each with the node that introduces it in the
* module: type-only exports and `declare` declarations emit nothing, a re-export emits only a run-time export of its
* target, and `export *` brings every run-time name of its target except `default` and the names the module exports
* itself.
*/
function runtimeExports(
moduleSymbol: ts.Symbol, checker: ts.TypeChecker, cache: RuntimeExportCache,
): ReadonlyMap<string, RuntimeExport> {
const cached = cache.get(moduleSymbol)
if (cached !== undefined) return cached
const result = new Map<string, RuntimeExport>()
// An `export *` cycle that reaches this module again sees the names collected so far.
cache.set(moduleSymbol, result)
const file = moduleSymbol.valueDeclaration
if (file === undefined || !ts.isSourceFile(file) || file.isDeclarationFile) {
declaredRuntimeExports(moduleSymbol, checker, result)
return result
}
const table = new Map(checker.getExportsOfModule(moduleSymbol).map(symbol => [ts.symbolName(symbol), symbol]))
const own = (name: string): ts.Symbol | undefined => {
const symbol = table.get(name)
return symbol === undefined ? undefined : resolvedTarget(symbol, checker)
}
const add = (name: string, node: ts.Node, symbol: ts.Symbol | undefined): void => {
if (!result.has(name)) result.set(name, { node, symbol })
}
const stars: ts.ExportDeclaration[] = []
for (const statement of file.statements) {
if (ts.isExportDeclaration(statement)) {
if (statement.isTypeOnly) continue
const clause = statement.exportClause
const specifier = statement.moduleSpecifier
if (clause === undefined) {
stars.push(statement)
} else if (ts.isNamespaceExport(clause)) {
add(clause.name.text, clause, specifier === undefined ? undefined : checker.getSymbolAtLocation(specifier))
} else {
for (const element of clause.elements) {
if (element.isTypeOnly) continue
if (specifier === undefined) {
const local = checker.getExportSpecifierLocalTargetSymbol(element)
if (local !== undefined && isTypeOnlyAlias(local, checker)) continue
const target = local === undefined ? undefined : resolvedTarget(local, checker)
if (target === undefined || (target.flags & ts.SymbolFlags.Value) !== 0) add(element.name.text, element, target)
} else {
const source = moduleRuntimeExports(specifier, checker, cache)
const reexported = source?.get((element.propertyName ?? element.name).text)
if (source === undefined || reexported !== undefined) add(element.name.text, element, reexported?.symbol)
}
}
}
} else if (ts.isExportAssignment(statement)) {
if (statement.isExportEquals !== true) add('default', statement, own('default'))
} else if (hasModifier(statement, ts.SyntaxKind.ExportKeyword) && !hasModifier(statement, ts.SyntaxKind.DeclareKeyword)) {
const asDefault = hasModifier(statement, ts.SyntaxKind.DefaultKeyword) ? 'default' : undefined
if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) {
const name = asDefault ?? statement.name?.text
if (name !== undefined) add(name, statement, own(name))
} else if (ts.isVariableStatement(statement)) {
for (const declaration of statement.declarationList.declarations) {
for (const name of bindingNames(declaration.name)) add(name, declaration, own(name))
}
} else if (ts.isEnumDeclaration(statement)) {
if (!hasModifier(statement, ts.SyntaxKind.ConstKeyword)) add(statement.name.text, statement, own(statement.name.text))
} else if (ts.isModuleDeclaration(statement) && ts.isIdentifier(statement.name)) {
const namespace = own(statement.name.text)
if (namespace !== undefined && (namespace.flags & ts.SymbolFlags.ValueModule) !== 0) {
add(statement.name.text, statement, namespace)
}
}
}
}
const explicit = new Set(result.keys())
for (const star of stars) {
const source = star.moduleSpecifier === undefined ? undefined : moduleRuntimeExports(star.moduleSpecifier, checker, cache)
if (source === undefined) {
add('*', star, undefined)
continue
}
for (const [name, { symbol }] of source) {
if (name !== 'default' && !explicit.has(name)) add(name, star, symbol)
}
}
return result
}
function isTypeReference(type: ts.Type): type is ts.TypeReference {
return (type.flags & ts.TypeFlags.Object) !== 0
&& ((type as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference) !== 0
}
/** Whether an instance type or one of its base types, through generic and mixin bases, is a root class. */
function reachesRoot(
type: ts.Type, checker: ts.TypeChecker, isRoot: (symbol: ts.Symbol) => boolean, seen: Set<ts.Type>,
): boolean {
if (seen.has(type)) return false
seen.add(type)
if (type.isIntersection()) return type.types.some(part => reachesRoot(part, checker, isRoot, seen))
const declared = isTypeReference(type) ? type.target : type
const symbol = declared.getSymbol()
if (symbol !== undefined && isRoot(symbol)) return true
return declared.isClassOrInterface()
&& checker.getBaseTypes(declared).some(base => reachesRoot(base, checker, isRoot, seen))
}
/** Whether a value is a class the Loader can construct: it has construct signatures and no abstract declaration. */
function isConstructibleClass(symbol: ts.Symbol, checker: ts.TypeChecker): boolean {
return checker.getTypeOfSymbol(symbol).getConstructSignatures().length > 0
&& !(symbol.declarations ?? []).some(declaration =>
ts.isClassDeclaration(declaration) && hasModifier(declaration, ts.SyntaxKind.AbstractKeyword))
}
/** The plugin form of an entry from its run-time exports, or undefined when the Loader cannot load it as a plugin. */
function pluginForm(exports: ReadonlyMap<string, RuntimeExport>, checker: ts.TypeChecker): PluginForm | undefined {
if (exports.get('apply')?.symbol !== undefined) return 'function'
const pluginClass = exports.get('default')?.symbol
return pluginClass !== undefined && isConstructibleClass(pluginClass, checker) ? 'service' : undefined
}
/** Classify one entry's exports in the face whose program compiled it. */
function classifyEntry(
project: TypeScriptProject, entry: PluginEntry, sourceFile: ts.SourceFile, service: ts.Symbol | undefined,
cache: RuntimeExportCache,
): EntryFacts {
const { checker, program } = project
const moduleSymbol = checker.getSymbolAtLocation(sourceFile)
if (moduleSymbol === undefined) return { form: undefined, valueExports: [] }
const exports = runtimeExports(moduleSymbol, checker, cache)
const form = pluginForm(exports, checker)
if (form === undefined) return { form, valueExports: [] }
const pluginClass = form === 'service' ? exports.get('default')?.symbol : undefined
const isRoot = (symbol: ts.Symbol): boolean => symbol === service
|| (ts.symbolName(symbol) === 'Error'
&& (symbol.declarations ?? []).some(declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile())))
const constructsRootClass = (target: ts.Symbol): boolean => {
const signatures = checker.getTypeOfSymbol(target).getConstructSignatures()
return signatures.length > 0
&& signatures.every(signature => reachesRoot(signature.getReturnType(), checker, isRoot, new Set()))
}
const valueExports: EntryValueExport[] = []
for (const [exportName, { node, symbol }] of exports) {
if (form === 'function' ? LOADER_FIELDS.has(exportName) : symbol === pluginClass) continue
// The Loader loads a default export instead of a function plugin's namespace, so the class allowance never covers it.
if (exportName !== 'default' && symbol !== undefined && constructsRootClass(symbol)) continue
valueExports.push({
file: entry.file,
line: lineOf(node ?? sourceFile, sourceFile),
packageName: entry.packageName,
exportName,
unresolved: symbol === undefined,
})
}
return { form, valueExports }
}
function duplicates(names: readonly string[]): string[] {
const seen = new Set<string>()
return [...new Set(names.filter(name => seen.has(name) || !seen.add(name)))]
}
/** Problems of the existing-export list against what the scan classified. */
function existingListProblems(
existing: ExistingEntryExports, entries: readonly PluginEntry[], facts: ReadonlyMap<string, EntryFacts>,
): string[] {
const problems: string[] = []
const entriesByPackage = new Map(entries.map(entry => [entry.packageName, entry]))
for (const [packageName, exportNames] of Object.entries(existing)) {
const entry = entriesByPackage.get(packageName)
if (entry === undefined) {
problems.push(`${packageName} has no ${ENTRY_GLOB} entry; remove its line`)
continue
}
const entryFacts = facts.get(entry.file)
// An entry that no face compiles is reported on its own; its exports are unknown.
if (entryFacts === undefined) continue
if (entryFacts.form === undefined) {
problems.push(`${packageName}: ${entry.file} is not a plugin entry; remove its line`)
continue
}
if (exportNames.length === 0) problems.push(`${packageName} lists no exports; remove its line`)
for (const name of duplicates(exportNames)) problems.push(`${packageName} lists ${name} more than once; keep one`)
const reported = new Set(entryFacts.valueExports.map(value => value.exportName))
for (const name of new Set(exportNames)) {
if (!reported.has(name)) {
problems.push(`${packageName} lists ${name}, which ${entry.file} no longer exports beyond the rule; remove it`)
}
}
}
return problems
}
/**
* Classify the entries one compiler face compiles and that no earlier face classified. The face's Program stays local
* to this call, so it is collectable before the next face builds its own.
*/
function classifyFace(
repositoryRoot: string, face: CompilerFace, entries: readonly PluginEntry[], facts: Map<string, EntryFacts>,
): void {
const project = new TypeScriptProject(repositoryRoot, face)
const service = cordisService(project)
const cache: RuntimeExportCache = new Map()
for (const entry of entries) {
if (facts.has(entry.file)) continue
const sourceFile = project.program.getSourceFile(resolve(repositoryRoot, entry.file))
if (sourceFile !== undefined) facts.set(entry.file, classifyEntry(project, entry, sourceFile, service, cache))
}
}
/**
* Check every plugin entry against the rule and the existing-export list.
* @param repositoryRoot - absolute root holding `packages/` and the `tsconfig.<face>.json` aggregates.
* @param existing - package name to the value exports that may remain.
* @param faces - compiler faces to load in order; the first face that compiles an entry classifies it.
* @returns the checked counts, the unlisted exports, the list problems, and the uncompiled entries.
*/
export function scanRepository(
repositoryRoot: string = root,
existing: ExistingEntryExports = EXISTING_PLUGIN_ENTRY_EXPORTS,
faces: readonly CompilerFace[] = ['host', 'client'],
): ScanResult {
const entries = discoverEntries(repositoryRoot)
const facts = new Map<string, EntryFacts>()
for (const face of faces) classifyFace(repositoryRoot, face, entries, facts)
const reported = entries.flatMap(entry => facts.get(entry.file)?.valueExports ?? [])
const violations = reported
.filter(value => existing[value.packageName]?.includes(value.exportName) !== true)
.sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line
|| left.exportName.localeCompare(right.exportName))
const checked = (form: PluginForm): number => entries.filter(entry => facts.get(entry.file)?.form === form).length
return {
checkedEntries: { function: checked('function'), service: checked('service') },
violations,
listProblems: existingListProblems(existing, entries, facts),
unloadedEntries: entries.filter(entry => !facts.has(entry.file)).map(entry => entry.file),
listedExports: reported.length - violations.length,
}
}
/**
* Render a scan as failure lines.
* @param result - one repository scan.
* @returns one line per failure, empty when the tree passes.
*/
export function scanFailures(result: ScanResult): string[] {
return [
...PLUGIN_FORMS.filter(form => result.checkedEntries[form] === 0)
.map(form => `no ${form} plugin entry matches ${ENTRY_GLOB}; entry discovery or classification is broken`),
...result.unloadedEntries.map(file =>
`${file} is compiled by neither tsconfig.host.json nor tsconfig.client.json, so its exports go unchecked`),
...result.violations.map(value => `${value.file}:${String(value.line)} ${value.packageName} exports `
+ `${value.exportName}${value.unresolved ? ', whose target does not resolve' : ''}`),
...result.listProblems.map(problem => `${EXISTING_EXPORTS_FILE}: ${problem}`),
]
}
/** CLI entry: report every failure and exit 1, or confirm the invariant holds. */
function main(): void {
const result = scanRepository()
const failures = scanFailures(result)
if (failures.length === 0) {
console.log(`${GATE}: ${String(result.checkedEntries.function)} function plugin and`
+ ` ${String(result.checkedEntries.service)} service plugin entries export only what the Loader loads, types,`
+ ` and Service or Error classes, apart from ${String(result.listedExports)} export(s) listed in`
+ ` ${EXISTING_EXPORTS_FILE}.`)
return
}
console.error(`${GATE}: ${String(failures.length)} problem(s):`)
for (const failure of failures) console.error(` ${failure}`)
if (result.violations.length > 0) {
console.error('\nA function plugin entry exports name, inject, Config, and apply, and a service plugin entry'
+ ' default-exports its plugin class; either may also export types and classes extending Cordis Service or'
+ ` Error (${RULE}).`)
console.error('Keep any other value in an internal module: same-package tests import that module, and other'
+ ' packages reach the behavior through a ctx service.')
}
process.exitCode = 1
}
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) main()
+3 -1
View File
@@ -7,6 +7,7 @@ import {
checkDeclaredPluginRecordWrites,
checkPluginRecordCallers,
DEPENDENCY_POLICY_FILE,
ENTRY_EXPORT_LIST_FILE,
findPluginRecordReferences,
isAdmittedCaller,
OWNER_FILE,
@@ -133,11 +134,12 @@ describe('verify-plugin-record-callers', () => {
expect(checkPluginRecordCallers(corpus(source))).toEqual([])
})
it('admits experimental source, the owner, tests, this gate, and the dependency policy', () => {
it('admits experimental source, the owner, tests, this gate, the dependency policy, and the entry export list', () => {
for (const file of [
EXPERIMENTAL,
OWNER_FILE,
DEPENDENCY_POLICY_FILE,
ENTRY_EXPORT_LIST_FILE,
'packages/session/session-persistence/tests/live-write-contract.ts',
'apps/web/tests/session.e2e.ts',
'examples/demo/tests/demo.spec.ts',
+9 -4
View File
@@ -4,8 +4,9 @@
* `appendPluginRecord` in `@deepseek-ai/dsh-session` appends an ignorable `plugin:` record that the
* experimental persistence catalogue lists and that a Session format migration keeps only on a best-effort
* basis. Experimental packages may rely on that; a release package must declare its events instead.
* The owning module and test files, which exercise the operation, are exempt, as is the published
* dependency policy, which names the function to classify the export without calling it.
* The owning module and test files, which exercise the operation, are exempt, as are the published
* dependency policy and the plugin entry export list, which name the function to classify or record its
* export without calling it.
*
* Discovery is syntax-aware: every identifier spelled `appendPluginRecord` counts — an import, a
* named re-export, a call, a namespace member, a destructured binding, or an alias source — and so
@@ -46,6 +47,9 @@ const GATE_FILES: ReadonlySet<string> = new Set([
/** The published dependency policy names the restricted function to classify the export's package edge. */
export const DEPENDENCY_POLICY_FILE = 'scripts/package-dependency-policy.ts'
/** The plugin entry export list names the restricted function to record the session entry's existing export. */
export const ENTRY_EXPORT_LIST_FILE = 'scripts/plugin-entry-existing-exports.ts'
const SOURCE_EXTENSION = /\.(?:[cm]?[jt]s|[jt]sx)$/u
/** A line continuation, which a string or template literal drops from its value. */
@@ -103,11 +107,12 @@ export function isTestFile(file: string): boolean {
/**
* Whether a file may reference the restricted function.
* @param file - repository-relative path, in POSIX separators.
* @returns whether the file is experimental source, the owner, a test, this gate, or the dependency policy.
* @returns whether the file is experimental source, the owner, a test, this gate, the dependency policy, or the plugin
* entry export list.
*/
export function isAdmittedCaller(file: string): boolean {
return file.startsWith(EXPERIMENTAL_PREFIX) || file === OWNER_FILE || isTestFile(file) || GATE_FILES.has(file)
|| file === DEPENDENCY_POLICY_FILE
|| file === DEPENDENCY_POLICY_FILE || file === ENTRY_EXPORT_LIST_FILE
}
function scriptKind(file: string): ts.ScriptKind {
+103 -5
View File
@@ -1,8 +1,9 @@
import { execFileSync } from 'node:child_process'
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 { collectUpgradeGuideViolations } from './verify-upgrade-guides.ts'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { collectStaleUpgradeGuideAdditions, collectUpgradeGuideViolations } from './verify-upgrade-guides.ts'
const roots: string[] = []
@@ -39,17 +40,38 @@ const VALID_ZH = VALID
.replace('## Change', '## 变更')
.replace('## Migration', '## 迁移')
function fixtureRoot(files: Record<string, string>): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-upgrade-guides-'))
roots.push(root)
function writeGuides(root: string, files: Record<string, string>): void {
for (const [file, source] of Object.entries(files)) {
const path = join(root, 'docs/upgrade-guide', file)
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, source)
}
}
function fixtureRoot(files: Record<string, string>): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-upgrade-guides-'))
roots.push(root)
writeGuides(root, files)
return root
}
/** Run Git with an identity and no user or system configuration, so the fixture ignores the host's settings. */
function git(cwd: string, ...args: string[]): string {
return execFileSync('git', ['-c', 'user.name=t', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'init.defaultBranch=master', ...args], {
cwd,
encoding: 'utf8',
env: { ...process.env, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' },
})
}
/** Commit `files` with the root version `version` on top of the current branch. */
function commit(root: string, version: string, files: Record<string, string>): void {
writeFileSync(join(root, 'package.json'), `${JSON.stringify({ version })}\n`)
writeGuides(root, files)
git(root, 'add', '-A')
git(root, 'commit', '-q', '-m', version)
}
describe('upgrade guide gate', () => {
it('accepts an absent tree and conforming guide pairs, including prerelease versions and CRLF files', () => {
expect(collectUpgradeGuideViolations(fixtureRoot({}))).toEqual([])
@@ -127,4 +149,80 @@ describe('upgrade guide gate', () => {
'v0.1.7/over-limit/guide.zh.md': `${VALID_ZH}${'词 '.repeat(600)}\n`,
}))).toEqual(['docs/upgrade-guide/v0.1.7/over-limit/guide.md: 501 words exceeds the 500-word ceiling'])
})
describe('added guide versions', () => {
const MESSAGE = ': added outside the current version directory; the root version is 0.2.2-rc.1, so move the guide to docs/upgrade-guide/v0.2.2-rc.1/<item>/'
beforeEach(() => {
vi.stubEnv('GIT_CONFIG_GLOBAL', '/dev/null')
vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1')
})
afterEach(() => {
vi.unstubAllEnvs()
})
/** An `origin` whose master holds released guides and whose `release/dsh-0.2.1` branch adds a backported one. */
function originRoot(): string {
const origin = fixtureRoot({})
git(origin, 'init', '-q')
commit(origin, '0.2.2-alpha.3', { 'v0.2.2-alpha.3/frozen/guide.md': VALID, 'v0.2.2-alpha.3/moving/guide.md': VALID })
git(origin, 'checkout', '-q', '-b', 'release/dsh-0.2.1')
commit(origin, '0.2.1-rc.4', { 'v0.2.1-rc.4/backport/guide.md': VALID })
git(origin, 'checkout', '-q', 'master')
return origin
}
/** A clone of `origin`'s master whose index bumps the root version to 0.2.2-rc.1 and stages `files`. */
function bumpedClone(origin: string, files: Record<string, string>, ...cloneArgs: string[]): string {
const root = fixtureRoot({})
git(root, 'clone', '-q', '--single-branch', ...cloneArgs, origin, '.')
writeFileSync(join(root, 'package.json'), `${JSON.stringify({ version: '0.2.2-rc.1' })}\n`)
writeGuides(root, files)
git(root, 'add', '-A')
return root
}
it('accepts guides added in the current directory, edits of released guides, and moves out of a released directory', () => {
const root = bumpedClone(originRoot(), { 'v0.2.2-rc.1/current/guide.md': VALID, 'v0.2.2-alpha.3/frozen/guide.md': `${VALID}edited\n` })
git(root, 'mv', 'docs/upgrade-guide/v0.2.2-alpha.3/moving', 'docs/upgrade-guide/v0.2.2-rc.1/moving')
expect(collectStaleUpgradeGuideAdditions(root, 'HEAD')).toEqual([])
})
it('rejects guides added in a released directory unless the release branch of their line has them', () => {
const root = bumpedClone(originRoot(), {
'v0.2.2-alpha.3/stale/guide.md': VALID,
'v0.2.1-rc.4/backport/guide.md': VALID,
'v0.2.1-rc.4/backport/guide.zh.md': VALID_ZH,
'v0.2.0-rc.2/no-branch/guide.md': VALID,
'README.md': VALID,
})
expect(collectStaleUpgradeGuideAdditions(root, 'HEAD')).toEqual([
'docs/upgrade-guide/v0.2.0-rc.2/no-branch/guide.md',
'docs/upgrade-guide/v0.2.1-rc.4/backport/guide.zh.md',
'docs/upgrade-guide/v0.2.2-alpha.3/stale/guide.md',
].map(path => `${path}${MESSAGE}`))
expect(git(root, 'for-each-ref', 'refs/remotes/origin/release')).toBe('')
})
it('reads a release branch tip in a shallow clone, fetching it only when absent, without cutting the history it already has', () => {
const origin = originRoot()
git(origin, 'merge', '-q', '--no-edit', 'release/dsh-0.2.1')
commit(origin, '0.2.2-alpha.3', { 'v0.2.2-alpha.3/later/guide.md': VALID })
const root = bumpedClone(`file://${origin}`, { 'v0.2.1-rc.4/backport-again/guide.md': VALID }, '--depth=3')
const history = git(root, 'rev-list', 'HEAD')
expect(git(root, 'rev-parse', '--is-shallow-repository').trim()).toBe('true')
expect(collectStaleUpgradeGuideAdditions(root, 'HEAD')).toEqual([`docs/upgrade-guide/v0.2.1-rc.4/backport-again/guide.md${MESSAGE}`])
expect(git(root, 'rev-list', 'HEAD')).toBe(history)
git(origin, 'checkout', '-q', 'release/dsh-0.2.1')
commit(origin, '0.2.1-rc.5', { 'v0.2.1-rc.4/backport-again/guide.md': VALID })
expect(collectStaleUpgradeGuideAdditions(root, 'HEAD')).toEqual([])
expect(git(root, 'rev-list', 'HEAD')).toBe(history)
})
it('names the failing Git command for an unknown base', () => {
const root = bumpedClone(originRoot(), {})
expect(() => collectStaleUpgradeGuideAdditions(root, 'no-such-ref')).toThrow(/`git diff .* no-such-ref -- docs\/upgrade-guide` failed: /u)
})
})
})
+58
View File
@@ -1,12 +1,15 @@
/**
* Enforce the `docs/upgrade-guide/v<version>/<item>/guide.md` layout, metadata,
* sections, and word ceiling defined by the `dsh-create-upgrade-guide` skill.
* With `--base <ref>`, it also rejects guides added since that commit outside the root version's directory.
* `verify-translation-pairing` owns the Chinese sibling's pairing record.
* @module scripts/verify-upgrade-guides
*/
import { execFileSync, spawnSync } from 'node:child_process'
import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { parseArgs } from 'node:util'
import { JSON_SCHEMA, load } from 'js-yaml'
import { fromMarkdown } from 'mdast-util-from-markdown'
@@ -74,8 +77,63 @@ export function collectUpgradeGuideViolations(root: string): string[] {
return violations
}
/**
* Report tracked guides added since `base` outside `docs/upgrade-guide/v<version>/`, where `<version>` is the
* root `package.json` version. A version directory is frozen once that version is released, so a guide that a
* pull request wrote before a release must move to the new version's directory before it merges. A guide that
* the tip of `origin`'s `release/dsh-<x.y.z>` branch for its version line already contains passes, because
* merging a release branch forward carries guides that were current on it. The tip is fetched by commit id,
* without updating any ref, only when such a guide exists and the commit is absent locally; a shallow
* repository fetches only that commit.
* @param root - Repository root: a Git working tree with an `origin` remote.
* @param base - Commit the working tree is compared with: the base-branch commit a pull request merges.
* @returns diagnostics prefixed by the repository-relative guide path.
* @throws Error naming the Git command when Git fails, such as for an unknown `base` or an unreachable `origin`.
*/
export function collectStaleUpgradeGuideAdditions(root: string, base: string): string[] {
const git = (args: readonly string[]): string => {
try {
return execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
} catch (error: unknown) {
const stderr = (error as { stderr?: unknown }).stderr
throw new Error(`\`git ${args.join(' ')}\` failed: ${typeof stderr === 'string' && stderr.trim() !== '' ? stderr.trim() : String(error)}`, { cause: error })
}
}
const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version?: unknown }
if (typeof version !== 'string') throw new Error('package.json: version must be a string')
const current = `${GUIDE_ROOT}/v${version}/`
const released = new Map<string, ReadonlySet<string>>()
const releasedGuides = (line: string): ReadonlySet<string> => {
const tip = git(['ls-remote', 'origin', `refs/heads/release/dsh-${line}`]).split('\t')[0]?.trim() ?? ''
if (tip === '') return new Set()
if (spawnSync('git', ['cat-file', '-e', `${tip}^{commit}`], { cwd: root, stdio: 'ignore' }).status !== 0) {
// Fetching a commit already in a shallow repository with `--depth` would cut the history behind it.
const shallow = git(['rev-parse', '--is-shallow-repository']).trim() === 'true'
// A background maintenance run after a shallow fetch rewrites .git/shallow under later Git commands.
git(['-c', 'maintenance.auto=false', '-c', 'gc.auto=0', 'fetch', '--quiet', '--no-tags', '--no-write-fetch-head', ...(shallow ? ['--depth=1', '--filter=blob:none'] : []), 'origin', tip])
}
return new Set(git(['ls-tree', '-r', '-z', '--name-only', tip, '--', GUIDE_ROOT]).split('\0').filter(Boolean))
}
return git(['diff', '-z', '--name-only', '--no-renames', '--diff-filter=A', base, '--', GUIDE_ROOT])
.split('\0')
.filter((path) => {
const line = /^v(\d+\.\d+\.\d+)/u.exec(path.split('/')[2] ?? '')?.[1]
// `collectUpgradeGuideViolations` reports a path outside any version directory.
if (path === '' || path.startsWith(current) || line === undefined) return false
if (!released.has(line)) released.set(line, releasedGuides(line))
return released.get(line)?.has(path) !== true
})
.map(path => `${path}: added outside the current version directory; the root version is ${version}, so move the guide to ${current}<item>/`)
}
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
const { values } = parseArgs({ options: { base: { type: 'string' } } })
const violations = collectUpgradeGuideViolations(ROOT)
try {
if (values.base !== undefined) violations.push(...collectStaleUpgradeGuideAdditions(ROOT, values.base))
} catch (error: unknown) {
violations.push(`cannot check guides added since ${values.base ?? ''}: ${error instanceof Error ? error.message : String(error)}`)
}
if (violations.length > 0) {
process.stderr.write('verify-upgrade-guides: violations found (see .agents/skills/dsh-create-upgrade-guide/SKILL.md):\n')
for (const violation of violations) process.stderr.write(` ${violation}\n`)
+17 -7
View File
@@ -1,3 +1,4 @@
import { expectDesktopArchive } from './desktop-archive-workflow-test.ts'
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -11,7 +12,8 @@ const workflow = yaml.load(readFileSync(resolve(root, '.github/workflows/windows
permissions: Record<string, string>
concurrency: { group: string; 'cancel-in-progress': boolean }
jobs: Record<string, {
'runs-on': string
defaults?: { run: { shell: string } }
'runs-on': string | string[]
env: Record<string, string>
steps: Array<{
id?: string
@@ -60,6 +62,7 @@ it.skipIf(process.platform !== 'win32')('resets only the allocated checkout with
it('routes manual packaging to the dedicated runner with explicit preset and signing selection', () => {
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { version_mode: { default: 'default', options: ['default', 'follow-dsh', 'build-number', 'manual'] } } })
expect(workflow.jobs.package).not.toHaveProperty('name')
expect(job['runs-on']).toBe('dsh-win-package-trial')
expect(JSON.stringify(job.env)).not.toContain('runner.')
@@ -77,7 +80,7 @@ it('routes manual packaging to the dedicated runner with explicit preset and sig
expect(workflow.on.workflow_dispatch!.inputs.version_mode!.default).toBe('default')
expect(workflow.on.workflow_dispatch!.inputs.source_ref!.default).toBe('master')
expect(workflow.on.workflow_dispatch!.inputs.update_channel!.default).toBe('nightly')
expect(job.env.PACKAGE_VERSION_MODE).toBe('${{ inputs.version_mode }}')
expect(job.env.PACKAGE_VERSION_MODE).toBe("${{ inputs.version_mode == 'follow-dsh' && 'product' || inputs.version_mode == 'build-number' && 'auto' || inputs.version_mode }}")
expect(job.env.PACKAGE_SOURCE_REF).toBe('${{ inputs.source_ref }}')
expect(job.env.DSH_DESKTOP_UPDATE_CHANNEL).toBe('${{ inputs.update_channel }}')
expect(job.env.DSH_PACKAGING_PRESET).toBe('${{ inputs.preset }}')
@@ -105,16 +108,16 @@ it('validates before building and passes the same mode and version to checks and
it('retains failure diagnostics and uploads only the selected successful installer', () => {
const uploads = job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(3)
expect(uploads).toHaveLength(1)
const archive = workflow.jobs['upload-artifact']!
const archival = expectDesktopArchive(archive, 1)
expect(uploads[0]!.if).toBe("always() && steps.checkout.outcome == 'success'")
expect(uploads[0]!.with).toMatchObject({
path: '${{ github.workspace }}/apps/desktop/.desktop-build/packaging-runs/',
'include-hidden-files': true,
})
for (const mode of ['unsigned', 'signed']) {
const upload = uploads.find(step => step.if === `success() && inputs.signing == '${mode}'`)!
expect(upload.with).toMatchObject({ path: '${{ steps.retained.outputs.directory }}/*', 'if-no-files-found': 'error', 'compression-level': 0 })
}
expect(archive.env.DESKTOP_ARCHIVE_NAME).toBe('windows-x64-${{ inputs.signing }}-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}.zip')
expect(archival[0]!.with).toMatchObject({ path: '${{ steps.archive.outputs.path }}', 'if-no-files-found': 'error', archive: false, overwrite: true, name: '${{ env.DESKTOP_ARCHIVE_NAME }}' })
})
it('normalizes priority in the dependency and packaging shells before launching their children', () => {
@@ -211,3 +214,10 @@ it.skipIf(process.platform !== 'win32')('stages helpers that remain usable when
rmSync(directory, { recursive: true, force: true, maxRetries: 3 })
}
})
it('archives with native PowerShell and the persistent packaging store', () => {
const archival = workflow.jobs['upload-artifact']!
expect(archival.defaults?.run.shell).toBe('pwsh')
expect(archival.steps.find(step => step.name === 'Configure persistent pnpm store')?.run)
.toBe(job.steps.find(step => step.name === 'Configure persistent pnpm store')?.run)
})