Merge master and regenerate plugin manager translation record
This commit is contained in:
commit
c2b668ccd8
1469 files changed
+81202
-4545
No files matched your search
+22
-7
@@ -43,10 +43,10 @@ describe('repository build CLI', () => {
|
||||
})
|
||||
|
||||
it('selects the complete build by default and one step set by scope', () => {
|
||||
expect(parseBuildArguments([])).toEqual({ scope: 'complete', profile: undefined })
|
||||
expect(parseBuildArguments(['--scope', 'artifacts', '--profile', 'official'])).toEqual({ scope: 'artifacts', profile: 'official' })
|
||||
expect(parseBuildArguments(['--scope', 'check'])).toEqual({ scope: 'check', profile: undefined })
|
||||
expect(parseBuildArguments(['--scope', 'typecheck'])).toEqual({ scope: 'typecheck', profile: undefined })
|
||||
expect(parseBuildArguments([])).toEqual({ scope: 'complete', profile: undefined, serial: false })
|
||||
expect(parseBuildArguments(['--scope', 'artifacts', '--profile', 'official'])).toEqual({ scope: 'artifacts', profile: 'official', serial: false })
|
||||
expect(parseBuildArguments(['--scope', 'check'])).toEqual({ scope: 'check', profile: undefined, serial: false })
|
||||
expect(parseBuildArguments(['--scope', 'typecheck'])).toEqual({ scope: 'typecheck', profile: undefined, serial: false })
|
||||
})
|
||||
|
||||
it.each([
|
||||
@@ -60,12 +60,27 @@ describe('repository build CLI', () => {
|
||||
})
|
||||
|
||||
describe('repository build steps', () => {
|
||||
it.each(['complete', 'check', 'typecheck'] as const)('gives Host compilers an 8 GiB heap in %s scope', (scope) => {
|
||||
it('parses the explicit serial build option', () => {
|
||||
expect(parseBuildArguments(['--profile', 'official', '--serial'])).toEqual({ scope: 'complete', profile: 'official', serial: true })
|
||||
})
|
||||
|
||||
it.each(['complete', 'artifacts', 'check', 'typecheck'] as const)('chains every %s step when serial execution is selected', (scope) => {
|
||||
const original = buildGates(root, scope)
|
||||
const serial = buildGates(root, scope, {}, true)
|
||||
expect(serial.map(gate => gate.id)).toEqual(original.map(gate => gate.id))
|
||||
for (const [index, gate] of serial.entries()) {
|
||||
const previous = serial[index - 1]
|
||||
if (previous !== undefined) expect(gate.needs).toContain(previous.id)
|
||||
for (const dependency of original[index]!.needs ?? []) expect(gate.needs).toContain(dependency)
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['complete', 'check', 'typecheck'] as const)('gives Host compilers and both aggregate checks an 8 GiB heap in %s scope', (scope) => {
|
||||
const gates = buildGates(root, scope)
|
||||
for (const gate of gates.filter(gate => gate.id === 'host-src' || gate.id === 'host-check')) {
|
||||
for (const gate of gates.filter(gate => gate.id === 'host-src' || gate.id === 'host-check' || gate.id === 'client-check')) {
|
||||
expect(gate.args[0]).toBe('--max-old-space-size=8192')
|
||||
}
|
||||
for (const gate of gates.filter(gate => gate.id === 'client-src' || gate.id === 'client-check')) {
|
||||
for (const gate of gates.filter(gate => gate.id === 'client-src')) {
|
||||
expect(gate.args.some(arg => arg.startsWith('--max-old-space-size'))).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
+17
-6
@@ -38,6 +38,8 @@ export interface BuildArguments {
|
||||
readonly scope: BuildScope
|
||||
/** Client build profile requested by `--profile`; `complete` and `artifacts` scopes only. */
|
||||
readonly profile: string | undefined
|
||||
/** Run build steps without overlap, including when a concurrency override is set. */
|
||||
readonly serial: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -53,6 +55,7 @@ export function parseBuildArguments(args: readonly string[]): BuildArguments {
|
||||
options: {
|
||||
profile: { type: 'string' },
|
||||
scope: { type: 'string' },
|
||||
serial: { type: 'boolean', default: false },
|
||||
},
|
||||
allowPositionals: false,
|
||||
})
|
||||
@@ -63,7 +66,7 @@ export function parseBuildArguments(args: readonly string[]): BuildArguments {
|
||||
if ((scope === 'check' || scope === 'typecheck') && values.profile !== undefined) {
|
||||
throw new Error(`build: --profile selects artifact values and does not apply to --scope ${scope}`)
|
||||
}
|
||||
return { scope, profile: values.profile }
|
||||
return { scope, profile: values.profile, serial: values.serial }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,6 +82,7 @@ export function parseBuildArguments(args: readonly string[]): BuildArguments {
|
||||
* @param root - Repository root containing the compiler and bundle configurations.
|
||||
* @param scope - Steps to include.
|
||||
* @param environment - Environment overlay applied to every step; the parent value of a key mapped to `undefined` is removed.
|
||||
* @param serial - Whether each step must wait for the preceding step in report order.
|
||||
* @returns The gate graph in report order.
|
||||
* @throws If an aggregate configuration is invalid.
|
||||
*/
|
||||
@@ -86,6 +90,7 @@ export function buildGates(
|
||||
root: string,
|
||||
scope: BuildScope,
|
||||
environment: Readonly<Record<string, string | undefined>> = {},
|
||||
serial = false,
|
||||
): Gate[] {
|
||||
const env = { ...environment }
|
||||
const gates: Gate[] = []
|
||||
@@ -112,6 +117,12 @@ export function buildGates(
|
||||
})
|
||||
}
|
||||
}
|
||||
if (serial) {
|
||||
return gates.map((gate, index) => {
|
||||
const previous = gates[index - 1]
|
||||
return previous === undefined ? gate : { ...gate, needs: [...new Set([...(gate.needs ?? []), previous.id])] }
|
||||
})
|
||||
}
|
||||
return gates
|
||||
}
|
||||
|
||||
@@ -153,16 +164,16 @@ async function main(): Promise<number> {
|
||||
if (!process.features.typescript) {
|
||||
throw new Error('build: Node.js TypeScript type stripping is unavailable in this Node.js process; remove --no-experimental-strip-types from NODE_OPTIONS or use a Node.js build with TypeScript support')
|
||||
}
|
||||
const { scope, profile } = parseBuildArguments(process.argv.slice(2))
|
||||
const { scope, profile, serial } = parseBuildArguments(process.argv.slice(2))
|
||||
const root = resolve(import.meta.dirname, '..')
|
||||
const name = scope === 'complete' ? 'build' : scope === 'typecheck' ? 'typecheck' : `build:${scope}`
|
||||
const budget = defaultParallelism()
|
||||
const workers = (gates: readonly Gate[]) => ({
|
||||
workers: Math.min(gates.length, budget),
|
||||
source: describeDefaultParallelism(),
|
||||
workers: serial ? 1 : Math.min(gates.length, budget),
|
||||
source: serial ? '--serial' : describeDefaultParallelism(),
|
||||
})
|
||||
if (scope === 'check' || scope === 'typecheck') {
|
||||
const gates = buildGates(root, scope)
|
||||
const gates = buildGates(root, scope, {}, serial)
|
||||
return runAggregate(name, gates, workers(gates))
|
||||
}
|
||||
|
||||
@@ -170,7 +181,7 @@ async function main(): Promise<number> {
|
||||
const clientEnvironment = resolveClientBuildEnvironment(repositoryEnvironment, profile ?? process.env[CLIENT_BUILD_PROFILE_SELECTOR])
|
||||
const environment = environmentOverlay(process.env, clientBuildProcessEnvironment(process.env, clientEnvironment))
|
||||
rmSync(resolve(root, CLIENT_BUILD_RECORD_PATH), { force: true })
|
||||
const gates = buildGates(root, scope, environment)
|
||||
const gates = buildGates(root, scope, environment, serial)
|
||||
const exitCode = await runAggregate(name, gates, workers(gates))
|
||||
if (exitCode !== 0) return exitCode
|
||||
const record = writeClientBuildRecord(root, clientEnvironment)
|
||||
|
||||
@@ -191,8 +191,18 @@ const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
|
||||
'@deepseek-ai/dsh-experimental-subagent-oar': ['LICENSE-OAR'],
|
||||
// CUA publishes its client API and attributed native source for local macOS builds.
|
||||
'@deepseek-ai/dsh-cua': ['lib/remote-types.js', 'lib/api.js', 'lib/bridge.js', 'lib/native-client.js', 'lib/protocol.js'],
|
||||
'@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'native/Package.swift', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'],
|
||||
'@deepseek-ai/dsh-experimental-cua-macos': ['native/bin', 'cua-helper.json', 'native/Package.swift', 'native/Info.plist', 'native/DSHComputerUse.icns', 'native/build_app.py', 'native/Sources', 'native/tests/swift', 'native/tests/test_swift.py', 'native/LICENSE.cua-driver', 'native/LICENSE.computer-use-icon', 'native/upstream.json', 'native/README.md', 'native/README.zh.md', 'native/protocol.schema.json'],
|
||||
'@deepseek-ai/dsh-webhook-github': ['examples/github-review/cordis.yml', 'examples/github-review/github-ready-review-rule.mjs'],
|
||||
// Liveshare publishes its built Relay gateway entry and the shared runtime
|
||||
// chunk that entry imports, plus the declaration-plane entry and its chunk.
|
||||
// Its `./types` export is a type-only module, so the emitted tree contributes
|
||||
// that one runtime file; the declarations still ship as the whole tree.
|
||||
'@deepseek-ai/dsh-experimental-liveshare': [
|
||||
'lib/owner-gateway/cli.js',
|
||||
'lib/retry-backoff-*.js',
|
||||
'lib/viewer-declarations.js',
|
||||
'lib/viewer-declarations-*.js',
|
||||
],
|
||||
// Owned Worker bundles import this public bootstrap before their business entry.
|
||||
'@deepseek-ai/dsh-app-boot': ['lib/worker/profile-resolution-bootstrap.js'],
|
||||
// Statically linked client libraries keep their stylesheets next to the emitted
|
||||
|
||||
@@ -138,7 +138,7 @@ describe('CI workflow', () => {
|
||||
expect(job.steps).toContainEqual(expect.objectContaining({ run: command }))
|
||||
}
|
||||
for (const [file, command] of [
|
||||
['release-publish.yml', 'pnpm run build:official'],
|
||||
['release-publish.yml', 'pnpm run build:official --serial'],
|
||||
['release-vendor-publish.yml', 'pnpm run build:lib:host'],
|
||||
] as const) {
|
||||
expect(workflowJob(loadWorkflow('.github/workflows/' + file), 'pack').steps)
|
||||
@@ -743,7 +743,7 @@ describe('CI workflow', () => {
|
||||
expect(uploadIndex).toBeGreaterThan(benchmarkIndex)
|
||||
})
|
||||
|
||||
it('splits the Wine Host TypeScript compile and retains its heap budget', () => {
|
||||
it('splits both Wine TypeScript faces and retains their aggregate heap budgets', () => {
|
||||
const wineGates = readFileSync(resolve(root, 'scripts/wine-windows-gates.sh'), 'utf8')
|
||||
|
||||
const references = wineGates.indexOf(
|
||||
@@ -757,6 +757,43 @@ describe('CI workflow', () => {
|
||||
expect(references).toBeGreaterThan(metadata)
|
||||
expect(aggregate).toBeGreaterThan(references)
|
||||
expect(wineGates).not.toContain('-b tsconfig.host.json')
|
||||
const clientReferences = wineGates.indexOf('wine_node "$scratch/logs/client-references.log" --import tsx/esm scripts/compile-referenced-projects.ts client')
|
||||
const clientAggregate = wineGates.indexOf('wine_node "$scratch/logs/client-tsc.log" --max-old-space-size=8192 "$tsc_js" -p tsconfig.client.json --pretty false')
|
||||
expect(clientReferences).toBeGreaterThan(aggregate)
|
||||
expect(clientAggregate).toBeGreaterThan(clientReferences)
|
||||
expect(wineGates).not.toContain('-b tsconfig.client.json')
|
||||
expect(wineGates).toContain(' "$scratch/logs/client-references.log" \\')
|
||||
})
|
||||
|
||||
it('runs only Wine for its manual suite and retains master-push scheduling', () => {
|
||||
const master = loadWorkflow('.github/workflows/ci-master.yml')
|
||||
if (!isRecord(master.on) || !isRecord(master.on.workflow_dispatch)
|
||||
|| !isRecord(master.on.workflow_dispatch.inputs) || !isRecord(master.on.workflow_dispatch.inputs.suite)
|
||||
|| !isRecord(master.jobs)) throw new TypeError('CI master must define manual suites and jobs')
|
||||
expect(master.on.workflow_dispatch.inputs.suite.options).toEqual([
|
||||
'larger-runner-benchmark', 'consolidated-runner-benchmark', 'ssh-helper', 'wine',
|
||||
])
|
||||
const wine = workflowJob(master, 'windows')
|
||||
if (typeof wine.if !== 'string') throw new TypeError('Wine must define a trigger condition')
|
||||
for (const [event, ref, suite, expected] of [
|
||||
['push', 'refs/heads/master', '', true],
|
||||
['push', 'refs/heads/topic', '', false],
|
||||
['pull_request', 'refs/pull/42/merge', 'wine', false],
|
||||
['workflow_dispatch', 'refs/heads/topic', 'wine', true],
|
||||
['workflow_dispatch', 'refs/tags/dsh-v0.2.2-alpha.2', 'wine', true],
|
||||
['workflow_dispatch', 'refs/heads/topic', 'ssh-helper', false],
|
||||
['workflow_dispatch', 'refs/heads/topic', 'larger-runner-benchmark', false],
|
||||
['workflow_dispatch', 'refs/heads/topic', 'consolidated-runner-benchmark', false],
|
||||
] as const) {
|
||||
expect(runInNewContext(wine.if, { github: { event_name: event, ref }, inputs: { suite } }, { timeout: 1000 })).toBe(expected)
|
||||
}
|
||||
const enabled = Object.entries(master.jobs).filter(([, job]) => {
|
||||
if (!isRecord(job)) throw new TypeError('CI master jobs must be objects')
|
||||
if (typeof job.if === 'boolean') return job.if
|
||||
if (typeof job.if !== 'string') throw new TypeError('CI master jobs must define trigger conditions')
|
||||
return runInNewContext(job.if, { github: { event_name: 'workflow_dispatch', ref: 'refs/heads/topic' }, inputs: { suite: 'wine' } }, { timeout: 1000 }) === true
|
||||
}).map(([name]) => name)
|
||||
expect(enabled).toEqual(['windows'])
|
||||
})
|
||||
|
||||
it('cancels superseded master runs without changing the post-merge job inventory', () => {
|
||||
|
||||
@@ -234,12 +234,12 @@ describe('client bundle purity gate', () => {
|
||||
expect(() => resolveId('@deepseek-ai/dsh-spill-policy/notice/internal')).toThrow(/purity/)
|
||||
})
|
||||
|
||||
it('inlines the stateless file-drag entry without admitting its subpaths or UI plugin', () => {
|
||||
expect(resolveId('@deepseek-ai/dsh-util-file-drag')).toBeNull()
|
||||
expect(() => resolveId('@deepseek-ai/dsh-util-file-drag/internal')).toThrow(/purity/)
|
||||
expect(() => resolveId('@deepseek-ai/dsh-client-ui-file-drag')).toThrow(/purity/)
|
||||
it.each(['file-drag'])('inlines the stateless %s entry without admitting its subpaths or UI plugin', (name) => {
|
||||
expect(resolveId(`@deepseek-ai/dsh-util-${name}`)).toBeNull()
|
||||
expect(() => resolveId(`@deepseek-ai/dsh-util-${name}/internal`)).toThrow(/purity/)
|
||||
expect(() => resolveId(`@deepseek-ai/dsh-client-ui-${name}`)).toThrow(/purity/)
|
||||
const deps = clientConfigs()[0]?.deps as { neverBundle: (specifier: string) => boolean }
|
||||
expect(deps.neverBundle('@deepseek-ai/dsh-util-file-drag')).toBe(false)
|
||||
expect(deps.neverBundle(`@deepseek-ai/dsh-util-${name}`)).toBe(false)
|
||||
})
|
||||
|
||||
it('inlines the browser-safe Timer entry while sharing Cordis through the module table', () => {
|
||||
|
||||
@@ -94,7 +94,7 @@ export function referencedProjectsCompilerArgs(
|
||||
* @returns Arguments for `process.execPath`, run from the repository root.
|
||||
*/
|
||||
export function aggregateCheckArgs(face: 'host' | 'client'): string[] {
|
||||
return [...hostHeapArgs(face), fileURLToPath(import.meta.resolve('typescript/bin/tsc')), '-p', `tsconfig.${face}.json`]
|
||||
return ['--max-old-space-size=8192', fileURLToPath(import.meta.resolve('typescript/bin/tsc')), '-p', `tsconfig.${face}.json`]
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -105,7 +105,7 @@ export function aggregateCheckArgs(face: 'host' | 'client'): string[] {
|
||||
* @returns Arguments for `process.execPath`, run from the repository root.
|
||||
*/
|
||||
export function aggregateBuildArgs(face: 'host' | 'client'): string[] {
|
||||
return [...hostHeapArgs(face), fileURLToPath(import.meta.resolve('typescript/bin/tsc')), '-b', `tsconfig.${face}.json`]
|
||||
return ['--max-old-space-size=8192', fileURLToPath(import.meta.resolve('typescript/bin/tsc')), '-b', `tsconfig.${face}.json`]
|
||||
}
|
||||
|
||||
function hostHeapArgs(face: 'host' | 'client'): string[] {
|
||||
|
||||
@@ -41,8 +41,8 @@ describe('Fiber configuration access', () => {
|
||||
const wrapper = ctx.plugin(apply, initial)
|
||||
await wrapper
|
||||
const fiber = wrapper.ctx.fiber
|
||||
const hook = vi.fn(function (this: Fiber, _config: unknown, next: () => unknown) {
|
||||
expect(this).toBe(fiber)
|
||||
const hook = vi.fn((target: Fiber, next: () => unknown) => {
|
||||
expect(target).toBe(fiber)
|
||||
return next()
|
||||
})
|
||||
fiber.ctx.on('internal/config', hook)
|
||||
@@ -66,7 +66,7 @@ describe('Fiber configuration access', () => {
|
||||
const wrapper = ctx.plugin(apply, initial)
|
||||
await wrapper
|
||||
const raw = { value: 2 }
|
||||
wrapper.update(raw)
|
||||
await wrapper.update(raw)
|
||||
await wrapper.await()
|
||||
expect(apply).toHaveBeenLastCalledWith(wrapper.ctx, raw)
|
||||
expect(wrapper.rawConfig).toBe(raw)
|
||||
@@ -78,14 +78,13 @@ describe('Fiber configuration access', () => {
|
||||
|
||||
it('retains a pending raw update until its injection is available', async () => {
|
||||
const ctx = root()
|
||||
ctx.provide('configAccessTest')
|
||||
const apply = vi.fn()
|
||||
const wrapper = ctx.plugin({ inject: ['configAccessTest'], apply }, { value: 1 })
|
||||
const raw = { value: 2 }
|
||||
wrapper.update(raw)
|
||||
await wrapper.ctx.fiber.update(raw)
|
||||
expect(wrapper.rawConfig).toBe(raw)
|
||||
expect(wrapper.effectiveConfig).toBeUndefined()
|
||||
ctx.set('configAccessTest', {})
|
||||
ctx.provide('configAccessTest', {})
|
||||
await wrapper
|
||||
expect(wrapper.effectiveConfig).toBe(raw)
|
||||
expect(apply).toHaveBeenCalledOnce()
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/** Cordis rc.11 updates retain dependency ownership and publish only current configuration. */
|
||||
import type { Awaitable } from '@deepseek-ai/cosmokit'
|
||||
import { Context, FiberState } from '@deepseek-ai/cordis'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
rc11Service: { alive: boolean }
|
||||
rc11View: string
|
||||
rc11Private: boolean
|
||||
}
|
||||
}
|
||||
|
||||
function root() {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
return ctx
|
||||
}
|
||||
|
||||
function barrier() {
|
||||
const gate = Promise.withResolvers<undefined>()
|
||||
onTestFinished(() => { gate.resolve(undefined) })
|
||||
return gate
|
||||
}
|
||||
|
||||
describe('Cordis rc.11 lifecycle', () => {
|
||||
it.each([false, true])('awaits the latest update while loading (inject: %s)', async (inject) => {
|
||||
const ctx = root()
|
||||
ctx.provide('rc11Dependency', 1)
|
||||
const started = barrier()
|
||||
const release = barrier()
|
||||
const applied: number[] = []
|
||||
const disposed: number[] = []
|
||||
const fiber = await ctx.plugin({ inject: inject ? ['rc11Dependency'] : [], async apply(owner: Context, config: { value: number }) {
|
||||
applied.push(config.value)
|
||||
if (config.value === 1) { started.resolve(undefined); await release.promise }
|
||||
owner.effect(() => () => { disposed.push(config.value) })
|
||||
} }, { value: 0 })
|
||||
const first = fiber.update({ value: 1 })
|
||||
await started.promise
|
||||
const second = fiber.update({ value: 2 })
|
||||
const third = fiber.update({ value: 3 })
|
||||
release.resolve(undefined)
|
||||
await Promise.all([first, second, third])
|
||||
expect(applied).toEqual([0, 1, 3])
|
||||
expect(disposed).toEqual([0, 1])
|
||||
expect(fiber.state).toBe(FiberState.ACTIVE)
|
||||
expect(fiber.effectiveConfig).toEqual({ value: 3 })
|
||||
await fiber.dispose()
|
||||
expect(disposed).toEqual([0, 1, 3])
|
||||
})
|
||||
|
||||
it('cleans up a superseded activation failure and accepts the latest update', async () => {
|
||||
const ctx = root()
|
||||
const started = barrier()
|
||||
const release = barrier()
|
||||
const cleanup = vi.fn()
|
||||
const fiber = ctx.plugin(async (owner, config: number) => {
|
||||
owner.effect(() => cleanup)
|
||||
if (config !== 1) return
|
||||
started.resolve(undefined)
|
||||
await release.promise
|
||||
throw new Error('superseded activation')
|
||||
}, 1)
|
||||
await started.promise
|
||||
const updating = fiber.update(2)
|
||||
release.resolve(undefined)
|
||||
await updating
|
||||
expect(cleanup).toHaveBeenCalledOnce()
|
||||
expect(fiber.state).toBe(FiberState.ACTIVE)
|
||||
expect(fiber.effectiveConfig).toBe(2)
|
||||
})
|
||||
|
||||
it.each(['dispose', 'restart'] as const)('retains isolated providers through dependent teardown on %s', async (action) => {
|
||||
const ctx = root()
|
||||
const realm = ctx.isolate('rc11Service')
|
||||
const disposing = barrier()
|
||||
const release = barrier()
|
||||
const events: string[] = []
|
||||
const provider = await ctx.plugin((owner) => {
|
||||
const service = { alive: true }
|
||||
owner.isolate('rc11Service', realm[Context.isolate].rc11Service).provide('rc11Service', service)
|
||||
owner.effect(() => () => { events.push('provider'); service.alive = false })
|
||||
})
|
||||
const consumer = await realm.inject(['rc11Service'], (owner) => {
|
||||
return async () => {
|
||||
disposing.resolve(undefined)
|
||||
await release.promise
|
||||
expect(owner.rc11Service.alive).toBe(true)
|
||||
events.push('consumer')
|
||||
}
|
||||
})
|
||||
const task = provider[action]()
|
||||
await disposing.promise
|
||||
expect(events).toEqual([])
|
||||
release.resolve(undefined)
|
||||
await task
|
||||
await consumer.await()
|
||||
expect(events).toEqual(['consumer', 'provider'])
|
||||
})
|
||||
|
||||
it('separates own isolated provisions from the committed injection', async () => {
|
||||
const ctx = root()
|
||||
ctx.provide('rc11View', 'outer')
|
||||
await ctx.inject(['rc11View'], async (owner) => {
|
||||
const isolated = owner.isolate('rc11View')
|
||||
const withdraw = isolated.reflect.provide('rc11View', 'inner')
|
||||
expect(owner.rc11View).toBe('outer')
|
||||
expect(isolated.rc11View).toBe('inner')
|
||||
await isolated.plugin((child) => { expect(child.rc11View).toBe('inner') })
|
||||
await withdraw()
|
||||
expect(owner.rc11View).toBe('outer')
|
||||
expect(isolated.rc11View).toBe('outer')
|
||||
})
|
||||
await ctx.plugin((owner) => {
|
||||
owner.isolate('rc11Private').provide('rc11Private', true)
|
||||
expect(() => owner.rc11Private).toThrow('without inject')
|
||||
})
|
||||
})
|
||||
|
||||
it('publishes successful retained-instance updates and ignores stale or rejected completions', async () => {
|
||||
const ctx = root()
|
||||
const old = barrier()
|
||||
const failed = Promise.withResolvers<undefined>()
|
||||
const values: unknown[] = []
|
||||
const fiber = await ctx.plugin((owner, config: number) => {
|
||||
values.push(config)
|
||||
owner.on('internal/update', (config: number) => {
|
||||
if (config === 1) return old.promise
|
||||
if (config === 3) return failed.promise
|
||||
})
|
||||
}, 0)
|
||||
const first = fiber.update(1)
|
||||
expect(fiber.effectiveConfig).toBe(0)
|
||||
await fiber.update(2)
|
||||
old.resolve(undefined)
|
||||
await first
|
||||
expect(fiber.effectiveConfig).toBe(2)
|
||||
const third = fiber.update(3)
|
||||
const rejected = expect(third).rejects.toThrow('update rejected')
|
||||
failed.reject(new Error('update rejected'))
|
||||
await rejected
|
||||
expect(fiber.rawConfig).toBe(3)
|
||||
expect(fiber.effectiveConfig).toBe(2)
|
||||
expect(values).toEqual([0])
|
||||
})
|
||||
|
||||
it.each(['raw retention', 'restart', 'dispose'] as const)('does not publish an old update after %s', async (action) => {
|
||||
const ctx = root()
|
||||
const release = barrier()
|
||||
const configs: object[] = []
|
||||
const fiber = await ctx.plugin((owner, config: object) => {
|
||||
configs.push(config)
|
||||
owner.on('internal/update', () => release.promise)
|
||||
}, { value: 0 })
|
||||
const old = fiber.update({ value: 1 })
|
||||
if (action === 'raw retention') fiber.rawConfig = { value: 2 }
|
||||
if (action === 'restart') await fiber.restart()
|
||||
if (action === 'dispose') await fiber.dispose()
|
||||
release.resolve(undefined)
|
||||
await old
|
||||
expect(fiber.effectiveConfig).toBe(configs.at(-1))
|
||||
})
|
||||
|
||||
it('keeps the restarted config identity when a listener delegates', async () => {
|
||||
const ctx = root()
|
||||
const applied: unknown[] = []
|
||||
const fiber = await ctx.plugin((owner, config) => {
|
||||
applied.push(config)
|
||||
owner.on('internal/update', (_config, next): Awaitable<void> => next())
|
||||
}, {})
|
||||
fiber.ctx.on('internal/config', (_fiber, next: () => object) => ({ ...next() }))
|
||||
await fiber.update({ value: 1 })
|
||||
expect(fiber.effectiveConfig).toBe(applied.at(-1))
|
||||
})
|
||||
|
||||
it('supports symbol events and rejects repeated waterfall delegation', async () => {
|
||||
const ctx = root()
|
||||
const name = Symbol('rc11-event')
|
||||
const callback = vi.fn()
|
||||
ctx.on(name, callback)
|
||||
ctx.emit(name, 1)
|
||||
expect(callback).toHaveBeenCalledWith(1)
|
||||
const waterfall = Symbol('rc11-waterfall')
|
||||
ctx.on(waterfall, (next: () => number) => { next(); return next() })
|
||||
expect(() => { ctx.waterfall(waterfall, () => 1) }).toThrow('next() called multiple times')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,85 @@
|
||||
/** Build company-signed, notarized CUA applications using the existing macOS packaging credentials. */
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
import { execa } from 'execa'
|
||||
import { create, extract } from 'tar'
|
||||
import { loadDesktopPackageEnvironment } from '../../apps/desktop/scripts/desktop-package-environment.mjs'
|
||||
import { resolveMacOSNotarizationEnvironment, resolveMacOSSigningEnvironment } from '../../apps/desktop/scripts/desktop-release-environment.mjs'
|
||||
import { withMacOSSigningKeychain } from '../../apps/desktop/scripts/macos-signing-keychain.mjs'
|
||||
import { withMacOSNotarizationProxy } from '../../apps/desktop/scripts/macos-notarization-proxy.ts'
|
||||
import { resolveMacOSPackageSettings } from '../../apps/desktop/scripts/macos-package-settings.mjs'
|
||||
import { notarizeMacOS } from '../../apps/desktop/scripts/notarize-macos.mjs'
|
||||
import { verifyMacOSRuntimeCode } from '../../apps/desktop/scripts/verify-macos-signature.mjs'
|
||||
import { CUA_APPLICATION, CUA_ARCHITECTURES, CUA_MANIFEST, readCuaApplication, sealCuaApplication, verifyCuaHelperPayload, type CuaHelperManifest } from './payload.ts'
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const { values } = parseArgs({ options: { out: { type: 'string' } }, allowPositionals: false })
|
||||
if (process.platform !== 'darwin' || !values.out) throw new Error('Usage on macOS: package.ts --out <new-output-directory>')
|
||||
const root = resolve(import.meta.dirname, '../..')
|
||||
const output = resolve(values.out)
|
||||
const environment = loadDesktopPackageEnvironment('darwin')
|
||||
const signing = resolveMacOSSigningEnvironment(environment)
|
||||
const notary = resolveMacOSNotarizationEnvironment(environment)
|
||||
const settings = resolveMacOSPackageSettings(environment)
|
||||
const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string }
|
||||
const commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim()
|
||||
mkdirSync(output, { recursive: false })
|
||||
const scratch = mkdtempSync(join(tmpdir(), 'dsh-cua-package-'))
|
||||
const controller = new AbortController()
|
||||
const stop = (): void => { controller.abort() }
|
||||
process.once('SIGINT', stop)
|
||||
process.once('SIGTERM', stop)
|
||||
const run = async (command: string, args: string[], env = environment): Promise<void> => {
|
||||
await execa(command, args, { cwd: root, env, extendEnv: false, stdio: 'inherit', cancelSignal: controller.signal, killDescendants: true })
|
||||
}
|
||||
const verify = async (application: string, architecture: 'arm64' | 'x64'): Promise<void> => {
|
||||
verifyMacOSRuntimeCode(application, signing)
|
||||
await run('/usr/bin/lipo', ['-verify_arch', architecture === 'x64' ? 'x86_64' : 'arm64', join(application, 'Contents/MacOS/dsh-cua-native')])
|
||||
await run('/usr/bin/xcrun', ['stapler', 'validate', application])
|
||||
await run('/usr/sbin/spctl', ['--assess', '--type', 'execute', '--verbose=4', application])
|
||||
}
|
||||
try {
|
||||
const payload = join(scratch, 'payload')
|
||||
const applications: CuaHelperManifest['applications'] = []
|
||||
await withMacOSSigningKeychain(environment, async (signingEnvironment) => {
|
||||
for (const architecture of CUA_ARCHITECTURES) {
|
||||
controller.signal.throwIfAborted()
|
||||
const directory = join(payload, 'native/bin', `darwin-${architecture}`)
|
||||
await run('/usr/bin/xcrun', ['python3', join(root, 'packages/experimental/cua-macos/native/build_app.py'),
|
||||
'--arch', architecture === 'x64' ? 'x86_64' : 'arm64', '--scratch-path', join(scratch, `swift-${architecture}`),
|
||||
'--output-directory', directory, '--identity', `Developer ID Application: ${signing.signingIdentity}`], signingEnvironment)
|
||||
const { application } = readCuaApplication(directory)
|
||||
await withMacOSNotarizationProxy(settings.notarizationProxy, () => notarizeMacOS({ appPath: application, ...notary }))
|
||||
await verify(application, architecture)
|
||||
applications.push({ architecture, bundle: sealCuaApplication(directory, application) })
|
||||
}
|
||||
})
|
||||
const manifest: CuaHelperManifest = { schemaVersion: 1, version, commit, teamId: signing.teamId, applications }
|
||||
writeFileSync(join(payload, CUA_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`)
|
||||
verifyCuaHelperPayload(payload, { version, commit })
|
||||
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 })
|
||||
for (const { architecture, bundle } of applications) {
|
||||
const application = join(extracted, 'native/bin', `darwin-${architecture}`, bundle, CUA_APPLICATION)
|
||||
await verify(application, architecture)
|
||||
}
|
||||
writeFileSync(join(output, CUA_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`)
|
||||
console.log(`CUA helper artifact: ${archive}`)
|
||||
} catch (error) {
|
||||
rmSync(join(output, 'cua-helper.tgz'), { force: true })
|
||||
throw error
|
||||
} finally {
|
||||
process.off('SIGINT', stop)
|
||||
process.off('SIGTERM', stop)
|
||||
rmSync(scratch, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
await main()
|
||||
@@ -0,0 +1,130 @@
|
||||
/** Final application bytes and source identity survive packaging; invalid inputs never reach publication. */
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { chmodSync, cpSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { execa } from 'execa'
|
||||
import { create } from 'tar'
|
||||
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) }
|
||||
function fixture() {
|
||||
const root = mkdtempSync(join(tmpdir(), 'cua-payload-test-'))
|
||||
onTestFinished(() => { rmSync(root, { recursive: true, force: true }) })
|
||||
const payload = join(root, 'payload')
|
||||
const applications = CUA_ARCHITECTURES.map((architecture) => {
|
||||
const directory = join(payload, 'native/bin', `darwin-${architecture}`)
|
||||
const application = join(directory, 'unsigned', CUA_APPLICATION)
|
||||
for (const [path, bytes] of Object.entries({
|
||||
'Contents/Info.plist': 'fixture identity', 'Contents/MacOS/dsh-cua-native': `executable ${architecture}`,
|
||||
'Contents/Resources/DSHComputerUse.icns': 'icon', 'Contents/_CodeSignature/CodeResources': 'signature',
|
||||
})) {
|
||||
mkdirSync(join(application, path, '..'), { recursive: true })
|
||||
writeFileSync(join(application, path), bytes)
|
||||
}
|
||||
chmodSync(join(application, 'Contents/MacOS/dsh-cua-native'), 0o755)
|
||||
return { architecture, bundle: sealCuaApplication(directory, application) }
|
||||
})
|
||||
const manifest = { schemaVersion: 1, ...identity, teamId: 'ABCDEFGHIJ', applications }
|
||||
writeFileSync(join(payload, CUA_MANIFEST), JSON.stringify(manifest))
|
||||
return { root, payload, manifest, directory: join(payload, 'native/bin/darwin-arm64') }
|
||||
}
|
||||
|
||||
it.skipIf(process.platform === 'win32')('matches the native build receipt hash and includes post-signing ticket bytes', () => {
|
||||
const f = fixture()
|
||||
const before = readCuaApplication(f.directory)
|
||||
const script = resolve('packages/experimental/cua-macos/native/build_app.py')
|
||||
const digest = execFileSync('python3', ['-c', 'import runpy,sys; from pathlib import Path; print(runpy.run_path(sys.argv[1])["bundle_digest"](Path(sys.argv[2])))', script, before.application], { encoding: 'utf8' }).trim()
|
||||
expect(cuaApplicationDigest(before.application)).toBe(digest)
|
||||
writeFileSync(join(before.application, 'Contents/ticket'), 'notarization ticket')
|
||||
expect(() => readCuaApplication(f.directory)).toThrow('digest')
|
||||
const after = sealCuaApplication(f.directory, before.application)
|
||||
expect(after).not.toBe(before.bundle)
|
||||
expect(readFileSync(join(readCuaApplication(f.directory).application, 'Contents/ticket'), 'utf8')).toBe('notarization ticket')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')('verifies staged and repacked provider bytes before publication', async () => {
|
||||
const f = fixture()
|
||||
expect(verifyCuaHelperPayload(f.payload, identity)).toEqual(f.manifest)
|
||||
const packageRoot = join(f.root, 'package')
|
||||
stageCuaHelperPayload(f.payload, packageRoot, identity)
|
||||
expect(() => { stageCuaHelperPayload(f.payload, packageRoot, identity) }).toThrow('empty native/bin')
|
||||
const tarball = join(f.root, 'provider.tgz')
|
||||
await create({ file: tarball, cwd: f.root, gzip: true, portable: true }, ['package'])
|
||||
await verifyCuaHelperTarball(tarball, identity)
|
||||
const application = readCuaApplication(join(packageRoot, 'native/bin/darwin-arm64')).application
|
||||
writeFileSync(join(application, 'Contents/MacOS/dsh-cua-native'), 'changed after signing')
|
||||
await create({ file: tarball, cwd: f.root, gzip: true, portable: true }, ['package'])
|
||||
await expect(verifyCuaHelperTarball(tarball, identity)).rejects.toThrow('digest')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')('keeps npm tarball bytes when reusing a helper and changes them after re-signing', async ({ signal }) => {
|
||||
const f = fixture()
|
||||
const require = createRequire(import.meta.url)
|
||||
const pnpm = join(dirname(require.resolve('pnpm')), 'bin/pnpm.cjs')
|
||||
const pack = async (label: string, mtime: Date): Promise<Buffer> => {
|
||||
const packageRoot = join(f.root, label, 'provider')
|
||||
const output = join(f.root, label, 'packed')
|
||||
mkdirSync(join(packageRoot, 'lib'), { recursive: true })
|
||||
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',
|
||||
files: ['lib/index.js', 'native/bin', CUA_MANIFEST],
|
||||
}))
|
||||
writeFileSync(join(packageRoot, 'lib/index.js'), 'export const provider = "fixture";\n')
|
||||
for (const entry of readdirSync(packageRoot, { recursive: true, withFileTypes: true })) {
|
||||
if (entry.isFile()) utimesSync(join(entry.parentPath, entry.name), mtime, mtime)
|
||||
}
|
||||
const result = await execa(process.execPath, [pnpm, '--dir', packageRoot, 'pack', '--pack-destination', output], {
|
||||
cwd: packageRoot, env: { CI: 'true' }, cancelSignal: signal, killDescendants: true, reject: false,
|
||||
})
|
||||
expect(result.isCanceled).toBe(false)
|
||||
expect(result.signal).toBeUndefined()
|
||||
expect(result.exitCode, result.stderr).toBe(0)
|
||||
const tarball = join(output, 'deepseek-ai-dsh-experimental-cua-macos-1.0.0.tgz')
|
||||
await verifyCuaHelperTarball(tarball, identity)
|
||||
return readFileSync(tarball)
|
||||
}
|
||||
const first = await pack('first', new Date('2001-01-01T00:00:00Z'))
|
||||
const reused = await pack('reused', new Date('2026-01-01T00:00:00Z'))
|
||||
expect(statSync(join(f.root, 'first/provider/cua-helper.json')).mtimeMs)
|
||||
.not.toBe(statSync(join(f.root, 'reused/provider/cua-helper.json')).mtimeMs)
|
||||
expect(reused.equals(first)).toBe(true)
|
||||
|
||||
const application = readCuaApplication(f.directory).application
|
||||
writeFileSync(join(application, 'Contents/_CodeSignature/CodeResources'), 'another signing timestamp')
|
||||
f.manifest.applications[0]!.bundle = sealCuaApplication(f.directory, application)
|
||||
writeFileSync(join(f.payload, CUA_MANIFEST), JSON.stringify(f.manifest))
|
||||
const rebuilt = await pack('rebuilt', new Date('2026-01-01T00:00:00Z'))
|
||||
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) => {
|
||||
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 === '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 })
|
||||
if (damage === 'permissions') chmodSync(join(before.application, 'Contents/MacOS/dsh-cua-native'), 0o644)
|
||||
if (damage === 'symlink') symlinkSync(join(f.root, 'outside'), join(before.application, 'outside'))
|
||||
writeFileSync(join(f.payload, CUA_MANIFEST), JSON.stringify(f.manifest))
|
||||
expect(() => { stageCuaHelperPayload(f.payload, join(f.root, 'consumer'), identity) }).toThrow()
|
||||
})
|
||||
|
||||
it('keeps company signing outside pull-request release rehearsals', () => {
|
||||
const workflow = readFileSync(resolve('.github/workflows/cua-helper-package.yml'), 'utf8')
|
||||
expect(workflow).toContain('workflow_dispatch:')
|
||||
expect(workflow).toContain('workflow_call:')
|
||||
expect(workflow).not.toContain('pull_request:')
|
||||
expect(workflow).toContain('dsh-mac-package-trial')
|
||||
const release = readFileSync(resolve('.github/workflows/release-publish.yml'), 'utf8')
|
||||
expect(release).toContain('needs: cua-helper')
|
||||
expect(release).toContain('scripts/cua-helper/stage.ts')
|
||||
expect(readFileSync(resolve('.github/workflows/release.yml'), 'utf8')).not.toContain('cua-helper-package.yml')
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
/** Integrity and source binding for notarized Computer Use applications consumed by npm packaging. */
|
||||
import { createHash } from 'node:crypto'
|
||||
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Architectures carried by each published macOS provider package. */
|
||||
export const CUA_ARCHITECTURES = ['arm64', 'x64'] as const
|
||||
/** Native application name shared with the provider receipt. */
|
||||
export const CUA_APPLICATION = 'DSH Computer Use.app'
|
||||
/** Completion record written only after both applications pass distribution checks. */
|
||||
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),
|
||||
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()
|
||||
/** Verified build identity and application generations. */
|
||||
export type CuaHelperManifest = z.infer<typeof Manifest>
|
||||
|
||||
/**
|
||||
* Hash application-relative file names, bytes and executable bits, matching build_app.py.
|
||||
* @param application - Real application directory; links and special files are rejected.
|
||||
* @returns SHA-256 of the complete application, including its notarization ticket.
|
||||
*/
|
||||
export function cuaApplicationDigest(application: string): string {
|
||||
const root = lstatSync(application)
|
||||
if (!root.isDirectory() || root.isSymbolicLink()) throw new Error('CUA application must be a real directory')
|
||||
const files: string[] = []
|
||||
const visit = (directory: string): void => {
|
||||
for (const name of readdirSync(join(application, directory))) {
|
||||
const path = directory ? `${directory}/${name}` : name
|
||||
const stat = lstatSync(join(application, path))
|
||||
if (stat.isDirectory()) visit(path)
|
||||
else if (stat.isFile()) files.push(path)
|
||||
else throw new Error(`CUA application contains a link or special file: ${path}`)
|
||||
}
|
||||
}
|
||||
visit('')
|
||||
const digest = createHash('sha256')
|
||||
for (const path of files.sort()) {
|
||||
const file = join(application, path)
|
||||
digest.update(`${path}\0`).update(createHash('sha256').update(readFileSync(file)).digest())
|
||||
.update(Buffer.from([(lstatSync(file).mode & 0o111) === 0 ? 0 : 1]))
|
||||
}
|
||||
return digest.digest('hex')
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the complete signed application and validate its immutable receipt.
|
||||
* @param directory - One architecture's native/bin directory.
|
||||
* @returns Selected application path and its content digest.
|
||||
*/
|
||||
export function readCuaApplication(directory: string): { application: string; bundle: string } {
|
||||
if (!lstatSync(directory).isDirectory() || !lstatSync(join(directory, 'current.json')).isFile()) throw new Error('CUA receipt requires regular files and directories')
|
||||
const { bundle } = z.object({ bundle: Digest }).strict().parse(JSON.parse(readFileSync(join(directory, 'current.json'), 'utf8')))
|
||||
if (!lstatSync(join(directory, bundle)).isDirectory()) throw new Error('CUA generation must be a real directory')
|
||||
const application = join(directory, bundle, CUA_APPLICATION)
|
||||
for (const path of ['Contents/Info.plist', 'Contents/MacOS/dsh-cua-native', 'Contents/Resources/DSHComputerUse.icns', 'Contents/_CodeSignature/CodeResources']) {
|
||||
if (!lstatSync(join(application, path)).isFile()) throw new Error(`CUA application omits ${path}`)
|
||||
}
|
||||
if ((lstatSync(join(application, 'Contents/MacOS/dsh-cua-native')).mode & 0o111) === 0) throw new Error('CUA helper is not executable')
|
||||
if (cuaApplicationDigest(application) !== bundle) throw new Error('CUA application digest does not match current.json')
|
||||
if (readdirSync(directory).sort().join(',') !== [bundle, 'current.json'].sort().join(',')) throw new Error('CUA release contains unselected application generations')
|
||||
return { application, bundle }
|
||||
}
|
||||
|
||||
/**
|
||||
* Reselect a build after notarization has added its ticket, before distribution.
|
||||
* @param directory - Fresh, build-owned architecture directory.
|
||||
* @param application - Application just notarized and verified by the producer.
|
||||
* @returns Final content digest; old build receipts are replaced.
|
||||
*/
|
||||
export function sealCuaApplication(directory: string, application: string): string {
|
||||
const bundle = cuaApplicationDigest(application)
|
||||
const destination = join(directory, bundle, CUA_APPLICATION)
|
||||
if (destination !== application) {
|
||||
mkdirSync(join(directory, bundle))
|
||||
renameSync(application, destination)
|
||||
for (const name of readdirSync(directory)) {
|
||||
if (name !== bundle && name !== 'current.json') rmSync(join(directory, name), { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
writeFileSync(join(directory, 'current.json'), `${JSON.stringify({ bundle })}\n`)
|
||||
readCuaApplication(directory)
|
||||
return bundle
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @returns Validated producer metadata.
|
||||
*/
|
||||
export function verifyCuaHelperPayload(root: string, expected: { version: string; commit: 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 (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')
|
||||
for (const entry of manifest.applications) {
|
||||
const { bundle } = readCuaApplication(join(bin, `darwin-${entry.architecture}`))
|
||||
if (bundle !== entry.bundle) throw new Error('CUA application differs from the producer manifest')
|
||||
}
|
||||
return manifest
|
||||
}
|
||||
|
||||
/**
|
||||
* Stage verified native applications for the provider's ordinary pnpm pack command.
|
||||
* @param root - Extracted helper artifact.
|
||||
* @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 {
|
||||
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')
|
||||
cpSync(join(root, 'native/bin'), destination, { recursive: true })
|
||||
cpSync(join(root, CUA_MANIFEST), join(packageRoot, CUA_MANIFEST))
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/** Retained CUA selection stays within one producer, attempt and immutable artifact. */
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { selectCuaHelperArtifact } from './select-artifact.ts'
|
||||
|
||||
const repository = 'deepseek-harness/deepseek-harness'
|
||||
const base = `repos/${repository}/actions/runs/123`
|
||||
|
||||
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) => {
|
||||
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 === `${base}/artifacts?per_page=100`) return artifacts
|
||||
throw new Error(`Unexpected GitHub request ${path}`)
|
||||
})
|
||||
return { run, jobs, artifact, artifacts, api }
|
||||
}
|
||||
|
||||
it.each([undefined, '', '2'])('pins attempt %s and finds its artifact across pages', (attempt) => {
|
||||
const f = fixture()
|
||||
expect(selectCuaHelperArtifact(repository, { cua_run_id: '123', cua_run_attempt: attempt }, f.api))
|
||||
.toEqual({ runId: '123', attempt: '2', artifactId: '456' })
|
||||
expect(f.api.mock.calls.some(([path]) => path === base)).toBe(attempt !== '2')
|
||||
})
|
||||
|
||||
it('allows successful CUA packaging when later publication jobs failed', () => {
|
||||
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')
|
||||
})
|
||||
|
||||
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) => {
|
||||
const f = fixture()
|
||||
expect(() => selectCuaHelperArtifact(repository, inputs, f.api)).toThrow()
|
||||
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(['failure', 'cancelled', 'skipped', 'missing', 'duplicate'])(
|
||||
'rejects %s helper jobs without falling back to attempt 1', (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')
|
||||
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) => {
|
||||
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')
|
||||
})
|
||||
|
||||
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')
|
||||
expect(api).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
/** Select one retained, successful CUA packaging attempt without contacting the Mac runner. */
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { appendFileSync, readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { z } from 'zod'
|
||||
|
||||
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(),
|
||||
})) }))
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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')
|
||||
}
|
||||
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')
|
||||
}
|
||||
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 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')
|
||||
}
|
||||
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) }
|
||||
}
|
||||
|
||||
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
|
||||
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}`)
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Query a distributed helper without requesting system permissions or inspecting applications."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
|
||||
def report_output(stdout, stderr):
|
||||
"""Render captured bytes for diagnostics without changing protocol input."""
|
||||
for label, output in [("stdout", stdout), ("stderr", stderr)]:
|
||||
if output:
|
||||
text = output.decode("utf-8", errors="replace") if isinstance(output, bytes) else output
|
||||
print(f"CUA smoke command {label}:\n{text}", file=sys.stderr, flush=True)
|
||||
|
||||
|
||||
def run_checked(command, timeout):
|
||||
"""Return captured bytes and preserve native diagnostics on failure or timeout."""
|
||||
try:
|
||||
return subprocess.run(command, check=True, capture_output=True, timeout=timeout)
|
||||
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
|
||||
report_output(error.stdout, error.stderr)
|
||||
raise
|
||||
|
||||
|
||||
def parse_startup_reply(result):
|
||||
"""Retain both output streams when a successful command returns an unreadable reply."""
|
||||
try:
|
||||
return json.loads(result.stdout.decode("utf-8"))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
report_output(result.stdout, result.stderr)
|
||||
raise
|
||||
|
||||
|
||||
def wait_for_exit(pid, seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return True
|
||||
time.sleep(0.025)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
executable = Path(sys.argv[1]).resolve(strict=True)
|
||||
key = hashlib.sha256(executable.read_bytes()).hexdigest()
|
||||
pid = None
|
||||
with tempfile.TemporaryDirectory(prefix="cua-smoke-", dir="/tmp") as directory:
|
||||
os.chmod(directory, 0o700)
|
||||
try:
|
||||
started = run_checked([str(executable), "--ensure-shared", "--runtime-key", key,
|
||||
"--runtime-directory", directory, "--startup-timeout-ms", "15000"], 25)
|
||||
ready = parse_startup_reply(started)
|
||||
assert ready["runtimeKey"] == key and ready["type"] == "ready", ready
|
||||
pid = ready["pid"]
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
||||
connection.settimeout(20)
|
||||
connection.connect(f"{directory}/{key}.sock")
|
||||
stream = connection.makefile("rwb", buffering=0)
|
||||
hello = {"type": "hello", "protocol": 1, "runtimeKey": key, "config": {
|
||||
"maxRequestBytes": 1048576, "maxResponseBytes": 33554432, "axTimeoutMs": 3000,
|
||||
"textEventIntervalMs": 0.25, "maxClickHoldMs": 5000, "screenshotTimeoutMs": 5000,
|
||||
"timeoutMs": 30000, "graceMs": 5000,
|
||||
}}
|
||||
stream.write((json.dumps(hello) + "\n").encode())
|
||||
admitted = json.loads(stream.readline())
|
||||
assert admitted["type"] == "ready" and admitted["pid"] == pid, admitted
|
||||
for method in ["getCapabilities", "permissionStatus"]:
|
||||
stream.write((json.dumps({"id": method, "method": method, "params": {}}) + "\n").encode())
|
||||
response = json.loads(stream.readline())
|
||||
assert response["id"] == method and "result" in response, response
|
||||
result = response["result"]
|
||||
if method == "getCapabilities":
|
||||
assert result["platform"] == "macos", result
|
||||
else:
|
||||
assert result["launchApplication"]["name"] == "DSH Computer Use.app", result.get("launchApplication", {}).get("name")
|
||||
assert isinstance(result["accessibility"], bool) and isinstance(result["screenRecording"], bool)
|
||||
connection.shutdown(socket.SHUT_WR)
|
||||
assert stream.read() == b"", "helper did not acknowledge connection cleanup"
|
||||
stream.close()
|
||||
assert wait_for_exit(pid, 10), "helper remained alive after its final connection closed"
|
||||
pid = None
|
||||
print("CUA distribution smoke: capabilities, helper identity and cleanup passed")
|
||||
finally:
|
||||
if pid is not None:
|
||||
for action in [signal.SIGTERM, signal.SIGKILL]:
|
||||
try:
|
||||
os.kill(pid, action)
|
||||
except ProcessLookupError:
|
||||
break
|
||||
if wait_for_exit(pid, 5):
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("failed helper did not exit during cleanup")
|
||||
run_checked(["/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister",
|
||||
"-u", str(executable.parents[2])], 10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,13 @@
|
||||
/** Native smoke failures must expose the captured launch error in CI logs. */
|
||||
import { execa } from 'execa'
|
||||
import { expect, it } from 'vitest'
|
||||
|
||||
it.skipIf(process.platform === 'win32')('retains native startup and timeout diagnostics', async ({ signal }) => {
|
||||
const result = await execa('python3', ['-B', '-m', 'unittest', 'discover', '-s', 'scripts/cua-helper', '-p', 'test_smoke.py'], {
|
||||
cancelSignal: signal, killDescendants: true, reject: false,
|
||||
})
|
||||
expect(result.isCanceled).toBe(false)
|
||||
expect(result.signal).toBeUndefined()
|
||||
expect(result.exitCode, result.stderr).toBe(0)
|
||||
expect(result.stderr).toMatch(/Ran [1-9]\d* tests?\b/)
|
||||
})
|
||||
@@ -0,0 +1,14 @@
|
||||
/** 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 { 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})`)
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Smoke command failures retain native diagnostics without performing desktop operations."""
|
||||
from contextlib import redirect_stderr
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import smoke
|
||||
|
||||
|
||||
class SmokeDiagnostics(unittest.TestCase):
|
||||
def test_success_returns_captured_reply_without_replaying_it(self):
|
||||
result = subprocess.CompletedProcess(["helper"], 0, b'{"type":"ready"}', b"")
|
||||
diagnostics = io.StringIO()
|
||||
with patch.object(smoke.subprocess, "run", return_value=result) as run, redirect_stderr(diagnostics):
|
||||
self.assertIs(smoke.run_checked(["helper"], 25), result)
|
||||
run.assert_called_once_with(["helper"], check=True, capture_output=True, timeout=25)
|
||||
self.assertEqual(diagnostics.getvalue(), "")
|
||||
|
||||
def test_native_failure_keeps_code_message_and_stderr(self):
|
||||
error = subprocess.CalledProcessError(1, ["helper"],
|
||||
output='{"type":"error","code":"NATIVE_STARTUP","message":"launch failed"}',
|
||||
stderr="native diagnostic")
|
||||
diagnostics = io.StringIO()
|
||||
with patch.object(smoke.subprocess, "run", side_effect=error), redirect_stderr(diagnostics):
|
||||
with self.assertRaises(subprocess.CalledProcessError) as raised:
|
||||
smoke.run_checked(["helper"], 25)
|
||||
self.assertIs(raised.exception, error)
|
||||
self.assertIn(error.stdout, diagnostics.getvalue())
|
||||
self.assertIn(error.stderr, diagnostics.getvalue())
|
||||
|
||||
def test_timeout_keeps_partial_bytes_and_reraises(self):
|
||||
error = subprocess.TimeoutExpired(["helper"], 25, output=b"partial reply\xff", stderr=b"startup timeout")
|
||||
diagnostics = io.StringIO()
|
||||
with patch.object(smoke.subprocess, "run", side_effect=error), redirect_stderr(diagnostics):
|
||||
with self.assertRaises(subprocess.TimeoutExpired) as raised:
|
||||
smoke.run_checked(["helper"], 25)
|
||||
self.assertIs(raised.exception, error)
|
||||
self.assertIn("partial reply\ufffd", diagnostics.getvalue())
|
||||
self.assertIn("startup timeout", diagnostics.getvalue())
|
||||
|
||||
def test_non_utf8_command_output_preserves_exit_status(self):
|
||||
for status in [0, 1]:
|
||||
with self.subTest(status=status):
|
||||
command = [sys.executable, "-c",
|
||||
f"import os, sys; os.write(1, b'out\\xff'); os.write(2, b'err\\xfe'); sys.exit({status})"]
|
||||
diagnostics = io.StringIO()
|
||||
with redirect_stderr(diagnostics):
|
||||
if status == 0:
|
||||
result = smoke.run_checked(command, 10)
|
||||
self.assertEqual(result.stdout, b"out\xff")
|
||||
self.assertEqual(result.stderr, b"err\xfe")
|
||||
self.assertEqual(diagnostics.getvalue(), "")
|
||||
else:
|
||||
with self.assertRaises(subprocess.CalledProcessError) as raised:
|
||||
smoke.run_checked(command, 10)
|
||||
self.assertEqual(raised.exception.returncode, status)
|
||||
self.assertEqual(raised.exception.stdout, b"out\xff")
|
||||
self.assertIn("out\ufffd", diagnostics.getvalue())
|
||||
self.assertIn("err\ufffd", diagnostics.getvalue())
|
||||
|
||||
def test_valid_startup_reply_stays_silent(self):
|
||||
result = subprocess.CompletedProcess(["helper"], 0, b'{"type":"ready"}', b"diagnostic")
|
||||
diagnostics = io.StringIO()
|
||||
with redirect_stderr(diagnostics):
|
||||
self.assertEqual(smoke.parse_startup_reply(result), {"type": "ready"})
|
||||
self.assertEqual(diagnostics.getvalue(), "")
|
||||
|
||||
def test_empty_or_malformed_startup_reply_retains_output_and_fails(self):
|
||||
for stdout in [b"", b"launch diagnostic\n"]:
|
||||
with self.subTest(stdout=stdout):
|
||||
result = subprocess.CompletedProcess(["helper"], 0, stdout, b"native diagnostic")
|
||||
diagnostics = io.StringIO()
|
||||
with redirect_stderr(diagnostics), self.assertRaises(json.JSONDecodeError) as raised:
|
||||
smoke.parse_startup_reply(result)
|
||||
self.assertEqual(raised.exception.doc, stdout.decode())
|
||||
self.assertIn("native diagnostic", diagnostics.getvalue())
|
||||
if stdout:
|
||||
self.assertIn(stdout.decode(), diagnostics.getvalue())
|
||||
|
||||
def test_invalid_startup_encoding_is_rejected_and_reported(self):
|
||||
result = subprocess.CompletedProcess(["helper"], 0, b'{"type":"ready", "message":"\xff"}', b"native diagnostic")
|
||||
diagnostics = io.StringIO()
|
||||
with redirect_stderr(diagnostics), self.assertRaises(UnicodeDecodeError):
|
||||
smoke.parse_startup_reply(result)
|
||||
self.assertIn('"message":"\ufffd"', diagnostics.getvalue())
|
||||
self.assertIn("native diagnostic", diagnostics.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,24 @@
|
||||
/** Reject incomplete or modified CUA payloads before any npm publication. */
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { extract } from 'tar'
|
||||
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.
|
||||
* @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> {
|
||||
const root = mkdtempSync(join(tmpdir(), 'cua-publish-verify-'))
|
||||
try {
|
||||
await extract({ file: tarball, cwd: root, strict: true, filter: (path, entry) => {
|
||||
if (!path.startsWith('package/') || path.split('/').includes('..')
|
||||
|| !('type' in entry) || !['File', 'Directory'].includes(entry.type)) throw new Error(`Invalid CUA package entry: ${path}`)
|
||||
return true
|
||||
} })
|
||||
verifyCuaHelperPayload(join(root, 'package'), expected)
|
||||
} finally { rmSync(root, { recursive: true, force: true }) }
|
||||
}
|
||||
@@ -123,6 +123,9 @@ async function main(): Promise<void> {
|
||||
// 2. Current official artifacts, so the run never serves an earlier build.
|
||||
await runStep(root, ['run', 'build:official'], abort.signal, 'build:official')
|
||||
verifyBuiltBundles({ entries, packages })
|
||||
if (selection.members.some(member => member.name === '@deepseek-ai/dsh-experimental-cua-macos')) {
|
||||
await runStep(root, ['--dir', 'packages/experimental/cua-macos', 'run', 'build:native'], abort.signal, 'CUA native build')
|
||||
}
|
||||
|
||||
// 3. One immutable, run-owned directory; a later run never overwrites these bytes.
|
||||
const buildId = runId()
|
||||
|
||||
@@ -125,6 +125,7 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
sessionController: 'session.md',
|
||||
sessionSkillCatalog: 'skills.md',
|
||||
sessions: 'session.md',
|
||||
sessionLogDeepSeek: 'session.md',
|
||||
settings: 'settings.md',
|
||||
sessionTitle: 'session-title.md',
|
||||
skills: 'skills.md',
|
||||
@@ -138,6 +139,7 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
jobs: 'jobs.md',
|
||||
jobController: 'jobs.md',
|
||||
sessionTelemetry: 'session-telemetry.md',
|
||||
liveshareShares: 'liveshare.md',
|
||||
agentTeams: 'agent-team.md',
|
||||
claudeCodeMods: 'claude-code-mods.md',
|
||||
tokenMeter: 'token-meter.md',
|
||||
@@ -177,6 +179,8 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
* to a model as `cordis_runtime_inspect what:"client"`).
|
||||
*/
|
||||
export const SERVICE_WALK_EXEMPTIONS: Record<string, string> = {
|
||||
contextMenus: 'client-side interface-typed menu registry — packages/client/ui-context-menu/README.md owns the API',
|
||||
fileActions: 'client-side interface-typed file actions — packages/client/ui-file-actions/README.md owns the API',
|
||||
invocation: 'not a service: per-call accessor (RemoteInvocation | undefined) the Gateway derives for each Remote call — packages/api/gateway/README.md owns the contract',
|
||||
webTerminals: 'client-side terminal view models — packages/api/terminal-controller/README.md owns the API',
|
||||
appReady: 'not a service: launcher-provided successful-startup signal — packages/boot/cmdline/README.md owns the launcher contract',
|
||||
@@ -353,6 +357,25 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
OfficeToPdfResult: 'office-to-pdf.md',
|
||||
OfficeToPdfPriority: 'office-to-pdf.md',
|
||||
OfficeToPdfGeneration: 'office-to-pdf.md',
|
||||
CreatedShare: 'liveshare.md',
|
||||
CreateShareRequest: 'liveshare.md',
|
||||
OwnerIdentityRequest: 'liveshare.md',
|
||||
OwnerIdentityStatus: 'liveshare.md',
|
||||
OwnerRelayState: 'liveshare.md',
|
||||
OwnerShareList: 'liveshare.md',
|
||||
RelayConnectivityView: 'liveshare.md',
|
||||
RelayPublishView: 'liveshare.md',
|
||||
SetRelayRequest: 'liveshare.md',
|
||||
SetShareCapabilitiesRequest: 'liveshare.md',
|
||||
ShareAudit: 'liveshare.md',
|
||||
ShareAuditRequest: 'liveshare.md',
|
||||
ShareCapabilities: 'liveshare.md',
|
||||
ShareCapabilityOffers: 'liveshare.md',
|
||||
SharePermissions: 'liveshare.md',
|
||||
StopShareRequest: 'liveshare.md',
|
||||
StopShareResult: 'liveshare.md',
|
||||
TestPublishRequest: 'liveshare.md',
|
||||
UpdateSharePermissionsRequest: 'liveshare.md',
|
||||
Agent: 'core.md',
|
||||
AgentCancelCause: 'core.md',
|
||||
AgentFactory: 'core.md',
|
||||
@@ -373,8 +396,12 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
RestoredWorktree: 'worktrees.md',
|
||||
ChangeRequestListener: 'forge.md',
|
||||
ChangeRequestRef: 'forge.md',
|
||||
ChangeRequestSnapshot: 'forge.md',
|
||||
ChangeRequestUpdate: 'forge.md',
|
||||
ForgeActionFailure: 'forge.md',
|
||||
ForgeLineComment: 'forge.md',
|
||||
ForgeReviewRequest: 'forge.md',
|
||||
ForgeReviewResult: 'forge.md',
|
||||
ForgeBranches: 'forge.md',
|
||||
ForgeChangeRequestDiff: 'forge.md',
|
||||
ForgeChangeRequestStatesFrame: 'forge.md',
|
||||
@@ -689,6 +716,8 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
AgentMessageSource: 'subagent.md',
|
||||
SubagentCatalogEntry: 'subagent.md',
|
||||
SubagentCatalogState: 'subagent.md',
|
||||
SessionLogUploadRequest: 'session.md',
|
||||
SessionLogUploadExclusion: 'session.md',
|
||||
SessionProjectionsRequest: 'session.md',
|
||||
SessionProjectionsValue: 'session.md',
|
||||
SubagentDescendantListEntry: 'subagent.md',
|
||||
@@ -1104,15 +1133,16 @@ export const CORDIS_CATALOG_POLICY: CordisCatalogPolicy = {
|
||||
],
|
||||
}],
|
||||
inheritedEvents: [
|
||||
{ name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:331' },
|
||||
{ name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:333' },
|
||||
{ name: 'internal/service', summary: 'Interception hook for a service binding (no core producer).', source: 'vendor/cordis/src/events.ts:341' },
|
||||
{ name: 'internal/update', summary: 'Waterfall: a fiber config update is being applied.', source: 'vendor/cordis/src/events.ts:343' },
|
||||
{ name: 'internal/config', summary: 'Waterfall: a fiber config is being resolved before validation.', source: 'vendor/cordis/src/events.ts:339' },
|
||||
{ name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:345' },
|
||||
{ name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:347' },
|
||||
{ name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:349' },
|
||||
{ name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:351' },
|
||||
{ name: 'internal/plugin', summary: 'A plugin fiber was created.', source: 'vendor/cordis/src/events.ts:337' },
|
||||
{ name: 'internal/status', summary: 'A fiber changed lifecycle state.', source: 'vendor/cordis/src/events.ts:339' },
|
||||
{ name: 'internal/service', summary: 'A service binding was refreshed in the matching isolation scope.', source: 'vendor/cordis/src/events.ts:341' },
|
||||
{ name: 'internal/update', summary: 'Waterfall: apply resolved config; omitting next() keeps the current instance.', source: 'vendor/cordis/src/events.ts:348' },
|
||||
{ name: 'internal/commit', summary: 'Persist raw config from a programmatic update unless noSave is set.', source: 'vendor/cordis/src/events.ts:355' },
|
||||
{ name: 'internal/config', summary: 'Waterfall: resolve a candidate after injections are active without publishing it.', source: 'vendor/cordis/src/events.ts:362' },
|
||||
{ name: 'internal/get', summary: 'Waterfall: a service is being read from the store.', source: 'vendor/cordis/src/events.ts:364' },
|
||||
{ name: 'internal/set', summary: 'Waterfall: a service is being written to the store.', source: 'vendor/cordis/src/events.ts:366' },
|
||||
{ name: 'internal/listener', summary: 'A listener was registered.', source: 'vendor/cordis/src/events.ts:368' },
|
||||
{ name: 'internal/dispatch', summary: 'An event is being dispatched to listeners.', source: 'vendor/cordis/src/events.ts:370' },
|
||||
{ name: 'exit', summary: 'The process is exiting on a signal.', source: 'vendor/loader/src/index.ts:25' },
|
||||
{ name: 'loader/config-update', summary: 'The loader config tree changed.', source: 'vendor/loader/src/index.ts:26' },
|
||||
{ name: 'loader/entry-init', summary: 'A config entry is being initialized.', source: 'vendor/loader/src/index.ts:27' },
|
||||
|
||||
@@ -216,7 +216,7 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
pkg: 'experimental-client-ui-forge',
|
||||
title: 'Forge panel Remote',
|
||||
mode: 'service',
|
||||
note: 'Streams one panel state per followed Session: a read-only Git inspection in the Session sandbox, the recognized code host and its sign-in, and the bound change requests with polled status.',
|
||||
note: 'Streams one panel state per followed Session: Git inspection using Session permissions, the recognized code host and its sign-in, and the bound change requests with polled status.',
|
||||
},
|
||||
{
|
||||
key: 'worktrees',
|
||||
@@ -299,6 +299,14 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
consumers: ['agent-loop', 'compaction-basic'],
|
||||
note: 'Adapters register provider implementations; the loop and compaction call the provider-neutral stream service.',
|
||||
},
|
||||
{
|
||||
key: 'sessionLogDeepSeek',
|
||||
pkg: 'session-log-deepseek',
|
||||
title: 'Session-log upload policy',
|
||||
mode: 'core',
|
||||
implementations: [],
|
||||
note: 'Plugins register caller-owned exclusions before the canonical Session-log request contribution is prepared; unmatched requests use normal upload eligibility.',
|
||||
},
|
||||
{
|
||||
key: 'deepseekLlmApiExtensions',
|
||||
pkg: 'deepseek-llm-api-extensions',
|
||||
@@ -959,6 +967,13 @@ const SERVICE_ROLES: ServiceRole[] = [
|
||||
consumers: ['tool-cordis'],
|
||||
note: 'Registers host inspect providers, mirrors the client provider manifest, and routes client queries through the dynamic Cordis transport.',
|
||||
},
|
||||
{
|
||||
key: 'liveshareShares',
|
||||
pkg: 'experimental-liveshare',
|
||||
title: 'Owner share management Remote',
|
||||
mode: 'service',
|
||||
note: 'Publishes the owner share-management operations as one Typert Remote namespace that the owner client face calls; every method delegates to the same operations the same-origin routes used.',
|
||||
},
|
||||
]
|
||||
|
||||
function generatedHeader(title: string): string[] {
|
||||
|
||||
@@ -81,6 +81,17 @@ describe('Official bundle catalog generation', () => {
|
||||
expect(() => { syncOfficialBundleCatalog(root, true) }).toThrow('is stale')
|
||||
})
|
||||
|
||||
it('preserves default-hidden discovery before installation', () => {
|
||||
const root = fixture()
|
||||
const name = ON_DEMAND_BUNDLES[0]!
|
||||
updateManifest(root, name, { dsh: { bundle: { patch: './cordis.patch.yml', listedByDefault: false } } })
|
||||
expect(generateOfficialBundleCatalog(root)[0]?.listedByDefault).toBe(false)
|
||||
syncOfficialBundleCatalog(root, false)
|
||||
expect(readFileSync(join(root, output), 'utf8')).toContain('listedByDefault: false')
|
||||
updateManifest(root, name, { dsh: { bundle: { patch: './cordis.patch.yml', listedByDefault: 'hidden' } } })
|
||||
expect(() => generateOfficialBundleCatalog(root)).toThrow('listedByDefault must be a boolean')
|
||||
})
|
||||
|
||||
it.each([[], ['macos'], 'darwin'].map(platforms => ({ platforms })))('rejects invalid package platform metadata $platforms', ({ platforms }) => {
|
||||
const root = fixture()
|
||||
updateManifest(root, ON_DEMAND_BUNDLES[0]!, { dsh: { bundle: { patch: './cordis.patch.yml', platforms } } })
|
||||
|
||||
@@ -22,7 +22,7 @@ const OUTPUT = 'packages/util/official-bundles/src/catalog.generated.ts'
|
||||
*/
|
||||
export function generateOfficialBundleCatalog(root: string, names: readonly string[] = ON_DEMAND_BUNDLES): OfficialBundleCatalogEntry[] {
|
||||
if (names.length === 0 || new Set(names).size !== names.length) throw new Error('Official on-demand catalog must contain distinct package names')
|
||||
const manifests = new Map<string, { path: string; private: boolean; bundle: boolean; platforms?: DshBundleManifest['platforms']; runtime: string[] }>()
|
||||
const manifests = new Map<string, { path: string; private: boolean; bundle: boolean; platforms?: DshBundleManifest['platforms']; listedByDefault?: boolean; runtime: string[] }>()
|
||||
for (const path of globSync(['packages/*/*/package.json', 'apps/*/package.json', 'vendor/*/package.json'], { cwd: root }).map(path => path.replaceAll('\\', '/')).sort()) {
|
||||
const manifest = JSON.parse(readFileSync(resolve(root, path), 'utf8')) as {
|
||||
name: string
|
||||
@@ -30,12 +30,15 @@ export function generateOfficialBundleCatalog(root: string, names: readonly stri
|
||||
dependencies?: Record<string, string>
|
||||
optionalDependencies?: Record<string, string>
|
||||
peerDependencies?: Record<string, string>
|
||||
dsh?: { bundle?: { patch?: unknown; platforms?: DshBundleManifest['platforms'] } }
|
||||
dsh?: { bundle?: { patch?: unknown; platforms?: DshBundleManifest['platforms']; listedByDefault?: boolean } }
|
||||
}
|
||||
if (manifests.has(manifest.name)) throw new Error(`duplicate workspace package ${manifest.name}`)
|
||||
const listedByDefault = manifest.dsh?.bundle?.listedByDefault
|
||||
if (listedByDefault !== undefined && typeof listedByDefault !== 'boolean') throw new Error(`${manifest.name}: dsh.bundle.listedByDefault must be a boolean`)
|
||||
const runtime = ['dependencies', 'optionalDependencies', 'peerDependencies'] as const
|
||||
manifests.set(manifest.name, { path, private: manifest.private === true, bundle: manifest.dsh?.bundle?.patch !== undefined,
|
||||
...manifest.dsh?.bundle?.platforms === undefined ? {} : { platforms: manifest.dsh.bundle.platforms },
|
||||
...listedByDefault === undefined ? {} : { listedByDefault },
|
||||
runtime: runtime.flatMap(section => Object.keys(manifest[section] ?? {})) })
|
||||
}
|
||||
const visited = new Set<string>()
|
||||
@@ -77,7 +80,9 @@ export function generateOfficialBundleCatalog(root: string, names: readonly stri
|
||||
}
|
||||
}
|
||||
}
|
||||
return { packageName, ...entry.platforms === undefined ? {} : { platforms: entry.platforms },
|
||||
return { packageName,
|
||||
...entry.listedByDefault === undefined ? {} : { listedByDefault: entry.listedByDefault },
|
||||
...entry.platforms === undefined ? {} : { platforms: entry.platforms },
|
||||
meta: { title: meta.title, description: meta.description, icon: meta.icon } }
|
||||
})
|
||||
}
|
||||
@@ -95,6 +100,7 @@ export function renderOfficialBundleCatalog(entries: readonly OfficialBundleCata
|
||||
+ entries.map(entry => ' {\n'
|
||||
+ ` packageName: ${quote(entry.packageName)},\n`
|
||||
+ (entry.platforms === undefined ? '' : ` platforms: [${entry.platforms.map(quote).join(', ')}],\n`)
|
||||
+ (entry.listedByDefault === undefined ? '' : ` listedByDefault: ${entry.listedByDefault},\n`)
|
||||
+ ' meta: {\n'
|
||||
+ ` title: ${localized(entry.meta.title)},\n`
|
||||
+ ` description: ${localized(entry.meta.description)},\n`
|
||||
|
||||
@@ -4,6 +4,7 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import type { Awaitable } from '@deepseek-ai/cosmokit'
|
||||
import { Context, type Fiber, type Plugin } from '@deepseek-ai/cordis'
|
||||
import Loader, { Group } from '@deepseek-ai/cordis-plugin-loader'
|
||||
import Include from '@deepseek-ai/cordis-plugin-include'
|
||||
@@ -110,7 +111,7 @@ describe('volatile Loader updates', () => {
|
||||
it('bypasses custom update hooks for volatile changes and retains them for mixed changes', async () => {
|
||||
const ctx = await runtimeContext()
|
||||
const hooks: string[] = []
|
||||
const globalHook = vi.fn((_config: unknown, _noSave: boolean, next: () => void) => { next() })
|
||||
const globalHook = vi.fn((_config: unknown, next: () => Awaitable<void>) => next())
|
||||
ctx.on('internal/update', globalHook, { global: true })
|
||||
const fiber = await mountEntry(ctx, { Config, apply(owner: Context) {
|
||||
owner.on('internal/update', (config: ReturnType<typeof Config>) => {
|
||||
@@ -144,7 +145,7 @@ describe('volatile Loader updates', () => {
|
||||
await fiber.await()
|
||||
expect(apply).toHaveBeenCalledTimes(3)
|
||||
const ordinary = await mountEntry(ctx, { Config: z.object({ value: z.string() }), apply() { apply() } }, { value: 'same' })
|
||||
ordinary.update({ value: 'same' })
|
||||
await ordinary.update({ value: 'same' })
|
||||
await ordinary.await()
|
||||
expect(apply).toHaveBeenCalledTimes(5)
|
||||
})
|
||||
@@ -243,9 +244,9 @@ it('reloads real YAML and persists plain values independently of custom update h
|
||||
expect(include.store.group!.fiber).toBe(group)
|
||||
expect(group.uid).toBe(groupUid)
|
||||
expect(configs[0]!.title.get()).toBe('file-update')
|
||||
entry.fiber!.update({ title: 'program-update', group: { list: ['item'] } })
|
||||
await entry.fiber!.update({ title: 'program-update', group: { list: ['item'] } })
|
||||
expect(entry.options.config).toEqual({ title: 'program-update', group: { list: ['item'] } })
|
||||
entry.fiber!.update({ title: 'ephemeral' }, true)
|
||||
await entry.fiber!.update({ title: 'ephemeral' }, true)
|
||||
expect(entry.options.config).toEqual({ title: 'program-update', group: { list: ['item'] } })
|
||||
await ctx.fiber.dispose()
|
||||
const saved = await readFile(filename, 'utf8')
|
||||
@@ -298,11 +299,11 @@ it('updates volatile children through Group and Include custom updates and saves
|
||||
const originalConsumer = consumer.fiber
|
||||
const initial = configs[0]!
|
||||
|
||||
group.fiber!.update([child('group-update')])
|
||||
await group.fiber!.update([child('group-update')])
|
||||
await ctx.loader.await()
|
||||
expect(initial.title.get()).toBe('group-update')
|
||||
expect(group.options.config).toEqual([child('group-update')])
|
||||
includeEntry.fiber!.update({ path: includePath, patches: [{ id: 'consumer', config: { title: 'include-update' } }] })
|
||||
await includeEntry.fiber!.update({ path: includePath, patches: [{ id: 'consumer', config: { title: 'include-update' } }] })
|
||||
await ctx.loader.await()
|
||||
expect(initial.title.get()).toBe('include-update')
|
||||
expect(includeEntry.fiber).toBe(originalInclude)
|
||||
@@ -315,14 +316,14 @@ it('updates volatile children through Group and Include custom updates and saves
|
||||
|
||||
const ordinary = await ctx.loader.create({ name: 'cordis:volatile-test', config: {} })
|
||||
const entry = ctx.loader.resolve(ordinary)
|
||||
entry.fiber!.update({ title: 'custom-update', fixed: 'ordinary' })
|
||||
await entry.fiber!.update({ title: 'custom-update', fixed: 'ordinary' })
|
||||
expect(childUpdates).toHaveBeenCalledOnce()
|
||||
expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' })
|
||||
expect((entry.fiber!.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('hello')
|
||||
entry.fiber!.update({ title: 'ephemeral', fixed: 'ordinary' }, true)
|
||||
expect((entry.fiber!.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('custom-update')
|
||||
await entry.fiber!.update({ title: 'ephemeral', fixed: 'ordinary' }, true)
|
||||
expect(childUpdates).toHaveBeenCalledTimes(2)
|
||||
expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' })
|
||||
expect(() => { entry.fiber!.update({ nested: { count: -1 } }) }).toThrow()
|
||||
expect(() => { void entry.fiber!.update({ nested: { count: -1 } }) }).toThrow()
|
||||
expect(childUpdates).toHaveBeenCalledTimes(2)
|
||||
expect(entry.options.config).toEqual({ title: 'custom-update', fixed: 'ordinary' })
|
||||
})
|
||||
@@ -347,9 +348,9 @@ it('commits volatile edits in place and retains direct Fiber updates', async ()
|
||||
const current = fiber.effectiveConfig as ReturnType<typeof Config>
|
||||
expect(current.title.get()).toBe('mixed')
|
||||
|
||||
const hook = vi.fn((_config: unknown, _noSave: boolean, next: () => void) => { next() })
|
||||
const hook = vi.fn((_config: unknown, next: () => Awaitable<void>) => next())
|
||||
fiber.ctx.on('internal/update', hook)
|
||||
fiber.update({ title: 'direct' })
|
||||
await fiber.update({ title: 'direct' })
|
||||
await fiber.await()
|
||||
expect(hook).toHaveBeenCalledOnce()
|
||||
expect(apply).toHaveBeenCalledTimes(3)
|
||||
@@ -368,7 +369,7 @@ it('parses a volatile-only update through the config hook without patching the e
|
||||
const current = fiber.effectiveConfig as ReturnType<typeof Config>
|
||||
const resolveHook = vi.fn((_raw: unknown, next: () => unknown) => next())
|
||||
fiber.ctx.on('internal/config', resolveHook)
|
||||
const contextPatch = vi.fn((_entry: unknown, next: () => void) => { next() })
|
||||
const contextPatch = vi.fn((_entry: unknown, next: () => Awaitable<void>) => next())
|
||||
ctx.on('loader/patch-context', contextPatch)
|
||||
trim.mockClear()
|
||||
trace.length = 0
|
||||
@@ -594,7 +595,7 @@ it('keeps an ordinary plugin mounted when an absent object becomes its explicit
|
||||
it('keeps a noSave volatile value as the pending raw config across a no-op entry update', async () => {
|
||||
const ctx = await runtimeContext()
|
||||
const fiber = await mountEntry(ctx, { Config, apply() {} }, { title: 'saved' })
|
||||
fiber.update({ title: 'ephemeral' }, true)
|
||||
await fiber.update({ title: 'ephemeral' }, true)
|
||||
await fiber.await()
|
||||
expect((fiber.effectiveConfig as ReturnType<typeof Config>).title.get()).toBe('ephemeral')
|
||||
expect(fiber.entry!.options.config).toEqual({ title: 'saved' })
|
||||
|
||||
@@ -133,8 +133,7 @@ describe('catalog and local closure', () => {
|
||||
// A vendor package keeps its own version line, so a run must not assume one shared version.
|
||||
expect(packages.get('@deepseek-ai/cordis')?.manifest.version)
|
||||
.not.toBe(packages.get('@deepseek-ai/dsh-brand')?.manifest.version)
|
||||
// Nothing in this closure is built for another platform, on any host.
|
||||
expect(selection.foreignTargets).toEqual([])
|
||||
expect(selection.foreignTargets).toEqual(process.platform === 'darwin' ? [] : ['@deepseek-ai/dsh-experimental-cua-macos'])
|
||||
})
|
||||
|
||||
it('follows install, optional, and required peer edges but not optional peers', () => {
|
||||
|
||||
@@ -604,8 +604,6 @@
|
||||
"fd6a096d3e7b6ef3e57058b9246118020d10aab852ba64f3296ba07d9e8e7116": 1
|
||||
},
|
||||
"packages/client/ui-sidebar-documentpreview/tests/fixtures.client.ts": {
|
||||
"410ac7f98f84d730fc008a23d09f26dd5e8d329c91df6e4d8977255b07935a4c": 1,
|
||||
"5fac996b1dd9ca4a26580c92e56a82ebe711af84cb711042265e4c03d1997a17": 1,
|
||||
"bccbd200429e3147b8602a65bc06d46264a54c0318232051adeac835deaa311b": 1
|
||||
},
|
||||
"packages/client/ui-sidebar-documentpreview/tests/html-body.client.spec.tsx": {
|
||||
|
||||
@@ -51,11 +51,18 @@ const DUPLICATE_SAFE_PACKAGES: readonly string[] = [
|
||||
* prominent heading in the pull request description.
|
||||
*/
|
||||
const SAFE_HOST_DEPENDENCY_EXPORTS = {
|
||||
'@deepseek-ai/dsh-atomic-write': ['withFileLock'],
|
||||
'@deepseek-ai/dsh-atomic-write': ['withFileLock', 'writeFileAtomic'],
|
||||
'@deepseek-ai/dsh-computer-use/brand': ['ComputerUseProviderName'],
|
||||
'@deepseek-ai/dsh-credentials': ['credentialKey'],
|
||||
'@deepseek-ai/dsh-deque': ['Deque'],
|
||||
// The Liveshare wire codec and identity helpers are stateless functions over caller-owned values.
|
||||
'@deepseek-ai/dsh-experimental-liveshare-protocol': [
|
||||
'LIVESHARE_CAPABILITIES', 'LIVESHARE_PROTOCOL_VERSION', 'parseRelayFrame', 'parseShareAccessState',
|
||||
'parseTunnelWorkerCommand', 'parseTunnelWorkerEvent', 'rawText', 'sendFrame', 'unsupportedFrameRefusal',
|
||||
'viewerRequestFields', 'identityFromKey', 'identityKeyOf',
|
||||
],
|
||||
'@deepseek-ai/dsh-llm': ['callConfigEquals'],
|
||||
'@deepseek-ai/dsh-session': ['SessionId'],
|
||||
'@deepseek-ai/dsh-session-format': ['sessionFormatLogFilename'],
|
||||
'@deepseek-ai/dsh-storage-domain': ['defineDomain'],
|
||||
'@deepseek-ai/dsh-timeout': ['MAX_TIMER_DELAY_MS'],
|
||||
|
||||
@@ -86,6 +86,7 @@ describe('release families', () => {
|
||||
'@deepseek-ai/dsh-experimental-inspector-profile',
|
||||
'@deepseek-ai/dsh-experimental-inspector',
|
||||
'@deepseek-ai/dsh-experimental-liveshare-protocol',
|
||||
'@deepseek-ai/dsh-experimental-liveshare',
|
||||
'@deepseek-ai/dsh-personalized-recommendations',
|
||||
'@deepseek-ai/dsh-experimental-plugin-market-bundle',
|
||||
'@deepseek-ai/dsh-plugin-recommendations',
|
||||
@@ -263,7 +264,7 @@ describe('release families', () => {
|
||||
const dsh = member('apps/cli', '@deepseek-ai/dsh')
|
||||
const providers = ON_DEMAND_BUNDLES.map(name => member(`packages/subagent/${name}`, name))
|
||||
const plan = releaseFamily('dsh').publishOrder([dsh, ...providers])
|
||||
expect(plan.order.map(entry => entry.name)).toEqual([...ON_DEMAND_BUNDLES, dsh.name])
|
||||
expect(plan.order.map(entry => entry.name)).toEqual([...ON_DEMAND_BUNDLES.toSorted(), dsh.name])
|
||||
expect(dsh.manifest).toEqual({})
|
||||
expect(plan.droppedPeerEdges).toEqual([])
|
||||
})
|
||||
@@ -279,8 +280,8 @@ describe('release families', () => {
|
||||
peerDependencies: { '@deepseek-ai/dsh': 'workspace:*' },
|
||||
}))
|
||||
const plan = releaseFamily('dsh').publishOrder([dsh, ...providers])
|
||||
expect(plan.order.map(entry => entry.name)).toEqual([...ON_DEMAND_BUNDLES, dsh.name])
|
||||
expect(plan.droppedPeerEdges).toEqual(ON_DEMAND_BUNDLES.map(name => ({ consumer: name, peer: dsh.name })))
|
||||
expect(plan.order.map(entry => entry.name)).toEqual([...ON_DEMAND_BUNDLES.toSorted(), dsh.name])
|
||||
expect(plan.droppedPeerEdges).toEqual(ON_DEMAND_BUNDLES.toSorted().map(name => ({ consumer: name, peer: dsh.name })))
|
||||
})
|
||||
|
||||
it.each(['dependencies', 'optionalDependencies', 'peerDependencies'])(
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
* the same artifact safe.
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { verifyCuaHelperTarball } from '../cua-helper/verify-tarball.ts'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
@@ -184,6 +186,11 @@ export async function publishRelease(familyId: string, directory: string, distTa
|
||||
const tarball = join(directory, filename)
|
||||
return { tarball, ...packedIdentity(tarball) }
|
||||
})
|
||||
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 })
|
||||
}
|
||||
if (distTag !== undefined) {
|
||||
for (const member of order) verifyDistTag(member, distTag)
|
||||
}
|
||||
@@ -199,7 +206,8 @@ export async function publishRelease(familyId: string, directory: string, distTa
|
||||
throw new Error(
|
||||
`${name}@${version} is already published with different content`
|
||||
+ `\n registry: ${state.integrity}\n packed: ${local}`
|
||||
+ '\nBump the version, or investigate why the build is not reproducible.',
|
||||
+ '\nRetry a partial publication with its original release tarballs; rebuilding can change signed bytes.'
|
||||
+ '\nPublish a new version only when the package contents intentionally change.',
|
||||
)
|
||||
}
|
||||
console.log(`release publish: ${progress} ${name}@${version} already published, skipping`)
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Verify a release family's version baseline, and — when publishing — that the
|
||||
* run comes from the family's tag and its members are publishable.
|
||||
*
|
||||
* Publication happens only from GitHub Actions, so the tag and publishability
|
||||
* checks are gates on the workflow, not advisory local warnings
|
||||
* Publication happens only from GitHub Actions. Publishability is mandatory;
|
||||
* tag validation may be explicitly bypassed with `--skip-tag-check`
|
||||
* ([rationale](../../.agents/notes/implemented/process/2026-08-10-npm-release-sequences.md)).
|
||||
*/
|
||||
|
||||
@@ -73,7 +73,10 @@ function verifyTag(family: ReleaseFamily, members: readonly ReleaseMember[], ref
|
||||
/** Run the verification for the family named by `--family`. */
|
||||
function main(): void {
|
||||
const { values } = parseArgs({
|
||||
options: { family: { type: 'string' } },
|
||||
options: {
|
||||
family: { type: 'string' },
|
||||
'skip-tag-check': { type: 'boolean', default: false },
|
||||
},
|
||||
allowPositionals: false,
|
||||
})
|
||||
if (values.family === undefined) throw new Error('usage: verify.ts --family <dsh|vendor>')
|
||||
@@ -95,7 +98,11 @@ function main(): void {
|
||||
const publishing = process.env.RELEASE_PUBLISH === 'true'
|
||||
if (publishing) {
|
||||
verifyPublishable(members)
|
||||
verifyTag(family, members, process.env.GITHUB_REF ?? '')
|
||||
if (values['skip-tag-check']) {
|
||||
console.warn(`release verify: WARNING tag validation explicitly skipped for ref ${process.env.GITHUB_REF || '(no ref)'}`)
|
||||
} else {
|
||||
verifyTag(family, members, process.env.GITHUB_REF ?? '')
|
||||
}
|
||||
}
|
||||
|
||||
const versions = [...new Set(members.map(member => member.version))]
|
||||
|
||||
@@ -126,7 +126,10 @@ describe('master-only platform scheduling', () => {
|
||||
it('runs Wine once on hosted master CI and seeds its own apt cache', () => {
|
||||
const master = workflow('ci-master.yml')
|
||||
const wine = master.jobs.windows!
|
||||
expect(wine).toMatchObject({ if: masterPush, 'runs-on': 'ubuntu-latest' })
|
||||
expect(wine).toMatchObject({
|
||||
if: "(github.event_name == 'push' && github.ref == 'refs/heads/master') || (github.event_name == 'workflow_dispatch' && inputs.suite == 'wine')",
|
||||
'runs-on': 'ubuntu-latest',
|
||||
})
|
||||
expect(wine.needs).toBeUndefined()
|
||||
expect(wine['continue-on-error']).toBeUndefined()
|
||||
expect(master.jobs['wine-apt-cache']).toBeUndefined()
|
||||
|
||||
@@ -21,7 +21,16 @@ interface Workflow {
|
||||
on: Record<string, unknown>
|
||||
permissions: Record<string, string>
|
||||
concurrency?: Record<string, unknown>
|
||||
jobs: Record<string, { name: string; 'runs-on': string; steps: Step[] }>
|
||||
jobs: Record<string, {
|
||||
name: string
|
||||
'runs-on': string
|
||||
steps: Step[]
|
||||
uses?: string
|
||||
if?: string
|
||||
with?: Record<string, unknown>
|
||||
needs?: string
|
||||
permissions?: Record<string, string>
|
||||
}>
|
||||
}
|
||||
|
||||
function workflow(file: string): Workflow {
|
||||
@@ -33,9 +42,12 @@ 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)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+/g,
|
||||
.replace(/\b(?:github|vars|runner|inputs|needs)(?:\.[a-zA-Z_][a-zA-Z_0-9-]*)+/g,
|
||||
key => JSON.stringify(context[key] ?? ''))
|
||||
return runInNewContext(source, { fromJSON: JSON.parse }, { timeout: 1000 })
|
||||
return runInNewContext(source, {
|
||||
fromJSON: JSON.parse, startsWith: (value: string, prefix: string) => value.startsWith(prefix),
|
||||
cancelled: () => context['cancelled'] ?? false,
|
||||
}, { timeout: 1000 })
|
||||
}
|
||||
|
||||
function assertSharedPersistentStore(run: string | undefined): void {
|
||||
@@ -163,8 +175,80 @@ for (const [file, jobIds] of [['release.yml', ['dependencies', 'pack']], ['relea
|
||||
})
|
||||
}
|
||||
|
||||
it.each(['release-publish.yml', 'release-vendor-publish.yml'])('keeps %s manual and entirely hosted', (file) => {
|
||||
const publish = workflow(file)
|
||||
it('keeps vendor publication manual and entirely hosted', () => {
|
||||
const publish = workflow('release-vendor-publish.yml')
|
||||
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', () => {
|
||||
const publish = workflow('release-publish.yml')
|
||||
expect(Object.keys(publish.on)).toEqual(['workflow_dispatch'])
|
||||
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)
|
||||
}
|
||||
})
|
||||
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) => {
|
||||
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)
|
||||
})
|
||||
|
||||
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('validates retained attempts before downloading exactly one artifact with read-only Actions access', () => {
|
||||
const publish = workflow('release-publish.yml')
|
||||
expect(publish.permissions).toEqual({ contents: '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 }}',
|
||||
'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)
|
||||
}
|
||||
const stage = pack.steps.find(step => step.name === 'Stage verified native helper applications')!
|
||||
expect(stage.if).toBeUndefined()
|
||||
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)).toBeLessThan(pack.steps.findIndex(step => step.name === 'Pack release tarballs'))
|
||||
})
|
||||
@@ -1,6 +1,16 @@
|
||||
{
|
||||
"comment": "Maps each primary ` ```ts type-equiv ` or ` ```ts public-api ` block (by doc + declared symbol + projection) to the source declaration and original JSDoc it must match. Paired `.zh.md` blocks are byte-identical derivatives checked through their unsuffixed sibling and have no duplicate entry. Omit projection for the complete declaration; use public-api with a ` ```ts public-api ` block for a body-stripped public class declaration. verify-type-equiv.ts enforces a 1:1 correspondence between primary blocks and entries. Add an entry when you add a primary source-equivalence block; remove it when you remove the block.",
|
||||
"entries": [
|
||||
{
|
||||
"doc": "docs/subsystems/session.md",
|
||||
"symbol": "SessionLogUploadRequest",
|
||||
"source": "packages/session/session-log-deepseek/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/session.md",
|
||||
"symbol": "SessionLogUploadExclusion",
|
||||
"source": "packages/session/session-log-deepseek/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/compaction.md",
|
||||
"symbol": "ImageOffloadTarget",
|
||||
@@ -121,6 +131,16 @@
|
||||
"symbol": "RequestMessage",
|
||||
"source": "packages/llm/llm/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/llm-streaming.md",
|
||||
"symbol": "LlmRequestPurposeMap",
|
||||
"source": "packages/llm/llm/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/llm-streaming.md",
|
||||
"symbol": "LlmRequestPurpose",
|
||||
"source": "packages/llm/llm/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/llm-streaming.md",
|
||||
"symbol": "GenerateOptions",
|
||||
@@ -2861,6 +2881,21 @@
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeLocalChanges",
|
||||
"source": "packages/experimental/client-ui-forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeLineComment",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeReviewRequest",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
},
|
||||
{
|
||||
"doc": "docs/subsystems/forge.md",
|
||||
"symbol": "ForgeReviewResult",
|
||||
"source": "packages/experimental/forge/src/types.ts"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -117,9 +117,15 @@ describe('npm install layout verifier', () => {
|
||||
})
|
||||
|
||||
describe('resolution work budget', () => {
|
||||
it('accepts the measured dual-release graph', () => {
|
||||
expect(assertResolutionWorkBudget({ dshPackagesPerVersion: 320, checkedDshEdges: 2836 }))
|
||||
.toBe(907_520)
|
||||
it.each([
|
||||
[277, 2524, 699_148],
|
||||
[316, 2780, 878_480],
|
||||
[316, 2786, 880_376],
|
||||
[317, 2786, 883_162],
|
||||
[320, 2836, 907_520],
|
||||
])('accepts the measured dual-release graph with %i packages and %i edges', (packages, edges, units) => {
|
||||
expect(assertResolutionWorkBudget({ dshPackagesPerVersion: packages, checkedDshEdges: edges }))
|
||||
.toBe(units)
|
||||
})
|
||||
|
||||
it('accepts a graph exactly at the budget and rejects one internal edge above it', () => {
|
||||
|
||||
@@ -48,6 +48,8 @@ const NO_MODEL_EXPERIENCE_SECTION: Readonly<Record<string, string>> = {
|
||||
* blocks. A package moves on or off this list with its context behavior.
|
||||
*/
|
||||
const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
|
||||
'packages/client/ui-context-menu': { kind: 'none', reason: 'Client menu presentation and contributed callbacks add no model input.' },
|
||||
'packages/client/ui-file-actions': { kind: 'none', reason: 'Explicit user file saves and clipboard operations add no model input.' },
|
||||
'packages/client/ui-entry-customization': { kind: 'none', reason: 'Controls browser launchers and prepares a reviewable Creator draft without submitting model input.' },
|
||||
'packages/experimental/client-ui-cot-translation': { kind: 'indirect', reason: 'The translator owns optional paid queries; normal Session activation delegates startup context to the preset.' },
|
||||
'packages/experimental/cot-translation-bundle': { kind: 'indirect', reason: 'The GUI consumer delegates paid query prompts to the translator and normal activation context to the Session preset.' },
|
||||
@@ -56,6 +58,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
|
||||
'packages/experimental/api-speech-to-text': { kind: 'none', reason: 'Transports audio and preparation state; ordinary user submission owns model-visible text.' },
|
||||
'packages/experimental/speech-to-text-sensevoice': { kind: 'none', reason: 'Local recognition returns transient text without modifying model context.' },
|
||||
'packages/experimental/client-ui-voice-input': { kind: 'none', reason: 'Inserts reviewable text into the unsent draft without submitting to the Agent.' },
|
||||
'packages/experimental/liveshare': { kind: 'indirect', reason: 'The host drives viewer prompts into the shared Session, so model requests follow the viewer input the host forwards.' },
|
||||
'packages/experimental/plugin-market-bundle': { kind: 'indirect', reason: 'Mounts the pluginMarket service, which lets the Creator preset register the plugin_market tool documented in packages/boot/plugin-market.' },
|
||||
'packages/experimental/client-ui-action-cards': { kind: 'indirect', reason: 'Card actions go to the Host card service, which owns the logged tool, decisions and status notice.' },
|
||||
'packages/experimental/client-ui-creation-recommendations': { kind: 'indirect', reason: 'The page card body starts a Creator through the Host page kind; the Host owns its logged task.' },
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { describe, expect, it, type TestContext } from 'vitest'
|
||||
import { findRepositoryReferences, scanRepositoryReferences, uniquePrefixMatch } from './verify-repository-references.ts'
|
||||
import { findRepositoryReferences, repositoryCommits, scanRepositoryReferences, uniquePrefixMatch } from './verify-repository-references.ts'
|
||||
|
||||
const organizationUrl = `https://${['github.com', ['deepseek', 'harness'].join('-')].join('/')}`
|
||||
|
||||
@@ -51,6 +51,7 @@ function collidingCommitBodies(tree: string, length: number): [string, string] {
|
||||
for (let index = 0; ; index += 1) {
|
||||
const body = `tree ${tree}\nauthor T <[email protected]> 0 +0000\ncommitter T <[email protected]> 0 +0000\n\ncollision ${String(index)}\n`
|
||||
const prefix = createHash(algorithm).update(`commit ${String(Buffer.byteLength(body))}\0${body}`).digest('hex').slice(0, length)
|
||||
if (!/[a-f]/.test(prefix)) continue
|
||||
const previous = seen.get(prefix)
|
||||
if (previous !== undefined) return [previous, body]
|
||||
seen.set(prefix, body)
|
||||
@@ -72,6 +73,75 @@ describe('unique object-name prefix search', () => {
|
||||
})
|
||||
|
||||
describe('maintained repository reference policy', () => {
|
||||
const numericCommit = String(6_344_383)
|
||||
|
||||
it.each([
|
||||
['uv.lock', `artifact = { size = ${numericCommit} }`],
|
||||
['python/sdk/uv.lock', `sdist.size = ${numericCommit}`],
|
||||
['fixture.json', `{"context_length": ${numericCommit}}`],
|
||||
['package.json', `{"version": "1.0.${numericCommit}"}`],
|
||||
['config.toml', `rev = "${numericCommit}"`],
|
||||
['notes.md', `commit ${numericCommit}\nhttps://example.invalid/commit/${numericCommit}`],
|
||||
['source.ts', `// commit ${numericCommit}`],
|
||||
])('accepts decimal-only tokens in %s even when they name a commit', (file, source) => {
|
||||
expect(findRepositoryReferences(file, source, new Set([numericCommit]))).toEqual([])
|
||||
})
|
||||
|
||||
it.each([7, 12, 40])('accepts a decimal-only %i-character token beside a hexadecimal commit', (length) => {
|
||||
const decimal = '1'.repeat(length)
|
||||
const hexadecimal = `${'1'.repeat(length - 1)}a`
|
||||
expect(findRepositoryReferences('source.md', `${decimal} ${hexadecimal}`, new Set([decimal, hexadecimal]))).toEqual([
|
||||
{ file: 'source.md', line: 1, kind: 'commit-hash' },
|
||||
])
|
||||
expect(findRepositoryReferences('source.md', decimal, new Set([decimal]))).toEqual([])
|
||||
})
|
||||
|
||||
it.each([
|
||||
['python/sdk/uv.lock', 'size = "HASH"', 1],
|
||||
['fixture.json', '{"revision": "HASH"}', 1],
|
||||
['notes.md', 'release\ncommit HASH', 2],
|
||||
['source.ts', '// commit HASH', 1],
|
||||
] as const)('rejects commit tokens containing a hex letter in %s', (file, template, line) => {
|
||||
const hash = `${numericCommit}a`
|
||||
expect(findRepositoryReferences(file, template.replace('HASH', hash), new Set([hash]))).toEqual([
|
||||
{ file, line, kind: 'commit-hash' },
|
||||
])
|
||||
})
|
||||
|
||||
it('accepts byte counts in the real lockfile and still rejects references on added lines', () => {
|
||||
const file = 'python/sdk/uv.lock'
|
||||
const source = readFileSync(join(import.meta.dirname, '..', file), 'utf8').trimEnd()
|
||||
const sizes = new Set([...source.matchAll(/\bsize\s*=\s*(\d+)/g)].map(match => match[1] ?? ''))
|
||||
expect(sizes.size).toBeGreaterThan(0)
|
||||
expect(sizes).not.toContain('')
|
||||
expect(findRepositoryReferences(file, source, sizes)).toEqual([])
|
||||
const hash = `${numericCommit}a`
|
||||
expect(findRepositoryReferences(file, `${source}\n# commit ${hash}\n# ${organizationUrl}`, new Set([...sizes, hash]))).toEqual([
|
||||
{ file, line: source.split('\n').length + 1, kind: 'commit-hash' },
|
||||
{ file, line: source.split('\n').length + 2, kind: 'organization-url' },
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes a real numeric commit prefix from both candidate resolution and file findings', (test) => {
|
||||
const fixture = repository(test)
|
||||
const algorithm = fixture.tree.length === 64 ? 'sha256' : 'sha1'
|
||||
for (let index = 0; ; index += 1) {
|
||||
const body = `tree ${fixture.tree}\nauthor T <[email protected]> 0 +0000\ncommitter T <[email protected]> 0 +0000\n\nnumeric ${String(index)}\n`
|
||||
const commit = createHash(algorithm).update(`commit ${String(Buffer.byteLength(body))}\0${body}`).digest('hex')
|
||||
if (!/^\d{7}/.test(commit) || !/[a-f]/.test(commit.slice(0, 40))) continue
|
||||
fixture.git(['hash-object', '-t', 'commit', '-w', '--stdin'], body)
|
||||
const decimal = commit.slice(0, 7)
|
||||
const hexadecimal = commit.slice(0, Math.max(8, commit.search(/[a-f]/) + 1))
|
||||
const source = `commit ${decimal}\ncommit ${hexadecimal}`
|
||||
expect(repositoryCommits(fixture.root, [source])).toEqual(new Set([hexadecimal]))
|
||||
fixture.write('references.md', source)
|
||||
expect(scanRepositoryReferences(fixture.root)).toEqual([
|
||||
{ file: 'references.md', line: 2, kind: 'commit-hash' },
|
||||
])
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
it('permits only the independent kit repository and its source URLs', () => {
|
||||
for (const suffix of ['', '.git', '/tree/main/packages/entry']) {
|
||||
expect(findRepositoryReferences('package.json', `${organizationUrl}/libreoffice-kit${suffix}`, new Set())).toEqual([])
|
||||
@@ -84,9 +154,10 @@ describe('maintained repository reference policy', () => {
|
||||
it('rejects complete and abbreviated commit identifiers in tracked, staged, and new files', (test) => {
|
||||
const fixture = repository(test)
|
||||
fixture.write('tracked.md', `release\n${fixture.commit}\n${fixture.commit.toUpperCase()}\n`)
|
||||
fixture.write('staged.md', fixture.commit.slice(0, 7))
|
||||
const firstLetterEnd = fixture.commit.search(/[a-f]/) + 1
|
||||
fixture.write('staged.md', fixture.commit.slice(0, Math.max(7, firstLetterEnd)))
|
||||
fixture.git(['add', 'staged.md'])
|
||||
fixture.write('new.md', `\0${fixture.commit.slice(0, 12)}`)
|
||||
fixture.write('new.md', `\0${fixture.commit.slice(0, Math.max(12, firstLetterEnd))}`)
|
||||
|
||||
expect(scanRepositoryReferences(fixture.root)).toEqual(expect.arrayContaining([
|
||||
{ file: 'tracked.md', line: 2, kind: 'commit-hash' },
|
||||
|
||||
@@ -11,7 +11,8 @@ const organization = ['deepseek', 'harness'].join('-')
|
||||
const organizationUrl = new RegExp(`\\bgithub\\.com/${organization}(?![a-z0-9-])`)
|
||||
// The independent kit repository owns the engine source and documentation.
|
||||
const kitRepositoryUrl = new RegExp(`\\bgithub\\.com/${organization}/libreoffice-kit(?:\\.git)?(?=/|[^a-zA-Z0-9_.-]|$)`, 'g')
|
||||
const commitCandidate = /(?<![a-z0-9])[\da-f]{7,40}(?![a-z0-9])/gi
|
||||
// Decimal-only tokens collide with sizes, counts, and version components; see docs/AGENTS.md#repository-references.
|
||||
const commitCandidate = /(?<![a-z0-9])(?=[\da-f]{0,39}[a-f])[\da-f]{7,40}(?![a-z0-9])/gi
|
||||
const excludedPrefixes = ['vendor/', '.agents/notes/archived/']
|
||||
const gitOutputLimit = 64 * 1024 * 1024
|
||||
// One 41-byte line per object; 1.2 million objects produce about 49 MiB.
|
||||
@@ -37,6 +38,7 @@ function isMaintained(file: string): boolean {
|
||||
* @param source - File text or a symlink's stored target.
|
||||
* @param commits - Lowercase, unambiguous full or abbreviated commit identifiers.
|
||||
* @returns One finding per line and reference kind; digests and other Git object types are accepted.
|
||||
* Decimal-only tokens are ignored, including actual commit identifiers.
|
||||
*/
|
||||
export function findRepositoryReferences(
|
||||
file: string,
|
||||
@@ -107,7 +109,7 @@ export function uniquePrefixMatch(objects: readonly string[], prefix: string): s
|
||||
* Resolve commit-identifier candidates in maintained sources against the local object database.
|
||||
* @param repoRoot - Working tree whose Git objects are inspected.
|
||||
* @param sources - File texts or symlink targets to extract candidates from.
|
||||
* @returns Lowercase candidates that name exactly one available object, which is a commit.
|
||||
* @returns Lowercase candidates containing a hexadecimal letter that name exactly one available object, which is a commit.
|
||||
*/
|
||||
export function repositoryCommits(repoRoot: string, sources: Iterable<string>): Set<string> {
|
||||
const candidates = [...new Set([...sources].flatMap(source =>
|
||||
@@ -146,7 +148,7 @@ const invokedPath = process.argv[1]
|
||||
if (invokedPath !== undefined && import.meta.url === pathToFileURL(resolve(invokedPath)).href) {
|
||||
const references = scanRepositoryReferences(root)
|
||||
if (references.length === 0) {
|
||||
console.log('verify-repository-references: maintained files contain no repository commit identifiers or disallowed organization URLs.')
|
||||
console.log('verify-repository-references: maintained files contain no prohibited references (decimal-only tokens are ignored).')
|
||||
} else {
|
||||
console.error('verify-repository-references: use release tags or maintained repository links:')
|
||||
for (const { file, line, kind } of references) console.error(` ${file}:${String(line)} ${kind}`)
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
import { prepareWindowsBuildWorkspace, removeWindowsBuildWorkspace } from '../apps/desktop/scripts/windows-build-workspace.mjs'
|
||||
|
||||
it('clones the exact clean commit and removes only its run-owned checkout', () => {
|
||||
const root = realpathSync(mkdtempSync(join(tmpdir(), 'package-workspace-')))
|
||||
try {
|
||||
const sourceDirectory = join(root, 'original')
|
||||
mkdirSync(sourceDirectory)
|
||||
const git = (...args: string[]) => execFileSync('git', args, { cwd: sourceDirectory, encoding: 'utf8', stdio: 'pipe' }).trim()
|
||||
git('init')
|
||||
writeFileSync(join(sourceDirectory, 'source.txt'), 'selected source')
|
||||
writeFileSync(join(sourceDirectory, '.gitignore'), 'private.env\n')
|
||||
git('add', '.')
|
||||
git('-c', 'user.name=Fixture', '-c', '[email protected]', 'commit', '-m', 'fixture')
|
||||
writeFileSync(join(sourceDirectory, 'private.env'), 'ignored fixture')
|
||||
const options = { sourceDirectory, buildRoot: join(root, 'builds'), runId: '123', runAttempt: '1', sourceSha: git('rev-parse', 'HEAD') }
|
||||
expect(() => prepareWindowsBuildWorkspace({ ...options, buildRoot: sourceDirectory })).toThrow('outside existing Git')
|
||||
expect(() => prepareWindowsBuildWorkspace({ ...options, buildRoot: 'relative' })).toThrow('absolute')
|
||||
expect(() => prepareWindowsBuildWorkspace({ ...options, runId: '../other' })).toThrow('identity')
|
||||
expect(() => prepareWindowsBuildWorkspace({ ...options, sourceSha: '0'.repeat(40) })).toThrow('match')
|
||||
writeFileSync(join(sourceDirectory, 'source.txt'), 'dirty')
|
||||
expect(() => prepareWindowsBuildWorkspace(options)).toThrow('clean')
|
||||
writeFileSync(join(sourceDirectory, 'source.txt'), 'selected source')
|
||||
const output = join(root, 'actions-output')
|
||||
execFileSync(process.execPath, [resolve(import.meta.dirname, '../apps/desktop/scripts/windows-build-workspace.mjs')], {
|
||||
cwd: sourceDirectory,
|
||||
env: {
|
||||
...process.env,
|
||||
GITHUB_WORKSPACE: sourceDirectory,
|
||||
PACKAGE_BUILD_ROOT: options.buildRoot,
|
||||
GITHUB_RUN_ID: options.runId,
|
||||
GITHUB_RUN_ATTEMPT: options.runAttempt,
|
||||
PACKAGE_SOURCE_SHA: options.sourceSha,
|
||||
GITHUB_OUTPUT: output,
|
||||
},
|
||||
stdio: 'pipe',
|
||||
})
|
||||
const directory = join(options.buildRoot, 'windows-package-123-1', 'source')
|
||||
const temporaryDirectory = join(options.buildRoot, 'windows-package-123-1', 'temp')
|
||||
expect(readFileSync(output, 'utf8')).toBe(`directory=${directory}\ntemporaryDirectory=${temporaryDirectory}\n`)
|
||||
writeFileSync(join(temporaryDirectory, 'temporary.txt'), 'owned temporary data')
|
||||
expect(readFileSync(join(directory, 'source.txt'), 'utf8')).toBe('selected source')
|
||||
expect(existsSync(join(directory, 'private.env'))).toBe(false)
|
||||
expect(() => prepareWindowsBuildWorkspace(options)).toThrow()
|
||||
expect(() => { removeWindowsBuildWorkspace({ ...options, sourceSha: '0'.repeat(40) }) }).toThrow('ownership')
|
||||
expect(existsSync(directory)).toBe(true)
|
||||
const external = join(root, 'external')
|
||||
mkdirSync(external)
|
||||
writeFileSync(join(external, 'keep.txt'), 'keep')
|
||||
symlinkSync(external, join(directory, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir')
|
||||
removeWindowsBuildWorkspace(options)
|
||||
expect(existsSync(directory)).toBe(false)
|
||||
expect(existsSync(temporaryDirectory)).toBe(false)
|
||||
expect(readFileSync(join(external, 'keep.txt'), 'utf8')).toBe('keep')
|
||||
expect(readFileSync(join(sourceDirectory, 'source.txt'), 'utf8')).toBe('selected source')
|
||||
const linked = join(root, 'linked')
|
||||
symlinkSync(external, linked, process.platform === 'win32' ? 'junction' : 'dir')
|
||||
expect(() => prepareWindowsBuildWorkspace({ ...options, buildRoot: join(linked, 'builds') })).toThrow('links')
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
@@ -68,7 +68,7 @@ it('routes manual packaging to the dedicated runner with explicit preset and sig
|
||||
expect(workflow.concurrency).toEqual({ group: 'windows-desktop-package', 'cancel-in-progress': false })
|
||||
expect(workflow.permissions).toEqual({ contents: 'read' })
|
||||
expect(Object.keys(workflow.on.workflow_dispatch!.inputs).sort()).toEqual([
|
||||
'build_root', 'build_version', 'cache_namespace', 'compression_level', 'preset', 'signing', 'source_ref', 'test_release_id', 'update_channel', 'version_mode',
|
||||
'build_version', 'cache_namespace', 'compression_level', 'preset', 'signing', 'source_ref', 'test_release_id', 'update_channel', 'version_mode',
|
||||
])
|
||||
expect(workflow.on.workflow_dispatch!.inputs.signing!.default).toBe('signed')
|
||||
expect(workflow.on.workflow_dispatch!.inputs.compression_level).toMatchObject({ type: 'choice', options: ['3', '7'], default: '3', required: true })
|
||||
@@ -108,7 +108,7 @@ it('retains failure diagnostics and uploads only the selected successful install
|
||||
expect(uploads).toHaveLength(3)
|
||||
expect(uploads[0]!.if).toBe("always() && steps.checkout.outcome == 'success'")
|
||||
expect(uploads[0]!.with).toMatchObject({
|
||||
path: '${{ steps.build_workspace.outputs.directory || github.workspace }}/apps/desktop/.desktop-build/packaging-runs/',
|
||||
path: '${{ github.workspace }}/apps/desktop/.desktop-build/packaging-runs/',
|
||||
'include-hidden-files': true,
|
||||
})
|
||||
for (const mode of ['unsigned', 'signed']) {
|
||||
@@ -117,51 +117,6 @@ it('retains failure diagnostics and uploads only the selected successful install
|
||||
}
|
||||
})
|
||||
|
||||
it('routes all packaging consumers to the selected workspace and removes it only after successful uploads', () => {
|
||||
expect(workflow.on.workflow_dispatch!.inputs.build_root).toMatchObject({ type: 'string', default: '', required: false })
|
||||
expect(job.env.PACKAGE_BUILD_ROOT).toBe('${{ inputs.build_root }}')
|
||||
const selected = job.steps.find(step => step.id === 'build_workspace')!
|
||||
expect(selected.name).toBe('Select packaging workspace')
|
||||
expect(selected.env).toEqual({ PACKAGE_SOURCE_SHA: '${{ steps.checkout.outputs.commit }}' })
|
||||
expect(selected['working-directory']).toBeUndefined()
|
||||
expect(selected.run).toContain('if (!$env:PACKAGE_BUILD_ROOT)')
|
||||
expect(selected.run).toContain('"directory=$env:GITHUB_WORKSPACE" >> $env:GITHUB_OUTPUT')
|
||||
expect(selected.run).toContain('} else {')
|
||||
expect(selected.run).toContain('node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs"')
|
||||
expect(selected.run).toContain('exit $LASTEXITCODE')
|
||||
const index = job.steps.indexOf(selected)
|
||||
expect(index).toBeGreaterThan(job.steps.findIndex(step => step.uses?.startsWith('actions/setup-node@')))
|
||||
expect(index).toBeLessThan(job.steps.findIndex(step => step.name === 'Configure persistent pnpm store'))
|
||||
const consumers = [
|
||||
'Install locked dependencies',
|
||||
'Validate preset and resolve build version',
|
||||
'Check packaging configuration and toolchain',
|
||||
'Build installer and verify packaged runtime',
|
||||
'Retain complete package outside the checkout',
|
||||
]
|
||||
for (const name of consumers) {
|
||||
const step = job.steps.find(entry => entry.name === name)!
|
||||
expect(step['working-directory']).toBe('${{ steps.build_workspace.outputs.directory }}')
|
||||
expect(job.steps.indexOf(step)).toBeGreaterThan(index)
|
||||
}
|
||||
expect(job.steps.filter(step => step['working-directory'] === '${{ steps.build_workspace.outputs.directory }}'))
|
||||
.toHaveLength(consumers.length)
|
||||
const store = job.steps.find(step => step.name === 'Configure persistent pnpm store')!
|
||||
expect(store.run).toContain('[IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE)')
|
||||
expect(store['working-directory']).toBeUndefined()
|
||||
const cleanup = job.steps.at(-1)!
|
||||
expect(cleanup).toMatchObject({
|
||||
name: 'Remove isolated packaging workspace',
|
||||
if: "success() && inputs.build_root != ''",
|
||||
env: { PACKAGE_SOURCE_SHA: '${{ steps.checkout.outputs.commit }}' },
|
||||
run: 'node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs" --remove',
|
||||
})
|
||||
expect(cleanup['working-directory']).toBeUndefined()
|
||||
for (const upload of job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))) {
|
||||
expect(job.steps.indexOf(upload)).toBeLessThan(job.steps.indexOf(cleanup))
|
||||
}
|
||||
})
|
||||
|
||||
it('normalizes priority in the dependency and packaging shells before launching their children', () => {
|
||||
const command = '& "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort'
|
||||
expect(job.steps.find(entry => entry.name === 'Validate selected source and adapter support')!.run)
|
||||
@@ -172,33 +127,6 @@ it('normalizes priority in the dependency and packaging shells before launching
|
||||
}
|
||||
})
|
||||
|
||||
it('scopes the optional temporary directory to installer building without changing Actions or later steps', () => {
|
||||
const build = job.steps.find(step => step.name === 'Build installer and verify packaged runtime')!
|
||||
expect(build.env?.PACKAGE_BUILD_TEMP).toBe('${{ steps.build_workspace.outputs.temporaryDirectory }}')
|
||||
expect(build.run).toContain([
|
||||
'if ($env:PACKAGE_BUILD_TEMP) {',
|
||||
' $env:TEMP = $env:PACKAGE_BUILD_TEMP',
|
||||
' $env:TMP = $env:PACKAGE_BUILD_TEMP',
|
||||
'}',
|
||||
].join('\n'))
|
||||
expect(build.run!.indexOf('if ($env:PACKAGE_BUILD_TEMP)')).toBeLessThan(build.run!.indexOf('$packageArgs ='))
|
||||
expect(build.run).not.toContain('GITHUB_ENV')
|
||||
expect(build.run).not.toContain('RUNNER_TEMP')
|
||||
expect(job.env).not.toHaveProperty('TEMP')
|
||||
expect(job.env).not.toHaveProperty('TMP')
|
||||
expect(job.env).not.toHaveProperty('PACKAGE_BUILD_TEMP')
|
||||
for (const step of job.steps.filter(step => step !== build)) {
|
||||
expect(step.env ?? {}).not.toHaveProperty('PACKAGE_BUILD_TEMP')
|
||||
expect(step.env ?? {}).not.toHaveProperty('TEMP')
|
||||
expect(step.env ?? {}).not.toHaveProperty('TMP')
|
||||
expect(step.run ?? '').not.toMatch(/\$env:(?:TEMP|TMP)\s*=/u)
|
||||
}
|
||||
const selected = job.steps.find(step => step.id === 'build_workspace')!
|
||||
const defaultBranch = selected.run!.split('} else {')[0]!
|
||||
expect(defaultBranch).toContain('"directory=$env:GITHUB_WORKSPACE" >> $env:GITHUB_OUTPUT')
|
||||
expect(defaultBranch).not.toContain('temporaryDirectory')
|
||||
})
|
||||
|
||||
it.skipIf(process.platform !== 'win32')('keeps the dependency store stable across run-specific pnpm homes', () => {
|
||||
const directory = mkdtempSync(resolve(tmpdir(), 'windows-package-store-'))
|
||||
try {
|
||||
@@ -251,11 +179,9 @@ it('pins environment helpers to the workflow commit before selecting product sou
|
||||
expect(job.steps.indexOf(helper)).toBeLessThan(job.steps.indexOf(stage))
|
||||
expect(job.steps.indexOf(stage)).toBeLessThan(job.steps.indexOf(source))
|
||||
expect(stage.run).toContain('RUNNER_TEMP')
|
||||
expect(stage.run).toContain('windows-build-workspace.mjs')
|
||||
expect(stage.run).toContain('windows-packaging-priority.ps1')
|
||||
for (const step of job.steps.filter(step => step.name !== 'Stage workflow helpers')) {
|
||||
expect(step.run ?? '').not.toContain('./apps/desktop/scripts/windows-packaging-priority.ps1')
|
||||
expect(step.run ?? '').not.toContain('node apps/desktop/scripts/windows-build-workspace.mjs')
|
||||
}
|
||||
})
|
||||
|
||||
@@ -267,7 +193,7 @@ it.skipIf(process.platform !== 'win32')('stages helpers that remain usable when
|
||||
const temporary = resolve(directory, 'temporary')
|
||||
mkdirSync(scripts, { recursive: true })
|
||||
mkdirSync(temporary)
|
||||
for (const name of ['windows-packaging-priority.ps1', 'windows-build-workspace.mjs']) {
|
||||
for (const name of ['windows-packaging-priority.ps1']) {
|
||||
writeFileSync(resolve(scripts, name), readFileSync(resolve(root, 'apps/desktop/scripts', name)))
|
||||
}
|
||||
const stage = resolve(directory, 'stage.ps1')
|
||||
@@ -278,7 +204,6 @@ it.skipIf(process.platform !== 'win32')('stages helpers that remain usable when
|
||||
const helper = resolve(temporary, 'packaging-helpers-123-1/windows-packaging-priority.ps1')
|
||||
expect(execFileSync('pwsh', ['-NoProfile', '-File', helper, '-InspectOnly'], { cwd: source, stdio: 'pipe' }).toString())
|
||||
.toContain('packaging-process-priority')
|
||||
expect(existsSync(resolve(temporary, 'packaging-helpers-123-1/windows-build-workspace.mjs'))).toBe(true)
|
||||
expect(() => execFileSync('pwsh', ['-NoProfile', '-File', stage], {
|
||||
cwd: source, env: { ...env, GITHUB_RUN_ATTEMPT: '2' }, stdio: 'pipe',
|
||||
})).toThrow()
|
||||
|
||||
@@ -245,10 +245,9 @@ grep -q '^smoke: win32 x64' "$scratch/logs/smoke.log" || { echo 'wine-windows-ga
|
||||
# The build mirrors the root build:lib:host and build:lib:client scripts:
|
||||
# generate metadata, compile the Host package projects, type-check the Host
|
||||
# aggregate program, bundle the Host face, bundle apps/desktop from the Host
|
||||
# lib/ outputs, then compile and bundle the Client face. The Host compile is two
|
||||
# invocations because that is how the supported build splits it; a single
|
||||
# `tsc -b` holds the reference graph and the aggregate program in one process
|
||||
# and exceeds the heap the Host face is budgeted.
|
||||
# lib/ outputs, then compile and bundle the Client face. Each face compiles
|
||||
# package references separately from its aggregate program, matching the
|
||||
# supported build and releasing the reference graph before aggregate checking.
|
||||
# Both statuses are captured so one failure cannot hide the other's result.
|
||||
build_gate() {
|
||||
wine_node "$scratch/logs/host-typert.log" --import tsx/esm scripts/generate-typert.ts || return $?
|
||||
@@ -256,7 +255,8 @@ build_gate() {
|
||||
wine_node "$scratch/logs/host-tsc.log" --max-old-space-size=8192 "$tsc_js" -p tsconfig.host.json --pretty false || return $?
|
||||
wine_node "$scratch/logs/host-tsdown.log" "$tsdown_js" --env.DSH_BUILD_FACE host || return $?
|
||||
(cd apps/desktop && wine_node "$scratch/logs/desktop-tsdown.log" "../../$tsdown_js") || return $?
|
||||
wine_node "$scratch/logs/client-tsc.log" "$tsc_js" -b tsconfig.client.json --pretty false || return $?
|
||||
wine_node "$scratch/logs/client-references.log" --import tsx/esm scripts/compile-referenced-projects.ts client || return $?
|
||||
wine_node "$scratch/logs/client-tsc.log" --max-old-space-size=8192 "$tsc_js" -p tsconfig.client.json --pretty false || return $?
|
||||
wine_node "$scratch/logs/client-tsdown.log" "$tsdown_js" --env.DSH_BUILD_FACE client
|
||||
}
|
||||
site_gate() {
|
||||
@@ -288,6 +288,7 @@ report 'build (Typert, Host tsc/tsdown, desktop tsdown, Client tsc/tsdown)' "$bu
|
||||
"$scratch/logs/host-tsc.log" \
|
||||
"$scratch/logs/host-tsdown.log" \
|
||||
"$scratch/logs/desktop-tsdown.log" \
|
||||
"$scratch/logs/client-references.log" \
|
||||
"$scratch/logs/client-tsc.log" \
|
||||
"$scratch/logs/client-tsdown.log"
|
||||
report 'production site (vitepress build)' "$site_status" "$scratch/logs/site.log"
|
||||
|
||||
Reference in new issue
Block a user