Merge branch 'stack/agent-profiles-3-wire' into stack/agent-profiles-5-web-ui

The Client API carrier's `agentPresets` member was the one member of its class
without an `IApiClient[...]` annotation. Inferring it inlined `AgentPresetEntry`
into the emitted declaration by the specifier TS picks — the host `index.ts` —
dragging the whole gateway, and with it the host `Context` merges, into every
Client program importing the carrier. Annotated like its siblings.

`ApiRemoteAgentOptions.setup` now takes the inspected session rather than its
header alone: this layer resolves a resumed session's preset from the LOG,
because a session that switched while blank ran its turns under the newer
composition and the header is written once at creation.

Conflicts:
	apps/web/tests/snapshots/*/*.expected.md
	packages/client/ui-conversation/src/client/skeleton/InputBar.tsx
	packages/host/apiproxy/src/api-proxy.ts
	scripts/doc-budgets.manifest.json
This commit is contained in:
Yichen Jiang committed 2026-08-08 15:00:31 +08:00
commit beec364e04
649 files changed
+21091 -2838

No files matched your search

+34 -2
View File
@@ -7,7 +7,8 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { join, relative, resolve } from 'node:path'
import { isForbiddenPublicationFile } from './publication-payload.ts'
import { hasTypeRTRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts'
const root = resolve(import.meta.dirname, '..')
// vendor/* is single-level; packages/<group>/<pkg> nests one level deeper
@@ -122,6 +123,7 @@ function sameStringList(actual: readonly string[] | undefined, expected: readonl
function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
const extras = manifest.name ? packageFileExtras[manifest.name] ?? [] : []
const typeRTRemoteNavigation = hasTypeRTRemoteNavigation(manifest)
return [
'lib/index.js',
// Every package publishes its invariant ownership companion as a separate
@@ -145,9 +147,37 @@ function expectedDshPackageFiles(manifest: PackageManifest): readonly string[] {
// declarations.
...usesEmittedTreeDefaults(manifest) ? ['lib/types/**/*.js'] : [],
'lib/types/**/*.d.ts',
...hasExportPair(manifest, './typert', './lib/typert.host.d.ts', './lib/typert.host.js')
? ['lib/typert.host.js', 'lib/typert.host.d.ts']
: [],
...hasExportPair(manifest, './client/typert', './lib/typert.client.d.ts', './lib/typert.client.js')
? ['lib/typert.client.js', 'lib/typert.client.d.ts']
: [],
...typeRTRemoteNavigation
? [
'lib/typert.remote-client.js',
'lib/typert.remote-client.d.ts',
'lib/typert.remote-client.d.ts.map',
'src',
]
: [],
]
}
/** Whether one conditional export exactly names the generated runtime and declaration pair. */
function hasExportPair(
manifest: PackageManifest,
subpath: string,
types: string,
runtime: string,
): boolean {
const entry = manifest.exports?.[subpath]
return typeof entry === 'object'
&& entry !== null
&& entry.types === types
&& entry.default === runtime
}
/** Runtime target of an export entry: conditional `default`, or the bare-string shorthand. */
function exportDefault(manifest: PackageManifest, subpath: string): string | undefined {
const entry = manifest.exports?.[subpath]
@@ -175,8 +205,9 @@ function checkWorkspace({ dir, manifest }: WorkspaceManifest): string[] {
}
if (manifest.name?.startsWith('@deepseek-ai/')) {
const publicationPolicy = { typeRTRemoteNavigation: hasTypeRTRemoteNavigation(manifest) }
for (const file of manifest.files ?? []) {
if (isForbiddenPublicationFile(file)) {
if (isForbiddenPublicationFile(file, publicationPolicy)) {
errors.push(`${label}: package.json files must not publish ${JSON.stringify(file)}`)
}
}
@@ -275,6 +306,7 @@ const errors = [
...checkRepositoryVersion(),
...workspaceManifests().flatMap(checkWorkspace),
...checkHierarchyShape(),
...collectProjectReferenceFaceViolations(root),
]
if (errors.length > 0) {
console.error(errors.join('\n'))
+7 -2
View File
@@ -15,8 +15,13 @@ interface CssPlugin {
}
function cssPlugin(): CssPlugin {
const configs = clientBundle('@deepseek-ai/dsh-client-test', ['lib/types/index.js', 'lib/types/invariant.js'])
const plugins = (configs[1] as { plugins: CssPlugin[] }).plugins
const configs = clientBundle(
'@deepseek-ai/dsh-client-test',
['lib/types/index.js', 'lib/types/invariant.js'],
)({ env: { DSH_BUILD_FACE: 'client' } })
const client = configs.find(config => config.platform === 'browser')
if (client === undefined) throw new Error('client config missing')
const plugins = (client as { plugins: CssPlugin[] }).plugins
const plugin = plugins.find(candidate => candidate.name === 'dsh-css-modules-inline')
if (plugin === undefined) throw new Error('CSS Modules plugin missing from client config')
return plugin
+37 -12
View File
@@ -14,6 +14,24 @@ interface CssModulePlugin {
load?: (this: { addWatchFile: (id: string) => void }, id: string) => Promise<unknown>
}
function clientConfigs(id = '@deepseek-ai/dsh-client-test') {
return clientBundle(id, ['lib/types/index.js', 'lib/types/invariant.js'])(
{ env: { DSH_BUILD_FACE: 'client' } },
).filter(config => config.platform === 'browser')
}
describe('client bundle build faces', () => {
it('watches source in development and consumes emitted JavaScript in the Client build', () => {
const bundle = clientBundle('@deepseek-ai/dsh-client-test', ['lib/types/index.js'])
const development = bundle({ env: {} }).find(config => config.platform === 'browser')
const artifact = bundle({ env: { DSH_BUILD_FACE: 'client' } })
.find(config => config.platform === 'browser')
expect(development?.entry).toEqual({ client: 'src/client/index.ts' })
expect(artifact?.entry).toEqual({ client: 'lib/types/client/index.js' })
})
})
function clientSourceMapPath(packagePath: string): string {
return fileURLToPath(new URL(`../packages/${packagePath}/lib/client.js.map`, import.meta.url))
}
@@ -21,16 +39,16 @@ function clientSourceMapPath(packagePath: string): string {
function purityResolveId(): ResolveId {
// libEntry is spelled at every call site (no default) so the
// package-invariants text check can see the invariant entry per package.
const configs = clientBundle('@deepseek-ai/dsh-client-test', ['lib/types/index.js', 'lib/types/invariant.js'])
const plugins = (configs[1] as { plugins: { name: string; resolveId?: unknown }[] }).plugins
const configs = clientConfigs()
const plugins = (configs[0] as { plugins: { name: string; resolveId?: unknown }[] }).plugins
const gate = plugins.find(p => p.name === 'dsh-client-bundle-purity')
if (gate?.resolveId === undefined) throw new Error('purity plugin missing from client config')
return gate.resolveId as ResolveId
}
function cssModulePlugin(): CssModulePlugin {
const configs = clientBundle('@deepseek-ai/dsh-client-test', ['lib/types/index.js', 'lib/types/invariant.js'])
const plugins = (configs[1] as { plugins: CssModulePlugin[] }).plugins
const configs = clientConfigs()
const plugins = (configs[0] as { plugins: CssModulePlugin[] }).plugins
const plugin = plugins.find(candidate => candidate.name === 'dsh-css-modules-inline')
if (plugin?.resolveId === undefined || plugin.load === undefined) {
throw new Error('CSS Modules plugin missing from client config')
@@ -59,6 +77,13 @@ describe('client bundle purity gate', () => {
expect(resolveId('@deepseek-ai/dsh-brand')).toBeNull()
})
it('lets exact generated Remote contributions inline without admitting their package implementation', () => {
expect(resolveId('@deepseek-ai/dsh-goal/remote')).toBeNull()
expect(() => resolveId('@deepseek-ai/dsh-goal')).toThrow(/purity/)
expect(() => resolveId('@deepseek-ai/dsh-goal/client')).toThrow(/purity/)
expect(() => resolveId('@deepseek-ai/dsh-goal/remote/nested')).toThrow(/purity/)
})
it('throws on any other @deepseek-ai leak', () => {
expect(() => resolveId('@deepseek-ai/dsh-agent')).toThrow(/purity/)
expect(() => resolveId('@deepseek-ai/dsh-client-web')).toThrow(/purity/)
@@ -80,13 +105,13 @@ describe('client bundle purity gate', () => {
describe('client bundle debug artifacts', () => {
it('emits source maps for plugin TS and TSX outside the Vite module graph', () => {
const configs = clientBundle('@deepseek-ai/dsh-client-test', ['lib/types/index.js', 'lib/types/invariant.js'])
expect(configs[1]?.sourcemap).toBe(true)
const configs = clientConfigs()
expect(configs[0]?.sourcemap).toBe(true)
})
it('maps first-party sources to their repository package paths', () => {
const configs = clientBundle('@deepseek-ai/dsh-client-ui-goal', ['lib/types/index.js', 'lib/types/invariant.js'])
const outputOptions = configs[1]?.outputOptions
const configs = clientConfigs('@deepseek-ai/dsh-client-ui-goal')
const outputOptions = configs[0]?.outputOptions
if (typeof outputOptions !== 'object' || outputOptions === null) throw new Error('client output options missing')
const transform = outputOptions.sourcemapPathTransform
if (transform === undefined) throw new Error('client sourcemap path transform missing')
@@ -98,8 +123,8 @@ describe('client bundle debug artifacts', () => {
})
it('maps dual-face host sources to the host package group', () => {
const configs = clientBundle('@deepseek-ai/dsh-host-directory-picker-native', ['lib/types/index.js'])
const outputOptions = configs[1]?.outputOptions
const configs = clientConfigs('@deepseek-ai/dsh-host-directory-picker-native')
const outputOptions = configs[0]?.outputOptions
if (typeof outputOptions !== 'object' || outputOptions === null) throw new Error('client output options missing')
const transform = outputOptions.sourcemapPathTransform
if (transform === undefined) throw new Error('client sourcemap path transform missing')
@@ -109,8 +134,8 @@ describe('client bundle debug artifacts', () => {
})
it('maps inlined workspace sources to packages and leaves dependencies outside it unchanged', () => {
const configs = clientBundle('@deepseek-ai/dsh-client-connection', ['lib/types/index.js'])
const outputOptions = configs[1]?.outputOptions
const configs = clientConfigs('@deepseek-ai/dsh-client-connection')
const outputOptions = configs[0]?.outputOptions
if (typeof outputOptions !== 'object' || outputOptions === null) throw new Error('client output options missing')
const transform = outputOptions.sourcemapPathTransform
if (transform === undefined) throw new Error('client sourcemap path transform missing')
+1 -7
View File
@@ -22,13 +22,7 @@ export default defineConfig({
const bundlePath = join(root, 'lib/client.js')
await writeFile(sourcePath, 'export const version = "watch-v1"\n')
bundles = await watchClientPlugins(root, ['.'], 50)
await expect.poll(async () => {
try {
return (await readFile(bundlePath, 'utf8')).includes('watch-v1')
} catch {
return false
}
}, { timeout: 10_000 }).toBe(true)
expect(await readFile(bundlePath, 'utf8')).toContain('watch-v1')
await new Promise(resolve => setTimeout(resolve, 1_000))
await writeFile(sourcePath, `export const version = "watch-v2-${'x'.repeat(100)}"\n`)
+21 -2
View File
@@ -47,21 +47,40 @@ export function discoverPluginDirs(root = repoRoot): string[] {
* @param root - repository or fixture root passed to tsdown.
* @param pluginDirs - workspace-relative package directories to watch.
* @param pollInterval - optional source-watcher polling interval in milliseconds.
* @returns live bundles whose async disposers stop every watcher.
* @returns live bundles after every watcher has completed its initial build.
*/
export async function watchClientPlugins(
root: string,
pluginDirs: readonly string[],
pollInterval?: number,
): Promise<TsdownBundle[]> {
return build({
let resolveInitialBuilds: (() => void) | undefined
const initialBuilds = new Promise<void>((resolve) => { resolveInitialBuilds = resolve })
const initialized = new WeakSet<object>()
const readiness: { expectedBuilds?: number; initializedBuilds: number } = { initializedBuilds: 0 }
const bundles = await build({
cwd: root,
workspace: [...pluginDirs],
watch: true,
hooks: {
'build:done': ({ options }) => {
if (initialized.has(options)) return
initialized.add(options)
readiness.initializedBuilds += 1
if (
readiness.expectedBuilds !== undefined
&& readiness.initializedBuilds >= readiness.expectedBuilds
) resolveInitialBuilds?.()
},
},
...pollInterval !== undefined
? { inputOptions: { watch: { watcher: { usePolling: true, pollInterval } } } }
: {},
})
readiness.expectedBuilds = bundles.length
if (readiness.initializedBuilds >= readiness.expectedBuilds) resolveInitialBuilds?.()
await initialBuilds
return bundles
}
const invokedPath = process.argv[1]
+3 -4
View File
@@ -136,10 +136,9 @@ function formatDiagnostics(diagnostics: readonly ts.Diagnostic[], blocks: Block[
}
/**
* Reuse the host-aggregate references from a temp project one directory below
* root. Doc fragments speak the host vocabulary, so the standalone project
* seeds tsconfig.host.json (never the root solution: flattening host+client
* into one program collides the cordis Context merges).
* Reuse the Host aggregate references from a temp project one directory below
* root. Generated Client API examples opt out because their declarations do
* not exist until Host tsdown has run.
*/
function workspaceReferences(): { path: string }[] {
const file = join(root, 'tsconfig.host.json')
+3
View File
@@ -90,6 +90,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
FsWriteIntent: 'filesystem.md',
FsWriteOutcome: 'filesystem.md',
CreateGoalRequest: 'goal.md',
CreateGoalResult: 'goal.md',
EditGoalRequest: 'goal.md',
GoalBlockReason: 'goal.md',
GoalChanged: 'goal.md',
@@ -277,6 +278,7 @@ export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
TypertPackageRecord: 'registry package record is owned by packages/typert/registry/README.md',
TypertSchemaFilter: 'registry schema query filter is owned by packages/typert/registry/README.md',
TypertSchemaRecord: 'registry schema record is owned by packages/typert/registry/README.md',
TypeRTDisposer: 'TypeRT lifecycle contract is owned by packages/typert/type-meta/README.md',
'z.core.JSONSchema.BaseSchema': 'zod projection output is owned by the zod v4 API',
'z.core.ToJSONSchemaParams': 'zod projection parameters are owned by the zod v4 API',
InvariantInstaller: 'service-local contribution contract is owned by packages/support/invariants/README.md',
@@ -288,6 +290,7 @@ export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
ThemeTokens: 'service-local token dictionary is owned by packages/client/ui-theme/src/index.ts',
Translate: 'service-local bound translator is owned by packages/client/i18n/src/index.ts',
InvariantRegistration: 'service-local lifecycle handle is owned by packages/support/invariants/README.md',
InvokeRemoteRequest: 'gateway invocation contract is owned by packages/api/gateway/README.md',
PresetOption: 'deployment menu metadata is owned by packages/ui/permission/README.md',
PresetSpec: 'deployment preset composition is owned by packages/ui/permission/README.md',
KnobState: 'projection unit state shape is owned by packages/ui/permission/README.md',
+9 -2
View File
@@ -140,8 +140,15 @@ const SERVICE_ROLES: ServiceRole[] = [
pkg: 'typert-registry',
title: 'Runtime type registry',
mode: 'core',
consumers: ['typert-loader'],
note: 'Plugins register live zod contributions directly or through dsh-typert-loader; runtime consumers query schemas and reflection metadata at their own edges.',
consumers: ['typert-loader', 'api-gateway'],
note: 'Plugins register live zod contributions directly or through dsh-typert-loader; the API gateway consumes invocation descriptors and providers, while other runtime consumers query schemas and reflection metadata at their own edges.',
},
{
key: 'typertGateway',
pkg: 'api-gateway',
title: 'TypeRT Host invocation gateway',
mode: 'core',
note: 'Associates generated Remote descriptors with live Cordis services, resolves registered identities, and exposes unary calls through the shared Connection RPC carrier.',
},
{
key: 'sessionPersistence',
+14
View File
@@ -72,6 +72,20 @@ describe('package invariant gate', () => {
expect(collectPackageInvariantViolations(fixture())).toEqual([])
})
it('accepts an invariant reference owned by a package-local leaf project', () => {
const root = fixture({ invariantReference: false })
const dir = join(root, 'packages/core/probe')
writeFileSync(join(dir, 'tsconfig.json'), `${JSON.stringify({
files: [],
references: [{ path: './tsconfig.host.json' }],
}, null, 2)}\n`)
writeFileSync(join(dir, 'tsconfig.host.json'), `${JSON.stringify({
references: [{ path: '../../support/invariants' }],
}, null, 2)}\n`)
expect(collectPackageInvariantViolations(root)).toEqual([])
})
it('rejects missing publication metadata and build output', () => {
const violations = collectPackageInvariantViolations(fixture({
invariantExport: false,
+26 -4
View File
@@ -118,11 +118,8 @@ function checkBuild(
violations: PackageInvariantViolation[],
): void {
const tsconfigPath = `${owner.dir}/tsconfig.json`
const tsconfig = JSON.parse(readFileSync(resolve(root, tsconfigPath), 'utf8')) as {
references?: Array<{ path?: string }>
}
if (owner.packageName !== '@deepseek-ai/dsh-invariants'
&& !tsconfig.references?.some(reference => reference.path === '../../support/invariants')) {
&& !projectReferencesInvariants(root, owner.dir, tsconfigPath)) {
addViolation(
violations,
tsconfigPath,
@@ -138,6 +135,31 @@ function checkBuild(
}
}
function projectReferencesInvariants(root: string, ownerDir: string, entryPath: string): boolean {
const ownerRoot = resolve(root, ownerDir)
const target = resolve(root, 'packages/support/invariants')
const pending = [resolve(root, entryPath)]
const visited = new Set<string>()
while (pending.length > 0) {
const configPath = pending.pop()
if (configPath === undefined) break
if (visited.has(configPath)) continue
visited.add(configPath)
const config = JSON.parse(readFileSync(configPath, 'utf8')) as {
references?: Array<{ path?: string }>
}
for (const reference of config.references ?? []) {
if (reference.path === undefined) continue
const referenced = resolve(dirname(configPath), reference.path)
if (referenced === target) return true
if (!referenced.startsWith(`${ownerRoot}${sep}`)) continue
const childConfig = referenced.endsWith('.json') ? referenced : resolve(referenced, 'tsconfig.json')
if (existsSync(childConfig)) pending.push(childConfig)
}
}
return false
}
function checkSource(
owner: PackageInvariantOwner,
root: string,
+100
View File
@@ -0,0 +1,100 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { collectProjectReferenceFaceViolations } from './project-reference-faces.ts'
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
function writeJson(path: string, value: unknown): void {
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`)
}
function workspaceFixture(options: {
readonly host: readonly string[]
readonly client: readonly string[]
}): string {
const root = mkdtempSync(join(tmpdir(), 'dsh-project-reference-faces-'))
roots.push(root)
const shared = join(root, 'packages/core/shared')
const split = join(root, 'packages/api/split')
mkdirSync(shared, { recursive: true })
mkdirSync(split, { recursive: true })
writeJson(join(root, 'tsconfig.base.json'), {})
writeJson(join(root, 'tsconfig.base.client.json'), { extends: './tsconfig.base.json' })
writeJson(join(shared, 'package.json'), { name: '@deepseek-ai/dsh-shared' })
writeJson(join(shared, 'tsconfig.json'), {
extends: '../../../tsconfig.base.json',
references: [],
})
writeJson(join(split, 'package.json'), { name: '@deepseek-ai/dsh-split' })
writeJson(join(split, 'tsconfig.json'), {
files: [],
references: [{ path: './tsconfig.host.json' }, { path: './tsconfig.client.json' }],
})
writeJson(join(split, 'tsconfig.host.json'), { references: [{ path: '../../core/shared' }] })
writeJson(join(split, 'tsconfig.client.json'), { references: [{ path: '../../core/shared' }] })
writeJson(join(root, 'tsconfig.host.json'), {
references: options.host.map(path => ({ path })),
})
writeJson(join(root, 'tsconfig.client.json'), {
references: options.client.map(path => ({ path })),
})
return root
}
describe('Project Reference compiler faces', () => {
it('allows neutral projects in either graph and matching split leaves', () => {
const root = workspaceFixture({
host: ['./packages/core/shared', './packages/api/split/tsconfig.host.json'],
client: ['./packages/core/shared', './packages/api/split/tsconfig.client.json'],
})
expect(collectProjectReferenceFaceViolations(root)).toEqual([])
})
it('rejects the opposite leaf and the solution root of a split project', () => {
const root = workspaceFixture({
host: [
'./packages/api/split/tsconfig.host.json',
'./packages/api/split/tsconfig.client.json',
],
client: ['./packages/api/split'],
})
expect(collectProjectReferenceFaceViolations(root)).toEqual([
'tsconfig.client.json: Project Reference "./packages/api/split" enters split project packages/api/split from a Client config; reference "packages/api/split/tsconfig.client.json" instead',
'tsconfig.host.json: Project Reference "./packages/api/split/tsconfig.client.json" enters split project packages/api/split from a Host config; reference "packages/api/split/tsconfig.host.json" instead',
])
})
it('uses the referencing project face throughout the reachable graph', () => {
const root = workspaceFixture({
host: ['./packages/core/host-consumer'],
client: ['./packages/core/client-consumer'],
})
const hostConsumer = join(root, 'packages/core/host-consumer')
mkdirSync(hostConsumer, { recursive: true })
writeJson(join(hostConsumer, 'package.json'), { name: '@deepseek-ai/dsh-host-consumer' })
writeJson(join(hostConsumer, 'tsconfig.json'), {
extends: '../../../tsconfig.base.json',
references: [{ path: '../../api/split/tsconfig.client.json' }],
})
const clientConsumer = join(root, 'packages/core/client-consumer')
mkdirSync(clientConsumer, { recursive: true })
writeJson(join(clientConsumer, 'package.json'), { name: '@deepseek-ai/dsh-client-consumer' })
writeJson(join(clientConsumer, 'tsconfig.json'), {
extends: '../../../tsconfig.base.client.json',
references: [{ path: '../../api/split/tsconfig.host.json' }],
})
expect(collectProjectReferenceFaceViolations(root)).toEqual([
'packages/core/client-consumer/tsconfig.json: Project Reference "../../api/split/tsconfig.host.json" enters split project packages/api/split from a Client config; reference "packages/api/split/tsconfig.client.json" instead',
'packages/core/host-consumer/tsconfig.json: Project Reference "../../api/split/tsconfig.client.json" enters split project packages/api/split from a Host config; reference "packages/api/split/tsconfig.host.json" instead',
])
})
})
+129
View File
@@ -0,0 +1,129 @@
/** Validate compiler-face isolation across workspace Project Reference graphs. */
import { existsSync, globSync } from 'node:fs'
import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path'
import ts from 'typescript'
type ProjectFace = 'host' | 'client'
interface ProjectReferenceConfig {
readonly extends?: unknown
readonly references?: ReadonlyArray<{ readonly path?: unknown }>
}
const WORKSPACE_MANIFESTS = [
'packages/*/*/package.json',
'apps/*/package.json',
'vendor/*/package.json',
] as const
/**
* Find references that enter the wrong leaf of a split Host/Client project.
*
* A single-config project is neutral and may participate in either graph. Once
* a package declares both face configs, every reachable reference must name
* the leaf matching the aggregate from which traversal began.
*
* @param root - Repository root containing both aggregate tsconfigs.
* @returns Repo-relative diagnostics for every mismatched reference edge.
*/
export function collectProjectReferenceFaceViolations(root: string): string[] {
const splitRoots = splitProjectRoots(root)
const violations: string[] = []
const pending = [resolve(root, 'tsconfig.host.json'), resolve(root, 'tsconfig.client.json')]
const visited = new Set<string>()
for (let configPath = pending.pop(); configPath !== undefined; configPath = pending.pop()) {
if (visited.has(configPath) || !existsSync(configPath)) continue
visited.add(configPath)
const config = projectConfig(root, configPath)
const face = projectFace(root, configPath, config)
for (const reference of projectReferences(config)) {
const targetConfig = referenceConfigPath(configPath, reference)
const splitRoot = containingSplitRoot(splitRoots, targetConfig)
if (splitRoot !== undefined) {
if (face === undefined) {
violations.push(
`${repoPath(root, configPath)}: Project Reference ${JSON.stringify(reference)} enters split project ${repoPath(root, splitRoot)} from a config with no Host/Client face`,
)
continue
}
const expected = resolve(splitRoot, `tsconfig.${face}.json`)
if (targetConfig !== expected) {
violations.push(
`${repoPath(root, configPath)}: Project Reference ${JSON.stringify(reference)} enters split project ${repoPath(root, splitRoot)} from a ${faceLabel(face)} config; reference ${JSON.stringify(repoPath(root, expected))} instead`,
)
continue
}
}
pending.push(targetConfig)
}
}
return violations.sort()
}
function splitProjectRoots(root: string): string[] {
return globSync(WORKSPACE_MANIFESTS, { cwd: root })
.map(manifest => resolve(root, dirname(manifest)))
.filter(dir => existsSync(resolve(dir, 'tsconfig.host.json'))
&& existsSync(resolve(dir, 'tsconfig.client.json')))
.sort((left, right) => right.length - left.length)
}
function projectConfig(root: string, configPath: string): ProjectReferenceConfig {
const read = ts.readConfigFile(configPath, path => ts.sys.readFile(path))
if (read.error !== undefined) {
const message = ts.flattenDiagnosticMessageText(read.error.messageText, '\n')
throw new Error(`${repoPath(root, configPath)}: ${message}`)
}
return read.config as ProjectReferenceConfig
}
function projectReferences(config: ProjectReferenceConfig): string[] {
return (config.references ?? [])
.map(reference => reference.path)
.filter((path): path is string => typeof path === 'string')
}
function projectFace(
root: string,
configPath: string,
config: ProjectReferenceConfig,
seen = new Set<string>(),
): ProjectFace | undefined {
if (basename(configPath) === 'tsconfig.host.json') return 'host'
if (basename(configPath) === 'tsconfig.client.json') return 'client'
if (configPath === resolve(root, 'tsconfig.base.json')) return 'host'
if (configPath === resolve(root, 'tsconfig.base.client.json')) return 'client'
if (seen.has(configPath)) return undefined
seen.add(configPath)
const parent = localExtendsConfig(configPath, config.extends)
if (parent === undefined || !existsSync(parent)) return undefined
return projectFace(root, parent, projectConfig(root, parent), seen)
}
function localExtendsConfig(configPath: string, value: unknown): string | undefined {
if (typeof value !== 'string' || !value.startsWith('.')) return undefined
const target = resolve(dirname(configPath), value)
return target.endsWith('.json') ? target : `${target}.json`
}
function referenceConfigPath(sourceConfig: string, reference: string): string {
const target = resolve(dirname(sourceConfig), reference)
return target.endsWith('.json') ? target : resolve(target, 'tsconfig.json')
}
function containingSplitRoot(splitRoots: readonly string[], targetConfig: string): string | undefined {
return splitRoots.find((root) => {
const path = relative(root, targetConfig)
return path !== '..' && !path.startsWith(`..${sep}`) && !isAbsolute(path)
})
}
function repoPath(root: string, path: string): string {
return relative(root, path).split(sep).join('/')
}
function faceLabel(face: ProjectFace): string {
return face === 'host' ? 'Host' : 'Client'
}
+30 -1
View File
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest'
import { isForbiddenPublicationFile, validateTarballPayload } from './publication-payload.ts'
import {
hasTypeRTRemoteNavigation,
isForbiddenPublicationFile,
validateTarballPayload,
} from './publication-payload.ts'
function validateFixtureTarball(files: readonly string[]): () => void {
return () => {
@@ -51,4 +55,29 @@ describe('publication payload policy', () => {
'package/lib/styles/base.css',
])).not.toThrow()
})
it('allows only the TypeRT declaration map and its navigable source tree when requested', () => {
const policy = { typeRTRemoteNavigation: true }
expect(isForbiddenPublicationFile('src/index.ts', policy)).toBe(false)
expect(isForbiddenPublicationFile('lib/typert.remote-client.d.ts.map', policy)).toBe(false)
expect(isForbiddenPublicationFile('lib/types/index.d.ts.map', policy)).toBe(true)
expect(() => {
validateTarballPayload([
'package/lib/typert.remote-client.d.ts.map',
'package/src/index.ts',
], 'fixture.tgz', policy)
}).not.toThrow()
})
it('recognizes only the canonical Host-for-Client export pair', () => {
expect(hasTypeRTRemoteNavigation({
exports: {
'./remote': {
types: './lib/typert.remote-client.d.ts',
default: './lib/typert.remote-client.js',
},
},
})).toBe(true)
expect(hasTypeRTRemoteNavigation({ exports: { './remote': './lib/remote.js' } })).toBe(false)
})
})
+33 -3
View File
@@ -1,5 +1,22 @@
/** Publication payload policy shared by static manifests and packed tarballs. */
/** Publication exceptions required for TypeRT declaration-map navigation. */
export interface PublicationPayloadPolicy {
readonly typeRTRemoteNavigation?: boolean
}
/** Whether a package manifest exports generated Host-for-Client metadata with source navigation. */
export function hasTypeRTRemoteNavigation(manifest: unknown): boolean {
if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) return false
const exportsField = (manifest as Record<string, unknown>).exports
if (exportsField === null || typeof exportsField !== 'object' || Array.isArray(exportsField)) return false
const remote = (exportsField as Record<string, unknown>)['./remote']
if (remote === null || typeof remote !== 'object' || Array.isArray(remote)) return false
const entry = remote as Record<string, unknown>
return entry.types === './lib/typert.remote-client.d.ts'
&& entry.default === './lib/typert.remote-client.js'
}
/** Normalize a package manifest path or npm tarball member to its payload-relative path. */
function payloadPath(file: string): string {
const normalized = file.replaceAll('\\', '/').replace(/^\.\/+/, '').replace(/\/+$/, '')
@@ -7,17 +24,30 @@ function payloadPath(file: string): string {
}
/** Whether a package payload path exposes source or declaration-map intermediates. */
export function isForbiddenPublicationFile(file: string): boolean {
export function isForbiddenPublicationFile(
file: string,
policy: PublicationPayloadPolicy = {},
): boolean {
const normalized = payloadPath(file)
if (policy.typeRTRemoteNavigation === true
&& (normalized === 'src'
|| normalized.startsWith('src/')
|| normalized === 'lib/typert.remote-client.d.ts.map')) {
return false
}
return normalized === 'src'
|| normalized.startsWith('src/')
|| normalized.endsWith('.d.ts.map')
}
/** Reject source and declaration-map members in a packed npm tarball. */
export function validateTarballPayload(files: readonly string[], context: string): void {
export function validateTarballPayload(
files: readonly string[],
context: string,
policy: PublicationPayloadPolicy = {},
): void {
for (const file of files) {
if (!isForbiddenPublicationFile(file)) continue
if (!isForbiddenPublicationFile(file, policy)) continue
const normalized = payloadPath(file)
if (normalized === 'src' || normalized.startsWith('src/')) {
throw new Error(`${context} publishes source file ${file}`)
+11 -10
View File
@@ -18,7 +18,7 @@ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep
import { createInterface } from 'node:readline/promises'
import { pathToFileURL } from 'node:url'
import { parseArgs } from 'node:util'
import { validateTarballPayload } from './publication-payload.ts'
import { hasTypeRTRemoteNavigation, validateTarballPayload } from './publication-payload.ts'
const DEFAULT_REGISTRY = 'https://registry.npm.harnessment.com'
const DEFAULT_OUTPUT_DIRECTORY = '.artifacts/npm-baseline'
@@ -320,7 +320,11 @@ class ReleaseBundle {
if (expected === undefined || !missingNames.delete(artifact.name)) {
throw new Error(`unexpected or duplicate packed package: ${artifact.name}`)
}
if (expected.origin === 'harness') validateTarballPayload(artifact.files, tarball)
if (expected.origin === 'harness') {
validateTarballPayload(artifact.files, tarball, {
typeRTRemoteNavigation: hasTypeRTRemoteNavigation(artifact.manifest),
})
}
if (artifact.version !== version) {
throw new Error(`${tarball} has version ${artifact.version}; expected ${version}`)
}
@@ -394,7 +398,11 @@ class ReleaseBundle {
throw new Error(`tarball checksum mismatch: ${pkg.tarball}`)
}
const artifact = inspectTarball(path, runner)
if (pkg.origin === 'harness') validateTarballPayload(artifact.files, pkg.tarball)
if (pkg.origin === 'harness') {
validateTarballPayload(artifact.files, pkg.tarball, {
typeRTRemoteNavigation: hasTypeRTRemoteNavigation(artifact.manifest),
})
}
if (artifact.name !== pkg.name || artifact.version !== this.manifest.version) {
throw new Error(`tarball identity mismatch: ${pkg.tarball}`)
}
@@ -463,13 +471,6 @@ class InstalledBundleSmoke {
+ `expected ${this.bundle.manifest.version}`,
)
}
const config = this.runner.capture(
process.execPath,
[bin, '--dump-default-config'],
consumerRoot,
environment,
)
if (config === '') throw new Error('installed dsh --dump-default-config returned no output')
this.probeWeb(bin, consumerRoot, environment)
console.log('publish-npm-baseline: installed dsh entry and Web startup probes passed')
} finally {
+14 -7
View File
@@ -224,6 +224,7 @@ export function gatesForMode(selected: Mode): Gate[] {
pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
pnpmScript('client-domain-graph', 'verify-client-domain-graph', { label: 'client domain graph' }),
pnpmScript('test', 'test'),
pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
pnpmScript('duplication', 'duplication'),
snapshotGate(),
pnpmScript('build', 'build'),
@@ -240,12 +241,19 @@ export function gatesForMode(selected: Mode): Gate[] {
}
}
function ciPrimaryGates(): Gate[] {
function ciSharedStaticGates(): Gate[] {
return [
pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
pnpmScript('constraints', 'constraints'),
pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
pnpmScript('issue-management', 'test:issue-management', { label: 'Issue management policy' }),
]
}
function ciPrimaryGates(): Gate[] {
return [
...ciSharedStaticGates(),
pnpmScript('typecheck', 'typecheck'),
lintGate(),
pnpmScript('duplication', 'duplication'),
@@ -255,8 +263,8 @@ function ciPrimaryGates(): Gate[] {
...docSyncLeafGates(),
pnpmScript('module-graph', 'verify-module-graph', { label: 'module graph' }),
pnpmScript('knip', 'knip'),
// typecheck and build now drive the same root solution graph; without the
// dependency two concurrent `tsc -b` runs race the same tsbuildinfo files.
// typecheck and build both drive the Host and Client tsc graphs; without
// the dependency concurrent runs race the same tsbuildinfo files.
// The tsc step is an incremental no-op after typecheck.
pnpmScript('build', 'build', { needs: ['typecheck'] }),
pnpmScript('publint', 'publint', { needs: ['build'] }),
@@ -339,10 +347,7 @@ function runningNodeMajor(): number {
function ciStaticGates(options: { ownsBuild: boolean }): Gate[] {
return [
pnpmScript('runtime-closure', 'verify-runtime-closure', { label: 'runtime closure' }),
pnpmScript('constraints', 'constraints'),
pnpmScript('package-invariants', 'verify-package-invariants', { label: 'package invariants' }),
pnpmScript('cordis-config', 'verify-cordis-config', { label: 'Cordis config' }),
...ciSharedStaticGates(),
...options.ownsBuild ? [pnpmScript('build', 'build')] : [],
...docSyncLeafGates({
includeDocTypecheck: options.ownsBuild,
@@ -569,6 +574,7 @@ function docSyncLeafGates(options: {
pnpmScript('markdown-links', 'verify-md-links', { label: 'markdown links' }),
pnpmScript('doc-refs', 'verify-doc-refs', { label: 'doc refs' }),
pnpmScript('package-paths', 'verify-package-paths', { label: 'package paths' }),
pnpmScript('config-source-ownership', 'verify-config-source-ownership', { label: 'config source ownership' }),
pnpmScript('package-readme-model-experience', 'verify-package-readme-model-experience', { label: 'package README model experience' }),
pnpmScript('mermaid', 'verify-mermaid'),
pnpmScript('agent-note-classification', 'verify-agent-note-classification', { label: 'agent note classification' }),
@@ -601,6 +607,7 @@ function builtBinSmokeGate(needs: string[] = ['build']): Gate {
'packages/ui/jsonrpc/tests/built-scope-carrier.e2e.ts',
'packages/subagent/subagent-codex/tests/loader-composition.e2e.ts',
'packages/subagent/subagent-claude-code/tests/loader-composition.e2e.ts',
'packages/api/remotes/tests/built-lib.e2e.ts',
// The worker-entry packages' built bundles: the only automated proof
// that lib/index.js resolves its sibling lib/worker.cjs under plain node
// (the e2e lane runs unbuilt, so these files self-skip there).
@@ -16,11 +16,11 @@
},
{
"role": "user",
"content": "# Development guide\n\nEnglish | [中文](development.zh.md)\n\nThe setup tutorial takes a new contributor from prerequisites to a checked checkout. The contributor reference that follows covers repository layout, daily workflow, and CI shape. Design rationale and implementation details belong to the linked Agent Notes and scripts.\n\n## Setup tutorial\n\n### Prerequisites\n\n- Node.js supports 22.19+ and 24+. CI covers 22.19, 24, and 26; see the [Node engine floor Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md).\n- Corepack-enabled pnpm. The repo pins `pnpm@11.7.0` in `package.json`; run `corepack enable` if `pnpm --version` does not resolve through Corepack.\n- Git 2.26 or newer; hook setup enables Git's worktree-specific configuration extension.\n- Optional: a DeepSeek API key for the Web, headless, and ACP automation demos and real-API e2e tests.\n\n### First-time setup\n\nInstall dependencies from the repo root:\n\n```sh\npnpm install\n```\n\nThe install also configures worktree-local lefthook hooks through `scripts/install-lefthook.mjs`. The [worktree-local hooks Agent Note](../.agents/notes/implemented/process/2026-07-27-worktree-local-lefthook.md) owns the safety and migration contract.\n\nIf hooks are missing because dependencies were restored from cache or `postinstall` was skipped, install them manually:\n\n```sh\nnode scripts/install-lefthook.mjs\n```\n\nIf the wrapper rejects existing Git configuration or reports a stale lock, follow its diagnostic and the linked Agent Note rather than editing worktree metadata speculatively. After moving a checkout, rerun the wrapper to regenerate the owned path.\n\nRun typecheck once after a fresh clone:\n\n```sh\npnpm run typecheck\n```\n\nSetup is complete when `pnpm run typecheck` exits successfully.\n\n## Contributor reference\n\n### TypeScript project layout\n\nThe repository typecheck runs the whole-repo `tsc -b` graph: it emits every package/vendor `lib/types` and checks examples, tests, and scripts through two no-emit aggregates.\n\nThe repository's TypeScript configuration has exactly three roles; every tsconfig file plays one of them.\n\n| File | Role | Forms a program? |\n|---|---|---|\n| `tsconfig.json` | Solution root: `extends` base, `files: []`, references to the two aggregates. The whole-repo `tsc -b tsconfig.json` graph, the tsserver discovery entry, and — through the inherited `paths` — the resolution config for tsx running `examples/` and `scripts/` (their nearest tsconfig is this file). | No |\n| `tsconfig.host.json` | Host aggregate: host-side packages (via references), examples, tests, scripts, website. Excludes `packages/client`. | Yes |\n| `tsconfig.client.json` | Client aggregate: `packages/client/*` packages and their tests, `apps/web`. | Yes |\n| `tsconfig.base.json` | Shared compilerOptions and the source `paths` map. Also the resolution facade the vitest configs point vite-tsconfig-paths at: it has no `include`, so its `paths` apply to every importer. | No |\n| `tsconfig.base.client.json` | Browser compiler shape (`jsx`, DOM libs, `types: []`) extended by the client aggregate and every `packages/client/*` package. | No |\n\nHost and client stay two aggregate programs because both sides declaration-merge the cordis `Context` interface under the same keys with different services; one program seeing both merges reports a collision. The collision exists only inside a `ts.Program` — module resolution never triggers it — which is why the solution may reference both aggregates and one paths facade may span both sides. Two disciplines follow:\n\n- `tsconfig.base.json` never gains `include` or `files`: they would leak into every extending package project and narrow the facade's match-all scope.\n- A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges. Program-backed generators and gates (`scripts/ts-project.ts` consumers, doc-typecheck standalone mode) are host-only by decision; the client side gains program-backed tooling only with a concrete need.\n\nStatic analysis and tests resolve workspace imports through the base `paths` map to `src` and must pass on a clean tree; gates that consume built `lib/` output declare that dependency explicitly. Decision record: [solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md); the tsc-first emit pipeline is the [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md).\n\nIf a relevant local check consumes built package output, build once first:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` includes `publint`, which validates package entrypoints against the built `lib/*.js` files, and `verify-node-next-types`, which validates built declarations against a temporary NodeNext consumerLine truncated
"content": "# Development guide\n\nEnglish | [中文](development.zh.md)\n\nThe setup tutorial takes a new contributor from prerequisites to a checked checkout. The contributor reference that follows covers repository layout, daily workflow, and CI shape. Design rationale and implementation details belong to the linked Agent Notes and scripts.\n\n## Setup tutorial\n\n### Prerequisites\n\n- Node.js supports 22.19+ and 24+. CI covers 22.19, 24, and 26; see the [Node engine floor Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md).\n- Corepack-enabled pnpm. The repo pins `pnpm@11.7.0` in `package.json`; run `corepack enable` if `pnpm --version` does not resolve through Corepack.\n- Git 2.26 or newer; hook setup enables Git's worktree-specific configuration extension.\n- Optional: a DeepSeek API key for the Web, headless, and ACP automation demos and real-API e2e tests.\n\n### First-time setup\n\nInstall dependencies from the repo root:\n\n```sh\npnpm install\n```\n\nThe install also configures worktree-local lefthook hooks through `scripts/install-lefthook.mjs`. The [worktree-local hooks Agent Note](../.agents/notes/implemented/process/2026-07-27-worktree-local-lefthook.md) owns the safety and migration contract.\n\nIf hooks are missing because dependencies were restored from cache or `postinstall` was skipped, install them manually:\n\n```sh\nnode scripts/install-lefthook.mjs\n```\n\nIf the wrapper rejects existing Git configuration or reports a stale lock, follow its diagnostic and the linked Agent Note rather than editing worktree metadata speculatively. After moving a checkout, rerun the wrapper to regenerate the owned path.\n\nRun typecheck once after a fresh clone:\n\n```sh\npnpm run typecheck\n```\n\nSetup is complete when `pnpm run typecheck` exits successfully.\n\n## Contributor reference\n\n### TypeScript project layout\n\nThe repository uses isolated Host and Client aggregates. An ordinary package is registered in exactly one aggregate: Host packages in `tsconfig.host.json` and Client packages in `tsconfig.client.json`.\n\n| File | Role | Forms a program? |\n|---|---|---|\n| `tsconfig.json` | Solution root: `extends` base, `files: []`, and references to the two aggregates. It is the tsserver discovery entry and the entry for explicitly running the complete Project Reference graph; through the inherited `paths`, it is also the resolution config for tsx running `examples/` and `scripts/`. | No |\n| `tsconfig.host.json` | Host aggregate: Host packages, examples, tests, scripts, website, and the exceptional Host project of `api/remotes`. | Yes |\n| `tsconfig.client.json` | Client aggregate: `packages/client/*` packages and their tests, `apps/web`, and the exceptional Client project of `api/remotes`. | Yes |\n| `tsconfig.base.json` | Shared compilerOptions and the source `paths` map. Also the resolution facade the vitest configs point vite-tsconfig-paths at: it has no `include`, so its `paths` apply to every importer. | No |\n| `tsconfig.base.client.json` | Browser compiler shape (`jsx`, DOM libs, `types: []`) extended by the Client aggregate and every `packages/client/*` package. | No |\n\nHost and Client stay two aggregate programs because both sides declaration-merge the cordis `Context` interface under the same keys with different services; one program seeing both merges reports a collision. The collision exists only inside a `ts.Program` — module resolution never triggers it — which is why the solution may reference both aggregates and one paths facade may span both sides. Three disciplines follow:\n\n- `tsconfig.base.json` never gains `include` or `files`: they would leak into every extending package project and narrow the facade's match-all scope.\n- A script that builds a repo-wide `ts.Program` seeds `tsconfig.host.json` or `tsconfig.client.json` explicitly — never the root solution, because flattening both aggregates into one program collides the `Context` merges.\n- A new package is registered in exactly one aggregate. Having both a Node loader entry and a browser entry is not a reason to split a package; an ordinary Client plugin produces both runtime artifacts during the Client build phase.\n\n`api/remotes` is the repository's only package with split Host and Client tsconfigs. Its Host entry must participate in the Host TypeRT graph, while its Client entry imports `/remote` declarations that Host tsdown must generate first. The package-root `tsconfig.json` is therefore only a solution, and the two aggregates and direct consumers reference `tsconfig.host.json` or `tsconfig.client.json` respectively. The workspace `constraints` gate walks the reachable Project Reference graph and checks each referencing project's own compiler face: a single-config target remains valid from either face, while a split target must name the matching leaf rather than its solution root or opposite leaf. Do not copy this structure to other packages; see the [`api-remotes` RLine truncated
},
{
"role": "assistant",
"content": "# 开发指南\n\n[English](development.md) | 中文\n\n搭建教程引导新贡献者从准备前置条件开始,直到检出通过检查。后面的贡献者参考介绍仓库布局、日常工作流和 CI 形态。设计依据与实现细节属于链接的 Agent Note 和脚本。\n\n## 搭建教程\n\n### 前置条件\n\n- Node.js 支持 22.19+ 与 24+。CI 覆盖 22.19、24 和 26;见 [Node 引擎下限 Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md)。\n- 启用了 Corepack 的 pnpm。仓库在 `package.json` 中固定使用 `pnpm@11.7.0`;如果 `pnpm --version` 无法通过 Corepack 解析,请先运行 `corepack enable`。\n- Git 2.26 或更高版本;钩子设置会启用 Git 的 worktree 专属配置扩展。\n- 可选:一个 DeepSeek API key,用于 Web、headless 和 ACP(Agent Client Protocol)自动化 agent(智能体)演示以及真实 API 的 e2e 测试。\n\n### 首次搭建\n\n在仓库根目录安装依赖:\n\n```sh\npnpm install\n```\n\n安装过程还会通过 `scripts/install-lefthook.mjs` 配置 worktree 本地的 lefthook 钩子。其安全与迁移契约由 [worktree 本地钩子 Agent Note](../.agents/notes/implemented/process/2026-07-27-worktree-local-lefthook.md) 负责。\n\n如果依赖是从缓存恢复或 `postinstall` 被跳过而导致缺少钩子,请手动安装:\n\n```sh\nnode scripts/install-lefthook.mjs\n```\n\n如果包装脚本拒绝现有 Git 配置或报告陈旧锁,请遵循其诊断和所链接的 Agent Note,不要凭猜测编辑 worktree 元数据。移动检出目录后,请重新运行包装脚本以重新生成自有路径。\n\n新克隆后请先运行一次类型检查:\n\n```sh\npnpm run typecheck\n```\n\n`pnpm run typecheck` 成功退出即表示搭建完成。\n\n## 贡献者参考\n\n### TypeScript 项目布局\n\n仓库类型检查会执行全仓 `tsc -b` 图:它会发射每个 package/vendor 的 `lib/types`,并通过两个 no-emit 聚合检查示例、测试和脚本。\n\n仓库的 TypeScript 配置只有三种角色;每个 tsconfig 文件恰好扮演其中一种。\n\n| 文件 | 角色 | 是否构成 program? |\n|---|---|---|\n| `tsconfig.json` | solution 根:`extends` base、`files: []`、引用两个聚合。全仓 `tsc -b tsconfig.json` 图、tsserver 发现入口,并经继承的 `paths` 充当 tsx 运行 `examples/` 与 `scripts/` 时的解析配置(它们最近的 tsconfig 就是此文件)。 | 否 |\n| `tsconfig.host.json` | host 聚合:host 侧各包(经 references)、示例、测试、脚本、website。排除 `packages/client`。 | 是 |\n| `tsconfig.client.json` | client 聚合:`packages/client/*` 各包及其测试、`apps/web`。 | 是 |\n| `tsconfig.base.json` | 共享 compilerOptions 与源码 `paths` 映射。同时是各 vitest 配置让 vite-tsconfig-paths 指向的解析门面:它没有 `include`,因此其 `paths` 适用于任何 importer。 | 否 |\n| `tsconfig.base.client.json` | 浏览器编译形状(`jsx`、DOM lib、`types: []`),由 client 聚合和每个 `packages/client/*` 包 extends。 | 否 |\n\nhost 与 client 保持两个聚合 program,是因为两侧在相同键下以不同服务对 cordis `Context` 接口做声明合并;单一 program 同时看到两份合并会报冲突。这种冲突只存在于 `ts.Program` 内部——模块解析永远不会触发它——所以 solution 可以同时引用两个聚合,一个 paths 门面也可以横跨两侧。由此推出两条纪律:\n\n- `tsconfig.base.json` 永不添加 `include` 或 `files`:它们会泄漏进每个 extends 它的包项目,并收窄门面的全匹配范围。\n- 构造全仓 `ts.Program` 的脚本显式种子 `tsconfig.host.json` 或 `tsconfig.client.json`——永不种子根 solution,因为把两个聚合展平进一个 program 会撞上 `Context` 合并冲突。基于 program 的生成器与门禁(`scripts/ts-project.ts` 的消费者、doc-typecheck standalone 模式)按决策仅覆盖 host 侧;client 侧只在出现真实需求时再获得基于 program 的工具。\n\n静态分析和测试通过 base 的 `paths` 映射把工作区 import 解析到 `src`,且必须在干净树上通过;消费构建产物 `lib/` 的门禁显式声明该依赖。决策记录:[solution-root note](../.agents/notes/implemented/process/2026-07-22-tsconfig-solution-root-two-aggregates.md);tsc-first 发射管线见 [ts-build-config note](../.agents/notes/implemented/process/2026-06-17-ts-build-config.md)。\n\n如果相关的本地检查需要使用构建后的包产物,请先构建一次:\n\n```sh\npnpm run build\n```\n\n`pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验 package 入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建Line truncated
"content": "# 开发指南\n\n[English](development.md) | 中文\n\n搭建教程引导新贡献者从准备前置条件开始,直到检出通过检查。后面的贡献者参考介绍仓库布局、日常工作流和 CI 形态。设计依据与实现细节属于链接的 Agent Note 和脚本。\n\n## 搭建教程\n\n### 前置条件\n\n- Node.js 支持 22.19+ 与 24+。CI 覆盖 22.19、24 和 26;见 [Node 引擎下限 Agent Note](../.agents/notes/implemented/process/2026-07-06-node-engine-floor.md)。\n- 启用了 Corepack 的 pnpm。仓库在 `package.json` 中固定使用 `pnpm@11.7.0`;如果 `pnpm --version` 无法通过 Corepack 解析,请先运行 `corepack enable`。\n- Git 2.26 或更高版本;钩子设置会启用 Git 的 worktree 专属配置扩展。\n- 可选:一个 DeepSeek API key,用于 Web、headless 和 ACP(Agent Client Protocol)自动化 agent(智能体)演示以及真实 API 的 e2e 测试。\n\n### 首次搭建\n\n在仓库根目录安装依赖:\n\n```sh\npnpm install\n```\n\n安装过程还会通过 `scripts/install-lefthook.mjs` 配置 worktree 本地的 lefthook 钩子。其安全与迁移契约由 [worktree 本地钩子 Agent Note](../.agents/notes/implemented/process/2026-07-27-worktree-local-lefthook.md) 负责。\n\n如果依赖是从缓存恢复或 `postinstall` 被跳过而导致缺少钩子,请手动安装:\n\n```sh\nnode scripts/install-lefthook.mjs\n```\n\n如果包装脚本拒绝现有 Git 配置或报告陈旧锁,请遵循其诊断和所链接的 Agent Note,不要凭猜测编辑 worktree 元数据。移动检出目录后,请重新运行包装脚本以重新生成自有路径。\n\n新克隆后请先运行一次类型检查:\n\n```sh\npnpm run typecheck\n```\n\n`pnpm run typecheck` 成功退出即表示搭建完成。\n\n## 贡献者参考\n\n### TypeScript 项目布局\n\n仓库使用相互隔离的 Host 与 Client aggregate。普通 package 只登记进其中一个 aggregate;Host 包进入 `tsconfig.host.json`,Client 包进入 `tsconfig.client.json`。\n\n| 文件 | 角色 | 是否构成 program? |\n|---|---|---|\n| `tsconfig.json` | solution 根:`extends` base、`files: []`、引用两个 aggregate。它是 tsserver 发现入口,也是显式执行整张 Project Reference 图时的入口;经继承的 `paths` 充当 tsx 运行 `examples/` 与 `scripts/` 时的解析配置。 | 否 |\n| `tsconfig.host.json` | Host aggregate:Host package、示例、测试、脚本和 website,以及 `api/remotes` 的 Host 特例 project。 | 是 |\n| `tsconfig.client.json` | Client aggregate:`packages/client/*` package 及其测试、`apps/web`,以及 `api/remotes` 的 Client 特例 project。 | 是 |\n| `tsconfig.base.json` | 共享 compilerOptions 与源码 `paths` 映射。同时是各 vitest 配置让 vite-tsconfig-paths 指向的解析门面:它没有 `include`,因此其 `paths` 适用于任何 importer。 | 否 |\n| `tsconfig.base.client.json` | 浏览器编译形状(`jsx`、DOM lib、`types: []`),由 Client aggregate 和每个 `packages/client/*` package extends。 | 否 |\n\nHost 与 Client 保持两个 aggregate program,是因为两侧在相同键下以不同服务对 cordis `Context` 接口做声明合并;单一 program 同时看到两份合并会报冲突。这种冲突只存在于 `ts.Program` 内部——模块解析永远不会触发它——所以 solution 可以同时引用两个 aggregate,一个 paths 门面也可以横跨两侧。由此推出三条纪律:\n\n- `tsconfig.base.json` 永不添加 `include` 或 `files`:它们会泄漏进每个 extends 它的包项目,并收窄门面的全匹配范围。\n- 构造全仓 `ts.Program` 的脚本显式种子 `tsconfig.host.json` 或 `tsconfig.client.json`——永不种子根 solution,因为把两个 aggregate 展平进一个 program 会撞上 `Context` 合并冲突。\n- 新 package 只登记进一个 aggregate。包同时具有 Node loader 入口和 browser 入口并不构成拆分理由;普通 Client plugin 的两份运行时产物都在 Client 构建阶段生成。\n\n`api/remotes` 是唯一拆分 Host/Client tsconfig 的仓库特例。它的 Host 入口必须进入 Host TypeRT 图,而 Client 入口导入 Host tsdown 才会生成的 `/remote` 声明,因此本包根 `tsconfig.json` 只作为 solution,两个 aggregate 和直接消费方分别引用 `tsconfig.host.json` 或 `tsconfig.client.json`。workspace `constraints` 门禁遍历可达的 Project Reference 图,并按各引用 project 自身的 compiler face 检查:只有单一配置的目标可由任一 face 引用,拆分配置的目标则必须引用匹配的 leaf,不得引用 solution 根或另一侧 leaf。不要把该结构推广到其他包;完整边界见 [`api-remotes` README](../packages/api/remotes/README.md)。\n\n根构建按生成依赖排序:\n\n```sh\ntsc -b tsconfig.host.json\ntsdown --env.DSH_BUILD_FACE host\ntsc -b tsconfig.client.json\ntsdown --env.DSH_BLine truncated
},
{
"role": "user",
+63 -3
View File
@@ -199,7 +199,7 @@
{
"doc": "docs/core-data-structures/goal.md",
"symbol": "GoalView",
"source": "packages/goal/goal/src/domain.ts"
"source": "packages/goal/goal/src/types.ts"
},
{
"doc": "docs/core-data-structures/goal.md",
@@ -219,12 +219,12 @@
{
"doc": "docs/core-data-structures/goal.md",
"symbol": "CreateGoalRequest",
"source": "packages/goal/goal/src/domain.ts"
"source": "packages/goal/goal/src/types.ts"
},
{
"doc": "docs/core-data-structures/goal.md",
"symbol": "EditGoalRequest",
"source": "packages/goal/goal/src/domain.ts"
"source": "packages/goal/goal/src/types.ts"
},
{
"doc": "docs/core-data-structures/goal.md",
@@ -1494,6 +1494,66 @@
"doc": "docs/core-data-structures/settings.md",
"symbol": "SettingsPathOp",
"source": "packages/settings/settings/src/index.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypeRTLookupMap",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypeRTContextMap",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypeRTLookupDefinition",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypeRTCodec",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "InvocationParameterDescriptor",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "InvocationDescriptor",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypeRTService",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypeRTRemoteNamespaceMap",
"source": "packages/typert/type-meta/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "InvokeRemoteRequest",
"source": "packages/api/gateway/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypertGatewayErrorCode",
"source": "packages/api/gateway/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypertGateway",
"source": "packages/api/gateway/src/types.ts"
},
{
"doc": "docs/core-data-structures/typert.md",
"symbol": "TypeRTClientRemote",
"source": "packages/typert/type-meta/src/types.ts"
}
]
}
@@ -0,0 +1,30 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { collectConfigSourceOwnershipViolations } from './verify-config-source-ownership.ts'
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true })
})
describe('configuration source ownership gate', () => {
it('rejects inline endpoints in shipped bundle patches', () => {
const root = mkdtempSync(join(tmpdir(), 'dsh-config-source-ownership-'))
roots.push(root)
const directory = join(root, 'packages/bundle/base')
mkdirSync(directory, { recursive: true })
writeFileSync(
join(directory, 'cordis.patch.yml'),
'config:\n baseURL: !!js process.env.DEEPSEEK_SEARCH_BASE_URL\n',
)
expect(collectConfigSourceOwnershipViolations(root)).toEqual([
'packages/bundle/base/cordis.patch.yml:2: inlines a credential or endpoint from the environment.'
+ ' The adapter resolves apiKeyEnv through ctx.credentials and the endpoint through the'
+ ' environment snapshot; inlining here bypasses both ladders.',
])
})
})
+56
View File
@@ -0,0 +1,56 @@
/**
* Gate for forbidden credential or endpoint environment inlines in shipped
* Cordis configuration.
* @module scripts/verify-config-source-ownership
*/
import { globSync, readFileSync } from 'node:fs'
import { resolve, sep } from 'node:path'
const ROOT = resolve(import.meta.dirname, '..')
/** Shipped Cordis configuration these rules apply to. */
const SHIPPED_CONFIG_GLOBS = [
'apps/*/config/*.yml',
'examples/*/*.cordis.yml',
'examples/*/cordis.yml',
'packages/bundle/*/cordis.patch.yml',
// The Python runtime ships its own default composition inside the wheel.
'python/*/src/**/cordis.yml',
]
/** Ordinary single-line forms this narrow source-shape check rejects; not full YAML analysis. */
const INLINE_DENY = /^\s*(apiKey|baseURL|apiKeyEnv|authToken|headers)\s*:\s*!!js\b/
/** Return every forbidden inline environment form in shipped configuration. */
export function collectConfigSourceOwnershipViolations(root: string): string[] {
const failures: string[] = []
for (const glob of SHIPPED_CONFIG_GLOBS) {
for (const file of globSync(glob, { cwd: root })) {
const rel = file.split(sep).join('/')
readFileSync(resolve(root, rel), 'utf8').split('\n').forEach((line, index) => {
if (!INLINE_DENY.test(line)) return
failures.push(
`${rel}:${String(index + 1)}: inlines a credential or endpoint from the environment.`
+ ' The adapter resolves apiKeyEnv through ctx.credentials and the endpoint through the'
+ ' environment snapshot; inlining here bypasses both ladders.',
)
})
}
}
return failures
}
if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
const failures = collectConfigSourceOwnershipViolations(ROOT)
if (failures.length > 0) {
process.stderr.write('verify-config-source-ownership: configuration source ownership violated:\n')
for (const failure of failures) process.stderr.write(` ${failure}\n`)
process.exit(1)
}
process.stdout.write(
'verify-config-source-ownership: no credential or endpoint uses the ordinary inline environment form'
+ ' in shipped configuration.\n',
)
}
@@ -33,6 +33,7 @@ const NO_MODEL_EXPERIENCE_SECTION: Readonly<Record<string, string>> = {
'packages/core/scope': 'The package is a model-agnostic registration and lifecycle primitive; model-facing consumers own any context selection.',
'packages/util/brand': 'The package is a type-only primitive erased at compile time.',
'packages/util/paths': 'The package only resolves harness-owned host paths; model-facing consumers own any rendered use.',
'packages/util/environment': 'The package only resolves host environment values; model-facing consumers own any rendered use.',
}
/**
@@ -59,10 +60,12 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/client/web-react': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/client/schema-form': { kind: 'none', reason: 'Browser-side form-rendering library; registers no model surface.' },
'packages/client/connection': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/api/remotes': { kind: 'none', reason: 'The Remote BFF selects business methods and identity policy; selected services own any model-visible effect.' },
'packages/client/runtime': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/client/ui-layout': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/client/ui-sidebar': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/client/ui-conversation': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/client/ui-deliverables': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/client/ui-slash': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' },
'packages/client/ui-command': { kind: 'indirect', reason: 'The dispatch paths trigger the host command.execute RPC; each command handler\'s host package owns any model-visible effect.' },
'packages/client/ui-model': { kind: 'indirect', reason: 'Selection routes session.selectModel; the host snapshots the target at the next prompt-assembly boundary and owns the model-visible effect.' },
@@ -126,6 +129,8 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/support/loader-smoke': { kind: 'none', reason: 'The test harness observes child-process streams without changing live requests.' },
'packages/support/llm-mock-server': { kind: 'none', reason: 'The test server substitutes provider wire behavior without invoking a real model.' },
'packages/support/llm-replay': { kind: 'none', reason: 'The keyless adapter invokes no provider model.' },
'packages/api/gateway': { kind: 'none', reason: 'Remote dispatch infrastructure; invoked business methods own any model-visible effect.' },
'packages/typert/type-meta': { kind: 'none', reason: 'Compiler-independent Remote protocol declarations; registers no model surface.' },
'packages/typert/generator': { kind: 'none', reason: 'The build-time generator runs outside any agent runtime and touches no model request.' },
'packages/tasks/tasks': { kind: 'indirect', reason: 'Producer and control-surface plugins own all model rendering over the task registry.' },
'packages/tasks/tasks-local': { kind: 'indirect', reason: 'The registry backend delegates model rendering to producer plugins and dsh-tool-tasks.' },
+12 -6
View File
@@ -204,12 +204,14 @@ cat "$scratch/logs/smoke.log"
grep -q '^smoke: win32 x64' "$scratch/logs/smoke.log" || { echo 'wine-windows-gates: Windows Node smoke did not report win32 x64' >&2; exit 1; }
# ---- the two blocking surfaces, concurrently ------------------------------
# The same shape run-gates gives ci-windows-blocking on native Windows:
# `build` = tsc -b then tsdown, `production site` = the VitePress build. Both
# statuses are captured so one failure cannot hide the other's result.
# The build preserves the face order from package.json: compile and bundle the
# Host face before compiling and bundling the Client face.
# Both statuses are captured so one failure cannot hide the other's result.
build_gate() {
wine_node "$scratch/logs/tsc.log" "$tsc_js" -b --pretty false || return $?
wine_node "$scratch/logs/tsdown.log" "$tsdown_js"
wine_node "$scratch/logs/host-tsc.log" "$tsc_js" -b tsconfig.host.json --pretty false || return $?
wine_node "$scratch/logs/host-tsdown.log" "$tsdown_js" --env.DSH_BUILD_FACE host || return $?
wine_node "$scratch/logs/client-tsc.log" "$tsc_js" -b tsconfig.client.json --pretty false || return $?
wine_node "$scratch/logs/client-tsdown.log" "$tsdown_js" --env.DSH_BUILD_FACE client
}
site_gate() {
cd website
@@ -235,7 +237,11 @@ report() {
for log in "$@"; do tail -n 200 "$log" >&2 || true; done
fi
}
report 'build (tsc -b, tsdown)' "$build_status" "$scratch/logs/tsc.log" "$scratch/logs/tsdown.log"
report 'build (Host tsc/tsdown, Client tsc/tsdown)' "$build_status" \
"$scratch/logs/host-tsc.log" \
"$scratch/logs/host-tsdown.log" \
"$scratch/logs/client-tsc.log" \
"$scratch/logs/client-tsdown.log"
report 'production site (vitepress build)' "$site_status" "$scratch/logs/site.log"
if (( build_status != 0 )); then exit "$build_status"; fi
exit "$site_status"