深入理解 DeepSeek Harness · 第 4 篇
Cordis 内核 III:Loader、叠加(Overlay)与 Patch 层级
前情回顾
第 3 篇把内核的另一半讲完:五种派发契约、围绕式中间件、依赖方(dependents)优先的卸载流程。现在这棵有契约的树还缺一个来源——它如何从一批 YAML 配置行里被装配出来。本篇就是那棵树的构造说明书。
本章要回答的问题
!!js 表达式什么时候求值、针对哪个上下文?profile 的 bundle 层、用户 patch、home patch、--patch 叠加按什么顺序合成?为什么 patch 是按行 id 整块替换配置,而不是合并字段?为什么列表顺序不决定加载顺序?preset patch 到底有没有专属解析器?
你会学到什么 / 先验知识
你会看懂 !!js 标量的解析、disabled 的求值时机、applyPatches() 的整块替换语义、readProfilePatches() 的五层顺序,以及为什么 overlay 无法移除上层已挂载的行为。先验是第 2 篇的服务仓库与第 3 篇的事件/副作用契约。
核心概念:从空列表开始叠加
dsh 的组合模型只有一句话:从一条空的条目列表开始,按顺序叠加各层 patch。第 1 篇引过的 [文档] docs/architecture.md:25 逐字写道:
Layers apply to an empty entry list: the profile's ordered bundles, its `cordis.patch.yml`, the home patch, then `--patch` overlays. A patch targets a row by id and replaces its whole config, or inserts new rows. A `preset` patch applies these operations inside that declaration’s `config.plugins`, with the same layer precedence.
[文档] docs/cordis-primer.md:39 补上表达式的求值时机:
`@deepseek-ai/cordis-plugin-include` parses `!!js` into expression nodes. Loader interpolates an entry's `config` (after declared injections activate, against that plugin context — `ctx.serviceName`) and its `disabled` field (at every mount decision, against the loader context); Include preserves nested row expressions until target activation. Other entry metadata stays literal. Use overlays when the environment selects plugins.
两句话定位了两条时间线:条目的 config 在它声明的 inject 激活之后、针对该插件自己的上下文求值;disabled 则在每一次挂载决策时、针对 loader 上下文求值。这个差别很重要——一个能按已就绪的服务决定参数,一个能按环境状态决定挂不挂。
graph LR
A[空条目列表] --> B[profile 的有序 bundle 层]
B --> C[profile 的 cordis.patch.yml]
C --> D[home patch]
D --> E[--patch overlays]
E --> F[遥测开关补丁]
F --> G[ settled 的插件树 ]
D -. 每次挂载决策 .-> H[disabled: !!js<br/>针对 loader 上下文]
G -. inject 激活后 .-> I[config: !!js<br/>针对插件上下文]
源码走读:四层机制
证据一:!!js 是一个标量标签,不是任意代码执行。 [源码] vendor/include/src/index.ts:23-32:
const JsExpr: ScalarTag = { tag: 'tag:yaml.org,2002:js', identify: isJsExpr, resolve: (source) => ({ __jsExpr: source }), // quoted like any other string stringify: (item, ctx, onComment, onChompKeep) => { const scalar = new Scalar((item.value as any).__jsExpr) return stringifyString(Object.assign(scalar, { type: item.type }), ctx, onComment, onChompKeep) }, }
resolve 只把 YAML 标量包成 { __jsExpr: source } 惰性节点,不在这里执行。stringify 把它再写回带引号的字符串。真正的求值发生在 Loader:evaluate() 把表达式字符串交给运行时解析。
证据二:disabled 在每次挂载决策时求值,并沿父链传播。 [源码] vendor/loader/src/config/entry.ts:92-116:
/** True when this entry or any owning parent entry is disabled. */ get disabled() { // group is always enabled if (this.options.group) return false let entry: Entry | undefined = this do { if (this._resolveDisabled(entry.options)) return true entry = entry.parent.ctx.fiber.entry } while (entry) return false } /** * Effective disabled state: a `!!js` expression evaluates against the loader * context. The raw node stays in the options, so write-back keeps the form. */ private _resolveDisabled(options: EntryOptions): boolean { return isJsExpr(options.disabled) ? Boolean(this.evaluate(options.disabled.__jsExpr)) : Boolean(options.disabled) } evaluate(expr: string) { return evaluate(this.ctx, expr) }
disabled 是一个 getter,不是装载时算好的标志:每次读取都会沿父条目链逐层调用 _resolveDisabled。!!js 节点被 evaluate(this.ctx, expr) 求值,原始节点仍留在 options 里,因此写回配置时表达式形式不丢。根节点 group 恒为启用状态——分组本身不做禁用决策。
证据三:patch 整块替换,且行序没有语义。 [源码] vendor/include/src/patch.ts:100-182(节选,保留关键分支):
export function applyPatches(data: EntryOptions[], patches: PatchOptions[] | undefined, warn: Warn = () => {}): PatchResult { data = structuredClone(data) const entries = new Map<string, EntryOptions>() const owners = new Map<string, EntryOwner.File | EntryOwner.Embedded>() const keys = new Map<string, Map<string, number>>() const mount = (list: EntryOptions[], owner: EntryOwner.File | EntryOwner.Embedded) => { for (const options of list) { if (options.id) { entries.set(options.id, options) owners.set(options.id, owner) // earlier overrides were aimed at the entry this one replaces keys.delete(options.id) } if (options.group && Array.isArray(options.config)) mount(options.config, owner) } } mount(data, FILE) patches?.forEach((patch, index) => { const { id, insert, name, ...overrides } = patch const target = id ? entries.get(id) : undefined if (insert) { if (id && !target) return warn('patch insert: entry %C not found', id) if (target && !target.group) return warn('patch insert: entry %C is not a group', id) const clone = structuredClone(insert) if (target) { if (!Array.isArray(target.config)) target.config = [] target.config.push(...clone) } else { data.push(...clone) } mount(clone, { type: 'embedded', index, key: 'insert' }) return } if (!id) return warn('patch: id is required for non-insert patches') if (!target) return warn('patch: entry %C not found', id) if (name && name !== target.name) { return warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name) } // the entries of a group config the patch replaces go away with it if ('config' in overrides && target.group && Array.isArray(target.config)) { unmount(target.config) } const overridden = keys.get(id) ?? new Map<string, number>() keys.set(id, overridden) for (const [key, value] of Object.entries(overrides)) { target[key] = value overridden.set(key, index) } // entries of a group config the patch supplies can be patched in turn if ('config' in overrides && target.group && Array.isArray(target.config)) { ensureIds(target.config, id => entries.has(id)) target.config = structuredClone(target.config) mount(target.config, { type: 'embedded', index, key: 'config' }) } }) return { data, index: new PatchIndex(owners, keys) } }
几个关键分支要逐条看。structuredClone(data) 保证原数据不被改;entries 是以 id 为键的索引,patch 靠它定位目标。insert 分支只往 group 里追加或往根列表追加新行——没有删除分支。target[key] = value 是整字段赋值,config 字段一旦被 patch,就是整个配置被换掉;keys 索引记录每个字段最后由哪一层 patch 写入,用于后续诊断。组(group)的配置被替换时,旧的子条目会先 unmount,新条目再 mount——这是整块替换而非合并的直接后果。
至于行序,entries 是一张以 id 为键的 map,装载顺序由第 2 篇的 inject 依赖图决定,列表顺序只用于读者分组。这一条在第 1 篇引过的 base patch 头注释里也逐字写着。
证据四:五层 patch 栈在一个函数里定序。 [源码] packages/boot/app-boot/src/profile-context.ts:68-86:
/** Read current bundle, user, and command-line overlay layers. * @param binName Diagnostic prefix for malformed or missing configuration. * @param context Data supplied by the profile launcher. * @param initialProfile Already loaded startup profile; omitted reads the current files. * @returns Detached ordered patches; this function does not update the Loader. * @throws When a present patch file or any overlay file is missing, unreadable, or not a patch list. */ export function readProfilePatches(binName: string, context: ProfileContext, initialProfile?: Profile): PatchOptions[] { const patches = structuredClone([ ...readBundlePatches(binName, context, initialProfile), ...(initialProfile?.patches ?? loadOptionalPatches(binName, context.patchPath) ?? []), ...(loadOptionalPatches(binName, join(context.home, PROFILE_PATCH_FILENAME)) ?? []), ...context.overlayPaths.flatMap(path => loadOverlayPatches(binName, path)), ]) const telemetryPatch = resolveTelemetryPatch(context.telemetryDisabledEnv, composeEntries([patches]).some(row => row.id === TELEMETRY_ROW_ID)) if (telemetryPatch !== undefined) patches.push(telemetryPatch) return patches }
四层叠加加上末尾的遥测开关补丁,正好五层:bundle 层 → profile 的 cordis.patch.yml → home patch → --patch overlays → 遥测开关。注意 JSDoc 的 @returns:这个函数只返回脱离上下文的有序补丁列表,并不更新 Loader。装配时机由第 14 篇的启动链路负责。
证据五:HMR 是一个可 patch 的普通条目。 [源码] packages/bundle/base/cordis.patch.yml:27-32:
# Profile configuration reloads by default; module roots are opt-in. - id: hmr name: '@deepseek-ai/dsh-hmr' disabled: !!js "!ctx.get('profileContext')" config: root: []
HMR(配置热重载)不是启动器里的特权开关,而是一行普通条目:disabled 用 !!js 针对 loader 上下文判断,config.root: [] 表示模块根目录默认不参与重载。Profile patch 可以覆盖这一行——这正是「无特权核心」在配置层的体现。
证据六:preset patch 没有独立解析器。 [文档] docs/architecture.md:25 已经说明它「applies these operations inside that declaration's config.plugins, with the same layer precedence」。仓库里没有独立的 preset patch 解析器;它的语义就是把 preset 行的 config.plugins 整行重述,并沿用同一套 patch 优先级。别去找一个不存在的 presetPatchParser。
设计取舍
① 为什么是行级 patch 而不是文件级覆盖? 因为产品形态之间的差异往往只在一两行配置:换一个模型路由、开一个 profile 专属的服务。文件级覆盖会让用户复制整份 bundle 配置,上游改动就再也合不回来。代价是 patch 与行 id 强耦合——applyPatches() 在找不到目标 id 时只能 warn(patch.ts:155),不会报错;写错 id 的 patch 会静默失效。
② 为什么 disabled 在每次挂载时求值,而不是装载时算好? 因为环境变量、profile 上下文这些条件可能在进程生命周期里变化;把判断留在 getter 里,热重载时就能重新决策。代价是求值次数增加,而且表达式必须写成纯判断——_resolveDisabled 只取 Boolean(...) 结果,复杂副作用不该塞进去。
③ 为什么 overlay 只能插入和替换、不能移除? 因为 applyPatches() 的 insert 分支只做 push,普通 patch 分支只做 target[key] = value,没有任何删除已挂载行的操作(patch.ts:140-178)。这让叠加语义保持简单可预测,代价是 sdk-minimal 必须自持完整树、不叠加 base——第 12 篇展开。
常见误解
「列表顺序就是加载顺序。」 不是。entries 索引按 id 存行,激活由 inject 依赖图决定;顺序只服务于读者。
「preset patch 有专属语法或解析器。」 没有。它只是把 preset 行的 config.plugins 整行重述并沿用同一优先级(docs/architecture.md:25)。
「!!js 等于在 YAML 里执行任意代码。」 解析阶段只生成 { __jsExpr: source } 惰性节点(include/src/index.ts:26);求值由 Loader 在明确的时机、针对明确的上下文进行(docs/cordis-primer.md:39)。它不是 YAML 里的自由代码执行。
小结
插件树从空列表开始叠加:五层顺序由 readProfilePatches() 一处定死(packages/boot/app-boot/src/profile-context.ts:75-86);!!js 解析为惰性表达式节点(vendor/include/src/index.ts:23-32),disabled 每次挂载沿父链求值(vendor/loader/src/config/entry.ts:92-116),config 则在 inject 激活后针对插件上下文插值(docs/cordis-primer.md:39);patch 以 id 定位、整块替换字段、只能插入不能删除(vendor/include/src/patch.ts:100-182),行序不决定加载顺序。preset 没有独立解析器,只是整行重述 config.plugins(docs/architecture.md:25)。
代价落在三处:patch 与行 id 强耦合且找不到目标时只警告、disabled 表达式必须保持纯判断、overlay 无法移除上层行为。第 5 篇进入运行时主干,看一次 turn 如何在这棵装配好的树上跑起来。
思考题
- 在
vendor/include/src/patch.ts:136-179找到insert与普通 patch 两个分支。如果你想「删掉 base 已挂载的一行」,这两个分支分别为什么做不到?这会如何逼出sdk-minimal的设计? - 在
vendor/loader/src/config/entry.ts:92-116找到disabledgetter。为什么它是 getter 而不是装载时算好的布尔字段?_resolveDisabled对!!js节点做了什么,原始节点为什么必须保留在 options 里? - 对比
docs/cordis-primer.md:39中config与disabled的求值时机与上下文:如果你想让某插件的config.model依赖「模型服务已就绪」,该写在config还是disabled里?反过来,想让某行只在特定环境下挂载,该写在哪?