diff --git a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.i18n.yaml b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.i18n.yaml index 11674d7747..9e8573a79d 100644 --- a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md -2026-07-20-dsh-cli-personal-config.md: 3331e36c86002d91fb272868268707fed014d01a -2026-07-20-dsh-cli-personal-config.zh.md: 172d84b075ed7ecc127c317b47e30581db67f89a +2026-07-20-dsh-cli-personal-config.md: 259c3865a9edcbc77949a9fe401af9a77e1e32c4 +2026-07-20-dsh-cli-personal-config.zh.md: 8f7c15c3c683cc855c6e3b704bfde8f87d4009d2 diff --git a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md index 3331e36c86..259c3865a9 100644 --- a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md +++ b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.md @@ -39,9 +39,9 @@ Hot-reload interplay: the include re-applies its `patches` on every config re-re ## Consequences - `dsh` from any directory (and `pnpm run demo:tui`) boots the personal provider/model with zero repo changes; verified end-to-end against a personal Anthropic proxy with Opus 4.8, including a bash tool round trip. -- Because an id-targeted patch replaces the whole `config`, a personal override restates the base fields it keeps and can drift when the base entry changes shape; the loader's entry-not-found/name-mismatch warnings are the only diagnostics. +- Because an id-targeted patch replaces the whole `config`, a personal override restates the base fields it keeps and can drift when the base entry changes shape; the loader's entry-not-found/name-mismatch warnings and [`dsh --dump-config`](2026-07-30-dsh-dump-config.md) (which prints the composed tree those patches produce) are the diagnostics. - Personal patches resolve ids against the booted file's own tree, so nested-include overlays (Code Mode) are not personalized; live-run parity for those leaves is deferred. -- `dsh-app-boot` depends on `js-yaml` (plus a load-only copy of the include's `!!js` YAML type) and, like `apps/cli`, on `@deepseek-ai/dsh-paths` for `resolveDshHome`. +- `dsh-app-boot` depends on `js-yaml` and imports the include's `!!js` YAML dialect (`entryListSchema`) directly, and, like `apps/cli`, depends on `@deepseek-ai/dsh-paths` for `resolveDshHome`. - When PR #443 lands, `apps/cli/src/bin.ts`'s dispatch chain and `apps/cli/package.json`'s dependency list conflict textually; both resolve as unions (their `web`/`-p` branches plus our default-TUI branch). ## Testing diff --git a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.zh.md b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.zh.md index 172d84b075..8f7c15c3c6 100644 --- a/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.zh.md +++ b/.agents/notes/implemented/feature/2026-07-20-dsh-cli-personal-config.zh.md @@ -39,9 +39,9 @@ PTY 冒烟测试的启动器把 `$DSH_HOME` 隔离到每个测试自己的目录 ## Consequences - 在任意目录运行 `dsh`(以及 `pnpm run demo:tui`)即可零仓库改动地使用个人提供方/模型;已针对个人 Anthropic 代理与 Opus 4.8 端到端验证,包括一次 bash 工具往返。 -- 由于按 id 定位的补丁替换整个 `config`,个人覆盖必须复述它保留的基础字段,并可能随基础配置项形态变化而漂移;loader 的「配置项未找到/名称不匹配」警告是仅有的诊断。 +- 由于按 id 定位的补丁替换整个 `config`,个人覆盖必须复述它保留的基础字段,并可能随基础配置项形态变化而漂移;诊断手段是 loader 的「配置项未找到/名称不匹配」警告和 [`dsh --dump-config`](2026-07-30-dsh-dump-config.md)(打印这些补丁合成出的配置树)。 - 个人补丁只在被启动文件自身的树里解析 id,因此嵌套 include 的 overlay(Code Mode)不会被个性化;这些叶子的实际运行等价性暂缓。 -- `dsh-app-boot` 依赖 `js-yaml`(外加一份只用于加载的 include `!!js` YAML 类型副本),并与 `apps/cli` 一样依赖 `@deepseek-ai/dsh-paths` 以获取 `resolveDshHome`。 +- `dsh-app-boot` 依赖 `js-yaml`,并直接导入 include 的 `!!js` YAML 方言(`entryListSchema`);与 `apps/cli` 一样依赖 `@deepseek-ai/dsh-paths` 以获取 `resolveDshHome`。 - PR #443 落地时,`apps/cli/src/bin.ts` 的分发链与 `apps/cli/package.json` 的依赖列表会产生文本冲突;两者都按并集解决(他们的 `web`/`-p` 分支加上我们的默认 TUI 分支)。 ## Testing diff --git a/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.i18n.yaml b/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.i18n.yaml new file mode 100644 index 0000000000..0cd2549e55 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.i18n.yaml @@ -0,0 +1,6 @@ +# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each +# side as of the last confirmed-consistent state. Both languages carry equal authority; +# after editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-30-dsh-dump-config.md +2026-07-30-dsh-dump-config.md: bc6504541c7868bad019a1bcd9f551435109e4c6 +2026-07-30-dsh-dump-config.zh.md: 5e173305a6cd03de3db4c763f26eeda6fba68ec7 diff --git a/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.md b/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.md new file mode 100644 index 0000000000..bc6504541c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.md @@ -0,0 +1,31 @@ +# Agent Note: dsh --dump-config prints the composed config tree + +Status: implemented + +English | [中文](2026-07-30-dsh-dump-config.zh.md) + +## Problem + +The booted tree is a composition the user never sees: the shipped base, a surface overlay, and the `--config` or personal `~/.dsh/config.yaml` overlay apply as sibling patch lists where each id-targeted patch replaces the row's whole `config` and an unmatched id only warns. Debugging a misbehaving personal overlay (a restated field dropped, a row id typo, a patch applying to the wrong surface) required mentally replaying the patch algorithm across three files. There was no way to see the effective tree or to diff it against the shipped defaults. + +## Decision + +`dsh --dump-config` and `dsh web --dump-config` print the composed entry list — base, surface overlay, then the `--config` or personal overlay, exactly the layers that surface's boot assembles — as YAML on stdout and exit without booting. `dsh --dump-default-config` / `dsh web --dump-default-config` stop at the surface overlay, so diffing the two outputs shows precisely what the user layer changes. + +The dump cannot drift from what boots because it shares the mounting code: the vendored include exports its patch algorithm as the pure `applyEntryPatches(data, patches, warn)` (the private `applyPatches` method now delegates to it) and its `!!js` YAML dialect as `entryListSchema`; `dsh-app-boot`'s `renderConfigDump()` composes labeled layers and renders through both, and `apps/cli/src/dump-config.ts` is a thin surface-selection wrapper. `!!js` expressions print verbatim and unevaluated — the dump shows composition, not one process's environment — and a patch whose target row is absent goes to stderr with its layer label, mirroring the Loader's boot-time warning. Launcher-owned boot-context values (session identity, web CLI-flag patches, the frontend dist path) are per-invocation facts outside the config tree and do not appear. The dump flags reject boot-only flags (`-p`, `--resume`, `--config-replace`) and each other, and `--dump-default-config` takes no `--config`. + +Each run of same-provenance rows is preceded by a `# ==` comment naming the file that contributed the rows and the layers that patched them (`# == base.cordis.yml, patched by tui.cordis.yml`), so the output shows which section comes from which file while remaining one loadable YAML document. Composition is one flattened `applyEntryPatches` call over all layers — boot's exact call shape, so even patch-visibility corner cases (a later layer targeting a group child that a plain `config` replacement introduced, invisible to the single-pass id index) compose identically; applying one call per layer would rebuild the index between layers and print a tree boot never mounts. Provenance is derived from single-call prefix snapshots (base + layers 1..k) diffed positionally: the patch algorithm only rewrites rows in place or appends, so a top-level index identifies one row across snapshots, and a layer counts as having patched a row when adding it changed that row (config replacement, disable, group insert). Patch lists are cloned per snapshot because `applyEntryPatches` pushes `insert` rows by reference from the patch list. + +`dsh-app-boot` previously duplicated the include's `!!js` YAML type for patch parsing; it now imports `entryListSchema`, so the dialect has one owner. + +## Alternatives considered + +**Boot the tree and dump `ctx.loader.entries()`.** Rejected: booting evaluates `!!js` expressions (leaking one machine's environment into the printed config), starts adapters and sessions as side effects, requires a TTY-independent teardown path, and is slow. The dump is for debugging composition, which is a pure function of the files. + +**Reimplement the patch merge in the CLI.** Rejected: a second implementation of `applyPatches` would silently drift from the vendored include — the exact failure mode the feature exists to debug. Exporting the include's own algorithm costs one logged vendor modification and guarantees identity. + +**A `/dump-config` TUI command instead of flags.** Rejected as the only form: the primary use is a piped `dsh --dump-config | diff - <(dsh --dump-default-config)` style workflow, which needs a boot-free non-TTY surface. A TUI command can be added later over the same `renderConfigDump`. + +## Consequences + +Config debugging becomes one command instead of mental patch replay, and support can ask for `--dump-config` output. The vendored include carries one more logged local modification (the `applyEntryPatches`/`entryListSchema` exports; behavior-preserving for mounting) to re-apply on upstream sync. Provenance tracking re-composes one prefix snapshot per layer and diffs rows by JSON stringify, so the dump does extra work proportional to layers² × rows; that cost lives only in the boot-free dump path. `renderConfigDump` is unit-tested for layer ordering, verbatim `!!js` round-tripping, provenance separators and grouping, labeled unmatched-patch warnings, and loud read/parse/shape failures; the built-bin e2e drives all four flag forms through `lib/bin.js` including the personal-overlay layer, its provenance label, and its stderr warning. diff --git a/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.zh.md b/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.zh.md new file mode 100644 index 0000000000..5e173305a6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-30-dsh-dump-config.zh.md @@ -0,0 +1,31 @@ +# Agent Note: dsh --dump-config 打印合成后的配置树 + +Status: implemented + +[English](2026-07-30-dsh-dump-config.md) | 中文 + +## Problem + +启动的配置树是一份用户从未见过的合成结果:已交付的基础配置、界面覆盖层,以及 `--config` 或个人 `~/.dsh/config.yaml` 覆盖层作为同级补丁列表依次应用,其中每个按 id 定向的补丁替换目标行的整个 `config`,未匹配的 id 只产生警告。调试一个行为异常的个人覆盖层(漏掉需要重述的字段、行 id 拼错、补丁应用到了错误的界面)需要在脑中跨三个文件重放补丁算法。既没有办法看到生效的树,也没有办法把它与已交付的默认值做 diff。 + +## Decision + +`dsh --dump-config` 和 `dsh web --dump-config` 把合成后的条目列表——基础配置、界面覆盖层、再叠 `--config` 或个人覆盖层,恰好是该界面启动时组装的那些层——以 YAML 打印到 stdout 后退出,不启动任何东西。`dsh --dump-default-config` / `dsh web --dump-default-config` 止步于界面覆盖层,因此对两份输出做 diff 就能精确看出用户层改了什么。 + +dump 不可能与实际启动漂移,因为它复用挂载代码:vendored include 把补丁算法导出为纯函数 `applyEntryPatches(data, patches, warn)`(私有的 `applyPatches` 方法现在委托给它),并把 `!!js` YAML 方言导出为 `entryListSchema`;`dsh-app-boot` 的 `renderConfigDump()` 通过这两者对带标签的层完成合成与渲染,`apps/cli/src/dump-config.ts` 只是选择界面的薄封装。`!!js` 表达式原样打印、不求值——dump 展示的是合成结果,不是某个进程的环境——目标行不存在的补丁会连同其层标签报到 stderr,与 Loader 启动时的警告一致。由启动器持有的启动上下文值(会话身份、web 的 CLI 标志补丁、前端 dist 路径)是每次调用的事实,位于配置树之外,不会出现。dump 标志拒绝仅用于启动的标志(`-p`、`--resume`、`--config-replace`)且两个 dump 标志互斥,`--dump-default-config` 不接受 `--config`。 + +每段来源相同的连续行之前都有一条 `# ==` 注释,标明贡献这些行的文件以及修补过它们的层(`# == base.cordis.yml, patched by tui.cordis.yml`),因此输出既展示每一节来自哪个文件,又仍是一份可加载的 YAML 文档。合成是对所有层展平后的一次 `applyEntryPatches` 调用——与启动的调用形状完全一致,因此即便是补丁可见性的边角情况(后一层定位到前一层通过普通 `config` 替换引入的组内子项,而单遍 id 索引看不到它)也与启动合成完全相同;若按层各调用一次,会在层与层之间重建索引,打印出一棵启动从不挂载的树。来源从单次调用的前缀快照(基础 + 第 1..k 层)按位置 diff 得出:补丁算法只会原地改写行或在末尾追加,因此顶层索引在各快照之间标识同一行;加入某层后该行发生变化(替换 config、禁用、组内插入)即视为该层修补了这一行。每个快照都会克隆补丁列表,因为 `applyEntryPatches` 会把 `insert` 行按引用从补丁列表推入结果。 + +`dsh-app-boot` 之前为解析补丁复制了 include 的 `!!js` YAML 类型;现在改为导入 `entryListSchema`,方言只有一个归属者。 + +## Alternatives considered + +**启动整棵树后 dump `ctx.loader.entries()`。** 拒绝:启动会求值 `!!js` 表达式(把某台机器的环境泄漏进打印的配置)、以副作用启动适配器和会话、需要独立于 TTY 的拆卸路径,而且慢。dump 是用来调试合成的,而合成是那些文件的纯函数。 + +**在 CLI 里重新实现补丁合并。** 拒绝:`applyPatches` 的第二个实现会与 vendored include 悄然漂移——这恰恰是该功能要调试的失败模式。导出 include 自己的算法只花费一条记录在案的 vendor 修改,却保证了同一性。 + +**用 `/dump-config` TUI 命令代替标志。** 作为唯一形式被拒绝:主要用法是 `dsh --dump-config | diff - <(dsh --dump-default-config)` 这类管道工作流,需要免启动、非 TTY 的界面。之后可以在同一个 `renderConfigDump` 之上再加 TUI 命令。 + +## Consequences + +配置调试从脑中重放补丁变成一条命令,支持工作也可以直接索要 `--dump-config` 输出。vendored include 多出一条记录在案的本地修改(导出 `applyEntryPatches`/`entryListSchema`;对挂载行为无影响),上游同步时需重新应用。来源追踪为每层重新合成一次前缀快照并按 JSON stringify 对行做 diff,因此 dump 有与层数²×行数成正比的额外开销;该开销只存在于免启动的 dump 路径。`renderConfigDump` 的单元测试覆盖层叠顺序、`!!js` 原样往返、来源分隔与分组、带标签的未匹配补丁警告,以及读取/解析/形状失败的大声报错;built-bin e2e 通过 `lib/bin.js` 驱动全部四种标志形式,包括个人覆盖层、其来源标签及其 stderr 警告。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index 1a6a21aac6..33fed58119 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write apps/cli/README.md -README.md: fc5bce195fb10872c605cada1bcb3ed79380265c -README.zh.md: 2fb1272231abb02e145e5c9925362de27307ca86 +README.md: cf038ad19c631721c7b3182ffe83e75e3837d9ba +README.zh.md: c790f973a9ab0071253ab161bd8bc7835ebb2e02 diff --git a/apps/cli/README.md b/apps/cli/README.md index fc5bce195f..cf038ad19c 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -3,7 +3,7 @@ English | [中文](README.zh.md) -Argv is parsed once through a [Commander](https://github.com/tj/commander.js) adapter ([`src/args.ts`](src/args.ts)): one program whose default (no subcommand) is the TUI/headless surface (`--config`, `-p`/`--prompt`, `--resume`), whose `meta` subcommand is the same TUI over this checkout, whose `upgrade` subcommand is an option-less guided-session entry, and whose `web` subcommand is the browser UI. `src/bin.ts` switches on the resolved mode and dynamic-imports only that mode's module. `dsh --help` lists every mode and `dsh web --help` renders the web usage, `dsh --version` prints this app's version, and an unknown option or a mistyped `--resume` fails loud (stderr, exit 1) instead of misrouting. Every subcommand that shares no option with the default surface — `upgrade`, `web`, `meta` — rejects a leaked `--config`/`-p`/`--resume` rather than running and dropping it. `dsh web`'s `--host`/`--port` are unvalidated pass-through overrides: the `dsh-host-webserver` schema is the single source of both the default (the shipped Web overlay value when a flag is absent) and validity, and rejects a bad value at boot. `--trusted-host` appends named authorities for the /api browser-trust fence; an all-interfaces bind additionally derives the machine's LAN IP literals itself ([`src/app-cli-entry.ts`](src/app-cli-entry.ts)), so the printed LAN URL works without flags. +Argv is parsed once through a [Commander](https://github.com/tj/commander.js) adapter ([`src/args.ts`](src/args.ts)): one program whose default (no subcommand) is the TUI/headless surface (`--config`, `-p`/`--prompt`, `--resume`, `--dump-config`, `--dump-default-config`), whose `meta` subcommand is the same TUI over this checkout, whose `upgrade` subcommand is an option-less guided-session entry, and whose `web` subcommand is the browser UI. `src/bin.ts` switches on the resolved mode and dynamic-imports only that mode's module. `dsh --help` lists every mode and `dsh web --help` renders the web usage, `dsh --version` prints this app's version, and an unknown option or a mistyped `--resume` fails loud (stderr, exit 1) instead of misrouting. Every subcommand that shares no option with the default surface — `upgrade`, `web`, `meta` — rejects a leaked `--config`/`-p`/`--resume`/dump flag rather than running and dropping it. `dsh web`'s `--host`/`--port` are unvalidated pass-through overrides: the `dsh-host-webserver` schema is the single source of both the default (the shipped Web overlay value when a flag is absent) and validity, and rejects a bad value at boot. `--trusted-host` appends named authorities for the /api browser-trust fence; an all-interfaces bind additionally derives the machine's LAN IP literals itself ([`src/app-cli-entry.ts`](src/app-cli-entry.ts)), so the printed LAN URL works without flags. The TUI surface: @@ -17,6 +17,8 @@ The TUI surface: `dsh upgrade` is a guided fresh-session entry over the default TUI surface: it mints a fresh session in the invoking directory and seeds its first turn with the bundled `dsh-upgrade` skill, exactly as if the user typed `/skill:`. The launcher passes the skill name on the boot context ([`INITIAL_SKILL_KEY`](../../packages/ui/tui/README.md)), which the TUI auto-invokes once the chat is live. Both take no options — `--config`, `-p`, and `--resume` fail loud — and seed only on this first launch, so a later `dsh --resume ` of the session is an ordinary TUI session with no re-injection. +`dsh --dump-config` and `dsh web --dump-config` print the composed config tree — the shipped base, the surface overlay, and the `--config` or personal overlay, exactly the layers that surface would boot — as YAML on stdout and exit without booting; `--dump-default-config` stops at the surface overlay, so diffing the two shows precisely what the user layer changes. Each run of rows is preceded by a `# ==` comment naming the file it comes from and the layers that patched it (e.g. `# == base.cordis.yml, patched by tui.cordis.yml`), so the output shows provenance while staying one loadable document. Composition runs through the include's own patch algorithm and YAML dialect (`applyEntryPatches`/`entryListSchema` from `@cordisjs/plugin-include`), so the dump cannot drift from what boots; `!!js` expressions print verbatim and unevaluated, and a patch whose target row is absent is reported on stderr with its layer, mirroring the Loader's boot-time warning. Launcher-owned boot-context values (session identity, CLI-flag patches) are per-invocation facts outside the config tree and do not appear. The dump flags reject boot-only flags (`-p`, `--resume`, `--config-replace`) rather than silently ignoring them, and `--dump-default-config` takes no `--config`. + The Web and headless surfaces boot `base.cordis.yml` plus `web.cordis.yml`, then apply `$DSH_HOME/config.yaml`; an explicit `--config ` replaces that personal overlay. Both surfaces otherwise share the same composition: both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, opt into first-message model titles, use the same bounded transient model-request retry policy as the TUI, and mount a disposable in-memory SQLite content-index service. That service is ACTIVE at boot, while its `node:sqlite` module and database handle open only on the first content search. This keeps Node 22 startup output free of SQLite's experimental warning before search is used; the first actual search may still emit the runtime warning. Each service instance owns its database, so parallel invocations neither share unsupported SQLite state nor leave derived index files behind, and the first search lazily reconciles live and persisted logs. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). The shipped TUI and Web compositions register the native DeepSeek adapter plus pi-ai OpenAI and Anthropic profiles. Credentials and endpoint overrides come from the provider-standard `DEEPSEEK_API_KEY` / `DEEPSEEK_BASE_URL`, `OPENAI_API_KEY` / `OPENAI_BASE_URL`, and `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL` pairs in the boot's layered environment. diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 2fb1272231..c790f973a9 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -3,7 +3,7 @@ [English](README.md) | 中文 -Argv 只会通过 [Commander](https://github.com/tj/commander.js) 适配器([`src/args.ts`](src/args.ts))解析一次:同一个程序的默认形式(无子命令)是 TUI/无头界面(`--config`、`-p`/`--prompt`、`--resume`),`meta` 子命令是以本 checkout 为 workspace 的同一个 TUI,`upgrade` 子命令是无选项的引导会话入口,`web` 子命令则是浏览器 UI。`src/bin.ts` 按解析后的 mode 分支,仅动态导入该 mode 的模块。`dsh --help` 列出所有 mode,`dsh web --help` 渲染 Web 用法,`dsh --version` 打印此应用的版本;未知选项或拼错的 `--resume` 会明确报错(stderr,退出码 1),而不会被错路由。凡与默认界面不共享任何选项的子命令(`upgrade`、`web`、`meta`)都会拒绝泄漏进来的 `--config`/`-p`/`--resume`,而不会照常运行并丢弃它。`dsh web` 的 `--host`/`--port` 是未验证的直通覆盖:`dsh-host-webserver` schema 是默认值(标志缺失时使用已交付的 Web 覆盖层值)和有效性的唯一真源,并在启动时拒绝错误值。`--trusted-host` 为 /api 浏览器信任栅栏追加具名权威;全接口绑定还会自行推导本机的 LAN IP 字面量([`src/app-cli-entry.ts`](src/app-cli-entry.ts)),因此打印出的 LAN URL 无需任何标志即可使用。 +Argv 只会通过 [Commander](https://github.com/tj/commander.js) 适配器([`src/args.ts`](src/args.ts))解析一次:同一个程序的默认形式(无子命令)是 TUI/无头界面(`--config`、`-p`/`--prompt`、`--resume`、`--dump-config`、`--dump-default-config`),`meta` 子命令是以本 checkout 为 workspace 的同一个 TUI,`upgrade` 子命令是无选项的引导会话入口,`web` 子命令则是浏览器 UI。`src/bin.ts` 按解析后的 mode 分支,仅动态导入该 mode 的模块。`dsh --help` 列出所有 mode,`dsh web --help` 渲染 Web 用法,`dsh --version` 打印此应用的版本;未知选项或拼错的 `--resume` 会明确报错(stderr,退出码 1),而不会被错路由。凡与默认界面不共享任何选项的子命令(`upgrade`、`web`、`meta`)都会拒绝泄漏进来的 `--config`/`-p`/`--resume`/dump 标志,而不会照常运行并丢弃它。`dsh web` 的 `--host`/`--port` 是未验证的直通覆盖:`dsh-host-webserver` schema 是默认值(标志缺失时使用已交付的 Web 覆盖层值)和有效性的唯一真源,并在启动时拒绝错误值。`--trusted-host` 为 /api 浏览器信任栅栏追加具名权威;全接口绑定还会自行推导本机的 LAN IP 字面量([`src/app-cli-entry.ts`](src/app-cli-entry.ts)),因此打印出的 LAN URL 无需任何标志即可使用。 TUI 界面: @@ -17,6 +17,8 @@ TUI 界面: `dsh upgrade` 是默认 TUI 界面之上的引导式全新会话入口:它在调用目录中创建一个全新会话,并以内置 `dsh-upgrade` skill 播种其首轮,效果等同于用户手动键入 `/skill:`。启动器将 skill 名称提供到启动上下文([`INITIAL_SKILL_KEY`](../../packages/ui/tui/README.md)),TUI 在聊天就绪后自动调用它。两者都不接受任何选项——`--config`、`-p`、`--resume` 都会明确报错——且仅在首次启动时播种,因此之后 `dsh --resume ` 恢复该会话时是普通 TUI 会话,不会重复注入。 +`dsh --dump-config` 和 `dsh web --dump-config` 把合成后的配置树——已交付的基础配置、界面覆盖层,以及 `--config` 或个人覆盖层,恰好是该界面启动时组装的那些层——以 YAML 打印到 stdout 后退出,不启动任何东西;`--dump-default-config` 止步于界面覆盖层,因此对两份输出做 diff 就能精确看出用户层改了什么。每段连续的行之前都有一条 `# ==` 注释,标明该段来自哪个文件以及被哪些层修补过(例如 `# == base.cordis.yml, patched by tui.cordis.yml`),因此输出既展示来源,又仍是一份可加载的文档。合成通过 include 自己的补丁算法和 YAML 方言(`@cordisjs/plugin-include` 的 `applyEntryPatches`/`entryListSchema`)完成,因此 dump 不可能与实际启动漂移;`!!js` 表达式原样打印、不求值,目标行不存在的补丁会连同其所在层报到 stderr,与 Loader 启动时的警告一致。由启动器持有的启动上下文值(会话身份、CLI 标志补丁)是每次调用的事实,位于配置树之外,不会出现。dump 标志会拒绝仅用于启动的标志(`-p`、`--resume`、`--config-replace`)而不是静默忽略它们,`--dump-default-config` 不接受 `--config`。 + Web 和无头界面启动 `base.cordis.yml` 与 `web.cordis.yml`,随后应用 `$DSH_HOME/config.yaml`;显式的 `--config ` 会替代该个人覆盖。除此之外,两者共享同一套组合:两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,选用首条消息模型标题,采用与 TUI 相同的有界暂时性模型请求重试策略,并挂载一个可丢弃的内存 SQLite 内容索引服务。该服务在启动时处于 ACTIVE 状态,但其 `node:sqlite` 模块与数据库句柄分别要到首次内容搜索才会导入和打开。这样可使 Node 22 在尚未使用搜索时的启动输出不出现 SQLite 实验性警告;首次实际搜索仍可能发出运行时警告。每个服务实例独占自己的数据库,因此并行调用既不会共享不受支持的 SQLite 状态,也不会留下派生索引文件,首次搜索还会惰性对账实时日志与持久化日志。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 已交付的 TUI 和 Web 组合会注册原生 DeepSeek 适配器,以及 pi-ai 的 OpenAI 和 Anthropic 提供方配置。凭据和端点覆盖来自启动分层环境中的提供方标准变量对:`DEEPSEEK_API_KEY` / `DEEPSEEK_BASE_URL`、`OPENAI_API_KEY` / `OPENAI_BASE_URL` 和 `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL`。 diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts index a1f0fff4c4..ac74b9468d 100644 --- a/apps/cli/src/args.ts +++ b/apps/cli/src/args.ts @@ -23,6 +23,22 @@ interface TuiInvocation { resume?: string } +/** + * Print the composed config tree and exit, without booting: `--dump-config` + * composes the shipped base, the surface overlay, and the `--config` or + * personal overlay — exactly the layers that surface would boot; + * `--dump-default-config` stops at the surface overlay (the shipped tree, no + * user layer). + */ +interface DumpConfigInvocation { + mode: 'dump-config' + surface: 'tui' | 'web' + /** Omit the `--config`/personal layer and print only the shipped composition. */ + defaultOnly: boolean + /** The `--config` overlay to compose instead of the personal one. */ + config?: string +} + /** Headless one-shot: `dsh -p "task"`. */ interface HeadlessInvocation { mode: 'headless' @@ -69,6 +85,7 @@ interface WebInvocation { /** The resolved `dsh` invocation: exactly one mode. `--help`/`--version`/errors exit inside {@link parseDshArgs}. */ export type DshInvocation = | TuiInvocation + | DumpConfigInvocation | HeadlessInvocation | MetaInvocation | SkillSessionInvocation @@ -82,6 +99,34 @@ interface WebOptions { dev?: boolean workspaceRoot?: string trustedHost?: string[] + dumpConfig?: boolean + dumpDefaultConfig?: boolean +} + +/** + * Resolve the two dump flags for one surface, or return `undefined` when + * neither was passed. Both flags together are contradictory (one includes the + * user layer, the other excludes it) and fail loud through `error`. + */ +function resolveDump( + surface: 'tui' | 'web', + options: { config?: string; dumpConfig?: boolean; dumpDefaultConfig?: boolean }, + error: (message: string) => never, +): DumpConfigInvocation | undefined { + if (options.dumpConfig !== true && options.dumpDefaultConfig !== true) return undefined + if (options.dumpConfig === true && options.dumpDefaultConfig === true) { + error('error: --dump-config and --dump-default-config are mutually exclusive') + } + const defaultOnly = options.dumpDefaultConfig === true + if (defaultOnly && options.config !== undefined) { + error('error: --dump-default-config prints the shipped tree and takes no --config') + } + return { + mode: 'dump-config', + surface, + defaultOnly, + ...options.config !== undefined && { config: options.config }, + } } /** @@ -135,7 +180,26 @@ Examples: .option('--resume ', 'continue a past session by id') .option('--config ', 'apply this overlay of loader patches instead of the personal one') .option('--config-replace ', 'boot this file as the entire tree, ignoring the shipped and personal configuration') - .action((options: { config?: string; configReplace?: string; prompt?: string; resume?: string }) => { + .option('--dump-config', 'print the composed config tree (base + surface + --config/personal overlay) and exit') + .option('--dump-default-config', 'print the shipped config tree (base + surface overlay, no user layer) and exit') + .action((options: { + config?: string + configReplace?: string + prompt?: string + resume?: string + dumpConfig?: boolean + dumpDefaultConfig?: boolean + }) => { + const dump = resolveDump('tui', options, message => program.error(message)) + if (dump !== undefined) { + // The dump prints composition; a boot-only flag alongside it would be + // silently ignored, so reject the mix loud. + if (options.prompt !== undefined || options.resume !== undefined || options.configReplace !== undefined) { + program.error('error: --dump-config/--dump-default-config take none of -p/--prompt, --resume, or --config-replace') + } + resolved = dump + return + } if (options.prompt !== undefined) { // A headless prompt owns the invocation; an empty task has nothing to // run, and --config/--resume are TUI inputs that must not silently @@ -168,10 +232,18 @@ Examples: // a leaked config/prompt/resume option is a mistyped invocation that must fail // loud rather than silently run and drop the input. const rejectParentOptions = (command: string): void => { - const parent = program.opts<{ config?: string; configReplace?: string; prompt?: string; resume?: string }>() + const parent = program.opts<{ + config?: string + configReplace?: string + prompt?: string + resume?: string + dumpConfig?: boolean + dumpDefaultConfig?: boolean + }>() if (parent.config !== undefined || parent.configReplace !== undefined - || parent.prompt !== undefined || parent.resume !== undefined) { - program.error(`error: ${command} takes none of --config, --config-replace, -p/--prompt, or --resume`) + || parent.prompt !== undefined || parent.resume !== undefined + || parent.dumpConfig !== undefined || parent.dumpDefaultConfig !== undefined) { + program.error(`error: ${command} takes none of --config, --config-replace, -p/--prompt, --resume, --dump-config, or --dump-default-config`) } } @@ -198,8 +270,15 @@ Examples: .option('--dev', 'developer mode: hot-reload the browser client') .option('--workspace-root ', 'parent directory for workspaces created from the browser UI') .option('--trusted-host ', 'extra authority the /api browser-trust fence accepts (host or host:port; repeatable)') + .option('--dump-config', 'print the composed config tree (base + web + --config/personal overlay) and exit') + .option('--dump-default-config', 'print the shipped config tree (base + web overlay, no user layer) and exit') .action((options: WebOptions) => { rejectParentOptions('web') + const dump = resolveDump('web', options, message => program.error(message)) + if (dump !== undefined) { + resolved = dump + return + } resolved = resolveWeb(options) }) diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index 6f7ae77c76..aeaaf42692 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -43,6 +43,11 @@ switch (invocation.mode) { await runTui(invocation.config, invocation.resume, undefined, undefined, invocation.configReplace) break } + case 'dump-config': { + const { runDumpConfig } = await import('./dump-config.ts') + runDumpConfig(invocation.surface, invocation.defaultOnly, invocation.config) + break + } case 'meta': { const { runMeta } = await import('./tui.ts') await runMeta() diff --git a/apps/cli/src/dump-config.ts b/apps/cli/src/dump-config.ts new file mode 100644 index 0000000000..39a87c2dc8 --- /dev/null +++ b/apps/cli/src/dump-config.ts @@ -0,0 +1,61 @@ +/** + * `dsh --dump-config` / `dsh web --dump-config` — print the composed config + * tree without booting: the shipped base, the surface overlay, and (unless + * `--dump-default-config`) the `--config` or personal overlay, composed + * through the include's own patch algorithm so the printed tree is exactly + * what that surface would mount. `!!js` expressions print verbatim, + * unevaluated — the dump shows composition, not one process's environment. + * Launcher-provided boot-context values (session identity, CLI-flag patches) + * are per-invocation facts outside the config tree and do not appear. + * @module @deepseek-ai/dsh/dump-config + */ + +import { basename, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { + loadOverlayPatches, + loadPersonalPatches, + PERSONAL_CONFIG_FILENAME, + renderConfigDump, + type ConfigDumpLayer, +} from '@deepseek-ai/dsh-app-boot' +import { resolveDshHome } from '@deepseek-ai/dsh-paths' + +const NAME = 'dsh' + +const BASE_CONFIG = fileURLToPath(new URL('../config/base.cordis.yml', import.meta.url)) +const SURFACE_OVERLAYS = { + tui: fileURLToPath(new URL('../config/tui.cordis.yml', import.meta.url)), + web: fileURLToPath(new URL('../config/web.cordis.yml', import.meta.url)), +} as const + +/* v8 ignore start -- composition over the unit-tested renderConfigDump; the + built-bin e2e drives this path end to end */ +/** + * Print one surface's composed config tree to stdout, with a comment + * separator naming the file each section of rows comes from (and the layers + * that patched it). + * @param surface - which surface overlay to compose over the shared base. + * @param defaultOnly - stop at the surface overlay (no `--config`/personal layer). + * @param config - the `--config` overlay path composed instead of the personal + * one, or `undefined` to use `$DSH_HOME/config.yaml`. + */ +export function runDumpConfig(surface: 'tui' | 'web', defaultOnly: boolean, config?: string): void { + const overlay = SURFACE_OVERLAYS[surface] + const layers: ConfigDumpLayer[] = [ + { label: basename(overlay), patches: loadOverlayPatches(NAME, overlay) }, + ] + if (!defaultOnly) { + if (config === undefined) { + const personal = loadPersonalPatches(NAME) + // The personal file may be absent; the shipped layers still print. + if (personal !== undefined) { + layers.push({ label: join(resolveDshHome(), PERSONAL_CONFIG_FILENAME), patches: personal }) + } + } else { + layers.push({ label: config, patches: loadOverlayPatches(NAME, config) }) + } + } + process.stdout.write(renderConfigDump(NAME, BASE_CONFIG, layers)) +} +/* v8 ignore stop */ diff --git a/apps/cli/tests/args.spec.ts b/apps/cli/tests/args.spec.ts index 396a0e6ca5..cda7818e63 100644 --- a/apps/cli/tests/args.spec.ts +++ b/apps/cli/tests/args.spec.ts @@ -45,6 +45,29 @@ describe('parseDshArgs', () => { .toEqual({ mode: 'web', dev: false, trustedHosts: ['harness.internal:3080', 'lab.internal', '10.0.0.9'] }) }) + it('routes the dump flags per surface: composed with the user layer, or shipped only', () => { + expect(parse(['--dump-config'])).toEqual({ mode: 'dump-config', surface: 'tui', defaultOnly: false }) + expect(parse(['--dump-config', '--config', 'c.yml'])) + .toEqual({ mode: 'dump-config', surface: 'tui', defaultOnly: false, config: 'c.yml' }) + expect(parse(['--dump-default-config'])).toEqual({ mode: 'dump-config', surface: 'tui', defaultOnly: true }) + expect(parse(['web', '--dump-config'])).toEqual({ mode: 'dump-config', surface: 'web', defaultOnly: false }) + expect(parse(['web', '--dump-config', '--config', 'w.yml'])) + .toEqual({ mode: 'dump-config', surface: 'web', defaultOnly: false, config: 'w.yml' }) + expect(parse(['web', '--dump-default-config'])).toEqual({ mode: 'dump-config', surface: 'web', defaultOnly: true }) + // The two dump flags contradict each other; boot-only flags alongside a + // dump would be silently ignored; the shipped tree takes no user overlay. + expect(exitCode(['--dump-config', '--dump-default-config'])).toBe(1) + expect(exitCode(['--dump-default-config', '--config', 'c.yml'])).toBe(1) + expect(exitCode(['--dump-config', '--resume', 's'])).toBe(1) + expect(exitCode(['--dump-config', '-p', 'task'])).toBe(1) + expect(exitCode(['--dump-config', '--config-replace', 'tree.yml'])).toBe(1) + expect(exitCode(['web', '--dump-config', '--dump-default-config'])).toBe(1) + expect(exitCode(['web', '--dump-default-config', '--config', 'w.yml'])).toBe(1) + // A leaked dump flag on a subcommand that has none is a mistyped invocation. + expect(exitCode(['meta', '--dump-config'])).toBe(1) + expect(exitCode(['upgrade', '--dump-config'])).toBe(1) + }) + it('exits nonzero instead of silently starting fresh or dropping inputs', () => { // Empty resume/prompt would be swallowed downstream; --prompt mixed with // TUI inputs must not lose them. (Bad host/port are gated by the webserver diff --git a/apps/cli/tests/built-bin.e2e.ts b/apps/cli/tests/built-bin.e2e.ts index d5bcbfd378..c9e1b29969 100644 --- a/apps/cli/tests/built-bin.e2e.ts +++ b/apps/cli/tests/built-bin.e2e.ts @@ -1,8 +1,9 @@ -import { existsSync } from 'node:fs' +import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { execa } from 'execa' -import { describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' /** * Published-entry smoke for the `dsh` bin: run the built `lib/bin.js` under @@ -22,13 +23,20 @@ import { describe, expect, it } from 'vitest' const repoRoot = fileURLToPath(new URL('../../../', import.meta.url)) const dshBin = join(repoRoot, 'apps/cli/lib/bin.js') -/** Run the built bin with PIPED stdio (stdin closed at EOF); resolve with output + exit code. */ -async function runBuiltBin(): Promise<{ stdout: string; code: number; stderr: string }> { - const result = await execa(process.execPath, [dshBin], { +/** + * Run the built bin with PIPED stdio (stdin closed at EOF); resolve with output + * + exit code. `env` isolates the Harness home for surfaces that read it. + */ +async function runBuiltBin( + args: readonly string[] = [], + env: Record = {}, +): Promise<{ stdout: string; code: number; stderr: string }> { + const result = await execa(process.execPath, [dshBin, ...args], { input: '', timeout: 25_000, killSignal: 'SIGKILL', reject: false, + env, }) if (result.timedOut) { throw new Error(`dsh built bin did not exit within 25s. stdout:\n${result.stdout}\nstderr:\n${result.stderr}`) @@ -45,4 +53,61 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)', // The refusal happens before any plugin mounts: stdout stays silent. expect(stdout).toBe('') }, 30_000) + + describe('dsh --dump-config', () => { + let home: string + beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'dsh-dump-bin-')) }) + afterEach(() => { rmSync(home, { recursive: true, force: true }) }) + + it('prints the shipped TUI composition without booting or needing a TTY', async () => { + const { stdout, code, stderr } = await runBuiltBin(['--dump-default-config'], { DSH_HOME: home }) + expect(code).toBe(0) + expect(stderr).toBe('') + // Base rows composed with the TUI overlay's surface values, `!!js` + // expressions verbatim (unevaluated), and TUI-only inserted rows present. + expect(stdout).toContain("name: '@deepseek-ai/dsh-agent-loop'") + expect(stdout).toContain('model: deepseek-v4-pro') + expect(stdout).toContain('cwd: !!js process.cwd()') + expect(stdout).toContain("name: '@deepseek-ai/dsh-tui'") + // Provenance comment separators name each section's source file. + expect(stdout).toContain('# == base.cordis.yml') + expect(stdout).toContain('# == base.cordis.yml, patched by tui.cordis.yml') + expect(stdout).toContain('# == tui.cordis.yml') + }, 30_000) + + it('layers the personal overlay in --dump-config and reports an unmatched patch on stderr', async () => { + writeFileSync(join(home, 'config.yaml'), [ + '- id: agent-loop', + ' config:', + ' agents:', + ' - id: main', + ' provider: custom-provider', + ' model: custom-model', + '- id: only-on-web', + ' config:', + ' value: 1', + '', + ].join('\n')) + const { stdout, code, stderr } = await runBuiltBin(['--dump-config'], { DSH_HOME: home }) + expect(code).toBe(0) + expect(stdout).toContain('provider: custom-provider') + expect(stdout).not.toContain('model: deepseek-v4-pro') + // The personal layer appears in the patched row's provenance and the + // skipped-patch warning carries its label. + expect(stdout).toContain(`patched by tui.cordis.yml, ${join(home, 'config.yaml')}`) + expect(stderr).toContain('patch: entry "only-on-web" not found') + + // The shipped view ignores the personal overlay entirely. + const shipped = await runBuiltBin(['--dump-default-config'], { DSH_HOME: home }) + expect(shipped.stdout).not.toContain('custom-provider') + expect(shipped.stdout).toContain('model: deepseek-v4-pro') + }, 30_000) + + it('composes the web overlay for `dsh web --dump-config`', async () => { + const { stdout, code } = await runBuiltBin(['web', '--dump-config'], { DSH_HOME: home }) + expect(code).toBe(0) + expect(stdout).toContain("name: '@deepseek-ai/dsh-host-webserver'") + expect(stdout).not.toContain("name: '@deepseek-ai/dsh-tui'") + }, 30_000) + }) }) diff --git a/packages/ui/app-boot/README.i18n.yaml b/packages/ui/app-boot/README.i18n.yaml index 684f322477..619a3ab81d 100644 --- a/packages/ui/app-boot/README.i18n.yaml +++ b/packages/ui/app-boot/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/ui/app-boot/README.md -README.md: 54f754842d9a6673ed6791b94656139f0f1be6a3 -README.zh.md: dd56084812e8241f0db24601ce2baeba51252d42 +README.md: 51bc5082512632dd493956b96c605aff47dc872e +README.zh.md: 644d3a3613a9516cb02881fac8ba7531bffa81eb diff --git a/packages/ui/app-boot/README.md b/packages/ui/app-boot/README.md index 54f754842d..51bc508251 100644 --- a/packages/ui/app-boot/README.md +++ b/packages/ui/app-boot/README.md @@ -14,6 +14,7 @@ Shared boot glue for the app bins ([`dsh`](../../../apps/cli/README.md), [`dsh-c | `loadPersonalPatches(binName, dir?)` | Parse the optional `config.yaml` in the Harness home (default [`resolveDshHome()`](../../util/paths/README.md): `$DSH_HOME`, else `~/.dsh`) — a top-level YAML array of include `PatchOptions` (id-targeted config overrides, `insert` lists, `!!js` allowed); absent file → `undefined`, an unreadable/unparsable/non-array file throws | | `loadOverlayPatches(binName, file)` | Parse a required patch-list file with the same shape as personal config; read or parse failures throw a labelled error | | `boot(binName, absoluteConfigPath, patches?, prepare?)` | Create the root context, install Loader, run optional host preparation before config-tree entries mount (`prepare` may use Loader and provide launcher-owned context slots such as [`MAIN_SESSION_ID_KEY`](../tui/README.md)), then mount and await the include tree, assert entries loaded and activated, and return the root context | +| `renderConfigDump(binName, absoluteConfigPath, layers, warn?)` | Compose the base config and labeled overlay layers offline — the include's own parser and patch algorithm (`entryListSchema`/`applyEntryPatches`), so the result equals what `boot()` mounts — and render YAML with `!!js` expressions verbatim; each run of same-provenance rows is preceded by a `# ==` comment naming the contributing file and the layers that patched it, keeping the output one loadable document; a patch matching no row goes to `warn` with its layer label (default: one stderr line), read/parse/shape failures throw | | `addHarnessSourceSection(ctx, sourceRoot)` | Add a global `harness:source` prompt section (ordered just after the harness identity, before the persona) telling the agent the on-disk path to its own source checkout; a no-op returning `undefined` when the booted tree has no `systemPrompt` service. The section is registered against that service's fiber, so a dev HMR reload of the system prompt drops it until the next boot | | `HARNESS_SOURCE_SECTION` | The `'harness:source'` section name `addHarnessSourceSection` registers under | diff --git a/packages/ui/app-boot/README.zh.md b/packages/ui/app-boot/README.zh.md index dd56084812..644d3a3613 100644 --- a/packages/ui/app-boot/README.zh.md +++ b/packages/ui/app-boot/README.zh.md @@ -14,6 +14,7 @@ | `loadPersonalPatches(binName, dir?)` | 解析 Harness home 中可选的 `config.yaml`(默认使用 [`resolveDshHome()`](../../util/paths/README.md):先取 `$DSH_HOME`,否则取 `~/.dsh`):其顶层是一个 YAML 数组,内容为 include 的 `PatchOptions`(按 id 定位的配置覆盖、`insert` 列表,允许 `!!js`);文件不存在时返回 `undefined`,文件不可读、不可解析或内容不是数组时抛出异常 | | `loadOverlayPatches(binName, file)` | 解析一份必需的 patch 列表文件,其形状与个人配置相同;读取或解析失败时抛出带标签的错误 | | `boot(binName, absoluteConfigPath, patches?, prepare?)` | 创建根上下文并安装 Loader,在配置树条目挂载前执行可选的宿主准备操作(`prepare` 可以使用 Loader,也可以提供由启动器拥有的上下文插槽,例如 [`MAIN_SESSION_ID_KEY`](../tui/README.md)),再挂载并等待 include 树结算,断言所有条目均已加载并激活,最后返回根上下文 | +| `renderConfigDump(binName, absoluteConfigPath, layers, warn?)` | 离线合成基础配置与带标签的覆盖层——使用 include 自己的解析器和补丁算法(`entryListSchema`/`applyEntryPatches`),因此结果与 `boot()` 挂载的内容一致——并渲染为 YAML,`!!js` 表达式原样保留;每段来源相同的连续行之前都有一条 `# ==` 注释,标明贡献该段的文件以及修补过它的层,输出仍是一份可加载的文档;未匹配到行的补丁连同其层标签交给 `warn`(默认:一行 stderr),读取/解析/形状失败则抛出 | | `addHarnessSourceSection(ctx, sourceRoot)` | 添加全局 `harness:source` 提示词段落(顺序紧随 harness 身份、位于 persona 之前),告知 agent(智能体)自身源代码 checkout 的磁盘路径;如果已启动树没有此项服务,则不执行操作并返回 `undefined`。这里的服务是 `systemPrompt`;该段落注册到它的 fiber,因此开发环境 HMR(热模块替换)重新加载系统提示词后,它会消失直至下次启动 | | `HARNESS_SOURCE_SECTION` | `'harness:source'` 段落名称,供 `addHarnessSourceSection` 注册使用 | diff --git a/packages/ui/app-boot/src/index.ts b/packages/ui/app-boot/src/index.ts index 015898f2cb..58b9d63bf8 100644 --- a/packages/ui/app-boot/src/index.ts +++ b/packages/ui/app-boot/src/index.ts @@ -12,7 +12,7 @@ import { basename, dirname, join, resolve } from 'node:path' import * as yaml from 'js-yaml' import { Context, type FiberState } from 'cordis' import Loader from '@cordisjs/plugin-loader' -import Include, { type PatchOptions } from '@cordisjs/plugin-include' +import Include, { applyEntryPatches, entryListSchema, type PatchOptions } from '@cordisjs/plugin-include' import { resolveDshHome } from '@deepseek-ai/dsh-paths' // Side-effect type import: resolves `ctx.get('systemPrompt')` to the service. import type {} from '@deepseek-ai/dsh-system-prompt' @@ -60,16 +60,12 @@ export function loadEnv( /** File inside the Harness home holding the personal loader overlay patches. */ export const PERSONAL_CONFIG_FILENAME = 'config.yaml' -// The include's YAML dialect: `!!js` scalars become expression nodes the -// Loader interpolates against each entry's context at mount time. Personal -// patches are parsed with the same schema so they may reference `process.env`. -// Load-only: this schema never dumps, so no `predicate`/`represent`. -const jsExprType = new yaml.Type('tag:yaml.org,2002:js', { - kind: 'scalar', - resolve: data => typeof data === 'string', - construct: data => ({ __jsExpr: String(data) }), -}) -const personalPatchesSchema = yaml.JSON_SCHEMA.extend(jsExprType) +// The include's YAML dialect (`!!js` scalars become expression nodes the +// Loader interpolates against each entry's context at mount time), imported +// from the include itself so patch parsing and config dumping can never drift +// from what the include mounts. Personal patches share it so they may +// reference `process.env`. +const personalPatchesSchema = entryListSchema /** * Load the optional personal overlay patches (`config.yaml` under the Harness @@ -149,6 +145,141 @@ function parsePatchList( return parsed as PatchOptions[] } +/** One overlay patch list with the label provenance comments print for it. */ +export interface ConfigDumpLayer { + /** Source name shown in provenance comments (a file basename or path). */ + label: string + /** The layer's patches, from {@link loadOverlayPatches} / {@link loadPersonalPatches}. */ + patches: PatchOptions[] +} + +/** + * Compose the effective entry list exactly as `boot()` would mount it: parse + * the base config file with the include's entry-list dialect, apply every + * layer's patches as ONE flattened list through the include's own patch + * algorithm (`applyEntryPatches`) — the same single call `boot()` makes, so + * even patch-visibility corner cases (a later layer targeting a group child a + * plain config replacement introduced, which the single-pass id index never + * sees) compose identically — then render the result as YAML in the same + * dialect (`!!js` expressions print verbatim, unevaluated). + * + * Every run of rows with the same provenance is preceded by a `# ==` comment + * naming the file that contributed the rows and any layers that patched them, + * so the output stays a loadable YAML document while showing which section + * comes from which file. Provenance is derived from single-call prefix + * snapshots (base + layers 1..k), diffed positionally: the patch algorithm + * only rewrites rows in place or appends, so a top-level index identifies one + * row across snapshots, and a layer whose addition changes the row (config + * replacement, disable, group insert) is listed as having patched it. + * + * A patch that matches no row is reported through `warn` with its layer + * label, mirroring the Loader's boot-time warning. Earlier layers' patches + * see an identical preceding state in every snapshot that includes them, so + * each snapshot's warning list extends the previous one and the new tail + * belongs to the added layer. + * @param binName - the diagnostic prefix on read/parse errors. + * @param absoluteConfigPath - the base config file `boot()` would include. + * @param layers - overlay layers in application order (later wins). + * @param warn - sink for skipped-patch diagnostics; defaults to stderr. + * @returns the composed entry list rendered as a YAML document with + * provenance comment separators. + */ +export function renderConfigDump( + binName: string, + absoluteConfigPath: string, + layers: ConfigDumpLayer[], + warn: (line: string) => void = line => void process.stderr.write(`${line}\n`), +): string { + let content: string + try { + content = readFileSync(absoluteConfigPath, 'utf8') + } catch (error) { + throw new Error(`${binName}: failed to read config ${absoluteConfigPath}: ${String(error)}`) + } + let parsed: unknown + try { + parsed = yaml.load(content, { schema: entryListSchema }) + } catch (error) { + throw new Error(`${binName}: failed to parse config ${absoluteConfigPath}: ${String(error)}`) + } + if (!Array.isArray(parsed)) { + throw new Error(`${binName}: config ${absoluteConfigPath} must be a top-level YAML array of entries`) + } + const baseLabel = basename(absoluteConfigPath) + // The YAML boundary yields untyped rows; the include validates entry shape + // at mount, and the dump prints whatever the file holds, so `EntryOptions` + // here is structural trust in the same file `boot()` would include. + const base = parsed as Parameters[0] + // snapshot_k = ONE application of layers 1..k flattened — boot's exact call + // shape for that prefix. snapshot_N is therefore the mounted composition. + // The patches are cloned per call: applyEntryPatches detaches the entry + // list but pushes `insert` rows by reference from the patch list, so + // sharing patch objects across snapshot calls would leak a later + // snapshot's mutations into an earlier one's result. + const snapshot = (count: number, warnings: string[]): ReturnType => { + const flattened = structuredClone(layers.slice(0, count).flatMap(layer => layer.patches)) + return applyEntryPatches(base, flattened, (message: string, ...args: unknown[]) => { + // The include logs through cordis's printf-style logger (`%C` = code); a + // dump has no logger, so substitute inline for a plain line. + let index = 0 + warnings.push(message.replace(/%C/g, () => JSON.stringify(args[index++]))) + }) + } + let previous = base + let previousWarnings: string[] = [] + const provenance: { origin: string; patchedBy: string[] }[] = base.map(() => ({ origin: baseLabel, patchedBy: [] })) + let composed = base + for (let count = 1; count <= layers.length; count += 1) { + const layer = layers[count - 1] + /* v8 ignore next -- count iterates 1..length, so the slot exists */ + if (layer === undefined) continue + const warnings: string[] = [] + composed = snapshot(count, warnings) + for (const line of warnings.slice(previousWarnings.length)) { + warn(`${binName}: [${layer.label}] ${line}`) + } + const before = previous.map(entry => JSON.stringify(entry)) + for (let index = 0; index < composed.length; index += 1) { + if (index >= before.length) provenance.push({ origin: layer.label, patchedBy: [] }) + else if (JSON.stringify(composed[index]) !== before[index]) provenance[index]?.patchedBy.push(layer.label) + } + previous = composed + previousWarnings = warnings + } + return groupedDump(composed, provenance) +} + +/** Render the composed rows grouped under one provenance comment per contiguous run. */ +function groupedDump( + composed: readonly unknown[], + provenance: readonly { origin: string; patchedBy: string[] }[], +): string { + const lines: string[] = [] + let currentLabel: string | undefined + let group: unknown[] = [] + const flush = (): void => { + if (currentLabel === undefined || group.length === 0) return + lines.push(`# == ${currentLabel}`) + lines.push(yaml.dump(group, { schema: entryListSchema, noRefs: true }).trimEnd()) + group = [] + } + for (let index = 0; index < composed.length; index += 1) { + const record = provenance[index] + /* v8 ignore next -- provenance is index-aligned with composed by construction */ + if (record === undefined) continue + const label = record.patchedBy.length === 0 + ? record.origin + : `${record.origin}, patched by ${record.patchedBy.join(', ')}` + if (label !== currentLabel) { + flush() + currentLabel = label + } + group.push(composed[index]) + } + flush() + return lines.join('\n') + '\n' +} + /** * The slice of `process` {@link installFailLoud} needs — injectable so tests * exercise the handler without registering on (or exiting) the real process. diff --git a/packages/ui/app-boot/tests/config-dump.spec.ts b/packages/ui/app-boot/tests/config-dump.spec.ts new file mode 100644 index 0000000000..99af81f2c2 --- /dev/null +++ b/packages/ui/app-boot/tests/config-dump.spec.ts @@ -0,0 +1,187 @@ +/** + * `renderConfigDump` behavior: the offline composition must equal what + * `boot()` mounts (same parser, same patch algorithm), print `!!js` + * expressions verbatim, separate provenance runs with comment lines while + * staying one loadable YAML document, and report skipped patches through + * `warn` instead of failing — mirroring the Loader's boot-time warning for a + * shared overlay whose row exists only on another surface. + */ + +import { mkdtempSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { describe, expect, it, vi } from 'vitest' +import * as yaml from 'js-yaml' +import { entryListSchema } from '@cordisjs/plugin-include' +import { loadOverlayPatches, renderConfigDump } from '../src/index.ts' + +const NAME = 'dsh-test-bin' + +const tmp = (): string => mkdtempSync(join(tmpdir(), 'dsh-config-dump-')) + +function writeBase(dir: string): string { + const base = join(dir, 'base.yml') + writeFileSync(base, [ + '- id: shared', + ' name: ./noop.mjs', + ' config:', + ' value: base', + ' key: !!js process.env.DSH_DUMP_SPEC', + '- id: untouched', + ' name: ./noop.mjs', + '', + ].join('\n')) + return base +} + +describe('renderConfigDump', () => { + it('composes overlay layers in order, prints !!js verbatim, and labels each section with its provenance', () => { + const dir = tmp() + const base = writeBase(dir) + const surface = join(dir, 'surface.yml') + writeFileSync(surface, [ + '- id: shared', + ' config:', + ' value: surface', + ' key: !!js process.env.DSH_DUMP_SPEC', + '- insert:', + ' - id: surface-extra', + ' name: ./noop.mjs', + '', + ].join('\n')) + const personal = join(dir, 'personal.yml') + writeFileSync(personal, [ + '- id: surface-extra', + ' config:', + ' value: personal', + '', + ].join('\n')) + + const dump = renderConfigDump(NAME, base, [ + { label: 'surface.yml', patches: loadOverlayPatches(NAME, surface) }, + { label: 'personal.yml', patches: loadOverlayPatches(NAME, personal) }, + ], () => {}) + // Comments do not break loadability: the dump parses as one document + // equal to what boot() would mount. + const parsed = yaml.load(dump, { schema: entryListSchema }) as { + id: string + config?: Record + }[] + expect(parsed).toEqual([ + { + id: 'shared', + name: './noop.mjs', + config: { value: 'surface', key: { __jsExpr: 'process.env.DSH_DUMP_SPEC' } }, + }, + { id: 'untouched', name: './noop.mjs' }, + { id: 'surface-extra', name: './noop.mjs', config: { value: 'personal' } }, + ]) + // Unevaluated: the expression text round-trips as a !!js scalar. + expect(dump).toContain('!!js process.env.DSH_DUMP_SPEC') + // Provenance separators: origin file, plus every layer that changed the + // row; an inserted row carries the inserting layer as its origin. + expect(dump).toContain('# == base.yml, patched by surface.yml') + expect(dump).toContain('# == base.yml\n- id: untouched') + expect(dump).toContain('# == surface.yml, patched by personal.yml\n- id: surface-extra') + expect(dump.indexOf('# == base.yml, patched by surface.yml')).toBeLessThan(dump.indexOf('# == base.yml\n- id: untouched')) + }) + + it('groups contiguous same-provenance rows under one separator', () => { + const dir = tmp() + const base = join(dir, 'base.yml') + writeFileSync(base, [ + '- id: a', + ' name: ./noop.mjs', + '- id: b', + ' name: ./noop.mjs', + '', + ].join('\n')) + const dump = renderConfigDump(NAME, base, [], () => {}) + expect(dump.match(/# == base\.yml/g)).toHaveLength(1) + expect(dump).toContain('# == base.yml\n- id: a') + }) + + it('composes all layers as one flattened patch list, exactly like boot()', () => { + // boot() flattens every layer into ONE applyEntryPatches call, whose id + // index sees inserted rows but NOT children introduced by a plain group + // `config` replacement. A per-layer composition would rebuild the index + // between layers and let the second layer patch that child — a tree the + // real boot never mounts. Pin the single-call semantics: the child patch + // is skipped (with the layer-labeled warning), matching boot. + const dir = tmp() + const base = join(dir, 'base.yml') + writeFileSync(base, [ + '- id: g', + ' name: ./group.mjs', + ' group: true', + ' config: []', + '', + ].join('\n')) + const warnings: string[] = [] + const dump = renderConfigDump(NAME, base, [ + { + label: 'a.yml', + patches: [{ id: 'g', config: [{ id: 'child', name: './noop.mjs', config: { v: 1 } }] }], + }, + { label: 'b.yml', patches: [{ id: 'child', config: { v: 2 } }] }, + ], line => void warnings.push(line)) + expect(warnings).toEqual([`${NAME}: [b.yml] patch: entry "child" not found`]) + const parsed = yaml.load(dump, { schema: entryListSchema }) as { + config?: { config?: { v?: number } }[] + }[] + expect(parsed[0]?.config?.[0]?.config?.v).toBe(1) + // The skipped layer did not change the row, so it is not in provenance. + expect(dump).toContain('# == base.yml, patched by a.yml\n- id: g') + expect(dump).not.toContain('b.yml\n- id: g') + }) + + it('reports a patch whose target row is absent through warn with its layer label and keeps composing', () => { + const dir = tmp() + const base = writeBase(dir) + const overlay = join(dir, 'overlay.yml') + writeFileSync(overlay, [ + '- id: only-on-another-surface', + ' config:', + ' value: ignored', + '- id: shared', + ' config:', + ' value: patched', + '', + ].join('\n')) + const warnings: string[] = [] + const dump = renderConfigDump( + NAME, base, + [{ label: 'overlay.yml', patches: loadOverlayPatches(NAME, overlay) }], + line => void warnings.push(line), + ) + expect(warnings).toEqual([`${NAME}: [overlay.yml] patch: entry "only-on-another-surface" not found`]) + const parsed = yaml.load(dump, { schema: entryListSchema }) as { config?: { value?: string } }[] + expect(parsed[0]?.config?.value).toBe('patched') + }) + + it('defaults its warn sink to one stderr line per skipped patch', () => { + const dir = tmp() + const base = writeBase(dir) + const write = vi.spyOn(process.stderr, 'write').mockReturnValue(true) + try { + renderConfigDump(NAME, base, [{ label: 'x.yml', patches: [{ id: 'absent', config: {} }] }]) + expect(write).toHaveBeenCalledWith(`${NAME}: [x.yml] patch: entry "absent" not found\n`) + } finally { + write.mockRestore() + } + }) + + it('fails loud on a missing, unparsable, or non-array base config', () => { + const dir = tmp() + expect(() => renderConfigDump(NAME, join(dir, 'absent.yml'), [], () => {})) + .toThrow(new RegExp(`^${NAME}: failed to read config `)) + const invalid = join(dir, 'invalid.yml') + writeFileSync(invalid, 'invalid: [unclosed\n') + expect(() => renderConfigDump(NAME, invalid, [], () => {})) + .toThrow(new RegExp(`^${NAME}: failed to parse config `)) + const scalar = join(dir, 'scalar.yml') + writeFileSync(scalar, 'id: not-a-list\n') + expect(() => renderConfigDump(NAME, scalar, [], () => {})) + .toThrow('must be a top-level YAML array of entries') + }) +}) diff --git a/vendor/README.md b/vendor/README.md index b140c057ab..2d3e1b6b05 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -39,6 +39,7 @@ Keep this log exhaustive — every divergence from upstream must be listed. 7. **`cordis/src/*.ts` JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed to the fork. 8. **`include/src/index.ts` hot-reload hardening**: `refresh()` awaits the full read-and-update and catches failures (logging a warning and keeping the last good entry tree) instead of rethrowing — upstream's throw escaped `@cordisjs/plugin-hmr`'s async watcher callback as an unhandled rejection, so one bad `cordis.yml` edit killed a live app. `read()` rejects a non-array parse result (an empty or mid-write truncated file parses to `undefined`, which upstream later crashed on) and commits `content`/`data` only on success, so reverting an edit to the exact last good content reads as "unchanged". `refresh()` and the `internal/update` listener re-apply `config.patches` before `root.update()`, matching initial load; upstream applied patches only in `[Service.init]`, so any config hot-reload silently reverted overlay-patched entries and removed inserted ones. `applyPatches` deep-copies via `structuredClone` instead of mutating the cached parse (repeated application converges; removing a patch reverts), and the veto-style `internal/update` listener persists the incoming config itself (`Fiber.update` only assigns behind `next()`), so later re-reads use the new patches. `[Service.init]` falls back to `initial` only on `ENOENT`; an existing-but-invalid file fails loud with its real parse error instead of "config file not found" (or a silent overwrite). `applyPatches` also indexes each `insert`ed entry as it is added, so a later patch in the same list can configure or disable a row an earlier patch inserted; upstream built the id index once before the patch loop, leaving inserted rows silently unpatchable. That matters because `dsh` composes one shared base (`apps/cli/config/base.cordis.yml`) with a surface overlay, an optional `--config` overlay, and the personal `~/.dsh/config.yaml` as sibling patch lists at one include level — patches never cross an include boundary, so surface-only rows would otherwise be unreachable from user config. Covered by `packages/ui/app-boot/tests/config-reload.spec.ts`. 9. **Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`; its built ESM/CJS entries retain explicit `.mjs`/`.cjs` extensions. +10. **`include/src/index.ts` patch-semantics export**: extracted the private `applyPatches` body into the exported pure function `applyEntryPatches(data, patches, warn)` (the method delegates to it) and exported the `!!js` YAML dialect as `entryListSchema`, so `dsh --dump-config` composes and prints exactly what the include would mount without booting a tree. Behavior-preserving for mounting; the extraction exists because config tooling must never reimplement (and drift from) the patch algorithm. ## Sync procedure diff --git a/vendor/include/src/index.ts b/vendor/include/src/index.ts index 29f6a3a951..29c894401c 100644 --- a/vendor/include/src/index.ts +++ b/vendor/include/src/index.ts @@ -13,7 +13,15 @@ const JsExpr = new yaml.Type('tag:yaml.org,2002:js', { represent: (data) => data['__jsExpr'], }) -const schema = yaml.JSON_SCHEMA.extend(JsExpr) +/** + * The entry-list YAML dialect: `!!js` scalars round-trip as expression nodes + * the Loader evaluates at entry activation. Exported so config tooling + * (`dsh --dump-config`) parses and prints exactly the dialect this include + * mounts. + */ +export const entryListSchema = yaml.JSON_SCHEMA.extend(JsExpr) + +const schema = entryListSchema const writable: Record = { '.json': 'application/json', @@ -23,6 +31,92 @@ const writable: Record = { const supported = new Set(Object.keys(writable)) +/** + * Apply patch lists to an entry list — THE patch semantics of this include, + * shared by mounting (`applyPatches`) and offline config tooling + * (`dsh --dump-config`) so a dump can never drift from what boots. The input + * is never mutated: patching shared entry objects would bake earlier patch + * values into the cached parse, so repeated application (config hot-reloads) + * could never revert a removed or changed patch. Inserted entries are indexed + * as they are added, so a later patch in the same list can target a row an + * earlier patch inserted. A patch that matches nothing warns and is skipped. + * @param data - the parsed entry list (JSON-safe plain data). + * @param patches - the patch list to apply, in order. + * @param warn - sink for skipped-patch diagnostics (printf-style, `%C` = code). + * @returns a detached entry list with every applicable patch applied. + */ +export function applyEntryPatches( + data: EntryOptions[], + patches: PatchOptions[] | undefined, + warn: (message: string, ...args: any[]) => void, +): EntryOptions[] { + if (!patches?.length) return [...data] + data = structuredClone(data) + + const entryMap = new Map() + const buildMap = (entries: EntryOptions[]) => { + for (const entry of entries) { + if (entry.id) entryMap.set(entry.id, entry) + if (entry.group && Array.isArray(entry.config)) { + buildMap(entry.config) + } + } + } + buildMap(data) + + for (const patch of patches) { + const { id, insert, name, ...overrides } = patch + + if (insert) { + if (id) { + const target = entryMap.get(id) + if (!target) { + warn('patch insert: entry %C not found', id) + continue + } + if (!target.group) { + warn('patch insert: entry %C is not a group', id) + continue + } + if (!Array.isArray(target.config)) target.config = [] + target.config.push(...insert) + } else { + data.push(...insert) + } + // Index what this patch added so a LATER patch in the same list can + // target it. Patch lists compose one layer per source (surface overlay, + // then `--config`, then the user's), and a layer must be able to + // configure or disable a row an earlier layer inserted; without this, + // inserted rows were silently unpatchable. + buildMap(insert) + continue + } + + if (!id) { + warn('patch: id is required for non-insert patches') + continue + } + + const target = entryMap.get(id) + if (!target) { + warn('patch: entry %C not found', id) + continue + } + + if (name && name !== target.name) { + warn('patch: name mismatch for %C (expected %C, got %C), skipping', id, target.name, name) + continue + } + + for (const [key, value] of Object.entries(overrides)) { + if (key === 'id') continue + target[key] = value + } + } + + return data +} + /** Runtime patch applied to entries loaded from an included config file. */ export interface PatchOptions { id?: string @@ -125,79 +219,9 @@ export class Include extends EntryTree { } private applyPatches(data: EntryOptions[], patches = this.config.patches): EntryOptions[] { - // Always detach from the cached parse: patching shared entry objects would - // bake earlier patch values into `this.data`, so repeated application - // (config hot-reloads) could never revert a removed or changed patch. The - // supported extensions guarantee JSON-safe plain data, so `structuredClone` - // cannot throw here. - if (!patches?.length) return [...data] - data = structuredClone(data) - - const entryMap = new Map() - const buildMap = (entries: EntryOptions[]) => { - for (const entry of entries) { - if (entry.id) entryMap.set(entry.id, entry) - if (entry.group && Array.isArray(entry.config)) { - buildMap(entry.config) - } - } - } - buildMap(data) - - for (const patch of patches) { - const { id, insert, name, ...overrides } = patch - - if (insert) { - if (id) { - const target = entryMap.get(id) - if (!target) { - this.ctx.root.logger?.('loader').warn('patch insert: entry %C not found', id) - continue - } - if (!target.group) { - this.ctx.root.logger?.('loader').warn('patch insert: entry %C is not a group', id) - continue - } - if (!Array.isArray(target.config)) target.config = [] - target.config.push(...insert) - } else { - data.push(...insert) - } - // Index what this patch added so a LATER patch in the same list can - // target it. Patch lists compose one layer per source (surface overlay, - // then `--config`, then the user's), and a layer must be able to - // configure or disable a row an earlier layer inserted; without this, - // inserted rows were silently unpatchable. - buildMap(insert) - continue - } - - if (!id) { - this.ctx.root.logger?.('loader').warn('patch: id is required for non-insert patches') - continue - } - - const target = entryMap.get(id) - if (!target) { - this.ctx.root.logger?.('loader').warn('patch: entry %C not found', id) - continue - } - - if (name && name !== target.name) { - this.ctx.root.logger?.('loader').warn( - 'patch: name mismatch for %C (expected %C, got %C), skipping', - id, target.name, name, - ) - continue - } - - for (const [key, value] of Object.entries(overrides)) { - if (key === 'id') continue - target[key] = value - } - } - - return data + return applyEntryPatches(data, patches, (message, ...args) => { + this.ctx.root.logger?.('loader').warn(message, ...args) + }) } async* [Service.init]() {