Merge remote-tracking branch 'origin/master' into refactor/llm-route-credential

master moved internal identity construction to brandString (#8214) and
added the empty-catch gate with its recorded baseline (#4862); both touch
files this branch changes or moves.

Conflicts:
- packages/llm/llm-deepseek/tests/adapter.spec.ts,
  packages/llm/llm-deepseek-account/tests/provider.spec.ts,
  packages/experimental/translator/tests/paid-fixture.ts, and
  packages/web/web-search-deepseek/tests/deepseek.spec.ts: master rewrote
  the id constructor calls to brandString<T>() with type-only imports,
  while this branch replaced the hand-built account stand-ins with
  accountStub. The result keeps master's id construction and imports and
  this branch's stand-ins; the one Session this branch's own search test
  creates follows master's construction.
- packages/web/web-deepseek-api/package.json and
  packages/web/web-search-deepseek/package.json: this branch's sorted
  devDependencies plus master's dsh-brand entry.
- docs/capability-seams.md and docs/capability-seams.zh.md: master's
  cuaPrograms consumer edge and this branch's deepseekAccount consumer
  edges coexist; the pairing record is recorded again from the merged
  pair.
- docs/module-graph.md, docs/module-graph.zh.md,
  docs/persistence-schema.json, and pnpm-lock.yaml: regenerated from the
  merged sources.

Beyond the conflicts:
- scripts/empty-catch.baseline.json: master recorded two clauses under
  packages/credentials/deepseek-account, which this branch moves to
  packages/account/deepseek-account. The two keys are renamed with the
  files, as the gate requires for a moved file.
- AGENTS.md: master's checker link and this branch's account/ layout row
  together exceeded the frozen 2,080-word ceiling by one word, so the row
  reads "account/ DeepSeek".
This commit is contained in:
LegGasai committed 2026-11-12 13:53:45 +08:00
commit f4ac78bb34
1923 files changed
+22997 -25323

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
/** Temporary-repository fixture shared by recorded-inventory gate specs. */
import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
/** Repository roots created by {@link createInventoryRepo}, removed by {@link removeInventoryRepos}. */
const roots: string[] = []
/**
* Write one fixture file, creating its parent directories.
* @param root - fixture repository root.
* @param file - repository-relative path.
* @param contents - file text.
*/
export function writeFixture(root: string, file: string, contents: string): void {
const path = join(root, file)
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, contents)
}
/**
* Run one Git command in a fixture repository.
* @param root - fixture repository root.
* @param args - Git arguments.
*/
export function gitFixture(root: string, ...args: string[]): void {
execFileSync('git', args, { cwd: root, stdio: 'pipe' })
}
/**
* Create a temporary repository with one seed source file per scanned area and an empty inventory.
* @param baselinePath - repository-relative inventory path the gate reads.
* @param seed - contents of each area's seed source file.
* @returns the repository root, tracked for {@link removeInventoryRepos}.
*/
export function createInventoryRepo(baselinePath: string, seed: string): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-inventory-'))
roots.push(root)
gitFixture(root, 'init', '--quiet')
for (const area of ['packages', 'apps', 'scripts', 'website']) {
writeFixture(root, `${area}/seed.ts`, seed)
}
writeFixture(root, baselinePath, '{}\n')
gitFixture(root, 'add', '.')
return root
}
/** Remove every repository created by {@link createInventoryRepo}. */
export function removeInventoryRepos(): void {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
}
+214
View File
@@ -0,0 +1,214 @@
/**
* Recorded-inventory bookkeeping for gates that reject one source form.
*
* A gate scans first-party source, records the findings that predate its rule as a fingerprint
* inventory, and rejects a finding the inventory does not allow. Keying by repository path and by
* the finding's syntax tokens keeps an allowance across formatting and comment edits, while a
* changed form is a new finding. Fixing a recorded finding leaves a stale allowance, which
* `--prune` retires; a partial fix that leaves a changed finding is a new finding, so a finding is
* fixed completely before pruning. No command adds an allowance.
*/
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { lstatSync, readFileSync, writeFileSync } from 'node:fs'
import { resolve } from 'node:path'
import ts from 'typescript'
/** Source areas every inventory gate must find, so a narrowed scan cannot pass silently. */
const AREAS = ['packages/', 'apps/', 'scripts/', 'website/'] as const
/** Source extensions an inventory gate scans, including tests and configuration files. */
const SOURCE_EXTENSIONS = /\.(?:[cm]?[jt]s|[jt]sx)$/u
/** Existing finding counts, keyed by repository path and syntax fingerprint. */
export type InventoryBaseline = Record<string, Record<string, number>>
/** One finding a gate rejects unless the inventory records it. */
export interface InventoryFinding {
/** Repository-relative path with forward slashes. */
file: string
/** SHA-256 of the finding's form, derived from syntax tokens that exclude comments and whitespace. */
fingerprint: string
}
/** Everything shared inventory bookkeeping needs to know about one gate. */
export interface InventoryGate<T extends InventoryFinding> {
/** Gate name that prefixes every diagnostic and names the `pnpm run` script. */
name: string
/** Repository-relative path of the recorded inventory. */
baselinePath: string
/** Scan first-party source for the rejected form. */
scan: (repoRoot: string) => T[]
/** Rejection text after the gate name for a finding the inventory does not allow. */
rejection: string
/** One line describing a finding, appended to {@link rejection}. */
describe: (finding: T) => string
/** Console line for a passing run, given the number of recorded findings. */
success: (count: number) => string
}
/**
* Whether a repository path belongs to an inventory gate's corpus.
* @param file - repository-relative path with forward slashes.
* @returns `true` for first-party source outside vendored code and frozen archived notes.
*/
export function isInventorySource(file: string): boolean {
return SOURCE_EXTENSIONS.test(file)
&& !file.startsWith('vendor/')
&& !file.startsWith('.agents/notes/archived/')
}
/**
* Hash a node's syntax tokens, so formatting and comment edits keep one identity.
* @param node - the node whose form the inventory records.
* @param source - the file that owns the node.
* @returns SHA-256 of the node's token texts.
*/
export function syntaxFingerprint(node: ts.Node, source: ts.SourceFile): string {
const tokens: string[] = []
const visit = (child: ts.Node): void => {
if (ts.isJSDoc(child)) return
if (ts.isToken(child)) tokens.push(child.getText(source))
else child.getChildren(source).forEach(visit)
}
visit(node)
return createHash('sha256').update(JSON.stringify(tokens)).digest('hex')
}
/**
* List the first-party source paths a gate scans.
* @param repoRoot - repository root containing the Git index.
* @param name - gate name for diagnostics.
* @returns sorted repository-relative paths of tracked and non-ignored untracked source files.
* @throws when a required source area is missing or an eligible path is a symlink.
*/
export function listInventorySources(repoRoot: string, name: string): string[] {
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
cwd: repoRoot,
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
}).split('\0').map(file => file.replaceAll('\\', '/')).filter(isInventorySource))].sort()
const present = files.filter((file) => {
const stat = lstatSync(resolve(repoRoot, file), { throwIfNoEntry: false })
if (stat?.isSymbolicLink()) throw new Error(`${name}: source symlink is unsupported: ${file}`)
return stat?.isFile() === true
})
for (const area of AREAS) {
if (!present.some(file => file.startsWith(area))) {
throw new Error(`${name}: source discovery omitted ${area}`)
}
}
return present
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
/**
* Read and validate one recorded inventory.
* @param gate - the gate whose findings the inventory allows.
* @param repoRoot - repository root holding the inventory.
* @returns the recorded counts, keyed by repository path and fingerprint.
* @throws when the inventory is malformed or names a path outside the gate's corpus.
*/
export function readInventoryBaseline<T extends InventoryFinding>(
gate: InventoryGate<T>,
repoRoot: string,
): InventoryBaseline {
const value: unknown = JSON.parse(readFileSync(resolve(repoRoot, gate.baselinePath), 'utf8'))
if (!isRecord(value)) throw new Error(`${gate.name}: baseline must be a file-to-counts object`)
const baseline: InventoryBaseline = {}
for (const [file, counts] of Object.entries(value)) {
if (!isInventorySource(file) || file.startsWith('/') || file.includes('\\') || file.split('/').includes('..')
|| !isRecord(counts) || Object.keys(counts).length === 0) {
throw new Error(`${gate.name}: invalid baseline file: ${file}`)
}
const parsed: Record<string, number> = {}
for (const [fingerprint, count] of Object.entries(counts)) {
if (!/^[a-f0-9]{64}$/u.test(fingerprint) || typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) {
throw new Error(`${gate.name}: invalid baseline count: ${file}:${fingerprint}`)
}
parsed[fingerprint] = count
}
baseline[file] = parsed
}
return baseline
}
/**
* Count exact findings without granting a file-wide allowance.
* @param findings - observed findings.
* @returns path and fingerprint counts in stable order for comparison and pruning.
*/
export function countInventory(findings: readonly InventoryFinding[]): InventoryBaseline {
const baseline: InventoryBaseline = {}
for (const { file, fingerprint } of findings) {
const counts = baseline[file] ??= {}
counts[fingerprint] = (counts[fingerprint] ?? 0) + 1
}
return Object.fromEntries(Object.entries(baseline).sort(([a], [b]) => a.localeCompare(b))
.map(([file, counts]) => [file, Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)))]))
}
/**
* Enforce one gate's recorded inventory, optionally deleting retired allowances.
* @param gate - the gate to enforce.
* @param repoRoot - repository root to scan.
* @param prune - remove stale entries only after establishing that no new finding exists.
* @returns the number of findings still present.
* @throws for new findings, malformed inventories, or stale entries without pruning.
*/
export function verifyInventory<T extends InventoryFinding>(
gate: InventoryGate<T>,
repoRoot: string,
prune = false,
): number {
const baseline = readInventoryBaseline(gate, repoRoot)
const findings = gate.scan(repoRoot)
const remaining = structuredClone(baseline)
const added: T[] = []
for (const finding of findings) {
const counts = remaining[finding.file]
const allowance = counts?.[finding.fingerprint] ?? 0
if (counts !== undefined && allowance > 0) counts[finding.fingerprint] = allowance - 1
else added.push(finding)
}
if (added.length > 0) {
throw new Error(`${gate.name}: ${gate.rejection}\n`
+ added.map(finding => ` ${gate.describe(finding)}`).join('\n'))
}
const stale = Object.entries(remaining).flatMap(([file, counts]) => Object.entries(counts)
.filter(([, count]) => count > 0).map(([fingerprint]) => ` ${file} (${fingerprint})`))
if (stale.length > 0) {
if (!prune) {
throw new Error(`${gate.name}: remove retired baseline entries with pnpm run ${gate.name} --prune.\n`
+ stale.join('\n'))
}
writeFileSync(resolve(repoRoot, gate.baselinePath), `${JSON.stringify(countInventory(findings), null, 2)}\n`)
}
return findings.length
}
/**
* Run one gate as a command: `--prune` retires stale entries, no argument verifies, anything else
* fails the process.
* @param gate - the gate to enforce.
* @param root - repository root to scan.
*/
export function runInventoryGate<T extends InventoryFinding>(gate: InventoryGate<T>, root: string): void {
try {
const args = process.argv.slice(2)
if (args.length === 1 && args[0] === '--prune') {
console.log(gate.success(verifyInventory(gate, root, true)))
} else if (args.length === 0) {
console.log(gate.success(verifyInventory(gate, root)))
} else {
throw new Error(`Usage: pnpm run ${gate.name} [--prune]`)
}
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}
}
+98
View File
@@ -0,0 +1,98 @@
/**
* External compatibility API tests for retained string constructors.
* Keep these direct calls confined to API compatibility tests, never business fixture helpers.
*/
import { describe, expect, it } from 'vitest'
import { AttachmentId, ImageVariantId } from '../packages/attachment/attachment/src/brand.ts'
import { BrowserUseProviderName } from '../packages/browser-use/browser-use/src/brand.ts'
import { RpcId } from '../packages/client/connection/src/rpc.ts'
import { CompactionId } from '../packages/compaction/compaction/src/brand.ts'
import { ComputerUseProviderName } from '../packages/computer-use/computer-use/src/brand.ts'
import { SessionId } from '../packages/core/session/src/types.ts'
import { OfficeKitGeneration, OfficeKitKey, OfficeSourceKey } from '../packages/document/office-kit/src/identity.ts'
import { WebhookDeliveryId, WebhookRuleId, WebhookSourceId } from '../packages/experimental/webhook/src/brand.ts'
import {
ApprovalRequestId as CordisApprovalRequestId,
CordisDynamicPackageId,
CordisDynamicPluginId,
CordisDynamicPluginRunId,
} from '../packages/extensions/cordis-host-runner/src/index.ts'
import { FsTargetKey, FsVersion } from '../packages/fs/fs/src/types.ts'
import { GoalId } from '../packages/goal/goal/src/runtime.ts'
import { CommandDefinitionId, CommandId } from '../packages/interaction/commands/src/brand.ts'
import { ApprovalRequestId as UserApprovalRequestId } from '../packages/interaction/user-approval/src/types.ts'
import { JobId } from '../packages/jobs/jobs/src/brand.ts'
import { DeepSeekFileId, DeepSeekFileScope } from '../packages/llm/llm-deepseek/src/file-id.ts'
import { RetryId } from '../packages/llm/llm-retry/src/brand.ts'
import {
LlmAttemptId,
MessageId,
ProviderRequestId,
ReasoningEffortId,
ToolCallId,
} from '../packages/llm/llm/src/brand.ts'
import { LspProviderId } from '../packages/lsp/lsp/src/brand.ts'
import { ScheduleId } from '../packages/schedule/schedule/src/domain.ts'
import { SessionSearchCursor } from '../packages/session-query/session-query/src/cursor.ts'
import { SessionPersistenceRevision } from '../packages/session/session-persistence/src/revision.ts'
import { SessionTitleProviderId } from '../packages/session/session-title/src/index.ts'
import { SpillLocator } from '../packages/spill/spill/src/types.ts'
import { SubagentRunId } from '../packages/subagent/subagent/src/types.ts'
import { TeamId, TeamMessageId, TeamTaskId } from '../packages/team/agent-team/src/types.ts'
import { TerminalSessionId } from '../packages/terminal/terminal/src/index.ts'
import { WorkflowRunId } from '../packages/workflow/workflow/src/types.ts'
import { WorkspaceId } from '../packages/workspace/workspace/src/index.ts'
describe('External compatibility API: retained string constructors', () => {
it.each<[string, (value: string) => string]>([
['attachment.AttachmentId', AttachmentId],
['attachment.ImageVariantId', ImageVariantId],
['browser-use.BrowserUseProviderName', BrowserUseProviderName],
['client-connection.RpcId', RpcId],
['compaction.CompactionId', CompactionId],
['computer-use.ComputerUseProviderName', ComputerUseProviderName],
['session.SessionId', SessionId],
['office-kit.OfficeKitGeneration', OfficeKitGeneration],
['office-kit.OfficeKitKey', OfficeKitKey],
['office-kit.OfficeSourceKey', OfficeSourceKey],
['webhook.WebhookDeliveryId', WebhookDeliveryId],
['webhook.WebhookRuleId', WebhookRuleId],
['webhook.WebhookSourceId', WebhookSourceId],
['cordis-host-runner.ApprovalRequestId', CordisApprovalRequestId],
['cordis-host-runner.CordisDynamicPackageId', CordisDynamicPackageId],
['cordis-host-runner.CordisDynamicPluginId', CordisDynamicPluginId],
['cordis-host-runner.CordisDynamicPluginRunId', CordisDynamicPluginRunId],
['fs.FsTargetKey', FsTargetKey],
['fs.FsVersion', FsVersion],
['goal.GoalId', GoalId],
['commands.CommandDefinitionId', CommandDefinitionId],
['commands.CommandId', CommandId],
['user-approval.ApprovalRequestId', UserApprovalRequestId],
['jobs.JobId', JobId],
['llm-deepseek.DeepSeekFileId', DeepSeekFileId],
['llm-deepseek.DeepSeekFileScope', DeepSeekFileScope],
['llm-retry.RetryId', RetryId],
['llm.LlmAttemptId', LlmAttemptId],
['llm.MessageId', MessageId],
['llm.ProviderRequestId', ProviderRequestId],
['llm.ReasoningEffortId', ReasoningEffortId],
['llm.ToolCallId', ToolCallId],
['lsp.LspProviderId', LspProviderId],
['schedule.ScheduleId', ScheduleId],
['session-query.SessionSearchCursor', SessionSearchCursor],
['session-persistence.SessionPersistenceRevision', SessionPersistenceRevision],
['session-title.SessionTitleProviderId', SessionTitleProviderId],
['spill.SpillLocator', SpillLocator],
['subagent.SubagentRunId', SubagentRunId],
['agent-team.TeamId', TeamId],
['agent-team.TeamMessageId', TeamMessageId],
['agent-team.TeamTaskId', TeamTaskId],
['terminal.TerminalSessionId', TerminalSessionId],
['workflow.WorkflowRunId', WorkflowRunId],
['workspace.WorkspaceId', WorkspaceId],
])('%s preserves the supplied string without validation or generation', (_name, constructor) => {
for (const value of ['', 'external-id:42', ' \t untrimmed \r\n', '标识/🔑:\u0000value']) {
expect(constructor(value)).toBe(value)
}
})
})
+1 -2
View File
@@ -453,8 +453,7 @@ describe('package payload constraints', () => {
},
)
it('exempts the private plugin market generator from release rules in its own directory only', () => {
const dir = 'apps/plugin-market-generator'
it.each(['apps/plugin-market-generator', 'apps/desktop-publisher'])('exempts private tool %s from release rules in its own directory only', (dir) => {
const manifest = JSON.parse(readFileSync(new URL(`../${dir}/package.json`, import.meta.url), 'utf8')) as WorkspaceManifest['manifest']
expect(checkWorkspaceManifest({ dir, manifest })).toEqual([])
expect(checkWorkspaceManifest({ dir: 'apps/other-tool', manifest })).not.toEqual([])
+5 -5
View File
@@ -63,12 +63,14 @@ const publishedRepositoryUrl = 'git+https://github.com/deepseek-ai/deepseek-harn
const experimentalPackageDirectory = /^packages\/experimental\/[^/]+$/
/** Private reference tool run from the repository; it publishes no files. */
const pluginMarketGeneratorDirectory = 'apps/plugin-market-generator'
/** Source-only private release tool, sharing the Desktop version. */
const desktopPublisherDirectory = 'apps/desktop-publisher'
/**
* Ordinary directories whose packages this repository publishes: one release member each. The reference plugin
* market generator is a private repository tool, not a published application.
*/
const standardReleaseMemberDirectory = new RegExp(
`^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`,
`^(?:packages/(?!experimental/)[^/]+/[^/]+|apps/(?!desktop(?:-host)?$|${pluginMarketGeneratorDirectory.slice('apps/'.length)}$|${desktopPublisherDirectory.slice('apps/'.length)}$)[^/]+|vendor/[^/]+)$`,
'u',
)
/** Installable application assembled by electron-builder rather than published to npm. */
@@ -190,7 +192,7 @@ 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', 'lib/config.js', 'lib/native-schema.js', 'lib/native-build.js', 'lib/guidance.js'],
'@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-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-cua-windows': ['native/bin'],
'@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
@@ -216,8 +218,6 @@ const packageFileExtras: Readonly<Record<string, readonly string[]>> = {
'@deepseek-ai/dsh-client-ui-theme': ['lib/styles'],
// The physical-key protocol is a public entry usable without the browser service.
'@deepseek-ai/dsh-client-shortcuts': ['lib/protocol.js'],
// The CPython side ships as source .py files, published as-is rather than built.
'@deepseek-ai/dsh-experimental-ptc-runtime-python': ['py/**/*.py'],
'@deepseek-ai/dsh-experimental-speech-to-text-sensevoice': ['runtime/assets.json'],
// Node profile configuration and process bootstraps have separate bundles.
'@deepseek-ai/dsh-ptc-runtime-node': ['lib/configuration.js', 'lib/process.js', 'lib/persistent-process.js'],
@@ -560,7 +560,7 @@ export function checkWorkspaceManifest({ dir, manifest }: WorkspaceManifest): st
return errors
}
if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && manifest.name?.startsWith('@deepseek-ai/')) {
if (dir.startsWith('apps/') && dir !== desktopApplicationDirectory && dir !== pluginMarketGeneratorDirectory && dir !== desktopPublisherDirectory && manifest.name?.startsWith('@deepseek-ai/')) {
const expectedFiles = appPackageFiles[manifest.name]
if (expectedFiles === undefined) {
errors.push(`${label}: app package has no publication files policy`)
+5 -1
View File
@@ -108,7 +108,11 @@ describe('Node compatibility self-hosted routing', () => {
)
}
expect(job.steps[0]?.with).toEqual({ 'persist-credentials': false })
expect(job.steps.some(step => step.uses?.startsWith('actions/cache/'))).toBe(false)
// The verified bubblewrap archive is the one remote cache this job restores
// and saves; it must stay excluded from the persistent self-hosted pool.
const remoteCaches = job.steps.filter(step => step.uses?.startsWith('actions/cache/'))
expect(remoteCaches.length).toBeGreaterThan(0)
for (const step of remoteCaches) expect(step.if).toContain("vars.DSH_CI_FAILOVER_LINUX != 'selfhosted'")
})
it('overrides runner exports inside setup-node without affecting later Node processes', () => {
+105
View File
@@ -0,0 +1,105 @@
# shellcheck shell=bash
# Sourced by CI preparation scripts; defines functions only.
# Prints the SHA-256 digest of <file>.
#
# CI runners do not all provide the same tool: GNU coreutils ships `sha256sum`,
# while macOS ships `shasum -a 256`. Probing both keeps a missing tool from
# being reported as a digest mismatch, which would discard a verified cached
# archive and send the next run back to a possibly unavailable download host.
sha256_digest() {
local output
if command -v sha256sum >/dev/null 2>&1; then
output="$(sha256sum < "$1")"
elif command -v shasum >/dev/null 2>&1; then
output="$(shasum -a 256 < "$1")"
else
echo 'No SHA-256 tool found: need sha256sum or shasum -a 256' >&2
return 2
fi
printf '%s\n' "${output%% *}"
}
# Succeeds when <file> has the SHA-256 digest <sha256>. Returns 2, reporting the
# missing tool on stderr, when neither digest tool exists.
#
# Usage: verified_sha256 <sha256> <file>
verified_sha256() {
local actual status=0
actual="$(sha256_digest "$2")" || status=$?
if (( status != 0 )); then
return "$status"
fi
[[ "$actual" == "$1" ]]
}
# Leaves a copy of <url> whose SHA-256 digest is <sha256> at <cache-file>.
#
# A cached file with the expected digest is used without network access, so a
# restored Actions cache keeps CI independent of the download host. A cached
# file with any other digest is discarded. A download is verified before it
# replaces <cache-file> atomically, so the cache only ever holds a verified
# payload. A failed download or verification leaves nothing at <cache-file> and
# reports the URL on stderr. A missing SHA-256 tool returns 2 instead of
# treating the payload as mismatched. Each attempt is bounded so a stalled host
# fails within minutes.
#
# Usage: acquire_verified_archive <url> <sha256> <cache-file>
acquire_verified_archive() {
local url="$1" sha256="$2" cache_file="$3" cache_dir
cache_dir="$(dirname -- "$cache_file")"
# Probe before the network work: a runner without a digest tool must fail
# immediately instead of downloading a payload it cannot verify.
sha256_digest /dev/null >/dev/null
if [[ -f "$cache_file" ]]; then
local cache_status=0
verified_sha256 "$sha256" "$cache_file" || cache_status=$?
if (( cache_status == 0 )); then
echo "Using verified cached archive $cache_file"
return 0
fi
if (( cache_status != 1 )); then
return "$cache_status"
fi
echo "Discarding cached archive $cache_file: SHA-256 mismatch" >&2
rm -f -- "$cache_file"
fi
if ! mkdir -p -- "$cache_dir"; then
echo "Failed to create $cache_dir while preparing $url" >&2
return 1
fi
local partial
if ! partial="$(mktemp "${cache_file}.partial.XXXXXX")"; then
echo "Failed to create a temporary file in $cache_dir while preparing $url" >&2
return 1
fi
# A cancelled job must not leave a partial payload in the directory that
# actions/cache/save uploads.
trap 'rm -f -- "$partial"' EXIT
if ! curl --fail --silent --show-error --location \
--connect-timeout 15 --max-time 60 \
--retry 8 --retry-all-errors --retry-max-time 240 \
--output "$partial" "$url"; then
rm -f -- "$partial"
trap - EXIT
echo "Failed to download $url and no verified cached copy exists at $cache_file" >&2
return 1
fi
local download_status=0
verified_sha256 "$sha256" "$partial" || download_status=$?
if (( download_status != 0 )); then
rm -f -- "$partial"
trap - EXIT
if (( download_status != 1 )); then
return "$download_status"
fi
echo "Downloaded $url does not have SHA-256 $sha256" >&2
return 1
fi
mv -f -- "$partial" "$cache_file"
trap - EXIT
}
+187
View File
@@ -0,0 +1,187 @@
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import {
chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync,
} from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, join, resolve } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
const library = resolve(import.meta.dirname, 'ci-verified-download.sh')
const url = 'https://downloads.invalid/payload.deb'
const payload = Buffer.from('verified payload\n')
const payloadSha256 = createHash('sha256').update(payload).digest('hex')
const bash = ['/bin/bash', '/usr/bin/bash'].find(candidate => existsSync(candidate)) ?? 'bash'
// Records each invocation, then copies FAKE_CURL_SOURCE to the --output path
// or fails as curl does for an HTTP error when no source is configured.
const fakeCurl = `#!/usr/bin/env bash
printf '%s\\n' "$*" >> "$FAKE_CURL_LOG"
output=''
while (( $# > 0 )); do
if [[ "$1" == --output ]]; then output="$2"; shift; fi
shift
done
if [[ -z "\${FAKE_CURL_SOURCE:-}" ]]; then
echo 'curl: (22) The requested URL returned error: 503' >&2
exit 22
fi
cp "$FAKE_CURL_SOURCE" "$output"
`
interface Fixture {
readonly root: string
readonly cacheDir: string
readonly cacheFile: string
readonly curlLog: string
readonly env: NodeJS.ProcessEnv
}
const fixtureRoots: string[] = []
afterEach(() => {
for (const root of fixtureRoots.splice(0)) rmSync(root, { recursive: true, force: true })
})
function createFixture(served?: Buffer): Fixture {
const root = mkdtempSync(join(tmpdir(), 'dsh-ci-verified-download-'))
fixtureRoots.push(root)
const bin = join(root, 'bin')
mkdirSync(bin)
writeFileSync(join(bin, 'curl'), fakeCurl)
chmodSync(join(bin, 'curl'), 0o755)
const curlLog = join(root, 'curl.log')
writeFileSync(curlLog, '')
const env: NodeJS.ProcessEnv = { ...process.env, PATH: bin + delimiter + (process.env.PATH ?? ''), FAKE_CURL_LOG: curlLog }
delete env.FAKE_CURL_SOURCE
if (served !== undefined) {
const source = join(root, 'served.deb')
writeFileSync(source, served)
env.FAKE_CURL_SOURCE = source
}
const cacheDir = join(root, 'cache', 'bubblewrap')
return { root, cacheDir, cacheFile: join(cacheDir, 'payload.deb'), curlLog, env }
}
interface AcquireResult {
readonly status: number | null
readonly signal: NodeJS.Signals | null
readonly stderr: string
}
function acquire(fixture: Fixture, env: NodeJS.ProcessEnv = fixture.env): AcquireResult {
const result = spawnSync(
bash,
['-c', 'set -euo pipefail; source "$1"; acquire_verified_archive "$2" "$3" "$4"', 'acquire', library, url, payloadSha256, fixture.cacheFile],
{ encoding: 'utf8', env, timeout: 30_000 },
)
return { status: result.status, signal: result.signal, stderr: result.stderr }
}
function curlCalls(fixture: Fixture): string[] {
return readFileSync(fixture.curlLog, 'utf8').split('\n').filter(line => line !== '')
}
function seedCache(fixture: Fixture, content: Buffer): void {
mkdirSync(fixture.cacheDir, { recursive: true })
writeFileSync(fixture.cacheFile, content)
}
// Builds a PATH that reaches only the named executables plus the fixture's fake
// curl, so a child can run on a host that provides a SHA-256 tool but see none.
function restrictedPath(fixture: Fixture, names: readonly string[]): string {
const bin = join(fixture.root, 'restricted-bin')
mkdirSync(bin, { recursive: true })
for (const name of names) {
const resolved = spawnSync('sh', ['-c', `command -v ${name}`], { encoding: 'utf8' }).stdout.trim()
if (resolved === '') throw new Error(`the test host does not provide ${name}`)
symlinkSync(resolved, join(bin, name))
}
return [bin, join(fixture.root, 'bin')].join(delimiter)
}
function hasDigestTool(): boolean {
return spawnSync('sh', ['-c', 'command -v sha256sum || command -v shasum'], { stdio: 'ignore' }).status === 0
}
// The library targets Linux CI runners; the suite needs bash and a SHA-256 tool
// (sha256sum or shasum -a 256) and skips elsewhere.
describe.skipIf(process.platform === 'win32' || !hasDigestTool())('acquire_verified_archive', () => {
it('uses a verified cached archive without contacting the download host', () => {
const fixture = createFixture()
seedCache(fixture, payload)
const result = acquire(fixture)
expect(result.signal).toBeNull()
expect(result.status).toBe(0)
expect(curlCalls(fixture)).toEqual([])
expect(readFileSync(fixture.cacheFile)).toEqual(payload)
})
it('fails with the URL when the download fails and no cached archive exists', () => {
const fixture = createFixture()
const result = acquire(fixture)
expect(result.signal).toBeNull()
expect(result.status).toBe(1)
expect(result.stderr).toContain(`Failed to download ${url} and no verified cached copy exists at ${fixture.cacheFile}`)
expect(curlCalls(fixture)).toHaveLength(1)
expect(readdirSync(fixture.cacheDir)).toEqual([])
})
it('bounds every download attempt and the retry window', () => {
const fixture = createFixture(payload)
expect(acquire(fixture).status).toBe(0)
const [call] = curlCalls(fixture)
expect(call).toContain('--connect-timeout 15 ')
expect(call).toContain('--max-time 60 ')
expect(call).toContain('--retry 8 ')
// The last attempt may still run for its full --max-time, so the bounded
// failure time is this window plus 60 seconds.
expect(call).toContain('--retry-max-time 240 ')
expect(call).toContain(url)
})
it('fails immediately and reports the missing tool instead of a digest mismatch', () => {
const fixture = createFixture(payload)
const env = { ...fixture.env, PATH: restrictedPath(fixture, ['bash', 'dirname', 'mkdir', 'mktemp', 'mv', 'rm']) }
const result = acquire(fixture, env)
expect(result.signal).toBeNull()
expect(result.status).toBe(2)
expect(result.stderr).toContain('No SHA-256 tool found')
expect(curlCalls(fixture)).toEqual([])
expect(existsSync(fixture.cacheFile)).toBe(false)
})
it('replaces a cached archive whose digest does not match with a verified download', () => {
const fixture = createFixture(payload)
seedCache(fixture, Buffer.from('corrupted payload\n'))
const result = acquire(fixture)
expect(result.signal).toBeNull()
expect(result.status).toBe(0)
expect(result.stderr).toContain('SHA-256 mismatch')
expect(curlCalls(fixture)).toHaveLength(1)
expect(readdirSync(fixture.cacheDir)).toEqual(['payload.deb'])
expect(readFileSync(fixture.cacheFile)).toEqual(payload)
})
it('rejects a downloaded archive whose digest does not match without caching it', () => {
const fixture = createFixture(Buffer.from('tampered payload\n'))
const result = acquire(fixture)
expect(result.signal).toBeNull()
expect(result.status).toBe(1)
expect(result.stderr).toContain(`Downloaded ${url} does not have SHA-256 ${payloadSha256}`)
expect(existsSync(fixture.cacheFile)).toBe(false)
expect(readdirSync(fixture.cacheDir)).toEqual([])
})
})
+82 -7
View File
@@ -41,12 +41,17 @@ describe('CI workflow', () => {
})
expect(workflowJob(ci, 'all-checks-passed').needs).toContain('node-compat')
const ordinaryJobs = Object.entries(ci.jobs)
.filter(([name]) => !['node-compat', 'all-checks-passed'].includes(name))
.filter(([name]) => !['node-compat', 'all-checks-passed', 'publisher-isolated'].includes(name))
for (const [name, job] of ordinaryJobs) {
if (!isRecord(job)) throw new TypeError(`${name} must define a job`)
expect(job).not.toHaveProperty('strategy')
expect(job).not.toHaveProperty('uses')
}
// Publisher smoke reuses the compatibility/build concurrency slots before those jobs start.
expect(compatibility.needs).toBe('publisher-isolated')
expect(workflowJob(ci, 'publisher-isolated').strategy).toMatchObject({ 'max-parallel': 1, matrix: { os: ['linux', 'macos'] } })
expect(workflowJob(ciWindows, 'windows-build').needs).toBe('windows-publisher')
expect(workflowJob(ciWindows, 'windows-publisher').defaults).toEqual({ run: { shell: 'pwsh' } })
// Python reports its own required verdict, so neither its jobs nor a
// reusable workflow caller remain in the Linux or Windows workflow.
expect(Object.keys(ci.jobs).filter(name => name.startsWith('python'))).toEqual([])
@@ -60,7 +65,7 @@ describe('CI workflow', () => {
expect(runtime.with).toMatchObject({ targets: 'node24-linux-x64,node24-win-x64' })
expect(runtime.uses).toBe('./.github/workflows/build-exe-for-python-sdk.yml')
const windowsJobs = Object.entries(ciWindows.jobs)
.filter(([name]) => name !== 'windows-checks-passed')
.filter(([name]) => !['windows-checks-passed', 'windows-publisher'].includes(name))
for (const [name, job] of windowsJobs) {
if (!isRecord(job)) throw new TypeError(`${name} must define a job`)
expect(job).not.toHaveProperty('strategy')
@@ -95,7 +100,7 @@ describe('CI workflow', () => {
expect(afterSdk).toBeLessThanOrEqual(11)
})
it('keeps the union of required PR verdicts equal to the pre-split blocking set', () => {
it('keeps required PR verdicts covering runtime and publisher jobs', () => {
const verdicts = [
['ci.yml', 'all-checks-passed'],
['ci-windows.yml', 'windows-checks-passed'],
@@ -112,9 +117,7 @@ describe('CI workflow', () => {
expect(verdict.needs.every(id => typeof id === 'string' && id in jobs)).toBe(true)
blocking.push(...(verdict.needs as string[]))
}
// Splitting the workflows only moves jobs between verdicts; the blocking
// set itself must stay identical, or branch protection would accept a
// failure it rejected before the split.
// Every blocking lane must contribute to a branch-protection verdict.
expect(blocking.sort()).toEqual([
'node-24',
'node-24-bench',
@@ -122,10 +125,12 @@ describe('CI workflow', () => {
'node-24-coverage',
'node-24-lint',
'node-compat',
'publisher-isolated',
'python-runtime',
'python-sdk',
'windows-build',
'windows-native-tests',
'windows-publisher',
])
})
@@ -547,7 +552,7 @@ describe('CI workflow', () => {
expect(aggregate.needs).not.toContain('windows')
// windows-coverage is temporarily non-blocking while Windows ACP
// half-close tests are stabilized; observational stays out too.
expect(windowsAggregate.needs).toEqual(['windows-build', 'windows-native-tests'])
expect(windowsAggregate.needs).toEqual(['windows-publisher', 'windows-build', 'windows-native-tests'])
expect(windowsAggregate.name).toBe('windows checks passed')
expect(windowsAggregate['runs-on']).toBe(aggregate['runs-on'])
expect(windowsAggregate.if).toBe(aggregate.if)
@@ -1112,6 +1117,76 @@ describe('bubblewrap preparation script', () => {
// Ubuntu removes superseded versions from its live package pool.
expect(script).not.toMatch(/https?:\/\/[^/'"\s]+\/ubuntu(?:-ports)?\/pool\//u)
})
it('verifies the archive against the pinned digest', () => {
const script = readFileSync(resolve(root, 'scripts/prepare-ci-bubblewrap.sh'), 'utf8')
expect(script).toMatch(/^readonly BUBBLEWRAP_SHA256='[0-9a-f]{64}'$/mu)
expect(script).toContain('acquire_verified_archive "$BUBBLEWRAP_URL" "$BUBBLEWRAP_SHA256" "$archive"')
})
// Ephemeral runners share a `~` layout: GitHub-hosted runners and Blacksmith
// (whose runners register as self-hosted but keep /home/runner as HOME). The
// in-house `vm-backup` pool keeps `~/.cache` on a different, persistent
// layout, so lanes that can select it must not restore or save this cache.
// `ci-master.yml` prepares bubblewrap only on lanes that can select the
// persistent runners, and the manual benchmark matrix includes their 64/96-core
// rows, so neither carries cache steps.
const hostedOnly = "vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'"
const cachedJobs = new Map<string, string | undefined>([
['ci.yml:node-24-coverage', hostedOnly],
['ci.yml:node-24-consumers', hostedOnly],
['ci.yml:node-compat', hostedOnly],
['e2e.yml:e2e', undefined],
])
it.each(['ci.yml', 'ci-master.yml', 'e2e.yml'])(
'%s caches the verified archive only on the lanes that run on ephemeral runners',
(name) => {
const script = readFileSync(resolve(root, 'scripts/prepare-ci-bubblewrap.sh'), 'utf8')
expect(script).toContain('readonly BUBBLEWRAP_CACHE_DIR="${HOME}/.cache/dsh-ci/bubblewrap"')
const cache = {
path: '~/.cache/dsh-ci/bubblewrap',
key: "bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}",
}
const workflow = loadWorkflow('.github/workflows/' + name)
if (!isRecord(workflow.jobs)) throw new TypeError(`${name} must define jobs`)
let preparations = 0
for (const [jobName, job] of Object.entries(workflow.jobs)) {
if (!isRecord(job) || !Array.isArray(job.steps)) continue
const steps = job.steps.filter(isRecord)
const preparation = steps.findIndex(step =>
typeof step.run === 'string' && step.run.includes('bash scripts/prepare-ci-bubblewrap.sh'))
if (preparation < 0) continue
preparations += 1
const key = `${name}:${jobName}`
if (!cachedJobs.has(key)) {
expect(
steps.filter(step => typeof step.uses === 'string' && step.uses.startsWith('actions/cache/')),
key,
).toEqual([])
continue
}
const guard = cachedJobs.get(key)
const cacheHit = "steps.bubblewrap-cache.outputs.cache-hit != 'true'"
expect(steps[preparation - 1]).toEqual({
name: 'Restore verified bubblewrap archive',
id: 'bubblewrap-cache',
...(guard === undefined ? {} : { if: guard }),
uses: 'actions/cache/[email protected]',
with: cache,
})
expect(steps[preparation + 1]).toEqual({
name: 'Save verified bubblewrap archive',
if: guard === undefined ? cacheHit : `(${guard}) && ${cacheHit}`,
uses: 'actions/cache/[email protected]',
with: cache,
})
}
expect(preparations).toBeGreaterThan(0)
},
)
})
describe('DeepSeek e2e workflow', () => {
+7 -7
View File
@@ -19,7 +19,7 @@ function fixture() {
'packages/experimental/cua-macos/native/Info.plist': 'application identity',
'scripts/cua-helper/package.ts': 'build helper',
'apps/desktop/scripts/notarize-macos.mjs': 'notarize helper',
'.github/workflows/cua-helper-package.yml': 'build configuration',
'.github/workflows/cua-helper-package-macos.yml': 'build configuration',
'.github/workflows/release-publish.yml': 'publish configuration',
'packages/client/unrelated/src/index.ts': 'unrelated feature',
}
@@ -62,7 +62,7 @@ it.each(['add', 'delete', 'rename', 'resource', 'dependency', 'script', 'workflo
if (change === 'resource') writeFileSync(join(f.root, 'packages/experimental/cua-macos/native/Info.plist'), 'changed identity')
if (change === 'dependency') writeFileSync(join(f.root, 'pnpm-lock.yaml'), 'changed dependency')
if (change === 'script') writeFileSync(join(f.root, 'apps/desktop/scripts/notarize-macos.mjs'), 'changed notarization')
if (change === 'workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package.yml'), 'changed build configuration')
if (change === 'workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package-macos.yml'), 'changed build configuration')
if (change === 'package manager') writeFileSync(join(f.root, 'package.json'), JSON.stringify({ packageManager: '[email protected]' }))
f.git('add', '-A')
expect(cuaHelperSourceDigest(f.root)).not.toBe(before)
@@ -170,7 +170,7 @@ it.each(['helper workflow', 'publish workflow', 'packaging script', 'manifest li
const f = fixture()
const previous = producerSnapshot(f.root)
const digest = cuaHelperSourceDigest(f.root)
if (change === 'helper workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package.yml'), 'forged uploader')
if (change === 'helper workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package-macos.yml'), 'forged uploader')
if (change === 'publish workflow') writeFileSync(join(f.root, '.github/workflows/release-publish.yml'), 'forged caller')
if (change === 'packaging script') writeFileSync(join(f.root, 'scripts/cua-helper/package.ts'), 'forged metadata')
if (change === 'manifest lifecycle') writeFileSync(join(f.root, 'package.json'), JSON.stringify({
@@ -229,11 +229,11 @@ it.skipIf(process.platform === 'win32').each(['match', 'miss', 'api failure', 'm
Object.assign(snapshot.responses, {
[base]: { run_attempt: 2 },
[`${base}/attempts/2`]: { id: 123, run_attempt: 2, status: 'completed', conclusion: 'success',
event: 'workflow_dispatch', path: '.github/workflows/cua-helper-package.yml', head_sha: snapshot.commit,
event: 'workflow_dispatch', path: '.github/workflows/cua-helper-package-macos.yml', head_sha: snapshot.commit,
repository: { full_name: repository }, head_repository: { full_name: repository } },
[`${base}/jobs?filter=all&per_page=100`]: { jobs: [{ name: 'package', conclusion: 'success', run_attempt: 2 }] },
[`${base}/artifacts?per_page=100`]: { artifacts: scenario === 'match'
? [{ id: 456, name: `cua-helper-123-2-${key}`, expired: false, size_in_bytes: 4096 }] : [] },
? [{ id: 456, name: `cua-helper-macos-123-2-${key}`, expired: false, size_in_bytes: 4096 }] : [] },
})
const data = join(f.root, 'responses.json')
writeFileSync(data, JSON.stringify(snapshot.responses))
@@ -251,7 +251,7 @@ globalThis.fetch = async (input, options) => {
}
if (process.env.FIXTURE_API_FAILURE === '1') return new Response('fixture API failure', { status: 503 });
const path = url.pathname.slice(1) + url.search;
if (path.includes('/workflows/')) return Response.json({ workflow_runs: path.includes('cua-helper-package.yml') ? [{ id: 123 }] : [] });
if (path.includes('/workflows/')) return Response.json({ workflow_runs: path.includes('cua-helper-package-macos.yml') ? [{ id: 123 }] : [] });
if (!(path in data)) throw new Error('unexpected GitHub path');
return Response.json(data[path]);
};
@@ -262,7 +262,7 @@ globalThis.fetch = async (input, options) => {
cwd: f.root, encoding: 'utf8', timeout: 60_000,
env: { ...process.env, NODE_OPTIONS: '', PATH: bin, GH_TOKEN: scenario === 'missing token' ? '' : 'fixture-token',
GITHUB_API_URL: 'https://api.github.com', GITHUB_REPOSITORY: repository, GITHUB_OUTPUT: output,
GITHUB_STEP_SUMMARY: summary, CUA_RUN_ID: '', CUA_BUILD_KEY: key,
GITHUB_STEP_SUMMARY: summary, CUA_MACOS_RUN_ID: '', CUA_BUILD_KEY: key,
FIXTURE_API_DATA: data, FIXTURE_API_FAILURE: scenario === 'api failure' ? '1' : '0' },
})
expect(result.error).toBeUndefined()
+1 -1
View File
@@ -12,7 +12,7 @@ const sourceDirectories = [
'packages/experimental/cua-macos/native', 'scripts/cua-helper', 'apps/desktop/scripts', 'patches',
]
const sourceFiles = new Set([
'.github/workflows/cua-helper-package.yml', '.github/workflows/release-publish.yml',
'.github/workflows/cua-helper-package-macos.yml', '.github/workflows/release-publish.yml',
'package.json', 'scripts/package.json', 'apps/package.json', 'apps/desktop/package.json', 'scripts/release/process.ts',
'pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc', '.pnpmfile.cjs', '.pnpmfile.mjs',
])
+5 -5
View File
@@ -72,7 +72,7 @@ it.skipIf(process.platform === 'win32')('keeps npm tarball bytes when reusing a
mkdirSync(output)
stageCuaHelperPayload(f.payload, packageRoot, identity)
writeFileSync(join(packageRoot, 'package.json'), JSON.stringify({
name: '@deepseek-ai/dsh-experimental-cua-macos', version: f.manifest.version, type: 'module',
name: '@deepseek-ai/dsh-cua-macos', version: f.manifest.version, type: 'module',
files: ['lib/index.js', 'native/bin', CUA_MANIFEST],
}))
writeFileSync(join(packageRoot, 'lib/index.js'), 'export const provider = "fixture";\n')
@@ -85,7 +85,7 @@ it.skipIf(process.platform === 'win32')('keeps npm tarball bytes when reusing a
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')
const tarball = join(output, 'deepseek-ai-dsh-cua-macos-1.0.0.tgz')
await verifyCuaHelperTarball(tarball, identity)
return readFileSync(tarball)
}
@@ -118,15 +118,15 @@ it.skipIf(process.platform === 'win32').each(['source', 'configuration', 'archit
})
it('keeps company signing outside pull-request release rehearsals', () => {
const workflow = readFileSync(resolve('.github/workflows/cua-helper-package.yml'), 'utf8')
const workflow = readFileSync(resolve('.github/workflows/cua-helper-package-macos.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('needs: cua-helper-macos')
expect(release).toContain('scripts/cua-helper/stage.ts')
expect(readFileSync(resolve('.github/workflows/release.yml'), 'utf8')).not.toContain('cua-helper-package.yml')
expect(readFileSync(resolve('.github/workflows/release.yml'), 'utf8')).not.toContain('cua-helper-package-macos.yml')
})
it.skipIf(process.platform === 'win32')('retains the original build commit and version when consuming identical helper sources', () => {
+34 -20
View File
@@ -8,16 +8,16 @@ const key = 'a'.repeat(64)
function fixture() {
const run = { id: 123, run_attempt: 2, status: 'completed', conclusion: 'success', event: 'workflow_dispatch',
path: '.github/workflows/cua-helper-package.yml', head_sha: 'c'.repeat(40), repository: { full_name: repository }, head_repository: { full_name: repository } }
path: '.github/workflows/cua-helper-package-macos.yml', head_sha: 'c'.repeat(40), repository: { full_name: repository }, head_repository: { full_name: repository } }
const jobs = [{ jobs: [{ name: 'package', conclusion: 'success', run_attempt: 2 }] }]
const matchesSource = vi.fn(async (_commit: string) => true)
const artifact = { id: 456, name: `cua-helper-123-2-${key}`, expired: false, size_in_bytes: 4096 }
const artifacts = [{ artifacts: [{ ...artifact, id: 455, name: `cua-helper-123-1-${key}` }] }, { artifacts: [artifact] }]
const artifact = { id: 456, name: `cua-helper-macos-123-2-${key}`, expired: false, size_in_bytes: 4096 }
const artifacts = [{ artifacts: [{ ...artifact, id: 455, name: `cua-helper-macos-123-1-${key}` }] }, { artifacts: [artifact] }]
const api = vi.fn(async (path: string, paginate?: boolean) => {
if (path === base) { expect(paginate).toBeUndefined(); return { run_attempt: 2 } }
if (path === `${base}/attempts/2`) { expect(paginate).toBeUndefined(); return run }
expect(paginate).toBe(true)
if (path.includes('/workflows/cua-helper-package.yml/runs?')) return [{ workflow_runs: [{ id: 123 }] }]
if (path.includes('/workflows/cua-helper-package-macos.yml/runs?')) return [{ workflow_runs: [{ id: 123 }] }]
if (path.includes('/workflows/release-publish.yml/runs?')) return [{ workflow_runs: [] }]
if (path === `${base}/jobs?filter=all&per_page=100`) return jobs
if (path === `${base}/artifacts?per_page=100`) return artifacts
@@ -38,7 +38,7 @@ it('allows successful helper packaging when later npm publication failed', async
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.run.conclusion = 'failure'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }, { name: 'Publish to npm', conclusion: 'failure', run_attempt: 2 }]
f.jobs[0]!.jobs = [{ name: 'cua-helper-macos / package', conclusion: 'success', run_attempt: 2 }, { name: 'Publish to npm', conclusion: 'failure', run_attempt: 2 }]
expect((await selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource))?.artifactId).toBe('456')
})
@@ -72,27 +72,34 @@ it.each(['workflow', 'event', 'repository', 'head_repository', 'id', 'attempt',
},
)
it.each(['failure', 'cancelled', 'skipped', 'missing', 'duplicate'])(
it('identifies a release run missing the macOS packaging job', async () => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }]
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource))
.rejects.toThrow('this run contains no cua-helper-macos / package job')
expect(f.api.mock.calls.some(([path]) => path.includes('/artifacts'))).toBe(false)
})
it.each(['failure', 'cancelled', 'skipped', 'duplicate'])(
'rejects %s helper jobs without falling back to attempt 1', async (status) => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.run.conclusion = 'failure'
f.jobs[0]!.jobs = status === 'missing' ? [] : status === 'duplicate'
? [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }, { name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }]
: [{ name: 'cua-helper / package', conclusion: status, run_attempt: 2 }]
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('last executed cua-helper / package job did not succeed')
f.jobs[0]!.jobs = status === 'duplicate'
? [{ name: 'cua-helper-macos / package', conclusion: 'success', run_attempt: 2 }, { name: 'cua-helper-macos / package', conclusion: 'success', run_attempt: 2 }]
: [{ name: 'cua-helper-macos / package', conclusion: status, run_attempt: 2 }]
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('last executed cua-helper-macos / package job did not succeed')
expect(f.api.mock.calls.some(([path]) => path.includes('/attempts/1') || path.includes('/artifacts'))).toBe(false)
},
)
it.each(['missing', 'expired', 'empty', 'mismatch', 'legacy'] as const)(
it.each(['missing', 'expired', 'empty'] as const)(
'rebuilds on automatic %s but rejects the same explicit selection', async (change) => {
const f = fixture()
if (change === 'missing') f.artifacts.pop()
if (change === 'expired') f.artifact.expired = true
if (change === 'empty') f.artifact.size_in_bytes = 0
if (change === 'mismatch') f.artifact.name = `cua-helper-123-2-${'b'.repeat(64)}`
if (change === 'legacy') f.artifact.name = 'cua-helper-123-2'
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('CUA reuse: run 123:')
},
@@ -101,9 +108,9 @@ it.each(['missing', 'expired', 'empty', 'mismatch', 'legacy'] as const)(
it('selects a match across workflows and pages after a newer failed producer', async () => {
const f = fixture()
const api = vi.fn(async (path: string, paginate?: boolean): Promise<unknown> => {
if (path.includes('/workflows/cua-helper-package.yml/runs?')) return [{ workflow_runs: [] }]
if (path.includes('/workflows/cua-helper-package-macos.yml/runs?')) return [{ workflow_runs: [] }]
if (path.includes('/workflows/release-publish.yml/runs?')) return [{ workflow_runs: [{ id: 124 }] }, { workflow_runs: [{ id: 123 }] }]
if (path.endsWith('/runs/124/artifacts?per_page=100')) return [{ artifacts: [{ ...f.artifact, name: `cua-helper-124-1-${key}` }] }]
if (path.endsWith('/runs/124/artifacts?per_page=100')) return [{ artifacts: [{ ...f.artifact, name: `cua-helper-macos-124-1-${key}` }] }]
if (path.endsWith('/runs/124')) return { run_attempt: 1 }
if (path.endsWith('/runs/124/attempts/1')) return { ...f.run, id: 124, run_attempt: 1, conclusion: 'failure' }
return f.api(path, paginate)
@@ -128,19 +135,26 @@ it.each(['', '123'])('propagates unavailable GitHub evidence with selection %j',
expect(api).toHaveBeenCalledTimes(1)
})
it('does not query job or attempt details when artifact names exclude the requested build key', async () => {
it.each([
['another build key', `cua-helper-macos-123-2-${'b'.repeat(64)}`],
['no build key', 'cua-helper-macos-123-2'],
['Windows', `cua-helper-windows-123-2-${key}`],
['no platform', `cua-helper-123-2-${key}`],
] as const)('skips an artifact with %s in discovery and rejects it by run ID', async (_case, name) => {
const f = fixture()
f.artifact.name = 'cua-helper-123-2-legacy'
f.artifacts.shift()
f.artifact.name = name
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
expect(f.api.mock.calls.map(([path]) => path).filter(path => !path.includes('/workflows/')))
.toEqual([`${base}/artifacts?per_page=100`])
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource))
.rejects.toThrow('no artifact matches')
})
it.each(['123', ''])('retains the original helper after a publish-only rerun with selection %j', async (runId) => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 1 },
f.jobs[0]!.jobs = [{ name: 'cua-helper-macos / package', conclusion: 'success', run_attempt: 1 },
{ name: 'Publish to npm', conclusion: 'success', run_attempt: 2 }]
f.artifacts.pop()
expect(await selectCuaHelperArtifact(repository, runId, key, f.api, f.matchesSource))
@@ -151,8 +165,8 @@ it.each(['123', ''])('retains the original helper after a publish-only rerun wit
it('does not reuse an older successful helper after a newer helper execution failed', async () => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 1 },
{ name: 'cua-helper / package', conclusion: 'failure', run_attempt: 2 }]
f.jobs[0]!.jobs = [{ name: 'cua-helper-macos / package', conclusion: 'success', run_attempt: 1 },
{ name: 'cua-helper-macos / package', conclusion: 'failure', run_attempt: 2 }]
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('did not succeed')
expect(f.matchesSource).not.toHaveBeenCalled()
+8 -7
View File
@@ -5,7 +5,7 @@ import { resolve } from 'node:path'
import { isEntry } from '../release/process.ts'
import { cuaHelperSourceMatches } from './build-inputs.ts'
const workflows = ['cua-helper-package.yml', 'release-publish.yml'] as const
const workflows = ['cua-helper-package-macos.yml', 'release-publish.yml'] as const
function record(value: unknown): Record<string, unknown> {
assert(value !== null && typeof value === 'object' && !Array.isArray(value), 'CUA reuse: invalid GitHub object')
@@ -61,16 +61,17 @@ export async function selectCuaHelperArtifact(repository: string, runId: string,
const workflow = workflows.find(name => run.path === `.github/workflows/${name}`)
assert(workflow && run.event === 'workflow_dispatch', 'CUA reuse: select a supported repository packaging or release run')
if (run.status !== 'completed') return 'the latest attempt has not completed'
if (workflow === 'cua-helper-package.yml' && run.conclusion !== 'success') return 'the latest packaging attempt did not succeed'
const jobName = workflow === 'cua-helper-package.yml' ? 'package' : 'cua-helper / package'
if (workflow === 'cua-helper-package-macos.yml' && run.conclusion !== 'success') return 'the latest packaging attempt did not succeed'
const jobName = workflow === 'cua-helper-package-macos.yml' ? 'package' : 'cua-helper-macos / package'
const jobs = rows(await api(`${base}/runs/${candidate}/jobs?filter=all&per_page=100`, true), 'jobs')
.filter(job => job.name === jobName)
if (jobs.length === 0) return `this run contains no ${jobName} job. Select a run that built the macOS helper`
const attempts = jobs.map(job => Number(id(job.run_attempt)))
assert(attempts.every(value => value <= Number(attempt)), 'CUA reuse: run advanced during selection; retry with the same run ID')
const producerAttempt = Math.max(0, ...attempts)
const producerAttempt = Math.max(...attempts)
const producers = jobs.filter(job => job.run_attempt === producerAttempt)
if (producers.length !== 1 || producers[0]?.conclusion !== 'success') return `the last executed ${jobName} job did not succeed`
const name = `cua-helper-${candidate}-${producerAttempt}-${buildKey}`
const name = `cua-helper-macos-${candidate}-${producerAttempt}-${buildKey}`
const artifacts = (retained ?? rows(await api(`${base}/runs/${candidate}/artifacts?per_page=100`, true), 'artifacts'))
.filter(artifact => artifact.name === name)
if (artifacts.length === 0) return 'no artifact matches the current source bytes and build configuration; use the producer run linked in its summary or rebuild'
@@ -99,7 +100,7 @@ export async function selectCuaHelperArtifact(repository: string, runId: string,
const candidateId = id(candidate.id)
const artifacts = rows(await api(`${base}/runs/${candidateId}/artifacts?per_page=100`, true), 'artifacts')
if (!artifacts.some(artifact => typeof artifact.name === 'string'
&& artifact.name.startsWith(`cua-helper-${candidateId}-`) && artifact.name.endsWith(`-${buildKey}`))) continue
&& artifact.name.startsWith(`cua-helper-macos-${candidateId}-`) && artifact.name.endsWith(`-${buildKey}`))) continue
const selected = await selectRun(candidateId, artifacts)
if (typeof selected !== 'string') return selected
}
@@ -193,7 +194,7 @@ if (isEntry(import.meta.url)) {
const repository = env.GITHUB_REPOSITORY
const root = resolve(import.meta.dirname, '../..')
const sourceMatches = new Map<string, boolean>()
const selection = await selectCuaHelperArtifact(repository, env.CUA_RUN_ID ?? '', env.CUA_BUILD_KEY, githubJson, async (commit) => {
const selection = await selectCuaHelperArtifact(repository, env.CUA_MACOS_RUN_ID ?? '', env.CUA_BUILD_KEY, githubJson, async (commit) => {
let matches = sourceMatches.get(commit)
if (matches === undefined) {
matches = await cuaHelperSourceMatches(root, repository, commit, githubJson)
+4 -4
View File
@@ -24,7 +24,7 @@ it('rejects debugging packages before dependency setup and pins the checked atte
const preflight = steps.findIndex(step => step.id === 'preflight')
expect(preflight).toBeGreaterThan(0)
expect(preflight).toBeLessThan(steps.findIndex(step => step.uses?.startsWith('pnpm/')))
expect(steps[preflight]?.run).toBe('node apps/desktop/scripts/preflight-desktop-publish.mjs')
expect(steps[preflight]?.run).toBe('node apps/desktop-publisher/src/preflight-desktop-publish.mjs')
expect(steps.find(step => step.id === 'route')?.env?.DESKTOP_PACKAGE_ATTEMPT).toBe('${{ steps.preflight.outputs.attempt }}')
})
@@ -92,12 +92,12 @@ it('defaults to production website upload and separates cache-only recovery', ()
for (const job of [upload, purge]) {
expect(job.if).toBe("inputs.upload_website && needs.prepare.outputs.preset != 'test'")
expect(job.environment).toBe('desktop-production')
const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop/scripts/preflight-desktop-publish-local.mjs')
const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop-publisher/src/preflight-desktop-publish-local.mjs')
expect(preflight).toBeGreaterThan(-1)
expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile'))
expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}')
}
expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts upload')
expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts purge')
expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts upload')
expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop-publisher/src/publish-website-ci.ts purge')
expect(purge.steps.some(step => step.run?.includes('publish-desktop-ci.ts'))).toBe(false)
})
+1 -1
View File
@@ -123,7 +123,7 @@ 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')) {
if (selection.members.some(member => member.name === '@deepseek-ai/dsh-cua-macos')) {
await runStep(root, ['--dir', 'packages/experimental/cua-macos', 'run', 'build:native'], abort.signal, 'CUA native build')
}
+283
View File
@@ -0,0 +1,283 @@
{
"apps/cli/tests/built-bin.e2e.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"apps/desktop/src/client/WelcomePage.tsx": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"apps/desktop/src/preload-platform-account.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"apps/web/tests/chat-scroll-contract.e2e.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"apps/web/tests/support.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/account/deepseek-account/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/account/deepseek-account/src/logout.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/api/gateway/src/client/remote-stream.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/api/gateway/tests/gateway-stream.host.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/api/workspace-files/src/client/change-feed.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/boot/app-boot/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/boot/plugin-manager/src/registry.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/boot/plugin-manager/tests/operations-process.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/boot/plugin-market/src/repository-cache.ts": {
"3d8f6e3468aecc6e006ee3e5f20a5c6c5277316636c8849756fc6d710e9d907b": 1
},
"packages/client/modules/src/index.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/store/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-open-in-app/src/client/controller.ts": {
"ea86beefffc83e1b3c38c7961e9dd8faf194c917ab229aac53c7716cb5b36687": 1
},
"packages/client/ui-open-in-app/src/client/open-path.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-schedule/src/client/recent-time-zones.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-sidebar-browser/src/client/browser/url.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/client/ui-sidebar-right/src/client/tab-inventory.ts": {
"ee22b9dbd07fc0b76f0464bf59386efb6925dab82c4539a2772b909b944ee33c": 1
},
"packages/client/ui-skill/src/client/SkillRow.tsx": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/context/file-reference-local/tests/search.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/client-ui-forge/src/panel.ts": {
"ea86beefffc83e1b3c38c7961e9dd8faf194c917ab229aac53c7716cb5b36687": 1
},
"packages/experimental/inspector/src/client/bridge/transport.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/client/cdp/console.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2
},
"packages/experimental/inspector/src/client/inspection/realm.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/experimental/inspector/src/worker/bridge/hub.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/experimental/inspector/src/worker/bridge/runtime-rpc.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 4
},
"packages/experimental/inspector/src/worker/bridge/session.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/cdp/domains/dom/model.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/cdp/realm-sessions.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/inspection/cordis-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/inspection/network-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/experimental/inspector/src/worker/inspection/query-router.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/inspection/realm-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/inspector/src/worker/realms/host/bridge.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3
},
"packages/experimental/inspector/src/worker/realms/host/sources.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/liveshare/src/client/owner-login.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3
},
"packages/experimental/liveshare/src/client/share-relay-address.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/experimental/liveshare/src/client/ShareEditPanel.tsx": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2
},
"packages/experimental/liveshare/src/host/shareable-catalog.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2
},
"packages/experimental/liveshare/src/host/tunnel-supervision.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/liveshare/src/host/viewer-dispatch.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/experimental/liveshare/tests/fixtures/base-llm.mjs": {
"8b2766548472fe722af04dc7c95b06d303bb164fd12fbec87a07ea6eaae7146a": 1
},
"packages/experimental/webhook-github/src/handler.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/src/client/client.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/src/transport/tunnel.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/tests/compile/transform-corpus-check.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/experimental/webworker-runtime/tests/polyfill/als-shim.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/host/directory-picker-browse/tests/service.spec.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/host/open-in-app/src/icons.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/host/open-in-app/src/resolver.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/identity/anonymous-user-id/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/llm/llm-deepseek/src/file-store.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/llm/llm-deepseek/src/files-api.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/llm/llm-pi-ai/src/replay.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/llm/llm/src/adapter-failure.ts": {
"19186deef10a7178489ddf20fcaf6688a0baf38bf6d9933cb78fe65023f3280f": 1
},
"packages/lsp/lsp-stdio/src/instance.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session-query/session-query-sqlite/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/session-query/session-query/src/cold-read.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session/session-persistence-jsonl/src/generation.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session/session-persistence-jsonl/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/session/session-persistence-jsonl/tests/zstd.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/shell/bash-local/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/shell/pwsh-local/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/skill/skill-filesystem/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/skill/skill/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/spill/spill-local/src/cleanup.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-acp/src/run.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-claude-code/src/run.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-codex/src/run.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/subagent/subagent-dsh-sdk/src/index.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent-dsh-sdk/src/run.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subagent/subagent/src/out-of-process.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subprocess/subprocess-local/src/index.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/subprocess/subprocess-local/src/linux-scope.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 5
},
"packages/subprocess/subprocess-local/src/output.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/subprocess/subprocess-local/src/runner-protocol.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/subprocess/subprocess-local/src/spawn-runner.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 4
},
"packages/subprocess/subprocess-local/src/spawn.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 3
},
"packages/subprocess/subprocess-local/src/windows-job.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"packages/subprocess/subprocess-local/tests/native-containment.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 2
},
"packages/subprocess/subprocess-local/tests/native-windows.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"packages/subprocess/subprocess-local/tests/spawn.spec.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 5
},
"packages/test-support/client-runtime/src/assembly/test-client.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"scripts/gen-session-format-catalog.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"scripts/run-gates.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 2,
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"scripts/slot-walk.ts": {
"10ea16f7e56fe8d9176f54f90b2c2137b20e2c60e3f5cb45d6dc09fe23c52eae": 1
},
"vitest.e2e.config.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
},
"vitest.web.config.ts": {
"cf101add035f69891416d7350e9a824c2de6c0d1b7a253de6a73da923023b073": 1
}
}
+2 -2
View File
@@ -8,6 +8,8 @@
export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly<Record<string, string>> = {
'packages/experimental/cua': '@deepseek-ai/dsh-cua',
'packages/experimental/cua-bundle': '@deepseek-ai/dsh-cua-bundle',
'packages/experimental/cua-macos': '@deepseek-ai/dsh-cua-macos',
'packages/experimental/cua-mcp': '@deepseek-ai/dsh-cua-mcp',
'packages/experimental/cua-windows': '@deepseek-ai/dsh-cua-windows',
'packages/experimental/tool-session-query': '@deepseek-ai/dsh-tool-session-query',
'packages/experimental/session-title-all-prompts-llm': '@deepseek-ai/dsh-session-title-all-prompts-llm',
@@ -50,7 +52,6 @@ export const LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES: readonly string[]
'packages/experimental/computer-use-cua-driver-mcp',
'packages/experimental/computer-use-cua-driver-native',
'packages/experimental/cot-translation-bundle',
'packages/experimental/cua-macos',
'packages/experimental/forge',
'packages/experimental/forge-bundle',
'packages/experimental/forge-github',
@@ -60,7 +61,6 @@ export const LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES: readonly string[]
'packages/experimental/liveshare',
'packages/experimental/liveshare-protocol',
'packages/experimental/plugin-market-bundle',
'packages/experimental/ptc-runtime-python',
'packages/experimental/ralph-bundle',
'packages/experimental/session-inspector',
'packages/experimental/session-search',
+1
View File
@@ -83,6 +83,7 @@ export const SERVICE_PAGE: Record<string, string> = {
browserUse: 'browser-use.md',
computerUse: 'computer-use.md',
cuaAccess: 'computer-use.md',
cuaPrograms: 'computer-use.md',
commands: 'commands.md',
compaction: 'compaction.md',
cordisInspect: 'extensions.md',
+6 -1
View File
@@ -268,6 +268,11 @@ const SERVICE_ROLES: ServiceRole[] = [
mode: 'core', consumers: ['cua'],
note: 'The native provider owns application consent and cancellation; the optional Client page queries and changes those decisions through its Remote.',
},
{
key: 'cuaPrograms', pkg: 'cua', title: 'Computer Use program environments',
mode: 'core', consumers: ['cua-mcp'],
note: 'The provider owns the retained cua_run_code runtime; a host without a model releases one Agent\'s environment and reads the configured screenshot request target through it.',
},
{
key: 'officeKit', pkg: 'office-kit', title: 'Office rendering, conversion, and recalculation',
mode: 'core', consumers: ['client-ui-sidebar-documentpreview', 'tool-office'],
@@ -809,7 +814,7 @@ const SERVICE_ROLES: ServiceRole[] = [
pkg: 'ptc-runtime',
title: 'PTC execution seam',
mode: 'seam',
implementations: ['ptc-runtime-node', 'experimental-ptc-runtime-python'],
implementations: ['ptc-runtime-node'],
consumers: ['tool-executor-ptc', 'workflow-ptc'],
note: 'Runs programs against host-provided async bindings; tool-executor-ptc owns PTC presentation and workflow-ptc owns workflow orchestration.',
},
+3 -2
View File
@@ -15,7 +15,7 @@ import AgentRegistry from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
import type OfficeKit from '@deepseek-ai/dsh-office-kit'
import { createScope } from '@deepseek-ai/dsh-scope'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import SessionPersistence from '@deepseek-ai/dsh-session-persistence'
import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection'
import SqliteSessionQueryEngine from '@deepseek-ai/dsh-session-query-sqlite'
@@ -92,6 +92,7 @@ import * as ToolRalph from '@deepseek-ai/dsh-tool-ralph'
import * as ToolWorkflow from '@deepseek-ai/dsh-tool-workflow'
import * as ToolWorkspaceDependencies from '@deepseek-ai/dsh-tool-workspace-dependencies'
import { githubSlug } from './verify-md-links.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
/** Attachment seam marker that makes the attachments-conditional `read_image` schema harvestable. */
class CatalogAttachmentStore extends AttachmentStore {
@@ -664,7 +665,7 @@ const TOOL_PACKAGES: ToolPackage[] = [
await ctx.plugin(SubagentRuntime)
await ctx.plugin(CatalogSessionPersistence)
await ctx.plugin(TeamService)
const session = ctx.sessions.create(SessionId('tool-catalog-team-lead'))
const session = ctx.sessions.create(brandString<SessionId>('tool-catalog-team-lead'))
let agent!: Agent
await ctx.plugin(Object.assign(async (inner: Context) => {
agent = {
+3 -2
View File
@@ -8,12 +8,13 @@ import { availableParallelism, homedir, tmpdir } from 'node:os'
import { basename, join, relative, resolve } from 'node:path'
import { inspect, parseArgs } from 'node:util'
import { Context } from '@deepseek-ai/cordis'
import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
import { SESSION_FORMAT_VERSION, type SessionId } from '@deepseek-ai/dsh-session'
import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import { encodeSegment, generationLogFilename, parseGenerationLogFilename, type JsonlCompression } from '../packages/session/session-persistence-jsonl/src/format.ts'
import { JsonlGenerationSourceChangedError } from '../packages/session/session-persistence-jsonl/src/generation.ts'
import { classifyMigrationFailure, type MigrationFailureDiagnostic } from './migration-failure-summary.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
const usage = `Usage: pnpm run migrate:sessions-to-v4 [--sessions-dir PATH] [--jobs N]
@@ -134,7 +135,7 @@ function directoryId(directory: string): SessionId {
const segment = basename(directory)
const id = segment.replace(/~([0-9A-F]{4})/gu, (_match, hex: string) => String.fromCharCode(Number.parseInt(hex, 16)))
if (encodeSegment(id) !== segment) throw new Error(`noncanonical Session directory name ${JSON.stringify(segment)}`)
return SessionId(id)
return brandString<SessionId>(id)
}
/**
-3
View File
@@ -1062,9 +1062,6 @@
"148509a0193d8d3c16a606a15f5145770f454c2ebc70dd0ccaa51fc1a0f43e99": 1,
"2066ad746457f15b6737d62124c4ec81f2140fc3fa425187eac8e3b1c3b6ab0b": 8
},
"packages/experimental/ptc-runtime-python/src/index.ts": {
"b121cee14635b00f7891217013e4682493cf96f676710be60722fdf8b862aea3": 1
},
"packages/experimental/tool-ralph/src/index.ts": {
"6fe9024d30e0d4757a348b83d246925b3f5aeaf2e79a0eff4bf12f3c9fb5826b": 1,
"cec7714d93bd00a87b261199e97562ce99a73ae4b4e2414728d874d24bfed7a4": 1
+20 -1
View File
@@ -10,6 +10,7 @@ import { loadOverlayPatches } from '../packages/boot/app-boot/src/index.ts'
import { readPluginMeta } from '../packages/boot/app-boot/src/package-meta.ts'
import { bundlePatchPaths, composeEntries, initProfile, readProfileManifest } from '../packages/boot/app-boot/src/profile.ts'
import { OPTIONAL_BUNDLES, PROFILE_TEMPLATES } from '../packages/util/official-bundles/src/bundles.ts'
import { HIDDEN_BUNDLES } from '../packages/util/official-bundles/src/plugin-manager.ts'
import type { DshBundleManifest } from '../packages/util/package-manifest/src/types.ts'
import { createPluginProfile } from '../apps/desktop/src/project-manager.ts'
@@ -31,6 +32,9 @@ function bundle(name: string): { dir: string; patches: ReturnType<typeof loadOve
return { dir: entry.dir, patches: bundlePatchPaths(entry.dir, entry.manifest.dsh.bundle).flatMap(path => loadOverlayPatches('test', path)) }
}
/** Optional bundles that compose a profile of their own; the plugin page hides them, the Host inventory still reports them. */
const STANDALONE_PROFILE_BUNDLES: readonly string[] = ['@deepseek-ai/dsh-cua-mcp']
const lightweight = [
'@deepseek-ai/dsh-experimental-session-search',
'@deepseek-ai/dsh-experimental-ralph-bundle',
@@ -105,7 +109,22 @@ describe('optional bundles', () => {
expect(OPTIONAL_BUNDLES).not.toContain('@deepseek-ai/dsh-experimental-inspector')
})
it.each(OPTIONAL_BUNDLES)('%s composes over the Web profile without a skipped patch', (name) => {
// A bundle that composes a profile of its own is never layered over a GUI profile; HIDDEN_BUNDLES keeps it off the plugin page.
const standalone = OPTIONAL_BUNDLES.filter(name => STANDALONE_PROFILE_BUNDLES.includes(name))
const layered = OPTIONAL_BUNDLES.filter(name => !standalone.includes(name))
it.each(standalone)('%s composes its own profile alone over the empty root and stays off the plugin page', (name) => {
const { patches } = bundle(name)
const warnings: string[] = []
const composed = composeEntries([patches], message => warnings.push(message))
expect(warnings).toEqual([])
const topLevelIds = composed.flatMap(entry => typeof entry.id === 'string' ? [entry.id] : [])
expect(topLevelIds.length).toBeGreaterThan(0)
expect(topLevelIds).toHaveLength(new Set(topLevelIds).size)
expect(HIDDEN_BUNDLES).toContain(name)
})
it.each(layered)('%s composes over the Web profile without a skipped patch', (name) => {
const { patches } = bundle(name)
const warnings: string[] = []
const composed = composeEntries([...shipped, patches], message => warnings.push(message))
+3 -4
View File
@@ -52,7 +52,6 @@ const DUPLICATE_SAFE_PACKAGES: readonly string[] = [
*/
const SAFE_HOST_DEPENDENCY_EXPORTS = {
'@deepseek-ai/dsh-atomic-write': ['withFileLock', 'writeFileAtomic'],
'@deepseek-ai/dsh-computer-use/brand': ['ComputerUseProviderName'],
'@deepseek-ai/dsh-credentials': ['credentialKey'],
'@deepseek-ai/dsh-deque': ['Deque'],
// Builds a dispatcher from the resolved proxy policy; the caller owns and closes it.
@@ -66,7 +65,6 @@ const SAFE_HOST_DEPENDENCY_EXPORTS = {
// The shipped profile templates are plain data; a consumer reads their bundle names only.
'@deepseek-ai/dsh-official-bundles': ['PROFILE_TEMPLATES'],
'@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'],
@@ -82,8 +80,9 @@ const PEER_REQUIRED_HOST_EXPORTS = {
// CUA mounts the installed provider and shares executor error classes with PTC.
'@deepseek-ai/dsh-ptc-runtime-node': ['default'],
'@deepseek-ai/dsh-tool-executor-ptc/run-code': ['RunCodeConfig', 'createRunCodeTool'],
// CUA checks UserQuestionError and preserves AttachmentError from image admission.
'@deepseek-ai/dsh-attachment': ['admitEncodedImages'],
// CUA checks UserQuestionError and preserves AttachmentError from image admission; longEdgeDimensions is pure
// arithmetic that rides the same peer.
'@deepseek-ai/dsh-attachment': ['admitEncodedImages', 'longEdgeDimensions'],
'@deepseek-ai/dsh-user-questions': ['UserQuestionError'],
// The tool registry and every subclass rely on `instanceof` against one HarnessError class.
'@deepseek-ai/dsh-error': ['HarnessError'],
+3 -2
View File
@@ -1,12 +1,13 @@
/** Developer field classification matches native admission and metadata preservation. */
import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { Session, SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
import { Session, type SessionId, SessionLogOffset } from '@deepseek-ai/dsh-session'
import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'
import type { SessionFormatEvent } from '@deepseek-ai/dsh-session-format'
import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
import { canonicalizeSchema, schemaDigest } from './persistence-schema-model.ts'
import { classifyPersistenceChange, parsePersistenceSnapshot } from './persistence-changes.ts'
import { brandString } from '@deepseek-ai/dsh-brand'
function toolAdditionSchema() {
const inventory = parsePersistenceSnapshot(readFileSync(new URL('../docs/persistence-schema.json', import.meta.url), 'utf8'))
@@ -61,7 +62,7 @@ describe('developer field compatibility', () => {
for (const event of events) reader.decodeRow(sessionFormatCatalog.encodeCurrentEvent(event))
const artifact = reader.finish()
expect(artifact.events).toEqual(events)
const restored = Session.fromRestore(SessionId(header.id), artifact.events as SessionEvent[],
const restored = Session.fromRestore(brandString<SessionId>(header.id), artifact.events as SessionEvent[],
artifact.header as unknown as SessionHeader, SessionLogOffset(0), 'detached')
expect(restored.deriveMessages()).toEqual([message])
})
+1 -5
View File
@@ -60,16 +60,12 @@ export const EXISTING_PLUGIN_ENTRY_EXPORTS = {
'CREDENTIALS_FILENAME', 'DOCUMENT_VERSION', 'parseCredentialsDocument', 'renderFlatLayoutMigration', 'resolveSpec',
],
'@deepseek-ai/dsh-cua': ['CuaConfig', 'installCua'],
'@deepseek-ai/dsh-cua-macos': ['GUIDANCE'],
'@deepseek-ai/dsh-experimental-claude-code-mods': [
'DEFAULT_TOOL_ALIASES', 'KNOWN_EVENTS', 'MODS_API_VERSION', 'SERVED_EVENTS', 'defineMod',
],
'@deepseek-ai/dsh-experimental-cua-macos': ['GUIDANCE'],
'@deepseek-ai/dsh-experimental-forge': ['changeRequestKey'],
'@deepseek-ai/dsh-experimental-inspector': ['resolveInspectorOptions', 'startInspector'],
'@deepseek-ai/dsh-experimental-ptc-runtime-python': [
'checkDoneValue', 'detachResidual', 'encodeJsonPlain', 'hasNonLosslessNumber', 'hasUnsafeIntegerToken',
'hostFrameParseCeiling', 'logTruncationMarker', 'readProcessStart', 'resolvePythonBin', 'validateChildFrame',
],
'@deepseek-ai/dsh-experimental-worktree': [
'CREATED_RECORD', 'createdWorktreeSchema', 'generatedWorktreeName', 'worktreeProjection',
],
+9 -3
View File
@@ -9,6 +9,13 @@ readonly BUBBLEWRAP_VERSION='0.12.0-1'
readonly BUBBLEWRAP_SHA256='db4d572a7927bfd34cc9b8e24b56983efa8e0483d03da6c810f6caae081dcc36'
# The recorded build remains addressable after Ubuntu prunes its live package pool.
readonly BUBBLEWRAP_URL="https://launchpad.net/ubuntu/+source/bubblewrap/${BUBBLEWRAP_VERSION}/+build/33546835/+files/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb"
# Workflows that run on ephemeral runners restore and save this directory as
# `~/.cache/dsh-ci/bubblewrap` with actions/cache, so a warm cache needs no
# Launchpad request; the persistent self-hosted pool keeps the directory itself.
readonly BUBBLEWRAP_CACHE_DIR="${HOME}/.cache/dsh-ci/bubblewrap"
# shellcheck source=scripts/ci-verified-download.sh
source "$(dirname -- "${BASH_SOURCE[0]}")/ci-verified-download.sh"
: "${RUNNER_TEMP:?prepare-ci-bubblewrap requires RUNNER_TEMP}"
: "${GITHUB_PATH:?prepare-ci-bubblewrap requires GITHUB_PATH}"
@@ -18,11 +25,10 @@ if [[ "$(uname -s)" != 'Linux' || "$(uname -m)" != 'x86_64' ]]; then
exit 1
fi
archive="${RUNNER_TEMP}/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb"
archive="${BUBBLEWRAP_CACHE_DIR}/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb"
root="${RUNNER_TEMP}/dsh-bubblewrap"
curl --fail --silent --show-error --location --retry 3 --retry-all-errors --output "$archive" "$BUBBLEWRAP_URL"
printf '%s %s\n' "$BUBBLEWRAP_SHA256" "$archive" | sha256sum --check --status
acquire_verified_archive "$BUBBLEWRAP_URL" "$BUBBLEWRAP_SHA256" "$archive"
mkdir -p "$root"
dpkg-deb --extract "$archive" "$root"
printf '%s\n' "$root/usr/bin" >> "$GITHUB_PATH"
+19 -4
View File
@@ -25,7 +25,7 @@ describe('PR preview workflow', () => {
expect(preview['runs-on']).toContain('DSH_CI_FAILOVER_LINUX')
expect(workflow.on).toEqual({ pull_request: { types: ['opened', 'synchronize', 'reopened'] } })
expect(workflow.permissions).toEqual({ contents: 'read', 'pull-requests': 'write' })
expect(preview.steps.find(step => step.uses === 'actions/[email protected]')?.with).toEqual({ 'persist-credentials': false })
expect(preview.steps.find(step => step.uses === 'actions/[email protected]')?.with).toEqual({ 'persist-credentials': false, 'fetch-depth': 2 })
})
it('fails the check only for build failures and warns about publication', () => {
@@ -33,11 +33,12 @@ describe('PR preview workflow', () => {
for (const name of ['Build workspace and check aggregate programs', 'Build the preview page and pack the VFS image', 'Shape the upload']) {
expect(byName(name)?.['continue-on-error'], `${name} must stay blocking`).toBeUndefined()
}
for (const name of ['Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) {
for (const name of ['Render the snapshot diff page', 'Upload to Cloudflare Pages', 'Verify the protected deployment serves the image', 'Comment the preview URL']) {
expect(byName(name)?.['continue-on-error'], `${name} must warn instead of failing`).toBe(true)
}
const report = byName('Report preview publication failures')
expect(report?.if).toBe("steps.upload.outcome == 'failure' || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'")
expect(report?.if).toBe("steps.snapshot-diff.outcome == 'failure' || steps.upload.outcome == 'failure'"
+ " || steps.verify.outcome == 'failure' || steps.comment.outcome == 'failure'")
expect(report?.run).toContain('::warning::')
})
@@ -78,6 +79,20 @@ describe('PR preview workflow', () => {
expect(verify.env?.CF_ACCESS_CLIENT_SECRET).toBe('${{ secrets.CF_ACCESS_CLIENT_SECRET }}')
const comment = preview.steps.find(step => step.name === 'Comment the preview URL')!
expect(comment.run).toContain('<!-- dsh-preview-url -->')
expect(comment.run).toContain('gh pr comment "$PR" --body-file -')
expect(comment.run).toContain('printf \'%s\' "$body" | gh pr comment "$PR" --body-file -')
expect(comment.run).toContain('[snapshot changes]($url/snapshot-diff/)')
expect(comment.env?.SNAPSHOT_DIFF).toBe('${{ steps.snapshot-diff.outcome }}')
expect(comment.run).toContain('if [ "$SNAPSHOT_DIFF" = success ]')
expect(comment.run).toContain('gh api -X PATCH')
expect(comment.run).toContain('select(.user.login == \\"github-actions[bot]\\"')
})
it('renders the snapshot diff page into the upload against the base branch tip', () => {
const steps = preview.steps.map(step => step.name)
const page = preview.steps.find(step => step.name === 'Render the snapshot diff page')!
expect(page.run).toBe('pnpm exec tsx scripts/snapshot-diff-page.ts --base HEAD^1 --head HEAD'
+ ' --out apps/web/dist/snapshot-diff --preview-manifest apps/web/dist/preview/fixtures.json')
expect(steps.indexOf('Render the snapshot diff page')).toBeGreaterThan(steps.indexOf('Shape the upload'))
expect(steps.indexOf('Render the snapshot diff page')).toBeLessThan(steps.indexOf('Upload to Cloudflare Pages'))
})
})
+15 -13
View File
@@ -1,9 +1,11 @@
import { getEventListeners } from 'node:events'
import { Context } from '@deepseek-ai/cordis'
import { agentEvents, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent'
import { createToolResultMessage, createUserMessage, ToolCallId } from '@deepseek-ai/dsh-llm'
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
import { WorkflowRunId } from '@deepseek-ai/dsh-workflow'
import { createToolResultMessage, createUserMessage } from '@deepseek-ai/dsh-llm'
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { WorkflowRunId } from '@deepseek-ai/dsh-workflow/types'
import AgentLoop from '@deepseek-ai/dsh-agent-loop'
import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit'
import SubagentRuntime from '@deepseek-ai/dsh-subagent'
@@ -31,9 +33,9 @@ async function harness(direct = false) {
const fiber = ctx.plugin(fixture, { ...config, ...direct ? { direct: { prompt: config.prompt, callId: 'direct-child' } } : {} })
await fiber
cleanups.push(() => fiber.dispose())
const parent = ctx.sessions.create(SessionId(config.parentSessionId))
const other = ctx.sessions.create(SessionId('other-parent'))
const session = ctx.sessions.create(SessionId('workflow-child'), { meta: { parentSession: parent.id } })
const parent = ctx.sessions.create(brandString<SessionId>(config.parentSessionId))
const other = ctx.sessions.create(brandString<SessionId>('other-parent'))
const session = ctx.sessions.create(brandString<SessionId>('workflow-child'), { meta: { parentSession: parent.id } })
// The dispatcher needs only the subject identity; the fixture reads its Session.
const agent = { id: session.id, session } as Agent
const controller = new AbortController()
@@ -41,7 +43,7 @@ async function harness(direct = false) {
const decision: PreStepDecision = { kind: 'enter', messages }
const next = vi.fn(async () => decision)
const start = (owner = parent, childId = agent.id) => owner.append('tool-workflow/agent-start', {
runId: WorkflowRunId('run'), seq: 1, label: 'workflow-child', childId,
runId: brandString<WorkflowRunId>('run'), seq: 1, label: 'workflow-child', childId,
})
const step = (overrides = {}) => agentEvents(ctx, agent).waterfall('agent/pre-step', {
modelSelection: { provider: 'mock', model: 'mock' },
@@ -76,7 +78,7 @@ describe('advanced Python snapshot workflow ordering', () => {
cleanups.push(() => assembly.dispose())
await assembly
ctx.llm.registerAdapter(['mock'], adapter)
const parent = await ctx.agentLoop.create(SessionId(config.parentSessionId), { provider: 'mock', model: 'mock' })
const parent = await ctx.agentLoop.create(brandString<SessionId>(config.parentSessionId), { provider: 'mock', model: 'mock' })
const run = await ctx.subagents.startActivation({
provider: 'spawn', label: 'workflow-child', delivery: 'caller',
parent, prompt: [{ type: 'text', text: config.prompt }], signal: new AbortController().signal,
@@ -87,7 +89,7 @@ describe('advanced Python snapshot workflow ordering', () => {
expect(adapter.requests).toHaveLength(0)
expect(child.session.snapshotEvents().some(event => event.type === 'subagent/descriptor')).toBe(true)
parent.session.append('tool-workflow/agent-start', {
runId: WorkflowRunId('run'), seq: 1, label: 'workflow-child', childId: child.id,
runId: brandString<WorkflowRunId>('run'), seq: 1, label: 'workflow-child', childId: child.id,
})
expect((await run.result).output).toEqual([{ type: 'text', text: 'child complete' }])
expect(adapter.requests).toHaveLength(1)
@@ -100,8 +102,8 @@ describe('advanced Python snapshot workflow ordering', () => {
expect(h.next).not.toHaveBeenCalled()
expect(getEventListeners(h.controller.signal, 'abort')).toHaveLength(1)
h.start(h.other)
h.start(h.parent, SessionId('other-child'))
h.parent.append('tool-workflow/run-start', { runId: WorkflowRunId('run'), name: 'workflow' })
h.start(h.parent, brandString<SessionId>('other-child'))
h.parent.append('tool-workflow/run-start', { runId: brandString<WorkflowRunId>('run'), name: 'workflow' })
await Promise.resolve()
expect(h.next).not.toHaveBeenCalled()
h.start()
@@ -115,7 +117,7 @@ describe('advanced Python snapshot workflow ordering', () => {
const pending = h.step()
h.parent.append('turn/start', { turn: 1 })
h.parent.append('step/start', { turn: 1, step: 1 })
const callId = ToolCallId('direct-child')
const callId = brandString<ToolCallId>('direct-child')
h.parent.append('tool/call', { turn: 1, step: 1, callId, name: 'subagent', arguments: '{}' })
const result = h.parent.append('tool/result', {
turn: 1, step: 1,
@@ -145,7 +147,7 @@ describe('advanced Python snapshot workflow ordering', () => {
: difference === 'turn' ? { turn: 2 }
: difference === 'step' ? { step: 2 } : {}
if (difference === 'parent') {
const session = h.ctx.sessions.create(SessionId('unrelated-child'), { meta: { parentSession: h.other.id } })
const session = h.ctx.sessions.create(brandString<SessionId>('unrelated-child'), { meta: { parentSession: h.other.id } })
Object.assign(h.agent, { session })
}
expect(await h.step(overrides)).toBe(h.decision)
+2 -2
View File
@@ -71,7 +71,8 @@ describe('release families', () => {
'@deepseek-ai/dsh-experimental-cot-translation-bundle',
'@deepseek-ai/dsh-creation-recommendations',
'@deepseek-ai/dsh-cua-bundle',
'@deepseek-ai/dsh-experimental-cua-macos',
'@deepseek-ai/dsh-cua-macos',
'@deepseek-ai/dsh-cua-mcp',
'@deepseek-ai/dsh-cua-windows',
'@deepseek-ai/dsh-cua',
'@deepseek-ai/dsh-experimental-forge-bundle',
@@ -88,7 +89,6 @@ describe('release families', () => {
'@deepseek-ai/dsh-personalized-recommendations',
'@deepseek-ai/dsh-experimental-plugin-market-bundle',
'@deepseek-ai/dsh-plugin-recommendations',
'@deepseek-ai/dsh-experimental-ptc-runtime-python',
'@deepseek-ai/dsh-experimental-ralph-bundle',
'@deepseek-ai/dsh-experimental-session-inspector',
'@deepseek-ai/dsh-experimental-session-search',
+1 -1
View File
@@ -317,7 +317,7 @@ describe('release publication channels', () => {
it('verifies helper sources from the repository root when publication is invoked from a subdirectory', async () => {
const fixture = packedRelease(['1.0.0'])
vi.mocked(packedIdentity).mockReturnValue({ name: '@deepseek-ai/dsh-experimental-cua-macos', version: '1.0.0' })
vi.mocked(packedIdentity).mockReturnValue({ name: '@deepseek-ai/dsh-cua-macos', version: '1.0.0' })
vi.mocked(verifyCuaHelperTarball).mockResolvedValue(undefined)
registry()
const root = resolve(import.meta.dirname, '../..')
+1 -1
View File
@@ -187,7 +187,7 @@ export async function publishRelease(familyId: string, directory: string, distTa
return { tarball, ...packedIdentity(tarball) }
})
for (const member of order) {
if (member.name !== '@deepseek-ai/dsh-experimental-cua-macos') continue
if (member.name !== '@deepseek-ai/dsh-cua-macos') continue
await verifyCuaHelperTarball(member.tarball, { sourceDigest: cuaHelperSourceDigest(resolve(import.meta.dirname, '../..')) })
}
if (distTag !== undefined) {
+12 -1
View File
@@ -383,7 +383,7 @@ describe('gate graph validation', () => {
'rescope-vendor', 'publint', 'constraints', 'default-product-isolation', 'product-use', 'official-bundle-catalog', 'provider-data', 'package-dependencies', 'application-entrypoints',
'dsh-package-licenses', 'node-next-types',
'optional-dependency-imports', 'client-packages', 'installer-locales', 'locale-metadata', 'client-ui-i18n', 'client-route-resolution', 'no-bare-dispatcher',
'plugin-record-callers', 'no-unknown-casts', 'no-top-level-await', 'plugin-entry-exports',
'plugin-record-callers', 'no-unknown-casts', 'empty-catch', 'no-top-level-await', 'plugin-entry-exports',
'cordis-config', 'runtime-closure',
])
})
@@ -449,6 +449,16 @@ describe('gate graph validation', () => {
},
)
it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
'rejects silent empty catches in %s',
(mode) => {
const gate = withPnpmEntrypoint(() => gatesForMode(mode).find(subject => subject.id === 'empty-catch'))
expect(gate?.args).toContain('verify-empty-catch')
expect(gate?.allowFailure).not.toBe(true)
},
)
it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
'keeps package dependency enforcement in %s',
(mode) => {
@@ -1014,6 +1024,7 @@ describe('Node 24 lane ownership', () => {
'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
'packages/team/agent-team/tests/built-lib.e2e.ts',
'packages/experimental/browser-use-stagehand-native/tests/built-attachment.e2e.ts',
]),
)
expect(subject.find(item => item.id === 'web-snapshot')).toMatchObject({
+2
View File
@@ -424,6 +424,7 @@ function sharedHygieneGates(): Gate[] {
pnpmScript('no-bare-dispatcher', 'verify-no-bare-dispatcher', { label: 'proxy-aware dispatchers' }),
pnpmScript('plugin-record-callers', 'verify-plugin-record-callers', { label: 'plugin record callers' }),
pnpmScript('no-unknown-casts', 'verify-no-unknown-casts', { label: 'no new unknown casts' }),
pnpmScript('empty-catch', 'verify-empty-catch', { label: 'no new silent catches' }),
pnpmScript('no-top-level-await', 'verify-no-top-level-await', { label: 'no module-scope await' }),
pnpmScript('plugin-entry-exports', 'verify-plugin-entry-exports', { label: 'plugin entry exports' }),
]
@@ -942,6 +943,7 @@ function builtBinSmokeGate(needs: string[] = ['build']): Gate {
'packages/ptc-runtime/ptc-runtime-node/tests/built-lib.e2e.ts',
'packages/session/session-persistence-jsonl/tests/built-migration-worker.e2e.ts',
'packages/lsp/lsp-stdio/tests/built-lib.e2e.ts',
'packages/experimental/browser-use-stagehand-native/tests/built-attachment.e2e.ts',
], {
label: 'built-bin smoke',
needs,
+5 -4
View File
@@ -3,8 +3,9 @@ import { LocalSpillStore } from '@deepseek-ai/dsh-spill-local'
import { LocalFileSystem } from '@deepseek-ai/dsh-fs-local'
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import { LocalBashExecutor } from '@deepseek-ai/dsh-bash-local'
import { SessionId } from '@deepseek-ai/dsh-session'
import { ToolCallId } from '@deepseek-ai/dsh-llm'
import type { SessionId } from '@deepseek-ai/dsh-session'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
@@ -31,8 +32,8 @@ it.skipIf(process.platform === 'win32')('resolves the exact spill verifier, reta
disposers.push(() => mapping.dispose())
await mapping
const saved = await ctx.spillStore.saveText({
owner: { sessionId: SessionId('query-verifier') },
source: { kind: 'tool', toolName: 'session_event_read', callId: ToolCallId('query'), label: 'result' },
owner: { sessionId: brandString<SessionId>('query-verifier') },
source: { kind: 'tool', toolName: 'session_event_read', callId: brandString<ToolCallId>('query'), label: 'result' },
suggestedName: 'session_event_read.txt', content: 'request/header session_event_search',
})
const adapter = ctx.plugin(commands)
+119
View File
@@ -0,0 +1,119 @@
import { describe, expect, it } from 'vitest'
import { addPreviewLink, catalogFiles, groupDiffs, readableUnits, renderSnapshotDiffPage, sideBySide } from './snapshot-diff-page.ts'
const limits = { context: 1, rows: 100, wordDiffChars: 100, timeoutMs: 5000 }
const text = (...lines: string[]) => [lines.map(line => `${line}\n`).join('')]
describe('snapshot diff page', () => {
it('renders JSONL records as labelled YAML blocks and keeps other files whole', () => {
const jsonl = [
'{"type":"user/message","data":{"text":"a\\nb"}}',
'{"method":"session.event","params":{"event":{"type":"turn/start"}}}',
'{"method":"ping"}',
'[1]',
'not json',
'',
].join('\n')
expect(readableUnits('s/session.jsonl', jsonl)).toEqual([
'# user/message\ntype: user/message\ndata:\n text: |-\n a\n b\n',
'# session.event turn/start\nmethod: session.event\nparams:\n event:\n type: turn/start\n',
'# ping\nmethod: ping\n',
'[1]\n',
'not json\n',
])
expect(readableUnits('s/prompt.md', 'a\nb')).toEqual(['a\nb'])
expect(readableUnits('s/prompt.md', '')).toEqual([])
})
it('collapses unchanged runs beyond the context and pairs changed lines with word highlights', () => {
const result = sideBySide(text('a', 'b', 'c', 'd', 'old word', 'e', 'f', 'g'), text('a', 'b', 'c', 'd', 'new word', 'e', 'added', 'f', 'g'), limits)
expect(result).toEqual({
added: 2, removed: 1, omitted: 0,
rows: [
['skip', 1, 1, ['a', 'b', 'c']],
['same', 4, 4, 'd'],
['change', 5, 5, [[true, 'old'], [false, ' word']], [[true, 'new'], [false, ' word']]],
['same', 6, 6, 'e'],
['add', 7, 'added'],
['same', 7, 8, 'f'],
['same', 8, 9, 'g'],
],
})
})
it('shows unmatched removed lines and leaves long lines without word highlights', () => {
const long = 'x'.repeat(101)
expect(sideBySide(text(long, 'gone', 'z'), text(`${long}!`, 'z'), limits).rows).toEqual([
['change', 1, 1, long, `${long}!`],
['del', 2, 'gone'],
['same', 3, 2, 'z'],
])
})
it('keeps an inserted JSONL record as one added block when later records also change', () => {
const record = (type: string, seq: number) => `{"type":"${type}","seq":${String(seq)},"a":1,"b":2,"c":3}`
const before = readableUnits('x.jsonl', [record('one', 1), record('three', 2)].join('\n'))
const after = readableUnits('x.jsonl', [record('one', 1), record('two', 2), record('three', 3)].join('\n'))
const rows = sideBySide(before, after, { ...limits, context: 0 }).rows ?? []
expect(rows.filter(row => row[0] === 'add').map(row => row[2])).toEqual(['# two', 'type: two', 'seq: 2', 'a: 1', 'b: 2', 'c: 3'])
expect(rows.filter(row => row[0] === 'change')).toEqual([['change', 9, 15, [[false, 'seq: '], [true, '2']], [[false, 'seq: '], [true, '3']]]])
})
it('reports omitted rows past the limit and no rows when the diff times out', () => {
const many = Array.from({ length: 10 }, (_, index) => `line ${String(index)}`)
expect(sideBySide([], text(...many), { ...limits, rows: 4 })).toMatchObject({ added: 10, removed: 0, omitted: 6 })
expect(sideBySide([], text(...many), { ...limits, rows: 4 }).rows).toHaveLength(4)
// The skip row holds lines 1–7 and costs 8, so only it and the next row fit in 9.
const collapsed = sideBySide(text('1', '2', '3', '4', '5', '6', '7', '8', 'old', '9'), text('1', '2', '3', '4', '5', '6', '7', '8', 'new', '9'), { ...limits, rows: 9 })
expect([collapsed.rows?.map(row => row[0]), collapsed.omitted]).toEqual([['skip', 'same'], 2])
const big = Array.from({ length: 4000 }, (_, index) => String(index))
expect(sideBySide(text(...big), text(...big.toReversed()), { ...limits, timeoutMs: 0 }))
.toEqual({ added: 4000, removed: 4000, omitted: 0 })
})
it('opens on the catalog, then groups scenarios and other files by directory in code point order', () => {
const catalog = ['snapshots/sdk/text-turn/system-prompt.expected.md', 'snapshots/session/text-turn/tool-schemas.expected.json']
const paths = ['snapshots/web/b/x', 'snapshots/sdk/sdk.snapshot.ts', 'snapshots/AGENTS.md', 'snapshots/web/B/x', 'snapshots/web/b/a/y']
expect(groupDiffs(paths, catalog)).toEqual([
{ title: 'SDK blank Session catalog', paths: catalog },
{ title: 'snapshots', paths: ['snapshots/AGENTS.md'] },
{ title: 'sdk', paths: ['snapshots/sdk/sdk.snapshot.ts'] },
{ title: 'web/B', paths: ['snapshots/web/B/x'] },
{ title: 'web/b', paths: ['snapshots/web/b/a/y', 'snapshots/web/b/x'] },
])
})
it.each([
['owns both sidecars', 'profile: sdk\n', 'sdk/text-turn', 'sdk/text-turn'],
['names a source in its own suite directory', 'profile: sdk-minimal\nheader:\n toolSchemasSource: other\n', 'sdk/text-turn', 'sdk/other'],
['names sources in another suite', 'profile: sdk\nheader:\n systemPromptSource: session/a\n toolSchemasSource: session/b\n', 'session/a', 'session/b'],
])('resolves catalog sidecars when the manifest %s', (_, manifest, prompt, schemas) => {
expect(catalogFiles(manifest)).toEqual({
systemPrompt: `snapshots/${prompt}/system-prompt.expected.md`,
toolSchemas: `snapshots/${schemas}/tool-schemas.expected.json`,
})
})
it.each([
['a non-string source', 'profile: sdk\nheader:\n toolSchemasSource: 1\n', 'header.toolSchemasSource must be a non-empty string'],
['an empty source', 'header:\n systemPromptSource: ""\n', 'header.systemPromptSource must be a non-empty string'],
])('rejects %s', (_, manifest, message) => {
expect(() => catalogFiles(manifest)).toThrow(message)
})
it('embeds the index so a path cannot close the script element', () => {
const files = [{ path: 'p</script><b>', added: 1, removed: 0 }]
const groups = [{ title: 't', paths: ['p</script><b>'] }]
const page = renderSnapshotDiffPage(files, groups, 'a → b')
expect(page).not.toContain('</script><b>')
const data = /<script type="application\/json" id="data">(.*)<\/script>/.exec(page)?.[1] ?? ''
expect(JSON.parse(data)).toEqual({ files, groups, heading: 'a → b' })
})
it('appends the page link to the Preview fixture manifest', () => {
const manifest = JSON.stringify({ version: 1, defaultFixture: null, fixtures: [] })
expect(JSON.parse(addPreviewLink(manifest, '../snapshot-diff/'))).toEqual({
version: 1, defaultFixture: null, fixtures: [], links: [{ label: 'Snapshot changes', href: '../snapshot-diff/' }],
})
})
})
+552
View File
@@ -0,0 +1,552 @@
/**
* Renders the PR preview's snapshot diff site: an `index.html` that lists every
* changed file under `snapshots/` between two revisions, grouped by scenario
* directory, plus one `files/<n>.json` per file holding its side-by-side diff
* rows, which the page loads when a group opens. The page opens on the SDK
* blank-Session catalog, the system prompt and tool schemas the
* `sdk/text-turn` scenario's first request carries, and shows "No change" for
* a catalog file whose content is equal on both sides.
*
* JSONL files are compared in a readable form: each record becomes a
* `# <label>` heading followed by its YAML rendering, so long records span
* several lines and multiline strings, such as prompts and runtime context,
* appear as text blocks. Records align as units before their lines are
* compared, so an inserted record shows as one added block.
*
* Usage: `tsx scripts/snapshot-diff-page.ts --base <rev> --head <rev> --out <dir> [--preview-manifest <fixtures.json>]`.
* `--preview-manifest` adds a link to the page in the Preview source chooser.
*/
import { execFileSync } from 'node:child_process'
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { dirname, join, posix, relative, sep } from 'node:path'
import { parseArgs } from 'node:util'
import { diffArrays, diffLines, diffWordsWithSpace } from 'diff'
import * as yaml from 'js-yaml'
/** Scenario whose first request represents a blank SDK Session. */
const CATALOG_SCENARIO = 'sdk/text-turn'
/** Limits that keep each per-file data file small enough to load and render. */
export interface DiffLimits {
/** Unchanged lines kept around each change before the rest collapse. */
readonly context: number
/** Rows kept per file, counting each line a collapsed run holds; the page notes how many rows it omits. */
readonly rows: number
/** Lines longer than this skip word-level highlighting. */
readonly wordDiffChars: number
/** Milliseconds the line diff may take before the file shows as replaced. */
readonly timeoutMs: number
}
const LIMITS: DiffLimits = { context: 3, rows: 4000, wordDiffChars: 2000, timeoutMs: 5000 }
/** A cell's text, or text segments whose `true` flag marks changed words. */
export type Cell = string | ReadonlyArray<readonly [boolean, string]>
/**
* One side-by-side row: an unchanged line, a changed pair, a line on one side
* only, or collapsed unchanged lines that the page can expand.
*/
export type Row =
| readonly ['same', number, number, string]
| readonly ['change', number, number, Cell, Cell]
| readonly ['del', number, string]
| readonly ['add', number, string]
| readonly ['skip', number, number, readonly string[]]
/** One changed file in the page index. */
export interface FileEntry {
readonly path: string
readonly added: number
readonly removed: number
/** Why rows are absent: a binary side, equal content with a changed mode or type, or a diff over the time limit. */
readonly note?: 'binary' | 'mode' | 'timeout'
}
/** A selectable entry on the page. */
export interface DiffGroup {
readonly title: string
/** Distinct {@link FileEntry.path} values the group shows, including unchanged ones. */
readonly paths: readonly string[]
}
/** The two sidecars that make up a scenario's request catalog. */
export interface CatalogFiles {
readonly systemPrompt: string
readonly toolSchemas: string
}
/** Names a record by its `type`, the `params.event.type` of a Session event notification, or its `method`. */
function recordLabel(record: object): string {
const { type, method, params } = record as { type?: unknown; method?: unknown; params?: { event?: { type?: unknown } } }
const eventType = params?.event?.type
if (typeof type === 'string') return type
if (typeof method === 'string') return typeof eventType === 'string' ? `${method} ${eventType}` : method
return 'record'
}
/**
* Splits file content into the units the page aligns before comparing lines.
* @param path - Repository-relative path; `.jsonl` selects the record view.
* @param text - File content.
* @returns The whole content as one unit, or for JSONL one unit per record: a
* `# <label>` heading and the record's YAML rendering, ending in a newline. A
* line that is not a JSON object stays as written.
*/
export function readableUnits(path: string, text: string): string[] {
if (!path.endsWith('.jsonl')) return text === '' ? [] : [text]
return text.split('\n').filter(line => line !== '').map((line) => {
let record: unknown
try {
record = JSON.parse(line)
} catch {
// A line that is not JSON is shown unchanged.
return `${line}\n`
}
if (typeof record !== 'object' || record === null || Array.isArray(record)) return `${line}\n`
return `# ${recordLabel(record)}\n${yaml.dump(record, { lineWidth: -1, noRefs: true })}`
})
}
interface LineChange {
readonly value: string
readonly added?: boolean
readonly removed?: boolean
}
/**
* Units count as the same record when they open with the same line, the
* record label, and at least half of the longer one's lines also occur in the other.
*/
function similar(left: readonly string[], right: readonly string[]): boolean {
if (left[0] !== right[0]) return false
const other = new Set(right)
let shared = 0
for (const line of new Set(left)) if (other.has(line)) shared++
return shared * 2 >= Math.max(new Set(left).size, other.size)
}
/**
* Diffs a run of removed units against a run of added units: units pair up by
* {@link similar} in order and each pair is diffed line by line, while
* unpaired units stay whole removals or additions.
*/
function pairedChanges(removed: readonly string[], added: readonly string[], deadline: number): LineChange[] | undefined {
if (removed.length === 1 && added.length === 1) return diffLines(removed[0] ?? '', added[0] ?? '', { timeout: remaining(deadline) })
const left = removed.map(unit => unit.split('\n'))
const right = added.map(unit => unit.split('\n'))
const indexes = (count: number) => Array.from({ length: count }, (_, index) => index)
const alignment = diffArrays(indexes(removed.length), indexes(added.length), {
timeout: remaining(deadline),
comparator: (a, b) => similar(left[a] ?? [], right[b] ?? []),
})
if (alignment === undefined) return undefined
const changes: LineChange[] = []
let l = 0
let r = 0
for (const part of alignment) {
for (let step = 0; step < part.count; step++) {
if (part.removed) changes.push({ value: removed[l++] ?? '', removed: true })
else if (part.added) changes.push({ value: added[r++] ?? '', added: true })
else {
const lines = diffLines(removed[l++] ?? '', added[r++] ?? '', { timeout: remaining(deadline) })
if (lines === undefined) return undefined
changes.push(...lines)
}
}
}
return changes
}
/** Milliseconds left before `deadline`; jsdiff gives up at once when none remain. */
function remaining(deadline: number): number {
return Math.max(0, deadline - Date.now())
}
/**
* Aligns whole units first, so an inserted or deleted record stays one block,
* then diffs lines inside each run of changed units.
*/
function lineChanges(before: readonly string[], after: readonly string[], deadline: number): LineChange[] | undefined {
const units = diffArrays([...before], [...after], { timeout: remaining(deadline) })
if (units === undefined) return undefined
const changes: LineChange[] = []
for (let index = 0; index < units.length; index++) {
const unit = units[index]
const next = units[index + 1]
if (unit === undefined) continue
if (unit.removed && next?.added) {
const paired = pairedChanges(unit.value, next.value, deadline)
if (paired === undefined) return undefined
changes.push(...paired)
index++
} else {
changes.push({ value: unit.value.join(''), added: unit.added, removed: unit.removed })
}
}
return changes
}
function linesOf(value: string): string[] {
const lines = value.split('\n')
if (lines.at(-1) === '') lines.pop()
return lines
}
/** Joins adjacent unchanged changes so context collapses across unit boundaries. */
function mergeCommon(changes: LineChange[] | undefined): LineChange[] | undefined {
if (changes === undefined) return undefined
const merged: LineChange[] = []
for (const change of changes) {
const last = merged.at(-1)
const common = !change.added && !change.removed
if (common && last !== undefined && !last.added && !last.removed) merged[merged.length - 1] = { value: last.value + change.value }
else if (change.value !== '') merged.push(change)
}
return merged
}
function wordCells(left: string, right: string, limits: DiffLimits): [Cell, Cell] {
if (left.length > limits.wordDiffChars || right.length > limits.wordDiffChars) return [left, right]
const parts = diffWordsWithSpace(left, right)
return [
parts.filter(part => !part.added).map(part => [part.removed, part.value] as const),
parts.filter(part => !part.removed).map(part => [part.added, part.value] as const),
]
}
/** Rows and line counts for one file; `rows` is absent when the diff timed out. */
export interface SideBySide {
readonly rows?: Row[]
readonly added: number
readonly removed: number
readonly omitted: number
}
/**
* Builds side-by-side rows for two unit lists from {@link readableUnits}.
* Unchanged runs keep `context` lines next to each change and collapse the
* rest into `skip` rows; removed and added runs pair up line by line as
* `change` rows with word highlights.
* @param before - Base units; empty for an added file.
* @param after - Head units; empty for a deleted file.
* @param limits - Context, row, word-diff, and time limits.
* @returns Rows, added and removed line counts, and rows left out by the row
* limit, with word highlights only on kept rows; `undefined` rows when the diff exceeded the time limit.
*/
export function sideBySide(before: readonly string[], after: readonly string[], limits: DiffLimits = LIMITS): SideBySide {
const changes = mergeCommon(lineChanges(before, after, Date.now() + limits.timeoutMs))
if (changes === undefined) return { added: linesOf(after.join('')).length, removed: linesOf(before.join('')).length, omitted: 0 }
const rows: Row[] = []
// A row costs 1, and a skip row also costs the lines it holds.
let cost = 0
let omitted = 0
const push = (row: Row) => {
const size = row[0] === 'skip' ? 1 + row[3].length : 1
if (cost + size > limits.rows) omitted++
else {
cost += size
rows.push(row)
}
}
let left = 1
let right = 1
let added = 0
let removed = 0
for (let index = 0; index < changes.length; index++) {
const change = changes[index]
if (change === undefined) continue
const lines = linesOf(change.value)
if (!change.added && !change.removed) {
const head = index === 0 ? 0 : limits.context
const tail = index === changes.length - 1 ? 0 : limits.context
if (lines.length <= head + tail + 1) {
for (const line of lines) push(['same', left++, right++, line])
continue
}
for (const line of lines.slice(0, head)) push(['same', left++, right++, line])
const hidden = lines.slice(head, lines.length - tail)
push(['skip', left, right, hidden])
left += hidden.length
right += hidden.length
for (const line of lines.slice(lines.length - tail)) push(['same', left++, right++, line])
continue
}
const next = changes[index + 1]
const removedLines = change.removed ? lines : []
const addedLines = change.removed && next?.added ? linesOf(next.value) : change.added ? lines : []
if (change.removed && next?.added) index++
removed += removedLines.length
added += addedLines.length
for (let line = 0; line < Math.max(removedLines.length, addedLines.length); line++) {
const before = removedLines[line]
const after = addedLines[line]
if (before !== undefined && after !== undefined) push(['change', left++, right++, before, after])
else if (before !== undefined) push(['del', left++, before])
else if (after !== undefined) push(['add', right++, after])
}
}
const withWords = rows.map((row): Row => row[0] === 'change' && typeof row[3] === 'string' && typeof row[4] === 'string'
? ['change', row[1], row[2], ...wordCells(row[3], row[4], limits)]
: row)
return { rows: withWords, added, removed, omitted }
}
/**
* Groups changed files for the page: the catalog first, then one group per
* scenario directory (`snapshots/<suite>/<scenario>`) and one per directory
* holding other changed files, in code point order.
* @param paths - Changed paths under `snapshots/`.
* @param catalogPaths - Paths the catalog group shows.
* @returns The catalog group followed by the directory groups.
*/
export function groupDiffs(paths: readonly string[], catalogPaths: readonly string[]): DiffGroup[] {
const groups = new Map<string, Set<string>>()
for (const path of paths) {
const segments = path.split('/')
const key = segments.slice(0, segments.length >= 4 ? 3 : -1).join('/')
groups.set(key, (groups.get(key) ?? new Set()).add(path))
}
const byCodePoint = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
return [
{ title: 'SDK blank Session catalog', paths: catalogPaths },
...[...groups].sort(([a], [b]) => byCodePoint(a, b))
.map(([key, members]) => ({ title: key.replace(/^snapshots\/?/, '') || 'snapshots', paths: [...members].sort(byCodePoint) })),
]
}
function referencedScenario(source: unknown, field: string): string {
if (source === undefined) return CATALOG_SCENARIO
if (typeof source !== 'string' || source === '') throw new Error(`snapshots/${CATALOG_SCENARIO}/snapshot.yml: header.${field} must be a non-empty string`)
return source.includes('/') ? source : `${CATALOG_SCENARIO.split('/')[0] ?? ''}/${source}`
}
/**
* Resolves the catalog sidecars from the catalog scenario's `snapshot.yml`,
* following `header.systemPromptSource` and `header.toolSchemasSource`; a
* single-segment source names a scenario in the catalog scenario's suite directory.
* @param manifestText - The catalog scenario's `snapshot.yml` text.
* @returns Repository-relative sidecar paths.
*/
export function catalogFiles(manifestText: string): CatalogFiles {
const manifest = (yaml.load(manifestText, { schema: yaml.JSON_SCHEMA }) ?? {}) as { header?: Record<string, unknown> }
const header = manifest.header ?? {}
return {
systemPrompt: `snapshots/${referencedScenario(header.systemPromptSource, 'systemPromptSource')}/system-prompt.expected.md`,
toolSchemas: `snapshots/${referencedScenario(header.toolSchemasSource, 'toolSchemasSource')}/tool-schemas.expected.json`,
}
}
/**
* Renders the page shell; file rows load from `files/<index>.json`, where the
* index is the file's position in `files`.
* @param files - Changed files.
* @param groups - Groups from {@link groupDiffs}; the first one opens by default.
* @param heading - Revision description shown under the title.
* @returns HTML text.
*/
export function renderSnapshotDiffPage(files: readonly FileEntry[], groups: readonly DiffGroup[], heading: string): string {
const data = JSON.stringify({ files, groups, heading }).replace(/</g, '\\u003c')
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Snapshot changes</title>
<style>
:root { color-scheme: light dark; font: 14px/1.45 system-ui, sans-serif; --line: #8884; --muted: #888; --add: #2da44e26; --add-word: #2da44e66; --del: #cf222e26; --del-word: #cf222e66; }
body { margin: 0; display: grid; grid-template-columns: minmax(200px, 300px) 1fr; height: 100vh; }
nav { overflow: auto; border-right: 1px solid var(--line); padding: 12px 0; }
nav h1 { font-size: 16px; margin: 0 16px 4px; }
nav p { margin: 0 16px 12px; color: var(--muted); font-size: 12px; }
nav button { display: flex; justify-content: space-between; gap: 8px; width: 100%; padding: 6px 16px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; }
nav button:hover { background: #8882; }
nav button[aria-current="true"] { background: #4a90e233; font-weight: 600; }
nav hr { border: 0; border-top: 1px solid var(--line); margin: 8px 0; }
.stat { font: 12px ui-monospace, monospace; white-space: nowrap; }
.stat .a { color: #1f883d; } .stat .r { color: #cf222e; }
main { overflow: auto; padding: 16px 24px; }
main h2 { font-size: 16px; margin: 0 0 12px; }
section { margin-bottom: 20px; border: 1px solid var(--line); border-radius: 6px; overflow: hidden; }
section h3 { display: flex; justify-content: space-between; gap: 12px; font: 600 13px ui-monospace, monospace; margin: 0; padding: 8px 12px; background: #8881; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; }
table { width: 100%; border-collapse: collapse; table-layout: fixed; font: 12px/1.5 ui-monospace, monospace; }
col.n { width: 4.5em; }
td { vertical-align: top; padding: 0 8px; white-space: pre-wrap; overflow-wrap: anywhere; }
td.n { color: var(--muted); text-align: right; user-select: none; padding-right: 6px; }
td.c + td.n { border-left: 1px solid var(--line); }
td.del { background: var(--del); } td.add { background: var(--add); }
td.del mark { background: var(--del-word); color: inherit; } td.add mark { background: var(--add-word); color: inherit; }
td.none { background: #8881; }
tr.skip td { padding: 2px 12px; color: var(--muted); background: #8881; }
tr.skip button { border: 0; background: none; color: #4a90e2; font: inherit; cursor: pointer; padding: 0; }
.empty { padding: 8px 12px; color: var(--muted); }
@media (max-width: 900px) {
body { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
nav { max-height: 30vh; border-right: 0; border-bottom: 1px solid var(--line); }
main { padding: 12px; }
col.n { width: 3.5em; }
}
</style>
</head>
<body>
<nav aria-label="Snapshots"><h1>Snapshot changes</h1><p id="heading"></p><div id="list"></div></nav>
<main id="view"></main>
<script type="application/json" id="data">${data}</script>
<script>
const { files, groups, heading } = JSON.parse(document.getElementById('data').textContent)
document.getElementById('heading').textContent = heading
const list = document.getElementById('list')
const view = document.getElementById('view')
const indexOf = new Map(files.map((file, index) => [file.path, index]))
function el(tag, props = {}, ...children) {
const node = Object.assign(document.createElement(tag), props)
node.append(...children)
return node
}
function stat(added, removed) {
return el('span', { className: 'stat' }, el('span', { className: 'a', textContent: '+' + added }), ' ', el('span', { className: 'r', textContent: '-' + removed }))
}
const buttons = groups.map((group, index) => {
const changed = group.paths.map(path => files[indexOf.get(path)]).filter(Boolean)
const button = el('button', { type: 'button', onclick: () => show(index) }, el('span', { textContent: group.title }),
stat(changed.reduce((sum, file) => sum + file.added, 0), changed.reduce((sum, file) => sum + file.removed, 0)))
list.append(button)
if (index === 0) list.append(el('hr'))
return button
})
if (groups.length === 1) list.append(el('p', { textContent: 'No other snapshot changed.' }))
function cell(value) {
if (typeof value === 'string') return [value]
return value.map(([changed, text]) => changed ? el('mark', { textContent: text }) : text)
}
function td(className, ...children) { return el('td', { className }, ...children) }
function rowNodes(row) {
switch (row[0]) {
case 'same': return [el('tr', {}, td('n', String(row[1])), td('c', row[3]), td('n', String(row[2])), td('c', row[3]))]
case 'change': return [el('tr', {}, td('n', String(row[1])), td('c del', ...cell(row[3])), td('n', String(row[2])), td('c add', ...cell(row[4])))]
case 'del': return [el('tr', {}, td('n', String(row[1])), td('c del', row[2]), td('n'), td('c none'))]
case 'add': return [el('tr', {}, td('n'), td('c none'), td('n', String(row[1])), td('c add', row[2]))]
case 'skip': {
const tr = el('tr', { className: 'skip' })
const expand = el('button', { type: 'button', textContent: 'Show ' + row[3].length + ' unchanged lines' })
expand.onclick = () => tr.replaceWith(...row[3].flatMap((line, i) => rowNodes(['same', row[1] + i, row[2] + i, line])))
tr.append(el('td', { colSpan: 4 }, expand))
return [tr]
}
}
return []
}
function table(data) {
const body = el('tbody', {}, ...data.rows.flatMap(rowNodes))
const node = el('table', {}, el('colgroup', {}, el('col', { className: 'n' }), el('col'), el('col', { className: 'n' }), el('col')), body)
return data.omitted ? [node, el('div', { className: 'empty', textContent: data.omitted + ' more rows omitted; see the pull request diff' })] : [node]
}
async function fileBody(index) {
const file = files[index]
if (file.note === 'binary') return [el('div', { className: 'empty', textContent: 'Binary file changed' })]
if (file.note === 'mode') return [el('div', { className: 'empty', textContent: 'Only the file mode or type changed' })]
if (file.note === 'timeout') return [el('div', { className: 'empty', textContent: 'Diff too large to compute; see the pull request diff' })]
const response = await fetch('files/' + index + '.json')
if (!response.ok) return [el('div', { className: 'empty', textContent: 'Could not load this diff (' + response.status + ')' })]
const data = await response.json()
return table(data)
}
let current = 0
async function show(index) {
current = index
const group = groups[index]
buttons.forEach((button, i) => button.setAttribute('aria-current', String(i === index)))
history.replaceState(null, '', '#' + encodeURIComponent(group.title))
view.replaceChildren(el('h2', { textContent: group.title }))
for (const path of group.paths) {
const fileIndex = indexOf.get(path)
const file = files[fileIndex]
const section = el('section', {}, el('h3', {}, el('span', { textContent: path }), file ? stat(file.added, file.removed) : ''))
view.append(section)
if (!file) { section.append(el('div', { className: 'empty', textContent: 'No change' })); continue }
const body = el('div', { className: 'empty', textContent: 'Loading…' })
section.append(body)
fileBody(fileIndex).then(nodes => { if (current === index) body.replaceWith(...nodes) },
error => { body.textContent = 'Could not load this diff: ' + error })
}
}
const initial = groups.findIndex(group => '#' + encodeURIComponent(group.title) === location.hash)
show(initial === -1 ? 0 : initial)
</script>
</body>
</html>
`
}
/**
* Appends a link to the page to a Preview fixture manifest.
* @param manifestText - `fixtures.json` text the packer wrote.
* @param href - Page URL relative to the manifest.
* @returns The updated manifest text.
*/
export function addPreviewLink(manifestText: string, href: string): string {
const manifest = JSON.parse(manifestText) as { links?: unknown[] }
return `${JSON.stringify({ ...manifest, links: [...manifest.links ?? [], { label: 'Snapshot changes', href }] }, null, 2)}\n`
}
function git(...args: string[]): Buffer {
return execFileSync('git', args, { maxBuffer: 1 << 30 })
}
/** Reads a blob, or returns an empty buffer when the path is absent at `rev`. */
function blob(rev: string, path: string): Buffer {
const entry = git('ls-tree', '-z', rev, '--', path).toString('utf8')
return entry === '' ? Buffer.alloc(0) : git('cat-file', 'blob', `${rev}:${path}`)
}
/** Requires a regular file, because a symlink blob holds its target path rather than the content it names. */
function assertRegularFile(rev: string, path: string): void {
const mode = git('ls-tree', rev, '--', path).toString('utf8').split(' ')[0]
if (mode !== '100644' && mode !== '100755') throw new Error(`catalog file ${path} at ${rev} is not a regular file (mode ${mode || 'missing'})`)
}
if (import.meta.main) {
const { values } = parseArgs({ options: { 'base': { type: 'string' }, 'head': { type: 'string' }, 'out': { type: 'string' }, 'preview-manifest': { type: 'string' } } })
const { base, head, out } = values
if (!base || !head || !out) throw new Error('usage: snapshot-diff-page.ts --base <rev> --head <rev> --out <dir> [--preview-manifest <fixtures.json>]')
const short = (rev: string) => git('rev-parse', '--short', rev).toString('utf8').trim()
const changed = git('diff', '-z', '--name-only', '--no-renames', base, head, '--', 'snapshots/').toString('utf8').split('\0').filter(path => path !== '')
const manifestAt = (rev: string) => catalogFiles(git('show', `${rev}:snapshots/${CATALOG_SCENARIO}/snapshot.yml`).toString('utf8'))
const from = manifestAt(base)
const to = manifestAt(head)
type Side = [rev: string, path: string]
const pairs: Array<{ path: string; before: Side; after: Side }> = changed
.map(path => ({ path, before: [base, path], after: [head, path] }))
const catalog = (['systemPrompt', 'toolSchemas'] as const).map((key) => {
assertRegularFile(base, from[key])
assertRegularFile(head, to[key])
if (from[key] === to[key]) return to[key]
// The source scenario moved: compare the two files under an `old → new` label.
const path = `${from[key]} → ${to[key]}`
if (!blob(base, from[key]).equals(blob(head, to[key]))) pairs.unshift({ path, before: [base, from[key]], after: [head, to[key]] })
return path
})
// Only the outputs this script writes are removed, so a mistaken --out cannot delete other files.
rmSync(join(out, 'files'), { recursive: true, force: true })
rmSync(join(out, 'index.html'), { force: true })
mkdirSync(join(out, 'files'), { recursive: true })
const files: FileEntry[] = pairs.map(({ path, before, after }, index) => {
const [left, right] = [blob(...before), blob(...after)]
if (left.equals(right)) return { path, added: 0, removed: 0, note: 'mode' }
if (left.includes(0) || right.includes(0)) return { path, added: 0, removed: 0, note: 'binary' }
const [leftText, rightText] = [left.toString('utf8'), right.toString('utf8')]
let [leftUnits, rightUnits] = [readableUnits(before[1], leftText), readableUnits(after[1], rightText)]
// A change the record view drops, such as blank lines, is shown in the raw text.
if (leftUnits.join('') === rightUnits.join('')) [leftUnits, rightUnits] = [[leftText], [rightText]]
const result = sideBySide(leftUnits, rightUnits)
if (result.rows === undefined) return { path, added: result.added, removed: result.removed, note: 'timeout' }
writeFileSync(join(out, 'files', `${String(index)}.json`), JSON.stringify({ rows: result.rows, omitted: result.omitted }))
return { path, added: result.added, removed: result.removed }
})
writeFileSync(join(out, 'index.html'), renderSnapshotDiffPage(files, groupDiffs(changed, catalog), `${short(base)} → ${short(head)}`))
const manifest = values['preview-manifest']
if (manifest) {
const href = `${relative(dirname(manifest), out).split(sep).join(posix.sep)}/`
writeFileSync(manifest, addPreviewLink(readFileSync(manifest, 'utf8'), href))
}
}
+5 -4
View File
@@ -1,8 +1,9 @@
import { Context } from '@deepseek-ai/cordis'
import { LocalSpillStore } from '@deepseek-ai/dsh-spill-local'
import { LocalFileSystem } from '@deepseek-ai/dsh-fs-local'
import { SessionId } from '@deepseek-ai/dsh-session'
import { ToolCallId } from '@deepseek-ai/dsh-llm'
import type { SessionId } from '@deepseek-ai/dsh-session'
import { brandString } from '@deepseek-ai/dsh-brand'
import type { ToolCallId } from '@deepseek-ai/dsh-llm/types'
import { mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
@@ -34,8 +35,8 @@ it.each([false, true])('keeps concurrent physical spill files private while reta
await fork
const content = `physical UTF-8 内容 ${index}`
const ref = await ctx.spillStore.saveText({
owner: { sessionId: SessionId('same-session') },
source: { kind: 'tool', toolName: 'bash', callId: ToolCallId('same-call'), label: 'result' },
owner: { sessionId: brandString<SessionId>('same-session') },
source: { kind: 'tool', toolName: 'bash', callId: brandString<ToolCallId>('same-call'), label: 'result' },
suggestedName: 'bash.txt', content,
})
expect(ref.bytes).toBe(Buffer.byteLength(content))
+23 -16
View File
@@ -188,20 +188,20 @@ it('keeps vendor publication manual and entirely hosted', () => {
it('keeps DSH publication manual and delegates all helper selections to the Mac workflow', () => {
const publish = workflow('release-publish.yml')
expect(Object.keys(publish.on)).toEqual(['workflow_dispatch'])
const helper = publish.jobs['cua-helper']!
const helper = publish.jobs['cua-helper-macos']!
expect(helper).toEqual({
if: "startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check",
uses: './.github/workflows/cua-helper-package.yml',
with: { reuse: true, preset: 'production', cua_run_id: '${{ inputs.cua_run_id }}' },
uses: './.github/workflows/cua-helper-package-macos.yml',
with: { reuse: true, preset: 'production', cua_macos_run_id: '${{ inputs.cua_macos_run_id }}' },
})
for (const [name, job] of Object.entries(publish.jobs)) {
if (name !== 'cua-helper') expect(job['runs-on']).toBe(hosted)
if (name !== 'cua-helper-macos') expect(job['runs-on']).toBe(hosted)
}
expect(JSON.stringify(publish)).not.toContain('cua_run_attempt')
expect(publish.on['workflow_dispatch']).toMatchObject({ inputs: { 'skip-tag-check': {
description: 'Skip release tag validation for the selected ref; other publication checks still apply.',
} } })
expect(publish.jobs['pack']!.needs).toBe('cua-helper')
expect(publish.jobs['pack']!.needs).toBe('cua-helper-macos')
expect(publish.jobs['pack']!.if).toBeUndefined()
})
@@ -210,12 +210,12 @@ it.each([
['refs/heads/master', false, false],
['refs/heads/master', true, true],
] as const)('gates helper selection for ref %s, skip=%s', (ref, skip, expected) => {
const expression = workflow('release-publish.yml').jobs['cua-helper']!.if!
const expression = workflow('release-publish.yml').jobs['cua-helper-macos']!.if!
expect(evaluate(expression, { 'github.ref': ref, 'inputs.skip-tag-check': skip })).toBe(expected)
})
it('skips installation and signing on a helper match and exports the original producer identifiers', () => {
const helper = workflow('cua-helper-package.yml')
const helper = workflow('cua-helper-package-macos.yml')
expect(helper.permissions).toEqual({ contents: 'read', actions: 'read' })
const job = helper.jobs['package']!
const select = job.steps.find(step => step.name === 'Find reusable CUA helper')!
@@ -248,39 +248,46 @@ it('skips installation and signing on a helper match and exports the original pr
})
})
it.each(['macos', 'windows'])('uploads an artifact named for the %s helper and its exact build', (platform) => {
const steps = workflow(`cua-helper-package-${platform}.yml`).jobs['package']!.steps
const upload = steps.find(step => step.uses?.startsWith('actions/upload-artifact@'))
const build = platform === 'macos' ? '${{ steps.build-inputs.outputs.build-key }}' : '${{ steps.metadata.outputs.build-key }}'
expect(upload?.with?.name).toBe([`cua-helper-${platform}`, '${{ github.run_id }}', '${{ github.run_attempt }}', build].join('-'))
})
it('downloads the selected producer artifact and verifies its build key before packing', () => {
const publish = workflow('release-publish.yml')
expect(publish.permissions).toEqual({ contents: 'read', actions: 'read' })
const pack = publish.jobs['pack']!
expect(pack.permissions).toEqual({ contents: 'read', actions: 'read' })
const download = pack.steps.find(step => step.name === 'Download selected CUA helper')!
const download = pack.steps.find(step => step.name === 'Download selected macOS CUA helper')!
expect(download).toMatchObject({ uses: 'actions/[email protected]', with: {
'artifact-ids': '${{ needs.cua-helper.outputs.artifact-id }}', 'run-id': '${{ needs.cua-helper.outputs.run-id }}',
'artifact-ids': '${{ needs.cua-helper-macos.outputs.artifact-id }}', 'run-id': '${{ needs.cua-helper-macos.outputs.run-id }}',
'github-token': '${{ github.token }}', path: 'dist/cua-helper',
} })
expect(download.if).toBeUndefined()
expect(download.with?.name).toBeUndefined()
const stage = pack.steps.find(step => step.name === 'Stage verified native helper applications')!
const stage = pack.steps.find(step => step.name === 'Stage verified macOS helper applications')!
expect(stage.if).toBeUndefined()
expect(stage.env).toEqual({ CUA_EXPECTED_BUILD_KEY: '${{ needs.cua-helper.outputs.build-key }}' })
expect(stage.env).toEqual({ CUA_EXPECTED_BUILD_KEY: '${{ needs.cua-helper-macos.outputs.build-key }}' })
expect(stage.run).toContain('scripts/cua-helper/stage.ts --from dist/cua-helper/extracted')
expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(download))
expect(pack.steps.indexOf(stage)).toBeLessThan(pack.steps.findIndex(step => step.name === 'Pack release tarballs'))
})
it('checks out the Actions run commit and exposes only the preset on the manual helper form', () => {
const helper = workflow('cua-helper-package.yml')
const helper = workflow('cua-helper-package-macos.yml')
const dispatch = helper.on['workflow_dispatch'] as { inputs: Record<string, unknown> }
const called = helper.on['workflow_call'] as { inputs: Record<string, unknown> }
expect(Object.keys(dispatch.inputs)).toEqual(['preset'])
expect(called.inputs).toEqual({ reuse: { type: 'boolean', default: false },
cua_run_id: { type: 'string', default: '' }, preset: { type: 'string', default: 'production' } })
cua_macos_run_id: { type: 'string', default: '' }, preset: { type: 'string', default: 'production' } })
const job = helper.jobs['package']!
const checkout = job.steps.find(step => step.uses === 'actions/[email protected]')!
expect(checkout.with).toEqual({ 'persist-credentials': false, clean: true })
expect(job.env).not.toHaveProperty('PACKAGE_SOURCE_REF')
expect(JSON.stringify(helper)).not.toContain('source_ref')
expect(workflow('release-publish.yml').jobs['cua-helper']!.with).not.toHaveProperty('source_ref')
expect(workflow('release-publish.yml').jobs['cua-helper-macos']!.with).not.toHaveProperty('source_ref')
})
it.each([
@@ -294,7 +301,7 @@ it.each([
const directory = mkdtempSync(join(tmpdir(), 'cua-workflow-ref-'))
onTestFinished(() => { rmSync(directory, { recursive: true, force: true }) })
writeFileSync(join(directory, 'package.json'), JSON.stringify({ version: '1.2.3' }))
const job = workflow('cua-helper-package.yml').jobs['package']!
const job = workflow('cua-helper-package-macos.yml').jobs['package']!
const validation = job.steps.find(step => step.name === 'Validate run ref and preset')!
const source = /^node -e '([\s\S]+)'$/u.exec(validation.run!.trim())?.[1]
expect(source).toBeDefined()
@@ -314,7 +321,7 @@ it.each([
[true, '', true],
[true, '456', false],
] as const)('builds for reuse=%s and selected artifact=%s only when required', (reuse, artifactId, build) => {
const steps = workflow('cua-helper-package.yml').jobs['package']!.steps
const steps = workflow('cua-helper-package-macos.yml').jobs['package']!.steps
const selection = steps.find(step => step.name === 'Find reusable CUA helper')!
expect(Boolean(evaluate(selection.if!, reuse ? { 'inputs.reuse': true } : {}))).toBe(reuse)
for (const step of steps.filter(step => step.uses === 'pnpm/[email protected]'
+278
View File
@@ -0,0 +1,278 @@
import { readFileSync, symlinkSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
createInventoryRepo,
gitFixture as git,
removeInventoryRepos,
writeFixture as write,
} from './baseline-inventory.fixture.ts'
import { countEmptyCatches, findEmptyCatches, scanEmptyCatches, verifyEmptyCatch } from './verify-empty-catch.ts'
const baselinePath = 'scripts/empty-catch.baseline.json'
const sourcePath = 'packages/example/src/index.ts'
const seed = 'try { run() } catch (_failure) { /* seed */ }\n'
const broken = 'try { run() } catch {}\n'
const recorded = 'try { run() } catch { /* reason */ }\n'
afterEach(removeInventoryRepos)
function fixture(): string {
return createInventoryRepo(baselinePath, seed)
}
function recordBaseline(root: string): string {
const text = `${JSON.stringify(countEmptyCatches(scanEmptyCatches(root)), null, 2)}\n`
write(root, baselinePath, text)
return text
}
function defects(file: string, text: string): (readonly string[])[] {
return findEmptyCatches(file, text).map(finding => finding.defects)
}
describe('empty catch syntax', () => {
it.each([
['unbound and unexplained', 'try { run() } catch {}', ['unnamed', 'unexplained']],
['unbound with a reason', 'try { run() } catch { /* already gone */ }', ['unnamed']],
['bound without a reason', 'try { run() } catch (_missing) {}', ['unexplained']],
['bound to a bare underscore', 'try { run() } catch (_) { /* already gone */ }', ['unnamed']],
['reason between the keyword and the block', 'try { run() } catch /* already gone */ {}', ['unnamed']],
['comment above the whole statement', '// already gone\ntry { run() } catch {}', ['unnamed', 'unexplained']],
['comment inside the try block', 'try { run() /* already gone */ } catch {}', ['unnamed', 'unexplained']],
['multi-statement try', 'try { first(); second() } catch (_missing) { /* already gone */ }', ['wide-try']],
['a body of empty statements', 'try { run() } catch { ;;; }', ['unnamed', 'unexplained']],
['a pattern that binds nothing', 'try { run() } catch ({}) { /* already gone */ }', ['unnamed']],
['an array pattern that binds nothing', 'try { run() } catch ([]) { /* already gone */ }', ['unnamed']],
['a pattern binding only the discarded name', 'try { run() } catch ({ _ }) { /* already gone */ }', ['unnamed']],
['a nested clause inside a handled clause', 'try { run() } catch (error) { try { log() } catch {} }', ['unnamed', 'unexplained']],
['a comment marker inside a trailing string', 'try { run() } catch (_missing) {} finally { log("// not a comment") }', ['unexplained']],
['a comment marker inside a trailing regular expression', 'try { run() } catch (_missing) {} finally { match(/[/*]/) }', ['unexplained']],
['a comment trailing a finally block', 'try { run() } catch (_missing) {} finally { stop() } // Reported above.', ['unexplained']],
['a comment after another statement on the closing line', 'try { run() } catch (_missing) {}; stop() // Stopped.', ['unexplained']],
['a comment on the line after the clause', 'try { run() } catch (_missing) {}\n// Stopped.\nstop()', ['unexplained']],
['a comment on the line after the clause with CRLF', 'try { run() } catch (_missing) {}\r\n// Stopped.\r\nstop()', ['unexplained']],
['a comment marker inside a binding default regular expression', 'try { run() } catch ({ message = /[/*]/ }) {}', ['unexplained']],
['a comment marker inside a binding default template', 'try { run() } catch ({ message = `${prefix}//` }) {}', ['unexplained']],
])('reports %s', (_name, text, expected) => {
expect(defects('input.ts', text)).toEqual([expected])
})
it.each([
['a named and explained clause', 'try { run() } catch (_missing) { /* already gone */ }'],
['an ordinary binding name', 'try { run() } catch (error) { /* reported above */ }'],
['a reason on the line above the clause', 'try { run() }\n// The session may already be gone.\ncatch (_missing) {}'],
['a reason on the line closing the clause', 'try { run() } catch (_missing) {} // The session may already be gone.'],
['a reason on the line closing the clause with CRLF', 'try { run() } catch (_missing) {} // Already gone.\r\nstop()'],
['a block comment above the clause', 'try { run() }\n/* The session may already be gone. */\ncatch (_missing) {}'],
['a reason between the clause and a finally block', 'try { run() } catch (_missing) {} /* Reported above. */ finally { stop() }'],
// One block or compound statement counts as one statement, however much it holds.
['a try holding one block', 'try { { first(); second() } } catch (_missing) { /* already gone */ }'],
['a try holding one if statement', 'try { if (ready) { first(); second() } } catch (_missing) { /* already gone */ }'],
['a finally block', 'try { run() } catch (_missing) { /* already gone */ } finally { stop() }'],
['empty statements beside the try statement', 'try { ; run() } catch (_missing) { /* already gone */ }'],
['a destructured binding', 'try { run() } catch ({ message }) { /* reported above */ }'],
['a handled clause around a conforming clause', 'try { run() } catch (error) { try { log() } catch (_inner) { /* reported */ } }'],
])('accepts %s', (_name, text) => {
expect(findEmptyCatches('input.ts', text)).toEqual([])
})
// A no-op body other than `;` is out of scope, so the gate must not claim it.
it.each([
['a handled clause', 'try { run() } catch (error) { report(error) }'],
['a clause that rethrows', 'try { run() } catch (error) { throw error }'],
['a clause with a return', 'try { return run() } catch { return undefined }'],
['a directive body', 'try { run() } catch { "use strict" }'],
['a void expression body', 'try { run() } catch { void 0 }'],
['a block expression body', 'try { run() } catch { {} }'],
['comment text inside a string', 'try { run() } catch (error) { report("// not a comment") }'],
])('ignores %s', (_name, text) => {
expect(findEmptyCatches('input.ts', text)).toEqual([])
})
it('parses TSX so a JSX sibling does not hide the clause', () => {
const text = 'export const view = <View onClick={() => { try { run() } catch {} }} />\n'
expect(defects('input.tsx', text)).toEqual([['unnamed', 'unexplained']])
})
it('reports normalized paths and the catch keyword line', () => {
const findings = findEmptyCatches('packages\\example\\index.ts', '\n\ntry { run() }\ncatch {}')
expect(findings).toHaveLength(1)
expect(findings[0]).toMatchObject({ file: 'packages/example/index.ts', line: 4 })
expect(findings[0]?.fingerprint).toMatch(/^[a-f0-9]{64}$/u)
})
it('changes the fingerprint when a clause gains a defect', () => {
const [recorded] = findEmptyCatches('input.ts', 'try { run() } catch { /* already gone */ }')
const [widened] = findEmptyCatches('input.ts', 'try { first(); second() } catch { /* already gone */ }')
const [unexplained] = findEmptyCatches('input.ts', 'try { run() } catch {}')
expect(widened?.fingerprint).not.toBe(recorded?.fingerprint)
expect(unexplained?.fingerprint).not.toBe(recorded?.fingerprint)
expect(findEmptyCatches('input.ts', 'try { stop() } catch { /* already gone */ }')[0]?.fingerprint)
.toBe(recorded?.fingerprint)
})
it('keeps syntax fingerprints through whitespace and comment edits', () => {
const original = findEmptyCatches('input.ts', 'try { run() } catch (_missing) {}')
const formatted = findEmptyCatches('input.ts', '\ntry {\n /* retried above */ run()\n}\ncatch (\n_missing\n) {\n}\n')
expect(formatted.map(finding => finding.fingerprint)).toEqual(original.map(finding => finding.fingerprint))
expect(findEmptyCatches('input.ts', 'try { run() } catch (_other) {}').map(finding => finding.fingerprint))
.not.toEqual(original.map(finding => finding.fingerprint))
})
it('counts identical clauses per file', () => {
expect(countEmptyCatches(findEmptyCatches('input.ts', `${broken}${broken}`))).toEqual({
'input.ts': { [findEmptyCatches('input.ts', broken)[0]?.fingerprint ?? '']: 2 },
})
})
})
describe('empty catch inventory', () => {
it('accepts a recorded clause after formatting without rewriting the baseline', () => {
const root = fixture()
write(root, sourcePath, broken)
const baseline = recordBaseline(root)
write(root, sourcePath, 'try { run() }\ncatch {\n}\n')
expect(verifyEmptyCatch(root)).toBe(1)
expect(verifyEmptyCatch(root, true)).toBe(1)
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(baseline)
})
it.each([
['another copy of a recorded clause', `${recorded}${recorded}`],
['a differently bound clause', 'try { stop() } catch (error) {}\n'],
['an unexplained clause', 'try { run() } catch (_missing) {}\n'],
['a wide try', 'try { first(); second() } catch (_missing) { /* reason */ }\n'],
['a recorded clause with a widened try', 'try { first(); second() } catch { /* reason */ }\n'],
['a recorded clause without its reason', 'try { run() } catch {}\n'],
])('rejects %s without changing the baseline', (_name, text) => {
const root = fixture()
write(root, sourcePath, recorded)
const baseline = recordBaseline(root)
write(root, sourcePath, text)
expect(() => verifyEmptyCatch(root)).toThrow(/verify-empty-catch: an empty catch/u)
expect(() => verifyEmptyCatch(root, true)).toThrow(/verify-empty-catch: an empty catch/u)
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(baseline)
})
it('keeps a recorded clause inside its file allowance when only its try statement changes', () => {
const root = fixture()
write(root, sourcePath, broken)
recordBaseline(root)
write(root, sourcePath, 'try { stop() } catch {}\n')
expect(verifyEmptyCatch(root)).toBe(1)
})
it('rejects a new clause when the inventory is empty', () => {
const root = fixture()
write(root, sourcePath, broken)
expect(() => verifyEmptyCatch(root)).toThrow(`${sourcePath}:1 (unnamed, unexplained)`)
})
it('points a rejection at the repository guidance for discarding an error', () => {
const root = fixture()
write(root, sourcePath, broken)
const skillPath = '.agents/skills/dsh-error-handling/SKILL.md'
expect(() => verifyEmptyCatch(root)).toThrow(`(see ${skillPath}#empty-catch-clauses)`)
expect(readFileSync(join(import.meta.dirname, '..', skillPath), 'utf8')).toMatch(/^### Empty catch clauses$/mu)
})
it('requires pruning retired counts while preserving the remaining clause', () => {
const root = fixture()
write(root, sourcePath, `${broken}${broken}`)
write(root, 'apps/retired.ts', broken)
recordBaseline(root)
write(root, sourcePath, broken)
unlinkSync(join(root, 'apps/retired.ts'))
expect(() => verifyEmptyCatch(root)).toThrow(/remove retired baseline entries/u)
expect(verifyEmptyCatch(root, true)).toBe(1)
expect(JSON.parse(readFileSync(join(root, baselinePath), 'utf8'))).toEqual(
countEmptyCatches(findEmptyCatches(sourcePath, broken)),
)
expect(verifyEmptyCatch(root)).toBe(1)
})
it('prunes a fixed clause and a deleted tracked file without treating them as discovery failures', () => {
const root = fixture()
write(root, sourcePath, broken)
git(root, 'add', sourcePath)
recordBaseline(root)
write(root, sourcePath, seed)
expect(() => verifyEmptyCatch(root)).toThrow(/remove retired baseline entries/u)
expect(verifyEmptyCatch(root, true)).toBe(0)
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe('{}\n')
})
// The shared inventory reader owns the complete malformed-input table; these two rows prove this
// gate reads through it rather than around it.
it.each([
['not an object', '[]'],
['excluded path', '{"vendor/input.ts":{"HASH":1}}'],
])('rejects a malformed baseline: %s', (_name, text) => {
const root = fixture()
const contents = text.replaceAll('HASH', 'a'.repeat(64))
write(root, baselinePath, contents)
expect(() => verifyEmptyCatch(root, true)).toThrow()
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(contents)
})
})
describe('empty catch source discovery', () => {
it('checks tracked source across areas, extensions, tests and root configuration', () => {
const root = fixture()
const files = [
'packages/example/src/input.ts',
'apps/example/input.tsx',
'scripts/input.mts',
'website/input.cts',
'packages/example/tests/input.js',
'apps/example/input.jsx',
'scripts/input.mjs',
'website/input.cjs',
'config.ts',
]
for (const file of files) write(root, file, broken)
git(root, 'add', '.')
expect(scanEmptyCatches(root).map(finding => finding.file)).toEqual(files.toSorted())
expect(() => verifyEmptyCatch(root)).toThrow(/verify-empty-catch: an empty catch/u)
})
it('includes untracked source while excluding ignored files, vendor, archives and other extensions', () => {
const root = fixture()
write(root, '.gitignore', 'ignored/\n')
for (const file of ['ignored/input.ts', 'vendor/input.ts', '.agents/notes/archived/input.ts', 'docs/input.md']) {
write(root, file, broken)
}
git(root, 'add', '.')
write(root, 'scripts/new.ts', broken)
expect(scanEmptyCatches(root).map(finding => finding.file)).toEqual(['scripts/new.ts'])
expect(() => verifyEmptyCatch(root)).toThrow('scripts/new.ts:1')
unlinkSync(join(root, 'scripts/new.ts'))
expect(verifyEmptyCatch(root)).toBe(0)
})
it.each(['packages', 'apps', 'scripts', 'website'])('rejects discovery missing %s', (area) => {
const root = fixture()
unlinkSync(join(root, `${area}/seed.ts`))
expect(() => verifyEmptyCatch(root)).toThrow(`source discovery omitted ${area}/`)
})
it('rejects a corpus without any catch clause', () => {
const root = fixture()
for (const area of ['packages', 'apps', 'scripts', 'website']) write(root, `${area}/seed.ts`, 'export {}\n')
expect(() => verifyEmptyCatch(root)).toThrow(/found no catch clause/u)
})
// Creating file symlinks requires privileges that Windows CI does not guarantee.
it.skipIf(process.platform === 'win32')('rejects a source symlink', () => {
const root = fixture()
write(root, 'target.txt', broken)
const link = join(root, 'scripts/linked.ts')
symlinkSync(join(root, 'target.txt'), link)
try {
expect(() => verifyEmptyCatch(root)).toThrow('source symlink is unsupported: scripts/linked.ts')
} finally {
unlinkSync(link)
}
})
})
+199
View File
@@ -0,0 +1,199 @@
/**
* Reject empty `catch` clauses that break the recorded rule, retiring the legacy clauses.
*
* An empty clause — a body whose statements, if any, are all bare `;` — must name the discarded
* error, state in a comment why the error needs no handling, and wrap a `try` holding one
* statement; a wider `try` hides statements whose failures the clause also discards. The reason
* comment may sit anywhere in the clause, between the `try` block and the `catch` keyword, or
* right after the clause on its closing line, before any further token.
*
* A body holding any other statement is out of scope: whether it handles the error is not
* decidable from syntax, so `catch { "use strict" }` and similar no-ops stay legal and the
* specification records that boundary. So is a file the parser cannot read past, which yields
* whatever clauses it recovered; the typecheck covers tracked source. A `try` holding one block or
* one compound statement, such as `if`, counts as one statement.
*
* Legacy clauses that break a condition are recorded in `scripts/empty-catch.baseline.json`. A
* clause's identity covers its syntax tokens and its broken conditions, so turning a recorded
* one-statement `try` into a wider one or deleting a recorded reason is a new finding, while edits
* inside the `try` that keep its conditions are not. Moving a file that holds recorded clauses
* renames its baseline key in the same change.
*/
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import ts from 'typescript'
import {
countInventory,
listInventorySources,
runInventoryGate,
syntaxFingerprint,
verifyInventory,
type InventoryBaseline,
type InventoryGate,
} from './baseline-inventory.ts'
const root = resolve(import.meta.dirname, '..')
/** Existing empty-clause counts, keyed by repository path and clause fingerprint. */
export type EmptyCatchBaseline = InventoryBaseline
/** One condition of the rule that an empty clause breaks. */
export type EmptyCatchDefect = 'unnamed' | 'unexplained' | 'wide-try'
/** One empty `catch` clause that breaks at least one condition. */
export interface EmptyCatch {
/** Repository-relative path with forward slashes. */
file: string
/** One-based line of the `catch` keyword. */
line: number
/** SHA-256 of the clause's syntax tokens, excluding comments and whitespace, and its defects. */
fingerprint: string
/** Broken conditions in {@link EmptyCatchDefect} order. */
defects: readonly EmptyCatchDefect[]
}
/** Findings plus the number of clauses examined, which detects a walk that stopped matching. */
interface EmptyCatchScan {
findings: EmptyCatch[]
clauses: number
}
/**
* Whether a comment states the clause's reason: in the trivia before any token of the clause,
* which starts just after the `try` block so a line above the `catch` keyword belongs to it, or
* after the clause on its closing line before the next token. Reading parsed comment ranges keeps
* comment markers inside strings, templates and regular expressions from counting.
* @param clause - the catch clause whose reason to look for.
* @param source - the file that owns the clause.
* @returns `true` when such a comment exists.
*/
function hasReason(clause: ts.CatchClause, source: ts.SourceFile): boolean {
const hasCommentAt = (position: number): boolean =>
(ts.getLeadingCommentRanges(source.text, position)?.length ?? 0) > 0
|| (ts.getTrailingCommentRanges(source.text, position)?.length ?? 0) > 0
const visit = (node: ts.Node): boolean => {
if (ts.isJSDoc(node)) return true
return ts.isToken(node) ? hasCommentAt(node.pos) : node.getChildren(source).some(visit)
}
return visit(clause) || (ts.getTrailingCommentRanges(source.text, clause.end)?.length ?? 0) > 0
}
/** Names a binding pattern binds, so `catch ({})` names nothing. */
function boundNames(name: ts.BindingName, names: string[]): void {
if (ts.isIdentifier(name)) {
names.push(name.text)
return
}
for (const element of name.elements) {
if (!ts.isOmittedExpression(element)) boundNames(element.name, names)
}
}
/** Bound names of the thrown value; empty for `catch {` and for a pattern that binds nothing. */
function bindingNames(clause: ts.CatchClause): readonly string[] {
const declaration = clause.variableDeclaration
if (declaration === undefined) return []
const names: string[] = []
boundNames(declaration.name, names)
return names
}
/** Statements other than a bare `;`, which cannot stand in for handling an error. */
function nonEmptyStatements(block: ts.Block): readonly ts.Statement[] {
return block.statements.filter(statement => !ts.isEmptyStatement(statement))
}
function analyze(file: string, text: string): EmptyCatchScan {
const normalized = file.replaceAll('\\', '/')
const source = ts.createSourceFile(normalized, text, ts.ScriptTarget.Latest, true)
const findings: EmptyCatch[] = []
let clauses = 0
const visit = (node: ts.Node): void => {
if (ts.isCatchClause(node)) {
clauses += 1
if (nonEmptyStatements(node.block).length === 0) {
const names = bindingNames(node)
const defects: EmptyCatchDefect[] = []
if (!names.some(name => name !== '_')) defects.push('unnamed')
if (!hasReason(node, source)) defects.push('unexplained')
if (!ts.isTryStatement(node.parent) || nonEmptyStatements(node.parent.tryBlock).length !== 1) {
defects.push('wide-try')
}
if (defects.length > 0) {
findings.push({
file: normalized,
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
fingerprint: createHash('sha256')
.update(`${syntaxFingerprint(node, source)}:${defects.join(',')}`)
.digest('hex'),
defects,
})
}
}
}
ts.forEachChild(node, visit)
}
visit(source)
return { findings, clauses }
}
/**
* Find empty catch clauses that break the rule.
* @param file - repository-relative source path; its extension selects the parse mode.
* @param text - source contents.
* @returns findings in AST traversal order; a clause whose body holds a real statement never matches.
*/
export function findEmptyCatches(file: string, text: string): EmptyCatch[] {
return analyze(file, text).findings
}
/**
* Scan tracked source and non-ignored new source, including tests and configuration files.
* @param repoRoot - repository root containing the Git index.
* @returns every empty clause that breaks the rule in the current working tree.
* @throws if discovery omits a required source area, finds no catch clause at all, or an eligible path is a symlink.
*/
export function scanEmptyCatches(repoRoot: string): EmptyCatch[] {
const scans = listInventorySources(repoRoot, 'verify-empty-catch')
.map(file => analyze(file, readFileSync(resolve(repoRoot, file), 'utf8')))
if (scans.every(scan => scan.clauses === 0)) {
throw new Error('verify-empty-catch: source discovery found no catch clause')
}
return scans.flatMap(scan => scan.findings)
}
const gate: InventoryGate<EmptyCatch> = {
name: 'verify-empty-catch',
baselinePath: 'scripts/empty-catch.baseline.json',
scan: scanEmptyCatches,
rejection: 'an empty catch must name the discarded error, state why it needs no handling,'
+ ' and keep its try to one statement (see .agents/skills/dsh-error-handling/SKILL.md#empty-catch-clauses).',
describe: finding => `${finding.file}:${String(finding.line)} (${finding.defects.join(', ')})`,
success: count => `verify-empty-catch: no new silent catches; ${String(count)} recorded clauses remain.`,
}
/**
* Count exact clauses without granting a file-wide allowance.
* @param findings - observed empty clauses.
* @returns path and fingerprint counts in stable order for comparison and pruning.
*/
export function countEmptyCatches(findings: readonly EmptyCatch[]): EmptyCatchBaseline {
return countInventory(findings)
}
/**
* Enforce the recorded clause inventory, optionally deleting retired allowances.
* @param repoRoot - repository root to scan.
* @param prune - remove stale entries only after establishing that no new clause breaks the rule.
* @returns the number of clauses that still break the rule.
* @throws for new broken clauses, malformed inventories, or stale entries without pruning.
*/
export function verifyEmptyCatch(repoRoot: string, prune = false): number {
return verifyInventory(gate, repoRoot, prune)
}
if (import.meta.filename === resolve(process.argv[1] ?? '')) {
runInventoryGate(gate, root)
}
+5 -27
View File
@@ -1,39 +1,17 @@
import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { readFileSync, symlinkSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createInventoryRepo, gitFixture as git, removeInventoryRepos, writeFixture as write } from './baseline-inventory.fixture.ts'
import { countUnknownCasts, findUnknownCasts, scanUnknownCasts, verifyNoUnknownCasts } from './verify-no-unknown-casts.ts'
const roots: string[] = []
const baselinePath = 'scripts/no-unknown-casts.baseline.json'
const sourcePath = 'packages/example/src/index.ts'
const assertion = 'const result = value as unknown\n'
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
function write(root: string, file: string, contents: string): void {
const path = join(root, file)
mkdirSync(dirname(path), { recursive: true })
writeFileSync(path, contents)
}
function git(root: string, ...args: string[]): void {
execFileSync('git', args, { cwd: root, stdio: 'pipe' })
}
afterEach(removeInventoryRepos)
function fixture(): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-unknown-casts-'))
roots.push(root)
git(root, 'init', '--quiet')
for (const area of ['packages', 'apps', 'scripts', 'website']) {
write(root, `${area}/seed.ts`, 'export {}\n')
}
write(root, baselinePath, '{}\n')
git(root, 'add', '.')
return root
return createInventoryRepo(baselinePath, 'export {}\n')
}
function recordBaseline(root: string): string {
+23 -104
View File
@@ -1,16 +1,22 @@
/** Reject new assertions to unknown while retiring the recorded existing assertions. */
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { lstatSync, readFileSync, writeFileSync } from 'node:fs'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import ts from 'typescript'
import {
countInventory,
listInventorySources,
runInventoryGate,
syntaxFingerprint,
verifyInventory,
type InventoryBaseline,
type InventoryGate,
} from './baseline-inventory.ts'
const root = resolve(import.meta.dirname, '..')
const baselinePath = 'scripts/no-unknown-casts.baseline.json'
/** Existing assertion counts, keyed by repository path and syntax fingerprint. */
export type UnknownCastBaseline = Record<string, Record<string, number>>
export type UnknownCastBaseline = InventoryBaseline
/** One direct assertion to unknown in authored source. */
export interface UnknownCast {
@@ -22,17 +28,6 @@ export interface UnknownCast {
fingerprint: string
}
function syntaxFingerprint(node: ts.Node, source: ts.SourceFile): string {
const tokens: string[] = []
const visit = (child: ts.Node): void => {
if (ts.isJSDoc(child)) return
if (ts.isToken(child)) tokens.push(child.getText(source))
else child.getChildren(source).forEach(visit)
}
visit(node)
return createHash('sha256').update(JSON.stringify(tokens)).digest('hex')
}
function assertsUnknown(type: ts.TypeNode): boolean {
if (ts.isParenthesizedTypeNode(type)) return assertsUnknown(type.type)
return type.kind === ts.SyntaxKind.UnknownKeyword
@@ -65,12 +60,6 @@ export function findUnknownCasts(file: string, text: string): UnknownCast[] {
return casts
}
function isSource(file: string): boolean {
return /\.(?:[cm]?[jt]s|[jt]sx)$/u.test(file)
&& !file.startsWith('vendor/')
&& !file.startsWith('.agents/notes/archived/')
}
/**
* Scan tracked source and non-ignored new source, including tests and configuration files.
* @param repoRoot - repository root containing the Git index.
@@ -78,47 +67,17 @@ function isSource(file: string): boolean {
* @throws if discovery omits a required source area or an eligible path is a symlink.
*/
export function scanUnknownCasts(repoRoot: string): UnknownCast[] {
const files = [...new Set(execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard', '-z'], {
cwd: repoRoot,
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
}).split('\0').map(file => file.replaceAll('\\', '/')).filter(isSource))].sort()
const present = files.filter((file) => {
const stat = lstatSync(resolve(repoRoot, file), { throwIfNoEntry: false })
if (stat?.isSymbolicLink()) throw new Error(`verify-no-unknown-casts: source symlink is unsupported: ${file}`)
return stat?.isFile() === true
})
for (const area of ['packages/', 'apps/', 'scripts/', 'website/']) {
if (!present.some(file => file.startsWith(area))) {
throw new Error(`verify-no-unknown-casts: source discovery omitted ${area}`)
}
}
return present.flatMap(file => findUnknownCasts(file, readFileSync(resolve(repoRoot, file), 'utf8')))
return listInventorySources(repoRoot, 'verify-no-unknown-casts')
.flatMap(file => findUnknownCasts(file, readFileSync(resolve(repoRoot, file), 'utf8')))
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function readBaseline(repoRoot: string): UnknownCastBaseline {
const value: unknown = JSON.parse(readFileSync(resolve(repoRoot, baselinePath), 'utf8'))
if (!isRecord(value)) throw new Error('verify-no-unknown-casts: baseline must be a file-to-counts object')
const baseline: UnknownCastBaseline = {}
for (const [file, counts] of Object.entries(value)) {
if (!isSource(file) || file.startsWith('/') || file.includes('\\') || file.split('/').includes('..')
|| !isRecord(counts) || Object.keys(counts).length === 0) {
throw new Error(`verify-no-unknown-casts: invalid baseline file: ${file}`)
}
const parsed: Record<string, number> = {}
for (const [fingerprint, count] of Object.entries(counts)) {
if (!/^[a-f0-9]{64}$/u.test(fingerprint) || typeof count !== 'number' || !Number.isSafeInteger(count) || count <= 0) {
throw new Error(`verify-no-unknown-casts: invalid baseline count: ${file}:${fingerprint}`)
}
parsed[fingerprint] = count
}
baseline[file] = parsed
}
return baseline
const gate: InventoryGate<UnknownCast> = {
name: 'verify-no-unknown-casts',
baselinePath: 'scripts/no-unknown-casts.baseline.json',
scan: scanUnknownCasts,
rejection: 'new assertions to unknown are forbidden. Use a typed value or narrow the input.',
describe: cast => `${cast.file}:${String(cast.line)} (${cast.fingerprint})`,
success: count => `verify-no-unknown-casts: no new assertions; ${String(count)} existing assertions remain.`,
}
/**
@@ -127,13 +86,7 @@ function readBaseline(repoRoot: string): UnknownCastBaseline {
* @returns path and fingerprint counts in stable order for comparison and pruning.
*/
export function countUnknownCasts(casts: readonly UnknownCast[]): UnknownCastBaseline {
const baseline: UnknownCastBaseline = {}
for (const { file, fingerprint } of casts) {
const counts = baseline[file] ??= {}
counts[fingerprint] = (counts[fingerprint] ?? 0) + 1
}
return Object.fromEntries(Object.entries(baseline).sort(([a], [b]) => a.localeCompare(b))
.map(([file, counts]) => [file, Object.fromEntries(Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)))]))
return countInventory(casts)
}
/**
@@ -144,43 +97,9 @@ export function countUnknownCasts(casts: readonly UnknownCast[]): UnknownCastBas
* @throws for new assertions, malformed inventories, or stale entries without pruning.
*/
export function verifyNoUnknownCasts(repoRoot: string, prune = false): number {
const baseline = readBaseline(repoRoot)
const casts = scanUnknownCasts(repoRoot)
const current = countUnknownCasts(casts)
const remaining = structuredClone(baseline)
const added: UnknownCast[] = []
for (const cast of casts) {
const counts = remaining[cast.file]
const allowance = counts?.[cast.fingerprint] ?? 0
if (counts !== undefined && allowance > 0) counts[cast.fingerprint] = allowance - 1
else added.push(cast)
}
if (added.length > 0) {
throw new Error('verify-no-unknown-casts: new assertions to unknown are forbidden. Use a typed value or narrow the input.\n'
+ added.map(cast => ` ${cast.file}:${String(cast.line)} (${cast.fingerprint})`).join('\n'))
}
const stale = Object.entries(remaining).flatMap(([file, counts]) => Object.entries(counts)
.filter(([, count]) => count > 0).map(([fingerprint]) => ` ${file} (${fingerprint})`))
if (stale.length > 0) {
if (!prune) {
throw new Error('verify-no-unknown-casts: remove retired baseline entries with pnpm run verify-no-unknown-casts --prune.\n'
+ stale.join('\n'))
}
writeFileSync(resolve(repoRoot, baselinePath), `${JSON.stringify(current, null, 2)}\n`)
}
return casts.length
return verifyInventory(gate, repoRoot, prune)
}
if (import.meta.filename === resolve(process.argv[1] ?? '')) {
try {
const args = process.argv.slice(2)
if (args.length > 1 || (args.length === 1 && args[0] !== '--prune')) {
throw new Error('Usage: pnpm run verify-no-unknown-casts [--prune]')
}
const count = verifyNoUnknownCasts(root, args[0] === '--prune')
console.log(`verify-no-unknown-casts: no new assertions; ${String(count)} existing assertions remain.`)
} catch (error) {
console.error(error instanceof Error ? error.message : String(error))
process.exitCode = 1
}
runInventoryGate(gate, root)
}
@@ -103,7 +103,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/ptc-runtime/ptc-runtime': { kind: 'indirect', reason: 'The service interface delegates model rendering to PTC mode in dsh-tools.' },
'packages/core/agent-tool-presentation': { kind: 'indirect', reason: 'The row only selects between the two projections dsh-tools owns; it registers no prompt, schema, or result of its own.' },
'packages/ptc-runtime/ptc-runtime-node': { kind: 'indirect', reason: 'The Node process backend delegates model rendering to PTC mode in dsh-tools.' },
'packages/experimental/ptc-runtime-python': { kind: 'indirect', reason: 'Explicit source-checkout compositions delegate model rendering to PTC mode in dsh-tools.' },
'packages/client/ui-agent-preset': { kind: 'indirect', reason: 'Browser-side settings row; the preset it selects owns every model-facing effect.' },
'packages/util/crypto': { kind: 'indirect', reason: 'Pure identifier minting; the ids consumers mint with it never enter prompts as semantic content.' },
'packages/util/deque': { kind: 'none', reason: 'In-process collection primitive; registers nothing model-facing.' },
@@ -136,6 +135,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/client/store': { kind: 'none', reason: 'Browser-side state primitives; register nothing model-facing.' },
'packages/client/ui-renderer': { kind: 'none', reason: 'Browser-side render assembly; registers nothing model-facing.' },
'packages/client/ui-session': { kind: 'none', reason: 'Browser-side Session adapter; registers nothing model-facing.' },
'packages/client/ui-session-status': { kind: 'none', reason: 'Browser-side Session status table; registers nothing model-facing.' },
'packages/client/connection': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/file-upload': { kind: 'none', reason: 'Browser-side request-body transport; registers nothing model-facing.' },
'packages/api/remotes': { kind: 'none', reason: 'The Remote BFF selects business methods and forwarded events; selected services own any model-visible effect.' },