DSH / Atlas
2026-08-06implementedarchitecturearchived 2026-09-04

Subagent list identity via the projection unit

subagent 列表经投影单元读取身份

Before the rewrite, `SubagentRuntime.listChildren` ran two full-log materializations — `listEvents` plus `readEvent` — on every listing for each direct child with `header.origin === 'subagent'`, each materialization accompanied by a full-log structuredClone, all to fold two fields, mode and label, out of the descriptor event. The descriptor's position in the log is not fixed — the fork prefix is arbitrarily long, and

English

Problem

Before the rewrite, SubagentRuntime.listChildren ran two full-log materializations — listEvents plus readEvent — on every listing for each direct child with header.origin === 'subagent', each materialization accompanied by a full-log structuredClone, all to fold two fields, mode and label, out of the descriptor event. The descriptor's position in the log is not fixed — the fork prefix is arbitrarily long, and zstd-compressed frames carry no seq index — so there is no shortcut to locating it; this path had no cache whatsoever, and its cost amplifies with transcript length × child count × listing frequency. It also dragged session-query in as a hard dependency of listing: in a deployment without a query backend, list_agents rejects wholesale with SUBAGENT_CONTROL_SESSION_QUERY_UNAVAILABLE, even though enumeration needs nothing but header facts.

The same root cause has a second symptom: on every Agent-bound RPC's owner check, the host-side hasSubagentDescriptor() scans the target session's own suffix, even though SessionHeader.origin already answers the vast majority of the same question.

The root cause is that the durable-subagent-catalog decision made the descriptor event (subagent/descriptor) the catalog's sole durable authority yet paired descriptor reads with no cache layer, and explicitly accepted the per-child double read as the "no-index correctness baseline". Web subagent conversations (#1569) already put "is this a subagent" into the header (SessionHeader.origin), so identity determination no longer reads the log; mode and label still had to be scanned.

Decision

mode and label are folded by the subagent projection unit (pure identity, two arms), and the unit is the sole authority over the fold rules. Enumeration uses the shared Session query corpus, while value retrieval walks a three-rung compute-and-discard ladder: a live child synchronously reads the registry's existing watermark cache (zero log reads); an unseeded cold child may use the optional sessionProjectionCache checkpoint because its exact inherited cut is known to be zero; every seeded child and every cache miss pays one body-bearing Session observation plus a fold through the registered subagent unit. No index, no cache of its own, no list-side write-back.

There are three families of escape from the per-child scan: promote mode/label into the header (the write path pays); build a durable derivation for the projection (a checkpoint ladder, or values landed during query-index rebuild with read-side reconciliation); or compute at read time (live from the watermark cache, cold from one full read). This note takes the third. "Values landed with the query index" was retired wholesale: query infrastructure was forced to learn domain vocabulary while the sole consumer is satisfied by read-time computation — the live child's zero reads come for free from session-projection's existing watermark cache, and the cold child's single full read is explicitly accepted as compute-and-discard. The first two routes and the retirement rationale are detailed under Alternatives considered.

Key points:

  • The subagent list uses the Session query corpus for enumeration and body-bearing observations: mode/label still comes through ctx.sessionProjections, and the list owns no descriptor parser or domain index.
  • Value retrieval is a three-rung compute-and-discard ladder: a live child reads sessionProjections.snapshot(session, ['subagent']) (the registry's existing watermark cache, zero log reads); an unseeded cold child may read sessionProjectionCache.cachedSnapshot(header, SessionLogOffset(0), ['subagent']); a seeded child or cache miss pays one Session observation carrying inheritedEventCount plus a fold through the registered subagent unit. Beyond that, absent is absent — no cache of its own, no list-side write-back, no index.
  • The subagent projection unit is the sole authority over the fold rules: live and cold snapshots both run the one registered unit; no second copy of descriptor-interpretation logic exists.
  • The descriptor (v2) remains untouched. Session, persistence, projection cache, and query now carry the exact inherited cut separately from the logical header; pre-existing data acquires exact values through one body-bearing observation when listing cannot prove a zero cut — no degraded unknown state and no durable format migration.

Relationship to existing notes:

  • This note supersedes two designs on the list read path in durable-subagent-catalog: enumeration through sessionQuery.traceSession, and per-child descriptor-event reads (the listEvents-plus-exact-readEvent double read with in-place diagnostic classification). The diagnostic row semantics is retained, with classification now derived by the list from projection-value absence and activity; the descriptor event remains the sole durable authority for mode/label and the fold input, and the resume authorization and Activation contracts are untouched. This is partial supersession; the two notes stay cross-linked.
  • The session-projection RFC is the authority for the registry contract, split by the later state-and-client-views note; this note adds the client-visible subagent identity unit and consumes it through live and cold snapshots. The fold rules are registered with the registry exactly once; every consuming surface computes through the one registered unit, and no second copy of the fold logic exists.

subagent projection unit

It hangs beside the existing subagentTiming (projection.ts, projection-types.ts), under key subagent. Both units provide client wire views; the identity unit keeps an optional wrapped host value and maps its absence to the client sentinel:

export type SubagentIdentityProjection =
  | { mode: 'one-shot'; label?: string; seq: SessionSeq }
  | { mode: 'continuable'; label: string; seq: SessionSeq }

declare module '@deepseek-ai/dsh-session-projection/types' {
  interface SessionProjectionStateMap {
    subagent: { identity?: SubagentIdentityProjection }
  }
  interface SessionProjectionMap {
    subagentTiming: SubagentTimingProjection
    subagent: SubagentIdentityProjection | null
  }
}
  • The projection is pure identity, and the projection system has no failure channel: a unit never throws; a corrupt payload or an unrecognized version folds exactly like a log with no descriptor at all. The host checkpoint state is the serializable wrapper { identity?: SubagentIdentityProjection }; absence is {}. Its client view is the non-optional SubagentIdentityProjection | null entry. null passes JSON losslessly, so a pushed reset replaces a stale identity instead of being dropped by stringify. The judging discipline: consuming surfaces treat null and an absent client key alike as no value. How "computed to nothing" is presented is the consumer's own business (see the listChildren four-state mapping below).
  • Label strength is decided by the descriptor schema: a continuable's label is mandatory at parse, a one-shot's was always optional; the mode/label discriminant matches the child row's strong contract below exactly (the row carries no seq — it is the projection's internal own-suffix proof).
  • The identity carries branded seq: the seq of the subagent/descriptor event it was folded from, mandatory on both arms and absent on the null sentinel. A live Session checks it through isOwnSeq(); a cold body-bearing observation compares it with inheritedEventCount. Header-only seeded candidates skip the cache because the header intentionally exposes no integer cut; unseeded candidates know the cut is zero. The unit maps the wrapper's validated identity to its client wire view and is checkpointed like every unit (the persist opt-in is gone); its stateVersion is 2, bumped when seq was added. Existing older checkpoint rows are invalidated by version mismatch per the registry contract, falling to the authoritative refold.
  • Fold rule: subagent/descriptor is last-wins, under the same descriptor-reset discipline as subagentTiming — ancestor descriptors in the fork prefix are overridden by the session's own descriptor. A corrupt or unrecognized-version payload is last-wins all the same: it resets to the null sentinel rather than keeping the prior identity, so a fork of a healthy ancestor does not inherit an identity its own descriptor cannot stand up.

Enumeration: query corpus with live preference

listChildren (list-children.ts) asks sessionQuery.listSessions() for the canonical live-preferred corpus, then pairs each listed id with ctx.sessions.get(id) when a live Session exists. The live header overrides the listed header for that id. Everything enumeration needs is header facts:

  • Filtering: header.origin === 'subagent' && header.parentSession === parentSessionId.
  • hasChildren: the same merged material, looked at one level down — a direct descendant exists with origin === 'subagent' whose parentSession is that child.
  • activity: a live record is running; one present only in persistence is inactive.
  • Ordering: createdAt ascending, then child id ascending (matching the old contract).
  • An absent sessionQuery service fails with SUBAGENT_CONTROL_QUERY_UNAVAILABLE; the shared query corpus owns whether a deployment can enumerate live-only or persisted Sessions.
  • A query-corpus failure fails the whole enumeration; per-child isolation applies only to per-child cold observations.

Value retrieval: the three-rung compute-and-discard ladder

For each enumerated child, mode/label retrieval walks a three-rung ladder — compute-and-discard, no cache of its own, no write-back (the third rung is the same shape as apiproxy session.history's cold read):

RungReadCost
1: live childctx.sessionProjections.snapshot(session, ['subagent'])Zero log reads — the registry's existing watermark cache, synchronous retrieval
2: unseeded cold child, cache hitThe optional sessionProjectionCache.cachedSnapshot(header, SessionLogOffset(0), ['subagent']); every valid seq is owned when the exact cut is zeroZero log reads
3: seeded child or cold fallbackOne body-bearing sessionQuery.observeSession(id) + the registered subagent projection, with inheritedEventCount available for the own-suffix checkOne full read computed per listing
  • Error contract: sessionProjections, the Session store, and sessionQuery are required runtime services for listing. Their explicit failures are SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE, SUBAGENT_CONTROL_SESSION_STORE_UNAVAILABLE, and SUBAGENT_CONTROL_QUERY_UNAVAILABLE; no empty result disguises a missing classification or corpus capability.
  • The cache is a purely optional acceleration layer: an absent service is skipped on a null check — no error code, no part in configuration validation (in contrast to sessionProjections, a required injection). A seeded header skips this rung because it cannot supply the cache identity's exact cut without a body read. For an unseeded child, anything the second rung throws (including a poisoned unit row detonating viewCheckpoint) silently falls to the third rung — the cache is derived data, so its faults never produce a corrupt verdict; the final judgment belongs to the authoritative refold. A row whose checkpoint cut predates the descriptor, an absent key, or a null sentinel likewise falls through.
  • Per-child isolation: a single child's failed cold full read only turns that row into an unavailable diagnostic, naturally retried on the next listing, without affecting siblings (see the four-state mapping).
  • The cold path's lifecycle witness: the observation must still point at the lifecycle that was enumerated. The witness fields are version, id, createdAt, cwd, parentSession, isSeeded, delegationDepth, origin, and agentPreset; a Session deleted and republished under the same id degrades to a corrupt row in the old parent's catalog, leaking nothing of the new owner's child.
  • Cold-read concurrency is bounded by the constant 4 — it constrains a read-only scan of local media, not deployment behavior; when a networked persistence backend appears, it is promoted to a validated Config field.
  • The cold-read cost, recorded honestly: every seeded child and every unseeded cache miss pays one full query observation per listing, at a cost proportional to its transcript size; the settled stance is compute-and-discard, and no cache of its own is built. The observation may reuse the query/persistence preparation layer, but listing does not depend on that optimization. A live child reads zero log throughout.
  • Cancellation: the caller's signal is checked before and after each persistence read, and a read that settles only after abort is rejected, normalized to the stable error code CANCELLED.

Authority model

  • The session log is the sole authority; this design adds no domain index, checkpoint of its own, or in-process memo. The sessionProjectionCache checkpoint the second rung reads is an existing composition item's derived data, which the list only reads. Values are computed on read and discarded. Seeded candidates use a body-bearing observation to classify the identity against the exact cut; unseeded cached identities need no seq gate because every valid seq is owned.
  • The Session and persistence write paths are entirely unaware of listing and projection consumption: no event-listener write-back, no fold-on-write.
  • Enumeration and value retrieval constitute no second authorization source and make no unpublished child visible — the two sources see only published live records and durably written persisted records, consistent with the rule the durable-subagent-catalog note laid down for derived read surfaces.

listChildren row shape and consuming surfaces

The SubagentListEntry data structure is identical to before the rewrite — the child and diagnostic arms, the kind discriminant, the three-valued reason, and the child arm's strong mode/label contract are all retained; the only change is the diagnostics' information source: the projection system has no failure channel, so diagnostics are derived by the list from projection-value absence and activity, and the list itself parses zero events. The "no value means await the hard read" rule guarantees the ladder always computes mode/label for healthy data.

export type SubagentListEntry =
  | ({
    readonly kind: 'child'
    readonly id: SessionId
    readonly activity: 'running' | 'inactive'
    readonly hasChildren: boolean
  } & (
    | { readonly mode: 'one-shot'; readonly label?: string }
    | { readonly mode: 'continuable'; readonly label: string }
  ))
  | {
    readonly kind: 'diagnostic'
    readonly id: SessionId
    readonly reason: 'corrupt' | 'unsupported' | 'unavailable'
  }

For each enumerated child, the ladder's result maps to a row through four states:

Ladder resultRow
Snapshot carries a non-null subagent identitychild row
Snapshot present, subagent null sentinel or key absent, and the child is inactivediagnostic row, reason corrupt (settled debris: a missing, corrupt, or unrecognized-version descriptor, no longer subdivided)
Snapshot present, subagent null sentinel or key absent, and the child is runningno row (creation window: the descriptor is not yet appended — the same window the old implementation omitted)
The cold full read failsdiagnostic row, reason unavailable
  • unsupported is no longer produced: the type and the wire enum retain the member under "data structures stay as they are", and this note records it as no longer produced.
  • Descriptor-less settled debris moves from the old implementation's omit into the corrupt diagnostic — damaged, dead child sessions in the corpus are visible rather than silently vanishing, which is exactly the original motivation for keeping diagnostics.
  • The list selects only the subagent wire unit, whose fold never throws: a corrupt or unrecognized-version payload folds to the null sentinel, which the four-state mapping turns into that child's corrupt row (a deterministic data fault, aligned with the old implementation's SESSION_QUERY_CORRUPT_SESSION→corrupt mapping semantics). Live and cold are treated alike, isolation is per-child, and siblings and the listing itself are unaffected. It is orthogonal to "value absent + running → omit": the creation window means "no data yet", a fold to nothing means "the data is bad" — a poisoned running child also gets a corrupt row rather than an omit.

Known boundary deviations (deliberately accepted, recorded with this note):

  • Multiple descriptors in the own suffix: the old implementation judged corrupt; last-wins now takes the final one (the provider contract guarantees exactly one anyway).
  • A live/persisted header conflict: the old implementation made it per-child corrupt; enumeration now prefers live with no consistency check, the conflict goes unnoticed, and the live record forms the row.
  • A source-read failure on damaged storage (e.g. a bad surface rejected by the cold full read): the old implementation mapped it to per-child corrupt; it is now uniformly an unavailable row (the read side cannot tell the causes apart).
  • An unknown parent: the old implementation threw not-found through session-query ('parent session … was not found'); the subagent-owned merge now yields an empty subset for a nonexistent parent, enumeration returns an empty list, and later operations on the wire land as child-level subagent-not-found — a silent change of semantics and wording, recorded as explicitly accepted.
  • Rung 2's later-event window applies only to an unseeded child: a cache row lands right after the first descriptor, the log then appends a second descriptor (or a malformed payload setting the null sentinel), and the process crashes before the next checkpoint. Cold listing can keep serving the old identity until a live run or cache write replaces the row. The precondition violates the provider's append-exactly-once contract and also requires missing every mandatory checkpoint; healthy children are unaffected. Seeded children never take rung 2 without the body-owned cut.

Consuming surfaces keep the same row and diagnostic wire shape. list_agents reaches the required query corpus plus projection registry; live identities come from the registry snapshot and cold identities from cache or query observation. Host ownership still uses header.origin, and history uses the shared live/cold Session query sources; no consumer parses descriptor events independently.

Change footprint

AreaFilesChange
subagentprojection.ts, projection-types.ts, index.tsNew client-visible subagent unit and its registration
subagentlist-children.ts and its typesQuery-corpus enumeration plus the projection-ladder four-state mapping; required projections/query services and optional projection-cache acceleration
host/apiproxySession controller/query integrationOwner checks use header.origin; live/cold history and listing consume the shared query and projection sources
tooltool-subagent-control/list-agents.tsModel-visible schema, description, and rendering remain unchanged
wire/clientapi/subagents.ts, runtime sessions/service.ts, GUITypes, row shape, and diagnostic handling unchanged; api/subagents.ts only reworded the history JSDoc to the dual arm
core/session, session-persistence, session-projection(-cache), session-query(-sqlite)body-bearing cut and branded seq plumbingLogical headers expose isSeeded; Session, persistence observations, cache identity, and query records carry exact inheritedEventCount separately

Alternatives considered

mode/label into SessionHeader. The strongest zero-read guarantee — rows form from the header alone. But a header change propagates into the persistence provider and compatibility check; pre-existing JSONL can only degrade to unknown or be backfilled. Read-time computation's answer for pre-existing data is "one inspect computation on first listing", touching no durable format.

The projection-cache ladder (cachedSnapshot ?? cold fold plus fail-soft write-back). The mechanism works — session-projection-cache's checkpoint ladder is designed for cold reads in the first place. But checkpoint write-back is a whole list-driven body of derived-data persistence and invalidation orchestration (floor/identity/putSoft); what was rejected is that orchestration as the primary mechanism. The settled three-rung ladder later reuses this cache opportunistically, read-only, as its second rung — no write-back, no orchestration, skipped when absent.

A bounded-read primitive on persistence to rescue pre-existing data. Opens a new persistence primitive for a one-time problem; superseded by the read-time inspect full read — the full read the first time pre-existing data is listed is itself the value retrieval.

Optional mode/label on list rows. Healthy data is always computable; optionality merely spills garbage-data handling complexity onto every consumer — each consuming surface has to grow filter branches and an unknown display state. The strong contract plus omit-when-uncomputable is cleaner.

Deleting diagnostic rows outright. Deletion turns corpus-corruption visibility into rows silently vanishing, and wire/tool/GUI would each have to absorb contract and snapshot changes; retention only asks the list side to derive the classification from projection-value absence and activity, at zero cost. That damaged, dead child sessions in the corpus must be visible is the original motivation for diagnostics' existence, and with retention the consuming surfaces stay wholly unchanged.

A registry computation failure channel (per-unit fault tolerance plus a supplementary failures field). To report corruption and unrecognized versions to consumers, the registry would catch unit exceptions and attach a per-key failure state beside the snapshot. Rejected: a failure is not a value and needs no channel — a unit never throws, absence is itself the signal, worst case the computation comes back empty, and how that is presented is the consumer's problem. An independent observation: the vendored Cordis emit (vendor/cordis/src/events.ts) catches nothing a listener throws, so with the projection driver hanging off session/event, a unit exception would escape along emit — which adds weight to the "a unit never throws" discipline, but fixing emit fault tolerance is outside this note's scope.

Values landed with query index preparation. Projection values folded into session index rows during the sqlite backend's reconciliation rebuild, for zero log reads in the steady read state: the projectionsFor bulk read face, the invalidation reconciliation of row values stored against the (key → stateVersion) registration set, and the SCHEMA bump. Retired wholesale: the direction was backwards — query infrastructure was forced to learn domain vocabulary (projection columns, registration-set reconciliation) while the sole consumer, the subagent list, is satisfied by read-time computation; with consumers down to zero, this derived persistence has no reason to exist. SESSION_QUERY_PROJECTIONS_UNAVAILABLE was deleted along with the read face.

Subagent hand-rolled parsing plus an in-process memo plus creation seeding. To excise the session-query dependency, the subagent package would parse descriptor events itself, avoid repeated full reads with an in-process memo, and seed initial values at creation. Superseded by the shipped ladder: live goes through the sessionProjections watermark cache and cold through the registered unit's fold, reusing the registry's single fold authority — no second copy of descriptor-interpretation logic appears, and no process-state cache or seeding ordering is introduced.

DeepReadonly on the session-query output surface (a read-path overhaul experiment). Make the public query outputs deeply readonly to pin immutable borrowing at the type level. Rejected on evidence: 3 TS2589 occurrences (excessively deep type instantiation) plus 17 sites of array-position contagion (consumers' array methods and spread sites forced to follow); deep immutability is guaranteed by core/session's runtime deep freeze, and that read-path overhaul is not part of this note.

Verification

packages/subagent/subagent/tests/list-children.spec.ts pins this contract: live identity checks use Session.isOwnSeq(); an unseeded cold identity may use the cache at cut zero; seeded candidates skip that cache rung and use an observation carrying inheritedEventCount; ancestor identities fail the own-suffix check; absent, null, poisoned, and unavailable cache/observation cases fall through or produce the documented diagnostic; lifecycle tampering degrades to corrupt across the complete witness field set. The existing keyless snapshots keep the healthy wire and model-visible surfaces fixed, while subagent-diagnostic pins diagnostic classification.

Consequences

  • Listing a live child reads zero log throughout; with the cache unmounted or missed, a cold child pays one full inspect read per listing, at a cost proportional to its transcript size and repeated with listing frequency — compute-and-discard is the settled stance: no cache of its own is built, nothing is written back, and short-term repeated full reads of the same id can hit the preparation-phase LRU, though listing does not depend on it.
  • The subagent list requires the Session query corpus and projection registry; missing services fail explicitly instead of producing incomplete rows. The optional projection cache changes only the number of body reads.
  • Identity interpretation exists only in the single unit registered with the registry: the list's three-rung ladder and GUI history's cold read use its live, cached, or observed wire snapshots, and no hand-written bypass fold exists; if some future consuming surface bypasses the unit with a hand-written fold, values will drift across read faces — a discipline this design requires be maintained, not a mechanical guarantee.
  • Per-child isolation is back: a single child's cold-read failure loses only that row and healthy siblings are unaffected; a persistence listing failure still fails the whole enumeration.
  • The diagnostic and enumeration semantics leaves five boundary deviations (multiple descriptors resolving to the last, header conflicts going unnoticed, damaged-source read failures changing classification, an unknown parent yielding an empty list instead of not-found, and the unseeded rung-2 later-event window). Seeded ancestor identities are no longer a deviation because body-bearing reads compare them with inheritedEventCount; resume authorization remains unaffected.
  • Pre-#1569 data without origin is no longer recognized as a subagent owner; it never entered the catalog anyway, and pre-release carries no compatibility promise.

Related

中文

问题

重写前的 SubagentRuntime.listChildren 对每个 header.origin === 'subagent' 的直接 child,每次列表都执行 listEvents 加 readEvent 两次整日志物化,且每次物化都伴随整日志 structuredClone,只为从描述符事件里折出 mode 与 label 两个字段。描述符在日志中的位置不固定——fork 前缀任意长,zstd 压缩帧没有 seq 索引——因此定位没有捷径;这条路径没有任何缓存,代价随 transcript(文本记录)长度 × child 数量 × 列表频率放大。它还把 session-query 拉成列表的硬依赖:没有 query backend 的部署,list_agents 以 SUBAGENT_CONTROL_SESSION_QUERY_UNAVAILABLE 整体拒绝,尽管枚举所需只是 header 事实。

同一根因还有第二个症状:host 侧的 hasSubagentDescriptor() 在每次 Agent(智能体)绑定 RPC 的属主判定上扫描目标会话的 own suffix,即便 SessionHeader.origin 已经回答了同一个问题的绝大部分。

根因在于 durable-subagent-catalog 决策把描述符事件(subagent/descriptor)定为目录的唯一持久权威,却没有为描述符读取配任何缓存层,并把逐 child 双读明确接受为「无索引的正确性基线」。web subagent conversations(#1569)已把「是不是 subagent」放进了 header(SessionHeader.origin),身份判定不再读日志;mode 与 label 仍然要扫。

决策

mode 与 label 由 subagent projection unit(纯身份两臂)折叠,unit 是折叠规则的唯一权威。枚举使用共享 Session query corpus,取值则走三级「算完即止」阶梯:live child 同步读注册表的既有水位缓存(零日志读);unseeded cold child 可以使用可选 sessionProjectionCache checkpoint,因为其精确 inherited cut 已知为零;每个 seeded child 与每次 cache miss 都执行一次含正文的 Session observation,再经注册的 subagent unit 折叠。无索引、不自建缓存、列表侧无回写。

消除逐 child 扫描的出路有三类:把 mode/label 提升进 header(写路承担);为投影建持久派生(checkpoint 阶梯,或随查询索引重建落值、读端对账);读时现算(live 走水位缓存,cold 一次整读)。本记录取第三条。「值随查询索引落库」已整体退役:查询基础设施被迫认识领域词汇,而唯一消费方读时现算即可满足——live child 的零读由 session-projection 既有水位缓存白拿,cold child 的一次整读被「算完即止」显式接受。前两条与退役理由详见考虑过的替代方案一节。

要点:

  • subagent 列表使用 Session query corpus 完成枚举与含正文 observation:mode/label 仍经 ctx.sessionProjections 获取,列表不拥有 descriptor parser 或领域索引。
  • 取值三级「算完即止」阶梯:live child 读 sessionProjections.snapshot(session, ['subagent'])(注册表既有水位缓存,零日志读);unseeded cold child 可读 sessionProjectionCache.cachedSnapshot(header, SessionLogOffset(0), ['subagent']);seeded child 或 cache miss 执行一次携带 inheritedEventCount 的 Session observation,再经注册的 subagent unit 折叠。再没有就没有——不自建缓存、列表侧无回写、无索引。
  • subagent projection unit 是折叠规则唯一权威:live 与 cold 快照都运行同一份已注册 unit,不存在第二份描述符解释逻辑。
  • 描述符(v2)保持不变。Session、persistence、projection cache 与 query 在 logical header 之外单独携带精确 inherited cut;listing 无法证明 cut 为零时,存量数据经一次含正文 observation 获得精确值——无 unknown 降级态,也无持久格式迁移。

与既有记录的关系:

  • 本记录取代 durable-subagent-catalog 中列表读路径的两项设计:经 sessionQuery.traceSession 枚举,与逐 child 读取描述符事件(listEvents 加精确 readEvent 双读、就地诊断分类)。diagnostic 行语义保留,分类改由列表按投影值缺席与 activity 派生;描述符事件仍是 mode/label 的唯一持久权威与折叠输入,恢复鉴权与激活约定不动。属部分取代,两记录保持交叉链接。
  • session-projection RFC 是 registry 约定的权威,其后由 state-and-client-views 记录拆分为 host 状态与客户端视图;本记录新增客户端可见的 subagent 身份 unit,并经 live 与 cold 快照消费它。折叠规则只在 registry 注册一份;任何消费面都经这一份已注册 unit 计算,不存在第二份折叠逻辑。

subagent projection unit

挂在现有 subagentTiming 旁(projection.ts、projection-types.ts),key 为 subagent。两个 unit 都提供客户端 wire view;身份 unit 在 host 状态中保留可选的包装值,并把缺席映射为客户端哨兵:

export type SubagentIdentityProjection =
  | { mode: 'one-shot'; label?: string; seq: SessionSeq }
  | { mode: 'continuable'; label: string; seq: SessionSeq }

declare module '@deepseek-ai/dsh-session-projection/types' {
  interface SessionProjectionStateMap {
    subagent: { identity?: SubagentIdentityProjection }
  }
  interface SessionProjectionMap {
    subagentTiming: SubagentTimingProjection
    subagent: SubagentIdentityProjection | null
  }
}
  • 投影是纯身份,projection 体系不做失败通道:unit 永不抛错;载荷损坏、版本不认识与整日志没有描述符一样。host checkpoint 状态使用可序列化的包装 { identity?: SubagentIdentityProjection },缺席为 {};客户端 view 则是非可选的 SubagentIdentityProjection | null 条目。null 完好通过 JSON,因此推送 reset 会替换旧身份,而不会被 stringify 丢掉。判定纪律:消费面把 null 与客户端 key 缺席一律视为无值。「算出来没有」如何呈现是消费方自己的事(见下文 listChildren 四态映射)。
  • label 强度由描述符 schema 决定:continuable 的 label 解析强制必有,one-shot 的本就可选;mode/label 判别与下文 child 行的强约定完全一致(行不携带 seq——它是投影内部的 own-suffix 证明)。
  • 身份携带品牌化 seq:折出该身份的 subagent/descriptor 事件 seq,两臂必有、null 哨兵无。live Session 通过 isOwnSeq() 检查它;cold 含正文 observation 则与 inheritedEventCount 比较。仅 header 的 seeded candidate 会跳过 cache,因为 header 有意不暴露整数 cut;unseeded candidate 知道 cut 为零。unit 把包装状态中校验后的身份映射为客户端 wire view,并与其他 unit 一律检查点化(persist 选项已删除);stateVersion 为 2,在增加 seq 时升版。更早的 checkpoint 行按 registry 约定版本失配失效、落权威重折。
  • 折叠规则:subagent/descriptor last-wins,与 subagentTiming 同一条 descriptor-reset 纪律——fork 前缀里的祖先描述符被自身描述符覆盖。损坏或版本不认识的载荷同样 last-wins:重置为 null 哨兵而非保留先前身份,健康祖先的 fork 不会继承自身描述符立不住的身份。

枚举:query corpus 与 live preference

listChildren(list-children.ts)通过 sessionQuery.listSessions() 取得 canonical live-preferred corpus,再把每个 listed id 与可能存在的 ctx.sessions.get(id) 配对;同 id 存在 live Session 时使用 live header。枚举所需全部是 header 事实:

  • 过滤:header.origin === 'subagent' && header.parentSession === parentSessionId。
  • hasChildren:同一份合并材料向下看一层——存在 origin === 'subagent' 且 parentSession 为该 child 的直接后代。
  • activity:live 记录为 running,仅存在于持久化的为 inactive。
  • 排序:createdAt 升序、再按 child id 升序(与旧约定一致)。
  • sessionQuery 服务缺席时以 SUBAGENT_CONTROL_QUERY_UNAVAILABLE 失败;共享 query corpus 负责决定部署能枚举 live-only 还是持久化 Session。
  • query corpus 失败使整次枚举失败;per-child 隔离只适用于逐 child cold observation。

取值:三级「算完即止」阶梯

对每个枚举出的 child,mode/label 取值走三级阶梯——算完即止,不自建缓存、无回写(第三级与 apiproxy session.history 的冷读同款):

级读法成本
1:live childctx.sessionProjections.snapshot(session, ['subagent'])零日志读——注册表既有水位缓存,同步取值
2:unseeded cold child,cache 命中可选 sessionProjectionCache.cachedSnapshot(header, SessionLogOffset(0), ['subagent']);精确 cut 为零时,每个合法 seq 都归 child 自有零日志读
3:seeded child 或 cold 兜底一次含正文 sessionQuery.observeSession(id) 加已注册的 subagent projection,使用 inheritedEventCount 做 own-suffix 检查每次列表一次整读现算
  • 错误约定:sessionProjections、Session store 与 sessionQuery 都是 listing 所需的 runtime service。三者分别以 SUBAGENT_CONTROL_PROJECTIONS_UNAVAILABLE、SUBAGENT_CONTROL_SESSION_STORE_UNAVAILABLE 与 SUBAGENT_CONTROL_QUERY_UNAVAILABLE 显式失败;缺失分类或 corpus 能力不会伪装成空结果。
  • cache 是纯可选加速层:服务缺席判空跳过——无错误码、不进配置校验(与 sessionProjections 的必需注入相对)。seeded header 会跳过该级,因为不读取正文就无法提供 cache identity 所需的精确 cut。对 unseeded child,第二级任何抛错(包括中毒 unit 行引爆 viewCheckpoint)都会静默落第三级——缓存是派生数据,其故障不产生 corrupt 判决,终审归权威重折;checkpoint 早于 descriptor、key 缺席或 null 哨兵也都会落底。
  • per-child 隔离:单 child 的 cold 整读失败只使该行成为 unavailable diagnostic,下次列表自然重试,不影响 sibling(见四态映射)。
  • 冷路径的生命周期见证:observation 必须仍指向枚举时的那个生命周期。见证字段为 version、id、createdAt、cwd、parentSession、isSeeded、delegationDepth、origin 与 agentPreset;同 id 删除后重新发布的 Session 对旧 parent 的目录降级为 corrupt 行,不外漏新 owner 的 child。
  • 冷读并发以常数 4 有界——它约束的是本地介质的一次只读扫描而非部署行为;出现联网 persistence backend 时提升为验证过的 Config 字段。
  • 冷读成本如实记录:每个 seeded child 与每次 unseeded cache miss 都会在每次列表时支付一次完整 query observation,成本与其 transcript 大小成正比;定案「算完即止」,不自建缓存。observation 可以复用 query/persistence preparation 层,但列表不依赖该优化。live child 全程零日志读。
  • 取消:每次 persistence 读前后检查调用方 signal,abort 之后才结算的读拒绝归一化为稳定错误码 CANCELLED。

权威模型

  • session log 是唯一权威;本方案不新增领域索引、自有 checkpoint 或进程 memo。第二级读取的 sessionProjectionCache checkpoint 是既有组合项的派生数据,列表只读。取值现算现弃;seeded candidate 用含正文 observation 按精确 cut 分类,unseeded cached identity 无需 seq 门,因为每个合法 seq 都归自身所有。
  • Session 与 persistence 写路完全不感知列表与投影消费:没有事件监听回写,没有写时折叠。
  • 枚举与取值不构成第二个鉴权来源,也不让尚未发布的 child 可见——两个来源只见已发布的 live 记录与已落盘的持久化记录,与 durable-subagent-catalog 记录对派生读面立下的规则一致。

listChildren 行形状与消费面

SubagentListEntry 数据结构与重写前完全一致——child 与 diagnostic 两臂、kind 判别、reason 三值、child 臂的 mode/label 强约定全部保留;变化只在诊断的信息来源:投影体系没有失败通道,diagnostic 由列表按投影值缺席与 activity 派生,列表本身零事件解析。「没有就等待硬读取」保证阶梯对健康数据必然算得出 mode/label。

export type SubagentListEntry =
  | ({
    readonly kind: 'child'
    readonly id: SessionId
    readonly activity: 'running' | 'inactive'
    readonly hasChildren: boolean
  } & (
    | { readonly mode: 'one-shot'; readonly label?: string }
    | { readonly mode: 'continuable'; readonly label: string }
  ))
  | {
    readonly kind: 'diagnostic'
    readonly id: SessionId
    readonly reason: 'corrupt' | 'unsupported' | 'unavailable'
  }

对每个枚举出的 child,阶梯取值结果按四态映射成行:

阶梯取值结果行
快照含非 null 的 subagent 身份child 行
快照在、subagent 为 null 哨兵或 key 缺席,且 child inactivediagnostic 行,reason corrupt(定局残骸:无、损坏或版本不认识的描述符,不再细分)
快照在、subagent 为 null 哨兵或 key 缺席,且 child running行不出现(创建窗口:描述符尚未追加,与旧实现同窗口 omit)
cold 整读失败diagnostic 行,reason unavailable
  • unsupported 不再被产出:类型与 wire 枚举按「数据结构保持现状」留存该成员,本记录留档其为不再产出。
  • descriptor-less 定局残骸从旧实现的 omit 归入 corrupt diagnostic——库里的坏、死子会话可见,不静默消失,这正是保留 diagnostic 的原始动机。
  • 列表只选择 subagent wire unit,且该折叠永不抛错:描述符损坏或版本不认识折为 null 哨兵,由四态映射收纳为该 child 的 corrupt 行(确定性数据故障,对齐旧实现 SESSION_QUERY_CORRUPT_SESSION→corrupt 的映射语义)。live 与 cold 同待遇,逐 child 隔离,sibling 与列表本身不受影响。它与「无值 + running → omit」正交:创建窗口是「尚无数据」,折为无值是「数据坏了」——running 的中毒 child 也出 corrupt 行而非 omit。

已知边界偏差(有意接受,随本记录留档):

  • own suffix 出现多个描述符,旧实现判 corrupt,现 last-wins 取末者(提供方约定本就保证恰一)。
  • live/persisted header 冲突,旧实现是 per-child corrupt;现枚举 live 优先、不做一致性校验,冲突不再被察觉,以 live 记录成行。
  • 损坏存储的源读失败(如坏 surface 被冷读整读拒收),旧实现映射 per-child corrupt,现统一成 unavailable 行(读侧无从区分成因)。
  • 未知 parent,旧实现经 session-query 抛 not-found(「parent session … was not found」);现自管合并对不存在的 parent 得到空子集,枚举返回空列表,wire 上后续操作落到 child 级 subagent-not-found——语义与文案的静默变化,显式接受。
  • rung 2 的更晚事件窗口只适用于 unseeded child:cache 行恰在首个 descriptor 后落盘,日志随后追加第二个 descriptor(或 malformed 载荷置 null 哨兵),且进程在下一次 checkpoint 前崩溃。cold listing 可能持续供出旧身份,直到一次 live 运行或 cache write 替换该行。其前提违反 provider 的「恰追加一次」约定,并且还需错过所有 mandatory checkpoint;健康 child 不受影响。seeded child 没有 body-owned cut 时绝不进入 rung 2。

消费面保持相同的 row 与 diagnostic wire 形状。list_agents 使用必需的 query corpus 与 projection registry;live identity 来自 registry snapshot,cold identity 来自 cache 或 query observation。Host ownership 仍使用 header.origin,history 使用共享的 live/cold Session query source;没有消费方独立解析 descriptor event。

改动落点

区域文件改动
subagentprojection.ts、projection-types.ts、index.ts新客户端可见 subagent unit 与注册
subagentlist-children.ts 及类型query-corpus 枚举加 projection 阶梯四态映射;必需 projections/query service 与可选 projection-cache 加速
host/apiproxySession controller/query integrationowner 检查使用 header.origin;live/cold history 与 listing 消费共享 query 和 projection source
tooltool-subagent-control/list-agents.tsmodel-visible schema、描述与渲染保持不变
wire/clientapi/subagents.ts、runtime sessions/service.ts、GUI类型、行形状与 diagnostic 处理零改动;api/subagents.ts 仅 history 的 JSDoc 措辞改为双臂
core/session、session-persistence、session-projection(-cache)、session-query(-sqlite)含正文 cut 与品牌化 seq 传递Logical header 暴露 isSeeded;Session、persistence observation、cache identity 与 query record 单独携带精确 inheritedEventCount

考虑过的替代方案

mode/label 进 SessionHeader。 零读保证最强——列表只看 header 就能成行。但 header 变更会传导到持久化 provider 与兼容性检查;存量 JSONL 只能降级为 unknown 或 backfill。读时现算对存量的答案是「第一次列表一次 inspect 现算」,不碰持久格式。

projection-cache 阶梯(cachedSnapshot ?? cold fold 加 fail-soft 写回)。 机制成立——session-projection-cache 的 checkpoint 阶梯本就为冷读设计。但 checkpoint 写回是一套由列表驱动的派生数据持久化与失效编排(floor/identity/putSoft);被否的是这套编排作为主机制。定稿的第三级阶梯后来以只读方式机会性复用该缓存作第二级——无写回、无编排、缺席即跳过。

给 persistence 加有界读原语抢救存量。 为一次性问题新开 persistence 原语;被读时 inspect 整读取代——存量第一次被列表时的整读就是取值本身。

list 行 mode/label 可选化。 健康数据必然可算;可选化只是把垃圾数据的处理复杂度外溢给全部消费方——每个消费面都要长出过滤分支和 unknown 展示态。强约定加算不出即 omit 更干净。

彻底删除 diagnostic 行。 删除把库损坏的可见性外溢为行静默消失,wire/tool/GUI 反要各自承担约定与快照变更;而保留只需列表侧按投影值缺席与 activity 派生分类,零成本。库里的坏、死子会话必须可见是 diagnostic 存在的原始动机,保留后消费面整体零改动。

registry 计算失败通道(per-unit 容错加 failures 附加字段)。 为把损坏、版本不认识报告给消费方,由 registry 捕获 unit 异常并在 snapshot 旁附 per-key 失败态。被否:failure 不是值,也不必是通道——unit 永不抛错,缺席本身就是信号,「大不了算出来没有」,如何呈现是消费方要考虑的事。一个独立观察:vendor cordis 的 emit(vendor/cordis/src/events.ts)对 listener 抛错零捕获,投影驱动挂在 session/event 上时 unit 异常会沿 emit 逃逸——这加重了「unit 永不抛错」纪律的分量,但 emit 容错的修复不属于本记录范围。

值随 query 索引 preparation 落库。 投影值在 sqlite backend 的对账重建里折叠落进 session 索引行,读稳态零日志:projectionsFor 批量读面、行值随 (key → stateVersion) 注册集存储的失效对账与 SCHEMA bump。整体退役:方向反了——查询基础设施被迫认识领域词汇(投影列、注册集对账),而唯一消费方 subagent 列表读时现算即可满足;消费方归零后,这套派生持久化没有存在理由。SESSION_QUERY_PROJECTIONS_UNAVAILABLE 随读面一并删除。

subagent 手工 parse 加进程 memo 加创建播种。 为摘除 session-query 依赖,由 subagent 包自己解析描述符事件、以进程内 memo 避免重复整读、创建时播种初值。被已交付的阶梯取代:live 走 sessionProjections 水位缓存、cold 走注册 unit 的折叠,复用 registry 这一份折叠权威,不再出现第二份描述符解释逻辑,也不引入进程态缓存与播种时序。

session-query 输出面 DeepReadonly(读路径改造实验)。 公开查询输出深只读化,以在类型层面钉死不可变借用。实证否决:3 处 TS2589(类型实例化过深)加 17 处数组位传染(消费方数组方法与展开处被迫跟改);深层不可变由 core/session 的运行时深冻结保证,该读路径改造未纳入本记录。

验证

packages/subagent/subagent/tests/list-children.spec.ts 固定本约定:live identity 通过 Session.isOwnSeq() 检查;unseeded cold identity 可在 cut 零时使用 cache;seeded candidate 跳过该 cache rung,转而使用携带 inheritedEventCount 的 observation;祖先 identity 无法通过 own-suffix 检查;缺席、null、中毒与不可用的 cache/observation 会按约定落底或产生 diagnostic;lifecycle 篡改按完整见证字段集降级为 corrupt。既有无密钥快照保持健康 wire 与 model-visible 面不变,subagent-diagnostic 则固定诊断分类。

后果

  • live child 的列表全程零日志读;cold child 在 cache 未挂载或未命中时每次列表一次 inspect 整读,成本与其 transcript 大小成正比、随列表频率重复——定案「算完即止」,不自建缓存、不回写,同 id 短期重复整读可命中准备阶段 LRU 但列表不依赖它。
  • subagent 列表要求 Session query corpus 与 projection registry;服务缺失会显式失败,而不是供出不完整 row。可选 projection cache 只改变正文读取次数。
  • 身份解释只存在于 registry 注册的一份 unit:列表三级阶梯与 GUI history 冷读使用其 live、cached 或 observed wire 快照,不存在手写旁路折叠;若未来某消费面绕开该 unit 手写折叠,各读面的值将漂移——这是本设计要求维持的纪律,不是机制保证。
  • per-child 隔离回归:单 child 冷读失败只损失该行,healthy sibling 不受影响;persistence 列表失败仍使整次枚举失败。
  • 诊断与枚举语义留下五处边界偏差(多描述符取末者、header 冲突不再被察觉、损坏源读失败改变分类、未知 parent 由 not-found 改为空列表、unseeded rung 2 更晚事件窗口)。seeded 祖先 identity 已不再构成偏差,因为含正文读取会把它与 inheritedEventCount 比较;恢复鉴权始终不受影响。
  • pre-#1569 的无 origin 存量不再被认作 subagent 属主;其本就不进目录,pre-release 无兼容承诺。

相关