docs(agent-note): refresh shared scoped-layer proposal
This commit is contained in:
@@ -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
|
||||
2026-07-12-scoped-layers-store.md: f2056446abb3b8d0793b6ef7898c01001ccf0460
|
||||
2026-07-12-scoped-layers-store.zh.md: 9726eb3de953af1086d8bcdd779fc02b3c324596
|
||||
2026-07-12-scoped-layers-store.md: 64d565542e39a5ffcea98bc3343504760f31a416
|
||||
2026-07-12-scoped-layers-store.zh.md: ebe823b980864f4f24d4888312a73d2a5ee34fb5
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Agent Note: Scoped-layers store — one aggregate layer per scope behind a scheduling helper
|
||||
# Agent Note: Shared scoped-layer storage
|
||||
|
||||
Status: proposed
|
||||
|
||||
@@ -6,34 +6,25 @@ English | [中文](2026-07-12-scoped-layers-store.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
Agent scoping ([the agent-scope Agent Note](../../implemented/architecture/2026-07-08-agent-scope-contexts.md), [runtime design](../../implemented/architecture/2026-07-12-agent-scope-runtime-design.md)) made "a registry with a global layer plus per-agent layers" a recurring shape, and every occurrence is hand-written. Six registration sites exist today — `tools.register`/`tools.restrict`/`tools.guard` in `dsh-tools` and `section`/`tools`/`variable` in `dsh-system-prompt` — each repeating the same 10-15-line effect choreography around its applicable global or scoped containers: read the calling context's tag, get or create the layer, validate, mutate, yield a rollback that deletes the entry and reclaims an emptied scoped layer, emit the applicable change event, and return the exact Cordis effect disposer.
|
||||
Agent scoping ([decision](../../implemented/architecture/2026-07-08-agent-scope-contexts.md), [runtime design](../../implemented/architecture/2026-07-12-agent-scope-runtime-design.md)) gives scope-aware registries the same recurring shape: one global registration layer plus one exact agent layer. Seven registration facades implement that shape independently: `tools.register`, `tools.restrict`, and `tools.guard` in `dsh-tools`; `SystemPrompt.section`, `SystemPrompt.tools`, and `SystemPrompt.variable` in `dsh-system-prompt`; and `CommandService.register` in `dsh-commands`.
|
||||
|
||||
Beyond the duplication, the risk concentrates in the choreography details:
|
||||
- The rollback must be collected before the change emit (so a throwing listener unwinds the insertion instead of leaking it)
|
||||
- The returned disposer must be Cordis's own function (a wrapper silently breaks nested ordered teardown)
|
||||
- Emptied scoped layers must be reclaimed (a disposed agent must not leave residue keyed by its dead `ScopeKey`)
|
||||
Each facade repeats the lifecycle choreography around its domain state: derive visibility from the calling context, create a scoped container on demand, attach ownership to the same Cordis fiber, install undo before notifying observers, return Cordis's exact disposer, and reclaim empty scoped state. The copies use separate maps and collection types, so a service has no object representing one scope's complete contribution and must reproduce cleanup for every table.
|
||||
|
||||
Every new consumer has to rewrite all of that correctly, and the copies have already diverged stylistically — two private layer helpers in `dsh-tools`, three inline IIFEs in `dsh-system-prompt`.
|
||||
The duplicated code carries three non-obvious requirements:
|
||||
|
||||
Finally, one agent's contribution to one service is scattered across several maps that know nothing of each other — there is no object that means "what this scope contributes here" — and the consumer count keeps growing: scoped guards and per-agent prompt/tool composition landed recently, while per-agent `fs/*` policy, `llm/*` overrides, and compaction policy are plausible future users of the same pattern.
|
||||
- Visibility and ownership must come from the same context; accepting them separately permits a registration visible in one scope but disposed with another.
|
||||
- Undo must be collected before a change callback runs, so a throwing callback rolls the mutation back.
|
||||
- The public disposer must be the exact function returned by `ctx.effect()`; wrapping it breaks Cordis's identity-based ordered teardown.
|
||||
|
||||
The shared part is lifecycle and insertion-ordered storage, not registry policy. Tool restrictions, reserved transport handling, prompt evaluation timing, command normalization, exact diagnostics, and callback containment remain different domain contracts.
|
||||
|
||||
## Proposal
|
||||
|
||||
`dsh-scope` gains a key-agnostic `store.ts`, with Cordis as its only peer dependency. The module implements the smallest abstraction shared by the six current sites: **business state and validation stay in an explicit layer class; one helper owns layer selection, effect attachment, rollback, notification, and reclamation**. One helper instance belongs to one service, and one layer instance aggregates everything a scope contributes to that service.
|
||||
`@deepseek-ai/dsh-scope` gains a key-agnostic `store.ts` implementation module. The package continues to peer on Cordis and `@deepseek-ai/dsh-invariants`, and its invariant companion remains unchanged. The package root exports four storage symbols: `ScopeLayer`, `ScopedLayers`, `NamedEntries`, and `AnonymousEntries`. `EntryValues` remains internal, and `store.ts` is not a package subpath.
|
||||
|
||||
- **`ScopedLayers<L>`** is a concrete scheduler, not a base class. It owns the global layer plus one `Map<ScopeKey, L>`, constructs scoped layers on demand through an explicit factory, and reclaims a layer when `isEmpty()`. Its `effect(ctx, action, options?)` accepts one synchronous action that returns one synchronous undo because that is the complete shape of all six current sites. The single `ctx` decides both the visible layer (`scopeOf(ctx)`) and the owning Cordis fiber (`ctx.effect`), so "visible to X, disposed with Y" stays unrepresentable. The helper yields the undo before notifying listeners, returns Cordis's exact disposer, and reclaims a newly created empty layer if validation or mutation throws. Reads are `global`/`peek` plus `merge` (named entries with scoped shadowing and an optional global-admission predicate), `values` (global then scoped concatenation without shadowing), and `keys` (the pre-restriction name universe).
|
||||
- **Explicit `ScopeLayer` classes** make each service's state visible to readers. `ToolLayer` and `PromptLayer` declare their three table properties and their `isEmpty()` aggregation directly; a small layer factory receives only the scope, while its closure may capture real constructor dependencies. Domain methods stay ordinary class methods. This costs a few repetitive declarations but avoids a mapped-type class factory, a scheduler/layer ownership cycle, reserved property names, and generated runtime structure.
|
||||
- **`NamedEntries<V>` and `AnonymousEntries<V>`** are the two shared insertion-ordered tables. Named entries expose `insert`/lookup and retain the current global/scoped duplicate wording through domain `kind` and per-agent-alternative labels; anonymous entries expose only `append`, using process-unique symbol keys for O(1) undo removal. Keeping the classes separate makes meaningless mixed named/anonymous operations unrepresentable and keeps key types sound. Their iterators borrow membership and typed contribution values; they do not clone or freeze values. `ScopedLayers` materializes only the merged arrays/maps already required by the service read paths.
|
||||
`ScopeLayer` keeps the aggregate concept explicit while requiring only whole-layer emptiness. A service defines one concrete layer whose tables and domain helpers fit that service; `ScopedLayers` owns construction, selection, lifecycle attachment, notification, and aggregate reclamation.
|
||||
|
||||
`dsh-tools` migrates its three tables into one `ToolLayer`: tools, compiled restrictions, and guards. The layer owns restriction admission and guard evaluation; the facade retains domain validation that needs service configuration, such as the reserved `run_code` name and the current known-global-name universe. Readonly allow/deny inputs are compiled once into internal sets. `dsh-system-prompt` likewise migrates sections, tool providers, and variables into one `PromptLayer`. Every registration facade performs its public argument validation and then makes one `effect` call with a label and, for guards, `silent: true`. A generic helper does not learn domain rules such as "restrictions require a scoped context."
|
||||
|
||||
`assemble` stays in the `SystemPrompt` facade for three reasons: the subject scope's layer may not exist and reads must not create it; shadowing requires merge-before-evaluate so a hidden section provider is never called; and the assembly waterfall and `toolOrder` use service-level resources. Sections and tool providers keep their current materialized derived views. Variable providers instead iterate the global and scoped `NamedEntries` directly, preserving today's live Map behavior when a provider registers another variable during assembly. Tool guards likewise iterate their `AnonymousEntries` directly.
|
||||
|
||||
Migration preserves public behavior and exact duplicate messages. The internal aggregate layer is reclaimed only after all three tables empty rather than when one table empties; no service API exposes layer identity. Direct live iteration retains current re-entrant variable-provider and guard behavior, while selector helpers continue to materialize the same section, tool-provider, and tool-resolution views their facades build today.
|
||||
|
||||
`ScopeLayer`, `EntryValues`, `ScopedLayers`, `NamedEntries`, and `AnonymousEntries` are public `dsh-scope` root exports with export JSDoc. Consumers import them from `@deepseek-ai/dsh-scope`; `store.ts` is an implementation module, not a package subpath.
|
||||
|
||||
## API sketch
|
||||
## Public interface
|
||||
|
||||
```ts ignore-check
|
||||
export interface ScopeLayer {
|
||||
@@ -41,22 +32,28 @@ export interface ScopeLayer {
|
||||
}
|
||||
|
||||
export class ScopedLayers<L extends ScopeLayer> {
|
||||
constructor(createLayer: (scope: ScopeKey | undefined) => L, options: { onChange?: () => void })
|
||||
constructor(
|
||||
createLayer: (scope: ScopeKey | undefined) => L,
|
||||
onChange: () => void,
|
||||
)
|
||||
|
||||
readonly global: L
|
||||
peek(scope: ScopeKey | undefined): L | undefined
|
||||
merge<T>(scope: ScopeKey | undefined, pick: (layer: L) => NamedEntries<T>, admitGlobal?: (name: string) => boolean): Map<string, T>
|
||||
values<T>(scope: ScopeKey | undefined, pick: (layer: L) => EntryValues<T>): T[]
|
||||
keys<T>(scope: ScopeKey | undefined, pick: (layer: L) => NamedEntries<T>): string[]
|
||||
effect(ctx: Context, action: (layer: L) => () => void, options: { label: string; silent?: boolean }): () => void
|
||||
|
||||
merge<V>(
|
||||
scope: ScopeKey | undefined,
|
||||
pick: (layer: L) => NamedEntries<V>,
|
||||
): Map<string, V>
|
||||
|
||||
effect(
|
||||
ctx: Context,
|
||||
action: (layer: L) => () => void,
|
||||
options: { label: string; notify?: boolean },
|
||||
): () => void
|
||||
}
|
||||
|
||||
export interface EntryValues<V> {
|
||||
values(): IterableIterator<V>
|
||||
isEmpty(): boolean
|
||||
}
|
||||
|
||||
export class NamedEntries<V> implements EntryValues<V> {
|
||||
constructor(kind: string, perAgentAlternative: string, scope: ScopeKey | undefined)
|
||||
export class NamedEntries<V> {
|
||||
constructor(duplicateError: (name: string) => Error)
|
||||
insert(name: string, value: V): () => void
|
||||
get(name: string): V | undefined
|
||||
has(name: string): boolean
|
||||
@@ -66,80 +63,61 @@ export class NamedEntries<V> implements EntryValues<V> {
|
||||
isEmpty(): boolean
|
||||
}
|
||||
|
||||
export class AnonymousEntries<V> implements EntryValues<V> {
|
||||
export class AnonymousEntries<V> {
|
||||
append(value: V): () => void
|
||||
values(): IterableIterator<V>
|
||||
isEmpty(): boolean
|
||||
}
|
||||
```
|
||||
|
||||
What a migrated consumer looks like — the heaviest current site shrinks from 30+ lines of choreography to a declaration and one-line facades:
|
||||
## Storage contract
|
||||
|
||||
```ts ignore-check
|
||||
class ToolLayer implements ScopeLayer {
|
||||
readonly tools = new NamedEntries<ToolDefinition>('tool', 'variant', this.scope)
|
||||
readonly restrictions = new AnonymousEntries<CompiledToolRestriction>()
|
||||
readonly guards = new AnonymousEntries<ToolGuardRegistration>()
|
||||
- The constructor creates `global` once with `createLayer(undefined)`. A scoped layer is created only by `effect()`; `peek()` and `merge()` never create one, and `peek(undefined)` returns `undefined` because the global layer is already explicit.
|
||||
- `merge()` is the only materialized generic read. It copies named global entries in insertion order, then applies matching scoped entries in their insertion order so same-name entries shadow without moving unrelated names.
|
||||
- `NamedEntries.insert()` checks and inserts atomically, returns an idempotent exact-entry undo, and obtains the registry's exact duplicate diagnostic from the caller-supplied factory. Lookup and iterators retain native `Map` order and live iteration.
|
||||
- `AnonymousEntries.append()` assigns a unique internal key per registration, so equal callbacks or values remain independent. Its iterator is live and insertion-ordered.
|
||||
- `effect()` derives the key with `scopeOf(ctx)` and attaches the action to that same `ctx.effect()`. It accepts one synchronous action returning one synchronous undo; actions must either return their undo or throw before retaining a contribution. The helper does not normalize the wider Cordis `Effect` union.
|
||||
- `effect()` collects the action's undo before calling `onChange` and returns the exact `ctx.effect()` disposer. Disposal runs the action undo before notification, is idempotent through Cordis, and removes a scoped layer only after its complete `ScopeLayer.isEmpty()` becomes true.
|
||||
- `options.notify` defaults to `true`. The callback's own policy stays authoritative: tool and prompt change callbacks may throw and trigger registration rollback; `CommandService.notifyChange()` contains observer failures; tool guards pass `notify: false`.
|
||||
|
||||
constructor(
|
||||
readonly scope: ScopeKey | undefined,
|
||||
) {}
|
||||
## Registry migrations
|
||||
|
||||
isEmpty(): boolean { return this.tools.isEmpty() && this.restrictions.isEmpty() && this.guards.isEmpty() }
|
||||
addRestriction(filter: ToolRestriction): () => void { /* compile to sets, append */ }
|
||||
admits(name: string): boolean { /* intersection over this.restrictions.values() */ }
|
||||
guardReason(view: Readonly<ToolExecution>): string | undefined { /* first monotonic denial */ }
|
||||
}
|
||||
`dsh-tools` defines one `ToolLayer` containing named tools plus anonymous compiled restrictions and guard registrations. `ToolRegistry` retains its private domain resolver for visible definitions, pre-restriction known names, restrictable global names, scoped shadowing, restrictions, and reserved `run_code` insertion. Guard evaluation continues to live-iterate global then scoped registrations so re-entrant additions retain current behavior.
|
||||
|
||||
class ToolRegistry extends Service {
|
||||
private readonly layers = new ScopedLayers(
|
||||
scope => new ToolLayer(scope),
|
||||
{ onChange: () => this.ctx.emit('tools/change') },
|
||||
)
|
||||
`dsh-system-prompt` defines one `PromptLayer` containing named sections and variables plus anonymous tool providers. Assembly merges sections before evaluating them, so a shadowed provider is never called. Tool-provider membership is materialized once per assembly. Variable providers continue to live-iterate global then scoped tables, preserving re-entrant registration behavior.
|
||||
|
||||
register(definition: ToolDefinition): () => void {
|
||||
return this.layers.effect(this.ctx,
|
||||
layer => layer.tools.insert(definition.name, definition),
|
||||
{ label: 'tools.register()' })
|
||||
}
|
||||
`dsh-commands` defines a one-table layer containing `NamedEntries<RegisteredCommand>`. Effective views use `merge()`, while `CommandService` retains definition normalization and freezing, exact duplicate diagnostics, sorted immutable descriptors, direct execution, HMR cleanup, and independently contained `commands/change` observers.
|
||||
|
||||
private resolveVisible(scope?: ScopeKey): ToolDefinition[] {
|
||||
const scoped = this.layers.peek(scope)
|
||||
return Array.from(this.layers.merge(scope, layer => layer.tools, name => scoped?.admits(name) ?? true).values())
|
||||
}
|
||||
}
|
||||
```
|
||||
All seven facades keep validation and diagnostics in their owning registry and continue to return the exact Cordis disposer. The migration changes neither public registry behavior nor model-, human-, wire-, persistence-, or configuration-visible output.
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Per-scope registry instances behind a parent/child delegation chain.** Instance explosion; the "deployment tools plus my tools" merged view needs a hand-built delegating registry per service; single-subscription observers (persistence, the ACP bridge) would have to discover and subscribe per instance; and a delegation chain cannot express subtraction (restrictions). A child registry would also have to reach back into a parent context, widening the exposure surface.
|
||||
**Keep the independent implementations.** This avoids a new library interface but leaves lifecycle ordering, disposer identity, and scope reclamation duplicated across seven facades.
|
||||
|
||||
**Explicit scope parameters on registration APIs.** Already rejected by the agent-scope Agent Note: omitting the parameter silently registers globally, and the shape can express visible-to-X-disposed-with-Y, which is almost always a bug.
|
||||
**One helper per table.** This removes some local code but preserves multiple per-scope maps and cannot reclaim one scope's aggregate contribution correctly.
|
||||
|
||||
**Extracting only the data structure, leaving the choreography in services.** Removes the safe half of the duplication and keeps the dangerous half — the rollback-before-emit ordering, raw-disposer, and reclamation rules are exactly where the bugs live.
|
||||
**Per-scope registry instances.** Child registries would need delegation for global-plus-scoped views, special subtraction for restrictions, and observer discovery across instances. They would move complexity rather than remove it.
|
||||
|
||||
**Accepting the full Cordis `Effect` union as a layer action.** None of the six sites has asynchronous setup, multiple undos, or an independent settlement boundary. Normalizing promises, iterables, async iterables, LIFO sealing, and partial failure would duplicate lifecycle machinery speculatively. The store accepts one synchronous action and one undo; a future real boundary can justify widening it.
|
||||
**Explicit scope parameters on registration methods.** Separate visibility and ownership inputs make mismatched lifetimes representable, while an omitted scope silently becomes global.
|
||||
|
||||
**Generating layer classes from a mapped-type table DSL.** The two consumers each declare three tables. A class factory would save a handful of lines while adding generated runtime shape, reserved names, polymorphic-`this` typing, and a second construction model. Explicit classes are easier to inspect and can still share the entry tables and `ScopedLayers`.
|
||||
**Accept the complete Cordis `Effect` union.** None of the seven registrations has asynchronous setup, multiple undos, or an independent settlement boundary. General normalization would duplicate Cordis lifecycle machinery without a current consumer.
|
||||
|
||||
**A fixed-container helper with built-in view semantics.** Pins container shapes and merge policy inside the helper; business gets no freedom, and every naming or single-value variation becomes a helper feature request.
|
||||
**Expose `ScopedLayers.values()`, `ScopedLayers.keys()`, or a global-admission predicate.** Those operations encode consumer-specific live/materialized and filtering policies. Direct table iteration preserves explicit live semantics, `merge()` covers the shared named shadowing operation, and `ToolRegistry` keeps its richer private resolver.
|
||||
|
||||
**One helper per table.** Reproduces today's scattered bookkeeping — that is the status quo being replaced, with N scope maps per service and no aggregate for an agent's contribution.
|
||||
**Put `values()` on `ScopeLayer` or export `EntryValues`.** A layer aggregates heterogeneous tables and has no coherent value type or iteration policy. `EntryValues` is useful only to share implementation details between the two table classes; making it public would enlarge the interface without giving callers a meaningful layer-wide read.
|
||||
|
||||
**`helper.get(ctx).effect(...)` two-step registration.** Splits layer creation from lifecycle attachment; a throw between the steps strands an empty layer, and the returned handle is an extra allocation per call.
|
||||
|
||||
**Layers holding a ctx and registering their own effects.** Turns data objects into lifecycle managers and reinstates the choreography once per business class.
|
||||
**Generate layers from a mapped-type table description.** Three-table and one-table concrete layers are short, inspectable, and free to hold domain helpers. A class generator would add a second construction model and generated runtime shape for little leverage.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- `store.ts` ships in `dsh-scope` (peer dependencies unchanged: Cordis only; module-graph position unchanged) with per-file 100% coverage of layer selection and reclamation, synchronous action/undo ordering, throwing-action cleanup, throwing-change-listener rollback, exact disposer identity, `label`/`silent`, factory typing, merge selectors, and separate named/anonymous entry semantics. Its five public symbols are re-exported from the package root and carry export JSDoc.
|
||||
- `dsh-tools` and `dsh-system-prompt` each collapse to one `ScopedLayers`; every registration facade validates its domain contract and then makes one `effect` call, and all keep returning the exact Cordis effect disposer.
|
||||
- Existing behavior, duplicate messages, validation order, live variable-provider re-entrancy, and live guard re-entrancy remain unchanged. Tests additionally pin aggregate reclamation timing and selector materialization.
|
||||
- Documentation lands in the same change: `dsh-scope`/`dsh-tools`/`dsh-system-prompt` READMEs; on implementation this Agent Note moves to `implemented/` and the [runtime-design Agent Note](../../implemented/architecture/2026-07-12-agent-scope-runtime-design.md)'s registration section is updated in place.
|
||||
- `dsh-scope` exports exactly the four proposed storage symbols from its root and covers global construction, lazy scoped construction, non-creating reads, named shadowing, aggregate reclamation, failure cleanup, notification ordering, exact disposer identity, caller-owned duplicate errors, independent anonymous duplicates, and live iterators.
|
||||
- `dsh-tools`, `dsh-system-prompt`, and `dsh-commands` migrate all seven registration facades while preserving validation order, exact diagnostics, views, notification policy, re-entrancy, and HMR disposal.
|
||||
- The `dsh-scope` README and scoped core-data documentation describe the public contract; architecture and runtime-design references identify the shared store without duplicating it. Consumer READMEs remain focused on their unchanged public behavior.
|
||||
- This pair moves to `implemented/architecture` in the implementation PR, changes `Proposal` to present-tense `Decision`, and records shipped consequences and verification. Existing keyless snapshots remain byte-identical.
|
||||
|
||||
## Risks
|
||||
|
||||
- The layer/facade boundary may not fit a future consumer's shape. Mitigation: `ScopeLayer` requires only `isEmpty()`, while the factory closure can capture constructor dependencies without giving a layer ownership of its scheduler.
|
||||
- A future registration may genuinely need asynchronous setup or several independently owned undos. The helper deliberately does not predict that lifecycle; such a consumer must first identify its owner and settlement boundary, then widen the contract with tests.
|
||||
- Explicit layer declarations repeat three property initializers and `isEmpty()` in each consumer. Accepted: the repetition keeps runtime state and types visible and avoids a second DSL for two classes.
|
||||
- Two core registries migrate at once. Mitigated by the behavior comparison performed during design and by landing the store with equivalence-pinning tests before either migration commit.
|
||||
- A future registration may need asynchronous setup or several independently owned undos. That consumer must identify its ownership and settlement boundary before widening this deliberately synchronous interface.
|
||||
- A throwing action that mutates outside the returned undo contract cannot be repaired generically. Entry operations are atomic, migrations perform fallible validation before insertion, and tests pin cleanup for factory and pre-retention action failures.
|
||||
- Aggregate reclamation keeps a scoped layer alive until every table empties. This is intentional and observable only as internal storage lifetime; tests pin that one table's disposal does not discard sibling contributions.
|
||||
- The public classes add a reusable package contract. Keeping reads narrow and domain policy in consumers limits how much future code must preserve.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# Agent Note: 作用域分层存储——每 scope 一个聚合层与统一调度 helper
|
||||
# Agent Note: 共享作用域分层存储
|
||||
|
||||
Status: proposed
|
||||
|
||||
@@ -6,34 +6,25 @@ Status: proposed
|
||||
|
||||
## 问题
|
||||
|
||||
agent 作用域落地之后([agent-scope Agent Note](../../implemented/architecture/2026-07-08-agent-scope-contexts.md)、[运行时设计篇](../../implemented/architecture/2026-07-12-agent-scope-runtime-design.md)),「一张全局层加若干 per-agent 层的注册表」成为反复出现的形态,而每一处都是手写的。今天已有六个登记口——`dsh-tools` 的 `tools.register`/`tools.restrict`/`tools.guard` 与 `dsh-system-prompt` 的 `section`/`tools`/`variable`——每处都围绕适用的全局或专属容器重复同一段 10-15 行的 effect 编排:读调用方上下文的标签、按需建层、校验、变更、yield 一个删除条目并回收空专属层的回滚、发适用的 change 事件,然后返回 Cordis effect 的原始 disposer。
|
||||
agent(智能体)作用域机制([决策](../../implemented/architecture/2026-07-08-agent-scope-contexts.md)、[运行时设计](../../implemented/architecture/2026-07-12-agent-scope-runtime-design.md))让支持作用域的注册表反复呈现同一种形态:一个全局注册层,加上一个与具体 agent 精确对应的层。七个注册门面各自独立实现这一形态:`tools.register`、`tools.restrict` 和 `tools.guard`(位于 `dsh-tools`);`SystemPrompt.section`、`SystemPrompt.tools` 和 `SystemPrompt.variable`(位于 `dsh-system-prompt`);以及 `CommandService.register`(位于 `dsh-commands`)。
|
||||
|
||||
除此之外:风险集中在编排细节上:
|
||||
- 回滚必须在 change 发出之前被收集(抛错的监听器才能回卷插入而不是泄漏)
|
||||
- 返回的 disposer 必须是 Cordis 自己的那个函数(包装器会静默破坏嵌套的有序拆除)
|
||||
- 清空的专属层必须被回收(被 dispose 的 agent 不得留下以死 `ScopeKey` 为键的残余)
|
||||
每个门面都围绕自己的领域状态重复相同的生命周期编排:从调用方上下文导出可见性,按需创建专属容器,把属主绑定到同一个 Cordis fiber,先装入 undo 再通知观察者,原样返回 Cordis 的 disposer,并回收空的专属状态。各份实现采用不同的映射与集合类型,因此服务内没有一个对象能表示某个 scope 的完整贡献,而且每张表都必须重复清理逻辑。
|
||||
|
||||
每个新消费者都要把这一切重新写对一遍,而各副本的写法已经分叉——`dsh-tools` 里有两个私有建层 helper,`dsh-system-prompt` 里是三处内联 IIFE。
|
||||
重复代码承载着三项不明显的要求:
|
||||
|
||||
最后,一个 agent 在一个服务里的贡献散落在几张互不相识的 Map 里——不存在一个「这个 scope 在这里贡献了什么」的对象——而消费者还在持续增多:专属 guard 与 per-agent 提示词/工具组合是最近落地的一批,per-agent 的 `fs/*` 策略、`llm/*` 覆盖与 compaction 策略则是同一模式的潜在后续用户。
|
||||
- 可见性与属主必须来自同一个上下文;若分开接受二者,就能登记出对一个 scope 可见、却随另一个 scope 销毁的贡献。
|
||||
- change 回调运行前必须收集 undo,抛错的回调才能回滚变更。
|
||||
- 公开 disposer 必须就是 `ctx.effect()` 返回的那个函数;包装它会破坏 Cordis 基于身份的有序拆除。
|
||||
|
||||
共享的是生命周期与保持插入顺序的存储,而不是注册表策略。工具限制、保留传输处理、提示词求值时机、命令规范化、精确诊断和回调异常隔离,仍分别属于不同的领域契约。
|
||||
|
||||
## 提案
|
||||
|
||||
`dsh-scope` 新增与键类型无关的 `store.ts`,peer 依赖仍只有 Cordis。模块只抽取六个现有登记口已经共同证明的最小形状:**业务状态与校验留在显式层类里;一个 helper 统一负责选层、挂 effect、回滚、通知与回收**。一个 helper 实例属于一个服务;一个层实例聚合某 scope 对该服务的全部贡献。
|
||||
`@deepseek-ai/dsh-scope` 新增与键类型无关的 `store.ts` 实现模块。该包(package)继续将 Cordis 和 `@deepseek-ai/dsh-invariants` 列为对等依赖(peer dependency),其不变量配套模块保持不变。包根导出四个存储符号:`ScopeLayer`、`ScopedLayers`、`NamedEntries` 和 `AnonymousEntries`。`EntryValues` 仍是内部接口,`store.ts` 不是包子路径。
|
||||
|
||||
- **`ScopedLayers<L>`** 是具体调度器,不作基类。它持有全局层与一张 `Map<ScopeKey, L>`,通过显式工厂按需构造专属层,并在层 `isEmpty()` 时回收。`effect(ctx, action, options?)` 只接受一个同步 action,action 只返回一个同步 undo,因为六个现有登记口的完整形状就是如此。单一 `ctx` 同时决定可见层(`scopeOf(ctx)`)与属主 Cordis fiber(`ctx.effect`),「对 X 可见、随 Y 销毁」因此不可表达。helper 在通知监听器前 yield undo,返回 Cordis 的原始 disposer,并在校验或变更抛错时回收刚建出的空层。读取接口是 `global`/`peek`,以及 `merge`(命名条目的专属遮蔽与可选全局放行谓词)、`values`(不遮蔽地依次拼接全局与专属条目)和 `keys`(限制前名字全集)。
|
||||
- **显式 `ScopeLayer` 类**让每个服务的状态一眼可见。`ToolLayer` 与 `PromptLayer` 直接声明各自三项表属性与 `isEmpty()` 聚合;一个小工厂只向构造器传入 scope,闭包仍可捕获真实构造依赖。领域方法仍是普通类方法。代价是几行重复声明,收益是不用引入 mapped-type 类工厂、scheduler/layer 属主环、保留属性名和生成式运行时结构。
|
||||
- **`NamedEntries<V>` 与 `AnonymousEntries<V>`** 是两种共用的保插入序条目表。命名表暴露 `insert`/查询,并通过领域 `kind` 与 per-agent alternative 标签保持现有全局/专属重名文案;匿名表只暴露 `append`,以进程内唯一 symbol 作键支持 O(1) 撤销删除。分成两类以后,无意义的命名/匿名混用不可表达,key 类型也保持健全。迭代器借用表成员与带类型的贡献值,不会 clone 或 freeze 值;`ScopedLayers` 只物化服务读路径本来就需要的合并数组或 Map。
|
||||
`ScopeLayer` 保留显式的聚合概念,同时只要求判断整个层是否为空。服务定义一个具体层,使其表结构与领域 helper 适合该服务;`ScopedLayers` 负责构造、选择、生命周期挂接、通知和聚合回收。
|
||||
|
||||
`dsh-tools` 把工具、已编译 restriction 与 guard 三张表合并进一个 `ToolLayer`。restriction 放行判断与 guard 求值归层所有;`run_code` 保留名、当前已知全局名集合等依赖服务配置的领域校验仍留在门面。只读 allow/deny 输入只编译一次,成为内部 Set。`dsh-system-prompt` 同样把 section、tool provider 与 variable 合并进一个 `PromptLayer`。每个登记门面先完成公开参数校验,再以 label 做一次 `effect` 调用;guard 额外传 `silent: true`。通用 helper 不理解「restriction 必须由 scoped context 调用」之类领域规则。
|
||||
|
||||
`assemble` 留在 `SystemPrompt` 门面,三条理由:主体 scope 的层可能不存在,读路径不得创建它;遮蔽语义要求先合并再求值,被遮蔽的 section provider 绝不能被调用;组装 waterfall 与 `toolOrder` 使用服务级资源。section 与 tool provider 保持既有的派生视图物化;variable provider 则直接遍历全局与专属 `NamedEntries`,保留 provider 在组装期间登记另一 variable 时的现有活 Map 行为。tool guard 同样直接遍历其 `AnonymousEntries`。
|
||||
|
||||
迁移保持公开行为与精确重名文案不变。内部聚合层会在三张表全部清空后才回收,而不是某一张表清空时回收;服务 API 不暴露层身份。直接活遍历保留现有 variable-provider 与 guard 重入行为,selector helper 则继续物化门面今天已经在构造的 section、tool-provider 与工具解析视图。
|
||||
|
||||
`ScopeLayer`、`EntryValues`、`ScopedLayers`、`NamedEntries` 与 `AnonymousEntries` 都是带 export JSDoc 的 `dsh-scope` 根导出。消费者从 `@deepseek-ai/dsh-scope` 导入;`store.ts` 是实现模块,不是 package subpath。
|
||||
|
||||
## API 草图
|
||||
## 公开接口
|
||||
|
||||
```ts ignore-check
|
||||
export interface ScopeLayer {
|
||||
@@ -41,22 +32,28 @@ export interface ScopeLayer {
|
||||
}
|
||||
|
||||
export class ScopedLayers<L extends ScopeLayer> {
|
||||
constructor(createLayer: (scope: ScopeKey | undefined) => L, options: { onChange?: () => void })
|
||||
constructor(
|
||||
createLayer: (scope: ScopeKey | undefined) => L,
|
||||
onChange: () => void,
|
||||
)
|
||||
|
||||
readonly global: L
|
||||
peek(scope: ScopeKey | undefined): L | undefined
|
||||
merge<T>(scope: ScopeKey | undefined, pick: (layer: L) => NamedEntries<T>, admitGlobal?: (name: string) => boolean): Map<string, T>
|
||||
values<T>(scope: ScopeKey | undefined, pick: (layer: L) => EntryValues<T>): T[]
|
||||
keys<T>(scope: ScopeKey | undefined, pick: (layer: L) => NamedEntries<T>): string[]
|
||||
effect(ctx: Context, action: (layer: L) => () => void, options: { label: string; silent?: boolean }): () => void
|
||||
|
||||
merge<V>(
|
||||
scope: ScopeKey | undefined,
|
||||
pick: (layer: L) => NamedEntries<V>,
|
||||
): Map<string, V>
|
||||
|
||||
effect(
|
||||
ctx: Context,
|
||||
action: (layer: L) => () => void,
|
||||
options: { label: string; notify?: boolean },
|
||||
): () => void
|
||||
}
|
||||
|
||||
export interface EntryValues<V> {
|
||||
values(): IterableIterator<V>
|
||||
isEmpty(): boolean
|
||||
}
|
||||
|
||||
export class NamedEntries<V> implements EntryValues<V> {
|
||||
constructor(kind: string, perAgentAlternative: string, scope: ScopeKey | undefined)
|
||||
export class NamedEntries<V> {
|
||||
constructor(duplicateError: (name: string) => Error)
|
||||
insert(name: string, value: V): () => void
|
||||
get(name: string): V | undefined
|
||||
has(name: string): boolean
|
||||
@@ -66,80 +63,61 @@ export class NamedEntries<V> implements EntryValues<V> {
|
||||
isEmpty(): boolean
|
||||
}
|
||||
|
||||
export class AnonymousEntries<V> implements EntryValues<V> {
|
||||
export class AnonymousEntries<V> {
|
||||
append(value: V): () => void
|
||||
values(): IterableIterator<V>
|
||||
isEmpty(): boolean
|
||||
}
|
||||
```
|
||||
|
||||
迁移后的消费者长什么样——现存最重的登记口从 30+ 行编排缩为一份声明加一行门面:
|
||||
## 存储契约
|
||||
|
||||
```ts ignore-check
|
||||
class ToolLayer implements ScopeLayer {
|
||||
readonly tools = new NamedEntries<ToolDefinition>('tool', 'variant', this.scope)
|
||||
readonly restrictions = new AnonymousEntries<CompiledToolRestriction>()
|
||||
readonly guards = new AnonymousEntries<ToolGuardRegistration>()
|
||||
- 构造器只创建一次 `global`,调用的是 `createLayer(undefined)`。只有 `effect()` 会创建专属层;`peek()` 和 `merge()` 从不创建专属层,而 `peek(undefined)` 返回 `undefined`,因为全局层已经显式存在。
|
||||
- `merge()` 是唯一会物化结果的通用读取接口。它按插入顺序复制全局命名条目,再按专属条目的插入顺序应用这些条目;同名条目完成遮蔽,但不会移动无关名称。
|
||||
- `NamedEntries.insert()` 以原子方式检查并插入,返回幂等且只撤销该精确条目的 undo,并通过调用方提供的工厂取得所属注册表的精确重名诊断。查询与迭代器保留 `Map` 的原生顺序和活遍历语义。
|
||||
- `AnonymousEntries.append()` 为每次登记分配唯一内部键,因此值相等的回调或其他值仍彼此独立。其迭代器是保留插入顺序的活迭代器。
|
||||
- `effect()` 通过 `scopeOf(ctx)` 导出键,并把 action 挂到同一个 `ctx.effect()` 上。它只接受一个同步 action,且该 action 只返回一个同步 undo;action 要么返回其 undo,要么必须在保留任何贡献之前抛错。helper 不会规范化更宽泛的 Cordis `Effect` union。
|
||||
- `effect()` 在调用 `onChange` 前收集 action 的 undo,并原样返回 `ctx.effect()` 的 disposer。销毁时先运行 action undo 再通知;Cordis 保证其幂等性;只有整个层的 `ScopeLayer.isEmpty()` 变为 true 后,helper 才删除专属层。
|
||||
- `options.notify` 默认为 `true`。回调自身的策略仍具最终效力:工具与提示词的 change 回调可以抛错并触发登记回滚;`CommandService.notifyChange()` 会隔离观察者失败;工具 guard 传入 `notify: false`。
|
||||
|
||||
constructor(
|
||||
readonly scope: ScopeKey | undefined,
|
||||
) {}
|
||||
## 注册表迁移
|
||||
|
||||
isEmpty(): boolean { return this.tools.isEmpty() && this.restrictions.isEmpty() && this.guards.isEmpty() }
|
||||
addRestriction(filter: ToolRestriction): () => void { /* compile to sets, append */ }
|
||||
admits(name: string): boolean { /* intersection over this.restrictions.values() */ }
|
||||
guardReason(view: Readonly<ToolExecution>): string | undefined { /* first monotonic denial */ }
|
||||
}
|
||||
`dsh-tools` 定义一个 `ToolLayer`,其中包含命名工具以及匿名的已编译 restriction 和 guard 登记。`ToolRegistry` 保留其私有领域解析器,由它处理可见定义、限制前的已知名称、可限制的全局名称、专属遮蔽、restriction,以及保留的 `run_code` 插入。guard 求值继续先活遍历全局登记,再活遍历专属登记,因此重入时新增的登记保持现有行为。
|
||||
|
||||
class ToolRegistry extends Service {
|
||||
private readonly layers = new ScopedLayers(
|
||||
scope => new ToolLayer(scope),
|
||||
{ onChange: () => this.ctx.emit('tools/change') },
|
||||
)
|
||||
`dsh-system-prompt` 定义一个 `PromptLayer`,其中包含命名的段落与变量,以及匿名工具提供方。组装流程在求值前合并段落,因此被遮蔽的提供方不会被调用。每次组装只物化一次工具提供方成员集合。变量提供方继续先活遍历全局表,再活遍历专属表,从而保留重入登记行为。
|
||||
|
||||
register(definition: ToolDefinition): () => void {
|
||||
return this.layers.effect(this.ctx,
|
||||
layer => layer.tools.insert(definition.name, definition),
|
||||
{ label: 'tools.register()' })
|
||||
}
|
||||
`dsh-commands` 定义一个单表层,其中包含 `NamedEntries<RegisteredCommand>`。生效视图使用 `merge()`;`CommandService` 则保留对定义的规范化与冻结处理、精确重名诊断、经过排序的不可变描述符、直接执行、HMR(热模块替换)清理,以及对各个 `commands/change` 观察者分别隔离失败的行为。
|
||||
|
||||
private resolveVisible(scope?: ScopeKey): ToolDefinition[] {
|
||||
const scoped = this.layers.peek(scope)
|
||||
return Array.from(this.layers.merge(scope, layer => layer.tools, name => scoped?.admits(name) ?? true).values())
|
||||
}
|
||||
}
|
||||
```
|
||||
七个门面都把校验与诊断留在所属注册表中,并继续返回 Cordis 的原始 disposer。迁移既不改变公开注册表行为,也不改变模型可见或人类可见的输出,以及协议、持久化或配置层面的可见输出。
|
||||
|
||||
## 备选方案
|
||||
|
||||
**每 scope 一个注册表实例,父子委托链。** 实例爆炸;「部署工具加我的工具」的合并视图要每个服务手写一个委托注册表;单订阅观察者(持久化、ACP bridge)必须逐实例发现并订阅;委托链表达不了减法(restriction)。子注册表还得反向触及父上下文,扩大暴露面。
|
||||
**保留彼此独立的实现。** 这样不必新增库接口,但七个门面仍会重复生命周期顺序、disposer 身份和 scope 回收。
|
||||
|
||||
**注册 API 上的显式 scope 参数。** agent-scope Agent Note 已否决:漏传参数即静默注册为全局,且该形状能表达「对 X 可见、随 Y 销毁」——几乎必然是 bug。
|
||||
**每张表一个 helper。** 这能减少一部分局部代码,但会保留多张按 scope 划分的映射,而且无法正确回收某个 scope 的聚合贡献。
|
||||
|
||||
**只抽数据结构、编排留在服务。** 消掉的是重复里安全的那一半,留下的是危险的那一半——回滚先于 emit 的顺序、原始 disposer、回收规则,恰是 bug 所在。
|
||||
**每 scope 一个注册表实例。** 子注册表需要通过委托获得全局加专属的视图,对 restriction 进行特殊的减法处理,并跨实例发现观察者。这只会转移复杂度,而不会消除复杂度。
|
||||
|
||||
**让 layer action 接受完整 Cordis `Effect` union。** 六个现有登记口都没有异步 setup、多份 undo 或独立 settlement 边界。现在就规范化 Promise、iterable、async iterable、LIFO 合成与部分失败,会重复一套纯属推测的生命周期 machinery。store 只接受一个同步 action 与一个 undo;未来出现真实边界时再凭证据拓宽。
|
||||
**注册方法上的显式 scope 参数。** 分开的可见性与属主输入让不匹配的生命周期成为可表达状态,而遗漏 scope 则会静默变成全局登记。
|
||||
|
||||
**由 mapped-type 表 DSL 生成层类。** 两个消费者各自只有三张表。类工厂省下几行代码,却引入生成式运行时形状、保留名、多态 `this` 类型和第二种构造模型。显式类更易检查,同时仍可复用两种条目表与 `ScopedLayers`。
|
||||
**接受完整的 Cordis `Effect` union。** 七个登记口都没有异步 setup、多份 undo 或独立 settlement 边界。通用规范化会在没有现有消费者需要它时重复 Cordis 的生命周期 machinery。
|
||||
|
||||
**内置视图语义的固定容器 helper。** 容器形态与合并策略被钉死在 helper 里;业务没有自由度,任何命名或单值变体都变成对 helper 的功能诉求。
|
||||
**暴露 `ScopedLayers.values()`、`ScopedLayers.keys()` 或全局放行谓词。** 这些操作会编码消费方特有的活遍历或物化策略,以及过滤策略。直接遍历条目表可保留显式的活语义,`merge()` 覆盖共享的命名遮蔽操作,而 `ToolRegistry` 继续保有功能更丰富的私有解析器。
|
||||
|
||||
**每张表一个 helper。** 复刻今天的散装簿记——那正是被替换的现状:每服务 N 张 scope Map,agent 的贡献没有聚合。
|
||||
**把 `values()` 放在 `ScopeLayer` 上,或导出 `EntryValues`。** 一个层会聚合异构表,因而没有一致的值类型或迭代策略。`EntryValues` 只适合在两个表类之间共享实现细节;将其公开只会扩大接口,却不能为调用方提供有意义的整层读取方式。
|
||||
|
||||
**`helper.get(ctx).effect(...)` 两步式登记。** 把建层与挂生命周期拆成两步;两步之间抛错会搁浅一个空层,返回的 handle 还是每次调用一笔额外分配。
|
||||
|
||||
**层持有 ctx、自己注册 effect。** 把数据对象变成生命周期管理者,编排在每个业务类里重演一遍。
|
||||
**通过 mapped-type 表描述生成层。** 三表与单表具体层都很短、易于检查,并可自由持有领域 helper。类生成器会增加第二种构造模型和生成式运行时形状,收益却很小。
|
||||
|
||||
## 验收标准
|
||||
|
||||
- `store.ts` 落在 `dsh-scope`(peer 依赖不变:仅 Cordis;模块图位置不变),逐文件 100% 覆盖选层与回收、同步 action/undo 顺序、action 抛错清理、change 监听器抛错回滚、原始 disposer 身份、`label`/`silent`、工厂类型、合并 selector,以及分开的命名/匿名条目语义。五个公开符号从 package 根重导出并带 export JSDoc。
|
||||
- `dsh-tools` 与 `dsh-system-prompt` 各收敛为一个 `ScopedLayers`;每个登记门面先校验领域契约再做一次 `effect` 调用,并继续返回 Cordis effect 的原始 disposer。
|
||||
- 既有行为、重名文案、校验顺序、variable-provider 活重入与 guard 活重入不变。测试另行钉住聚合回收时机与 selector 物化。
|
||||
- 文档随同一变更落地:`dsh-scope`/`dsh-tools`/`dsh-system-prompt` 的 README;实现后本 Agent Note 移入 `implemented/`,并就地更新[运行时设计 Agent Note](../../implemented/architecture/2026-07-12-agent-scope-runtime-design.md) 的注册章节。
|
||||
- `dsh-scope` 从包根恰好导出拟议的四个存储符号,并覆盖全局构造、专属层延迟构造、非创建式读取、命名遮蔽、聚合回收、失败清理、通知顺序、原始 disposer 身份、调用方拥有的重名错误、相同匿名值的独立登记和活迭代器。
|
||||
- `dsh-tools`、`dsh-system-prompt` 与 `dsh-commands` 迁移全部七个注册门面,同时保留校验顺序、精确诊断、视图、通知策略、重入行为和 HMR 清理。
|
||||
- `dsh-scope` README 与作用域核心数据文档描述公开契约;架构和运行时设计引用标识共享 store,但不重复其内容。各消费方 README 继续聚焦其未改变的公开行为。
|
||||
- 实现 PR 将本组文件移入 `implemented/architecture`,把 `Proposal` 改为以现在时书写的 `Decision`,并记录已落地的后果与验证。现有无密钥快照保持逐字节一致。
|
||||
|
||||
## 风险
|
||||
|
||||
- 层/门面边界可能不适配某个未来消费者的形状。缓解:`ScopeLayer` 只要求 `isEmpty()`;工厂闭包可捕获构造依赖,无需让层反向持有 scheduler。
|
||||
- 未来登记口可能真的需要异步 setup 或多份独立属主的 undo。helper 刻意不预测这种生命周期;该消费者必须先说明 owner 与 settlement 边界,再连同测试拓宽契约。
|
||||
- 显式层声明会在两个消费者中各重复三行属性初始化与一段 `isEmpty()`。接受:这点重复让运行时状态和类型保持可见,避免为两个类引入第二套 DSL。
|
||||
- 两个核心注册表同时迁移。缓解:设计期已完成逐行为对比,且 store 连同钉住等价性的测试先于任一迁移 commit 落地。
|
||||
- 未来的登记可能需要异步 setup 或多份分别拥有属主的 undo。该消费方必须先明确其属主与 settlement 边界,再拓宽这个刻意保持同步的接口。
|
||||
- 抛错的 action 若在返回的 undo 契约之外产生变更,通用 helper 无法修复。条目操作是原子的;迁移会在插入前执行可能失败的校验;测试会钉住工厂失败和保留贡献前的 action 失败清理。
|
||||
- 聚合回收会让专属层一直存活到所有表都清空。这是有意行为,并且只能通过内部存储生命周期观察到;测试会钉住销毁一张表时不会丢弃同层的其他贡献。
|
||||
- 公开类新增了一项可复用的包契约。保持读取接口狭窄并把领域策略留在消费方,可以减少未来代码必须维持的契约范围。
|
||||
|
||||
Reference in New Issue
Block a user