From 73dbbb751c2ad113cd65d40c99c1942d0c83dc06 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 9 Oct 2026 16:24:51 +0800 Subject: [PATCH] docs: give architecture review rules a per-artifact home Move `docs/defensive-patterns.md` into `docs/defensive-patterns/`, one page per artifact plus a README router, and state each rule as its requirement, the condition a reviewer judges it by, its boundary and approver, and a correct and a wrong example. - `general.md` (the moved page): the existing bug-class rules plus timing, value representation, shared-state ownership, decentralization, performance evidence, and migrations. - `package-surface.md`, `remote-and-api.md`, `client-components.md`, `conversation-and-session.md`: the review requirements for those artifacts, linking type definitions and semantics to `docs/subsystems/` instead of restating them. - `README.md`: the habits behind the rules and the route from artifact to page. - `dsh-code-review` reads the owning pages before judging a diff; the `dsh-architecture-discipline` routing skill is retired in favour of the directory, and every inbound reference is repaired. - Chinese counterparts, pairing records, and the documentation tier table are updated together. --- ...19-cooperative-tool-cancellation.i18n.yaml | 4 +- ...026-07-19-cooperative-tool-cancellation.md | 2 +- ...-07-19-cooperative-tool-cancellation.zh.md | 2 +- .../skills/dsh-ci-test-reliability/SKILL.md | 2 +- .agents/skills/dsh-client-ui-ux/SKILL.md | 7 + .agents/skills/dsh-code-review/SKILL.md | 11 +- .../skills/dsh-find-simplifications/SKILL.md | 2 +- .agents/skills/dsh-speed-up-perf/SKILL.md | 2 +- AGENTS.md | 2 +- docs/AGENTS.md | 5 +- docs/api-gateway.i18n.yaml | 9 +- docs/api-gateway.md | 6 + docs/api-gateway.zh.md | 12 + docs/defensive-patterns.i18n.yaml | 28 - docs/defensive-patterns.md | 33 -- docs/defensive-patterns.zh.md | 35 -- docs/defensive-patterns/README.i18n.yaml | 10 + docs/defensive-patterns/README.md | 25 + docs/defensive-patterns/README.zh.md | 27 + .../client-components.i18n.yaml | 46 ++ docs/defensive-patterns/client-components.md | 480 +++++++++++++++++ .../client-components.zh.md | 482 ++++++++++++++++++ .../conversation-and-session.i18n.yaml | 31 ++ .../conversation-and-session.md | 312 ++++++++++++ .../conversation-and-session.zh.md | 312 ++++++++++++ docs/defensive-patterns/general.i18n.yaml | 52 ++ docs/defensive-patterns/general.md | 218 ++++++++ docs/defensive-patterns/general.zh.md | 248 +++++++++ .../package-surface.i18n.yaml | 25 + docs/defensive-patterns/package-surface.md | 224 ++++++++ docs/defensive-patterns/package-surface.zh.md | 224 ++++++++ .../remote-and-api.i18n.yaml | 16 + docs/defensive-patterns/remote-and-api.md | 114 +++++ docs/defensive-patterns/remote-and-api.zh.md | 114 +++++ docs/development.i18n.yaml | 2 +- docs/development.zh.md | 2 + docs/subsystems/conversation.i18n.yaml | 2 +- docs/subsystems/conversation.zh.md | 2 + docs/subsystems/core.i18n.yaml | 2 +- docs/subsystems/core.zh.md | 2 + docs/subsystems/ptc-runtime.i18n.yaml | 4 +- docs/subsystems/ptc-runtime.md | 4 +- docs/subsystems/ptc-runtime.zh.md | 4 +- docs/subsystems/scope.i18n.yaml | 2 +- docs/subsystems/scope.zh.md | 2 + docs/subsystems/slots.i18n.yaml | 4 +- docs/subsystems/slots.zh.md | 4 + packages/AGENTS.md | 2 + packages/client/AGENTS.md | 3 + .../experimental/hooks-codex/src/index.ts | 2 +- .../ptc-runtime-python/src/index.ts | 2 +- packages/ptc-runtime/ptc-runtime/src/types.ts | 2 +- scripts/doc-budgets.manifest.json | 5 +- 53 files changed, 3045 insertions(+), 129 deletions(-) delete mode 100644 docs/defensive-patterns.i18n.yaml delete mode 100644 docs/defensive-patterns.md delete mode 100644 docs/defensive-patterns.zh.md create mode 100644 docs/defensive-patterns/README.i18n.yaml create mode 100644 docs/defensive-patterns/README.md create mode 100644 docs/defensive-patterns/README.zh.md create mode 100644 docs/defensive-patterns/client-components.i18n.yaml create mode 100644 docs/defensive-patterns/client-components.md create mode 100644 docs/defensive-patterns/client-components.zh.md create mode 100644 docs/defensive-patterns/conversation-and-session.i18n.yaml create mode 100644 docs/defensive-patterns/conversation-and-session.md create mode 100644 docs/defensive-patterns/conversation-and-session.zh.md create mode 100644 docs/defensive-patterns/general.i18n.yaml create mode 100644 docs/defensive-patterns/general.md create mode 100644 docs/defensive-patterns/general.zh.md create mode 100644 docs/defensive-patterns/package-surface.i18n.yaml create mode 100644 docs/defensive-patterns/package-surface.md create mode 100644 docs/defensive-patterns/package-surface.zh.md create mode 100644 docs/defensive-patterns/remote-and-api.i18n.yaml create mode 100644 docs/defensive-patterns/remote-and-api.md create mode 100644 docs/defensive-patterns/remote-and-api.zh.md diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml index 7354602835..4573f0a33f 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.i18n.yaml @@ -27,8 +27,8 @@ en: fbd101d4576afa92 zh: 35f5d3c2f6cad6a8 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/alternatives-considered: - en: 1f205f1a78d4fd5b - zh: 6c17e35da2909302 + en: c4d86feb135d2ac4 + zh: 67c56c0bc2213949 /agent-note-cooperative-tool-cancellation-at-the-registry-boundary/consequences: en: 24a9ad2c4c7c86b5 zh: debdd29d272e07ea diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md index 5ca2b44b24..967c7285df 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.md @@ -62,7 +62,7 @@ No registry test can prove that arbitrary third-party same-process code observes **Forbid around wrappers from replacing the signal.** Rejected because deadlines and nested operational scopes need lexical derivation. Capturing and fusing the caller signal preserves composition without allowing detachment. -**Race the tool promise against cancellation.** Rejected because it reports completion while side effects may remain live, violating the [quiescent-disposal rule](../../../../docs/defensive-patterns.md#dispose-must-reach-quiescence-not-just-request-it). +**Race the tool promise against cancellation.** Rejected because it reports completion while side effects may remain live, violating the [quiescent-disposal rule](../../../../docs/defensive-patterns/general.md#dispose-must-reach-quiescence-not-just-request-it). ## Consequences diff --git a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md index d6d49fb44c..87318c3316 100644 --- a/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-19-cooperative-tool-cancellation.zh.md @@ -62,7 +62,7 @@ Status: implemented **禁止环绕包装层替换信号。** 不予采纳,因为截止时间和嵌套操作作用域需要词法派生信号。捕获并融合调用方信号既保留组合能力,也不允许切断调用方取消。 -**让工具 promise 与取消竞速。** 不予采纳,因为这种方式会在副作用仍可能存活时报告完成,违反[dispose(资源释放)必须完全停稳的规则](../../../../docs/defensive-patterns.zh.md#dispose-must-reach-quiescence-not-just-request-it)。 +**让工具 promise 与取消竞速。** 不予采纳,因为这种方式会在副作用仍可能存活时报告完成,违反[dispose(资源释放)必须完全停稳的规则](../../../../docs/defensive-patterns/general.zh.md#dispose-must-reach-quiescence-not-just-request-it)。 ## 后果 diff --git a/.agents/skills/dsh-ci-test-reliability/SKILL.md b/.agents/skills/dsh-ci-test-reliability/SKILL.md index d9fd0f1700..ba97a37745 100644 --- a/.agents/skills/dsh-ci-test-reliability/SKILL.md +++ b/.agents/skills/dsh-ci-test-reliability/SKILL.md @@ -10,7 +10,7 @@ Build tests that remain correct under the repository's real CI topology, not onl ## Read the owning rules - Use [the testing policy](../../../docs/testing.md) to select unit, coverage, expected-output, snapshot, browser, or real-API evidence. -- Use [the defensive patterns](../../../docs/defensive-patterns.md) for lifecycle, subprocess, cancellation, and teardown behavior. +- Use [the defensive patterns](../../../docs/defensive-patterns/general.md) for lifecycle, subprocess, cancellation, and teardown behavior. - Read the active Vitest config and GitHub workflow when their worker or job topology affects the test. - For recorded-session scenarios, also follow [the snapshot instructions](../../../snapshots/AGENTS.md). - Use [dsh-pre-push-checks](../dsh-pre-push-checks/SKILL.md) after the test design is sound to select outgoing validation. diff --git a/.agents/skills/dsh-client-ui-ux/SKILL.md b/.agents/skills/dsh-client-ui-ux/SKILL.md index fa6ebb70a1..b37a1ca4ba 100644 --- a/.agents/skills/dsh-client-ui-ux/SKILL.md +++ b/.agents/skills/dsh-client-ui-ux/SKILL.md @@ -7,6 +7,13 @@ description: Design and review DeepSeek Harness client UI changes — visual tok This skill is guidance, not a complete checklist. It covers judgment calls that lint, typecheck, and the i18n gate cannot make: where feedback appears, what gets reused, and how surfaces behave at window edges and across platforms. Copy quality itself follows [dsh-prose-standard](../dsh-prose-standard/SKILL.md); locale ownership follows the [locale-owned copy decision](../../notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.md); styling ownership and token rules live in [docs/web-styling.md](../../../docs/web-styling.md) and the [ui-primitives component catalog](../../../packages/client/ui-primitives/README.md#component-catalog) — this skill adds judgment on top of those rules, not a second copy of them. +## Architecture prerequisites + +Component structure, state flow, and effect usage follow the architecture rules; read them before redesigning a component: + +- [packages/client/AGENTS.md](../../../packages/client/AGENTS.md) — Slot and props discipline, reactive read, export, ctx, and layering rules. +- [Client component rules](../../../docs/defensive-patterns/client-components.md) — those requirements stated with the defects they prevent. + ## Visual foundation - **Use existing tokens for color, radius, and spacing.** Before introducing a literal value, search the target page and its nearest established sibling (the Plugins page is the usual reference for full-page surfaces) for the token or value already in use, and adopt it. The same applies to whole treatments — toasts, menus, in-message artifact previews, sidebar tab layout, colors, clearance rules, page padding: reuse the established component or rule wherever one exists instead of inventing a parallel one. diff --git a/.agents/skills/dsh-code-review/SKILL.md b/.agents/skills/dsh-code-review/SKILL.md index e75ca07744..ff242b4819 100644 --- a/.agents/skills/dsh-code-review/SKILL.md +++ b/.agents/skills/dsh-code-review/SKILL.md @@ -7,10 +7,17 @@ description: Use when reviewing a pull request in the deepseek-harness repo — **This skill is guidance, not a complete checklist.** Verify and fetch the PR's live base and exact head, then run `pnpm --silent run change-scope --base --head ` before reading the diff and enough surrounding code to understand the design. The report identifies paths and dirty layers but does not replace semantic review. Re-establish the base and rerun it after a retarget or merge. Prioritize correctness, lifecycle, security, and broken required behavior over style; a short review with one substantiated blocker is better than a list of nits. +**Read the requirements before judging the diff.** Map the changed paths to the artifacts below, open each owning page from [Sources of truth](#sources-of-truth), and only then read the diff against those requirements. Judging a diff against memory of the rules is how a violation passes review. + ## Sources of truth - [AGENTS.md](../../../AGENTS.md) and [packages/AGENTS.md](../../../packages/AGENTS.md): standing repository and package authoring rules. -- [docs/defensive-patterns.md](../../../docs/defensive-patterns.md): subprocess, callback, async-state, and disposal bug classes. +- [docs/defensive-patterns/](../../../docs/defensive-patterns/README.md): the architecture requirements a change must satisfy and the habits behind them. Each page owns one artifact; read every page the diff touches: + - [general.md](../../../docs/defensive-patterns/general.md) — timing, async state, value representation, shared ownership, decentralization, refactors, migrations, performance evidence, disposal, callbacks, subprocesses. + - [package-surface.md](../../../docs/defensive-patterns/package-surface.md) — exports, package shape, build faces, dependency declarations, resolve hooks. + - [remote-and-api.md](../../../docs/defensive-patterns/remote-and-api.md) — remote services, `@Remote` methods, API dispatch, business ownership in `packages/api`. + - [client-components.md](../../../docs/defensive-patterns/client-components.md) — client components, slots, stores, hooks, effects, shared base packages. + - [conversation-and-session.md](../../../docs/defensive-patterns/conversation-and-session.md) — projection reads, Session retention, conversation nodes, renderers. - [docs/AGENTS.md](../../../docs/AGENTS.md): documentation placement and prose discipline. - [dsh-prose-standard](../dsh-prose-standard/SKILL.md): required coverage and editorial judgment for comments, docs, prompts, and visible strings. - [dsh-ci-test-reliability](../dsh-ci-test-reliability/SKILL.md): isolation and regression-proof rules for resource-owning, asynchronous, or flaky tests and fixtures. @@ -33,7 +40,7 @@ description: Use when reviewing a pull request in the deepseek-harness repo — - **Intent and interface contracts:** trace both sides of every changed interface. Confirm the implementation matches the PR and any Agent Note, including errors, cancellation, ownership, and disposal. - **Error handling:** apply [dsh-error-handling](../dsh-error-handling/SKILL.md) to changed failure paths, including their state guarantees and final user-visible reports. Reject catch-and-continue unless the state owner establishes that subsequent work's preconditions hold, including after recovery. -- **Lifecycle and concurrency:** for async setup, callbacks, processes, or teardown, apply [defensive-patterns.md](../../../docs/defensive-patterns.md). Check races before publication, cancellation during awaits, independent error reporting, callback containment, ownership before reentry, complete detach cleanup, and quiescent disposal. +- **Lifecycle and concurrency:** for async setup, callbacks, processes, or teardown, apply [defensive-patterns/general.md](../../../docs/defensive-patterns/general.md). Check races before publication, cancellation during awaits, independent error reporting, callback containment, ownership before reentry, complete detach cleanup, and quiescent disposal. - **Capability and consumer fit:** trace every current consumer, then flag consumer-specific behavior leaking into the interface under [the package rules](../../../packages/AGENTS.md). Flag the inverse too: a new public method on a generic service (registry, session, agent) whose only caller is one internal consumer is an unnecessary API expansion — require a private capability closure handed to that consumer at construction instead. - **Scope, ownership, and necessity:** map each abstraction, state machine, option, defensive copy, and compatibility path to its current contract, production consumer, and owning plugin or service. Challenge unrelated features and speculative generality, then test the PR against [the root rules](../../../AGENTS.md#conventions). - **Configuration and public choices:** ask what current-consumer evidence or prior art supports each default, public operation set, format, or imported external concept. Require an explicit choice or deferral when that evidence is absent. diff --git a/.agents/skills/dsh-find-simplifications/SKILL.md b/.agents/skills/dsh-find-simplifications/SKILL.md index fe98baba29..46955d8abd 100644 --- a/.agents/skills/dsh-find-simplifications/SKILL.md +++ b/.agents/skills/dsh-find-simplifications/SKILL.md @@ -9,7 +9,7 @@ Find changes that remove maintained obligations: APIs, representations, lifecycl ## Establish scope and constraints -Read `AGENTS.md`, [architecture](../../../docs/architecture.md) before judging packages, [defensive patterns](../../../docs/defensive-patterns.md), and [testing policy](../../../docs/testing.md). Consult the relevant active Agent Notes for intentional decisions; use the [note rules](../../notes/README.md) for new records. Archived notes are historical examples, not current authority: never inspect, verify, or repair their outbound links. +Read `AGENTS.md`, [architecture](../../../docs/architecture.md) before judging packages, [defensive patterns](../../../docs/defensive-patterns/README.md), and [testing policy](../../../docs/testing.md). Consult the relevant active Agent Notes for intentional decisions; use the [note rules](../../notes/README.md) for new records. Archived notes are historical examples, not current authority: never inspect, verify, or repair their outbound links. The two LLM adapters are intentional. JSONL is the sole first-party Session persistence provider, while the backend-neutral Service Definition supports out-of-tree providers. Do not propose deleting an LLM twin or the persistence seam unless the user explicitly overrides that constraint. Unused members within a protected design remain candidates when their removal preserves its purpose. diff --git a/.agents/skills/dsh-speed-up-perf/SKILL.md b/.agents/skills/dsh-speed-up-perf/SKILL.md index f8b5eb6141..491e39f81c 100644 --- a/.agents/skills/dsh-speed-up-perf/SKILL.md +++ b/.agents/skills/dsh-speed-up-perf/SKILL.md @@ -9,7 +9,7 @@ Turn a broad “make it faster” request into reproducible user-path measuremen ## Establish scope and current authority -Read [AGENTS.md](../../../AGENTS.md), [architecture](../../../docs/architecture.md), [testing policy](../../../docs/testing.md), [defensive patterns](../../../docs/defensive-patterns.md), and the affected packages’ instructions and Agent Notes. Use [CI test reliability](../dsh-ci-test-reliability/SKILL.md) for processes, clocks, browser tests, and asynchronous cleanup. +Read [AGENTS.md](../../../AGENTS.md), [architecture](../../../docs/architecture.md), [testing policy](../../../docs/testing.md), [defensive patterns](../../../docs/defensive-patterns/README.md), and the affected packages’ instructions and Agent Notes. Use [CI test reliability](../dsh-ci-test-reliability/SKILL.md) for processes, clocks, browser tests, and asynchronous cleanup. Agree on the user-visible endpoint, workload range, resource constraints, acceptable minor behavior differences, and stopping rule. Keep backend and browser end-to-end measurements separate: a fast history iterator or Client fold does not prove fast transport, paint, scrolling, or input response. Exclude model/network latency when measuring local overhead, and state that exclusion rather than calling the result complete product latency. diff --git a/AGENTS.md b/AGENTS.md index b3dbc0482c..39cedacc3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,7 +163,7 @@ Real-API tests/demos read `DEEPSEEK_API_KEY`, optional `DEEPSEEK_BASE_URL`, and ## Defensive patterns -Read [docs/defensive-patterns.md](docs/defensive-patterns.md) before lifecycle, concurrency, subprocess, or teardown work. +Read [docs/defensive-patterns/README.md](docs/defensive-patterns/README.md) before lifecycle, concurrency, subprocess, or teardown work. Its [review principles](docs/defensive-patterns/README.md#why-these-rules) apply per artifact across the repository. ## Type safety and documentation diff --git a/docs/AGENTS.md b/docs/AGENTS.md index d4bbea471f..1a1d53ded4 100644 --- a/docs/AGENTS.md +++ b/docs/AGENTS.md @@ -23,6 +23,7 @@ Each fact has one home: the tier whose job it is; elsewhere, link there. | [architecture.md](architecture.md) | Ordered map: composition, core packages, loop, seams, extension points; read before changing `packages/` | Type definitions (→ subsystems), per-package detail (→ package READMEs), decision rationale (→ Agent Notes), implementation-status annotations | | [subsystems/](subsystems/README.md) | One reference page per subsystem: type definitions, semantics, and the generated Cordis API | Behavior narration (→ architecture.md) | | [Agent Notes](../.agents/notes/README.md) | Active decision records: the why, what-was-given-up, and required verification; `implemented/` notes describe shipped reality in present tense | Migration plans, acceptance-task checklists, fixture walkthroughs, and spec-speak ("should…") once the decision has shipped; archived notes are frozen history, never current authority | +| [defensive-patterns/](defensive-patterns/README.md) | Rules this repository enforces in review, split by artifact: one general bug-class page plus per-domain pages | Type definitions and semantics (→ subsystems), decision rationale (→ Agent Notes) | | [postmortem/](postmortem/README.md) | Incident stories — the only tier where war-story narrative belongs | — | | [Persistence history](persistence-changes/README.md) and [format references](persistence-changes/historical-formats/README.md) | Type-change acknowledgements, release comparisons, and complete historical format schemas | Behavior-only changes; current runtime contracts | | [cookbook/](cookbook/adding-a-package.md) | Step-by-step how-tos with numbered verify steps | Design rationale (→ the Agent Note each guide links) | @@ -32,7 +33,7 @@ Each fact has one home: the tier whose job it is; elsewhere, link there. | Generated reference: the per-page `cordis-surface` regions in [subsystems/](subsystems/README.md), the [Cordis core API + inherited tier](cordis-api/context.md), [tool-catalog](tool-catalog.md), [config-catalog](config-catalog.md), [persistence-catalog](persistence-catalog.md), [module-graph.md](module-graph.md), [cli-help](cli-help.md) | Exhaustive English sources regenerated from source and freshness-gated; reviewed Chinese counterparts follow the [pairing workflow](i18n/README.md#scope-and-exclusions) | Hand edits to generated English sources or regions; Chinese counterparts update through pairing only | | Skills (`.agents/skills/`) | Reusable workflows and specialized decision standards | Product and runtime contracts (→ docs or source) | -Placement: bugs → postmortems; rationale → Agent Notes; procedures → cookbooks; type definitions → subsystems; package contracts → READMEs; standing orders → root `AGENTS.md` with a rationale link. +Placement: bugs → postmortems; rationale → Agent Notes; procedures → cookbooks; type definitions → subsystems; package contracts → READMEs; standing orders → root `AGENTS.md` with a rationale link; review-enforced rules → `defensive-patterns/`. ## Writing rules @@ -55,7 +56,7 @@ When the gate goes red: 2. **Condense** content that belongs here but can be shorter. 3. **Raise** the ceiling only when the words need the space; justify the manifest diff in the PR. A too-low ceiling is a budget bug. -Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 1,960; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 750 and this file ≤ 1,320; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `defensive-patterns.md` 550, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. +Ceilings are guardrails, not reduction targets. At or below target, retain at least 5% headroom; above target, freeze the ceiling until relocation or condensation brings the document under target. Lower a ceiling only when the document still has room. Targets: root `AGENTS.md` ≤ 1,960; `architecture.md` ≤ 2,400; subtree `AGENTS.md` ≤ 600, except `packages/AGENTS.md` ≤ 810 and this file ≤ 1,430; `packages/README.md` ≤ 994; plus `cordis-primer.md` 600, `testing.md` 1,300, `examples/AGENTS.md` 310. Review governs unbudgeted tiers. ## The slop checklist diff --git a/docs/api-gateway.i18n.yaml b/docs/api-gateway.i18n.yaml index 1072232f44..581a28929e 100644 --- a/docs/api-gateway.i18n.yaml +++ b/docs/api-gateway.i18n.yaml @@ -4,7 +4,7 @@ # pnpm run verify-translation-pairing --write docs/api-gateway.md /api-gateway: en: 735eb4f22d5f6f71 - zh: 1ca2759961efdc06 + zh: 697eef269b133039 /api-gateway/programming-model: en: ea12b64211f0d377 zh: 032e5c0d799c7529 @@ -22,7 +22,10 @@ zh: 2b70b61b1ff1fbb0 /api-gateway/development-mode: en: ba090d76471dd663 - zh: fcddcb232de98248 + zh: edf362f71b73eaf0 /api-gateway/boundaries: en: e6befc5f8c90f97b - zh: 3ade08102542a894 + zh: 4ace4a493fd2b41f +/api-gateway/boundaries/business-ownership: + en: 02c78afe5e2efcc5 + zh: 06cbd0d81293bc29 diff --git a/docs/api-gateway.md b/docs/api-gateway.md index 91f992dc5e..23fd5bef52 100644 --- a/docs/api-gateway.md +++ b/docs/api-gateway.md @@ -163,3 +163,9 @@ Remote handles unary method calls with one request and one result, and stream me The API layers are organized as `remotes → gateway → connection → webserver`. The BFF and Typert RPC layers live under `packages/api`; Connection and WebServer live at `packages/client/connection` and `packages/host/webserver`. Unary results containing `Uint8Array`, including nested fields and array entries, use [binary Remote transfer](../.agents/notes/implemented/architecture/2026-09-17-workspace-file-binary-transfer.md). A feature that needs a response outside the RPC envelope registers an exact Connection Fetch route. Lookup policy is configured per key, so all `agent` or `session` parameters share the cold-resume behavior. Accepting live objects only would require an explicit per-parameter or per-endpoint policy, which does not exist; the business method must not guess whether the object came from restoration. + +### Business ownership + +`packages/api` owns transport, call shape, and session lifecycle. A business rule — a state-dependent decision, a feature-specific handling path, or a per-feature filter — belongs to an independent business package and reaches this layer through a registration surface or projected data. A new business branch here needs an independent-package review. + +A new remote capability declares its own service instead of growing an existing one, marks the capability method with `@Remote`, and leaves client-facing types to inference. Remote payloads stay JSON with no output-side decode, and existing method and field names are additive. diff --git a/docs/api-gateway.zh.md b/docs/api-gateway.zh.md index 4e21bafa9b..9681a7a420 100644 --- a/docs/api-gateway.zh.md +++ b/docs/api-gateway.zh.md @@ -4,6 +4,8 @@ 本文是 Typert API Gateway 的当前状态参考。它描述业务服务如何声明一元与流式 Remote 方法、构建如何生成 Host 与 Client 约定,以及调用如何复用 Connection 的 RPC 与 `/api` 路由。会话事件、增量数据和其他流协议不属于本文范围;它们可以使用同一个 Connection,但不使用 Remote 方法描述符。 + + ## 编程模型 业务服务通过 `@Remote` 或 `@RemoteScope` 选择对 Client 开放的方法。未标记的方法不会进入生成的 Client 类型或运行时贡献,也不能通过 `ctx.remote` 调用。 @@ -156,6 +158,8 @@ pnpm run build:lib 运行中的 Client watcher 会在重新打包时消费这些生成文件。若已单独运行 `pnpm run build:lib:host` 刷新 Host 约定,也可再运行 `pnpm run build:lib:client` 完成 Client 侧;干净工作树不能跳过 Host 阶段。仅重新编译前端源码不能从 Host decorator 推导新类型。`pnpm run typecheck` 会执行 Host lib 阶段后再运行 Client tsc,CI 与发布构建也使用同一顺序。 + + ## 边界 Remote 处理单请求单结果的一元方法调用,以及项沿 Host → Client 方向流动、而 Client 的项经 `this.ctx.invocation.uplink()` 到达正在运行的 Host 方法的流方法。会话事件流、分页、增量 reduce、projection 和实体子流仍需要独立的数据协议与注册模型;即使它们复用 Connection,也不应伪装成 Remote 方法或放入调用描述符。 @@ -163,3 +167,11 @@ Remote 处理单请求单结果的一元方法调用,以及项沿 Host → Cli API 各层按 `remotes → gateway → connection → webserver` 组织。BFF 与 Typert RPC 层位于 `packages/api`;Connection 与 WebServer 位于 `packages/client/connection` 和 `packages/host/webserver`。包含 `Uint8Array` 的一元结果(包括嵌套字段和数组条目)使用[二进制 Remote 传输](../.agents/notes/implemented/architecture/2026-09-17-workspace-file-binary-transfer.zh.md)。需要 RPC 信封之外响应的功能注册精确的 Connection Fetch 路由。 lookup 策略按 key 配置,因此所有 `agent` 或 `session` 参数共享冷恢复行为。只接受 live 对象需要显式的逐参数或逐 endpoint 策略,而这种策略并不存在;不能通过业务方法内部猜测对象是否来自恢复。 + + + +### 业务所有权 + +`packages/api` 负责传输、调用形态与会话生命周期。业务规则——依赖状态的判断、与具体功能绑定的处理路径、逐功能的过滤——归独立业务包所有,经注册面或投影数据接入本层;在此新增业务分支须走独立包评审。 + +新的远程能力声明自己的 service,而不是继续扩大既有 service;能力方法用 `@Remote` 标注,面向 Client 的类型交给推断。远程载荷保持 JSON、不做输出侧 decode;既有的方法与字段名只增不改。 diff --git a/docs/defensive-patterns.i18n.yaml b/docs/defensive-patterns.i18n.yaml deleted file mode 100644 index 61e5aec2f2..0000000000 --- a/docs/defensive-patterns.i18n.yaml +++ /dev/null @@ -1,28 +0,0 @@ -# Bilingual-pair consistency record for defensive-patterns.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/defensive-patterns.md -/defensive-patterns: - en: 6316b1da0ae4561b - zh: f059647429c707d5 -/defensive-patterns/report-orthogonal-outcomes-independently: - en: 09cdbaa7cf763dc9 - zh: 11e5c13d77b2a563 -/defensive-patterns/honor-public-contracts-on-both-sides: - en: 157f966db7329171 - zh: 80da311819125f36 -/defensive-patterns/async-state-is-not-synchronous-state: - en: 33085f2b58bab16c - zh: be38e69a9c7d3f0e -/defensive-patterns/dispose-must-reach-quiescence-not-just-request-it: - en: 5c906be504b88a65 - zh: 8f428f59a87bb1a8 -/defensive-patterns/contain-callback-exceptions-in-the-dispatcher: - en: 3275390293995f44 - zh: 4d143e99a2a7c8cb -/defensive-patterns/never-hand-untrusted-output-the-ambient-environment-or-predictable-paths: - en: 09ad9d6433026468 - zh: cc0ba1a52859bb08 -/defensive-patterns/unlink-link-shaped-paths: - en: 644e6b1a9bd7b7d7 - zh: 823600c76c81ead1 diff --git a/docs/defensive-patterns.md b/docs/defensive-patterns.md deleted file mode 100644 index 25ec826913..0000000000 --- a/docs/defensive-patterns.md +++ /dev/null @@ -1,33 +0,0 @@ -# Defensive patterns - -English | [中文](defensive-patterns.zh.md) - -Hard-won bug-class rules: each pattern below is a class of defect that actually shipped or nearly shipped here, stated as the rule that prevents its recurrence. Read this before writing lifecycle, concurrency, subprocess, or teardown code. Test-tier counterparts (real entry path, world-verification, resource ownership) are in [testing.md](testing.md). - -## Report orthogonal outcomes independently - -A result can be several things at once — a process can time out AND exit 0 because it trapped the signal. Surface each independent fact (`timedOut`, `signal`, `exitCode`) on its own; never nest one flag's report inside another's branch, or a caller reads a cut-short run as a clean success. - -## Honor public contracts on BOTH sides - -When an implementation receives several representations of one outcome, normalize them before returning through the public API. `LlmAdapter.stream()` implementations may throw or emit `finish {kind:'error'|'aborted'}`, but `LlmRuntime.stream()` exposes model-request failures only as terminal finish chunks; middleware and consumer defects remain thrown. This keeps consumers from guessing whether a caught exception came from the provider, a wrapper, chunk logging, or their own assembly. Document the normalized contract where the type is defined; exercise every source form through the real consumer. - -## Async state is not synchronous state - -`agent.followup()` has no per-message completion or result; a background job's completion races turn boundaries; `reader.close()` fires for both EOF and disposal. Never treat `agent/status` or `whenIdle()` as the result of one follow-up: several queued follow-ups, steering, and injected work may share one `running` interval, while cancellation or disposal can discard unstarted items. An automation caller that truly owns a run must define its interval explicitly—for example, from its message's durable inbox receipt through the next whole-agent `idle`—and describe any selected output as interval-wide rather than causally attributed to that message. The guard cuts both ways: if the awaited transition can never occur, the wait hangs, so handle the "nothing to wait for" branch explicitly. - -## Dispose must reach quiescence, not just request it - -A teardown that issues kills/aborts but returns before the work stops leaves orphans. Make cleanup async and await the children's exit (kill → await `done`), and close listener/notification registries BEFORE killing so late completions stay silent. - -## Contain callback exceptions in the dispatcher - -Catch and report each listener's exception without rejecting the dispatch promise or starving later listeners. The listener's owner must handle state it mutates under the [error-handling rules](../.agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop); catching alone does not restore state. - -## Never hand untrusted output the ambient environment or predictable paths - -Spawned commands get a scrubbed env (drop `*KEY*`/`*SECRET*`/`*TOKEN*`/`*PASSWORD*`) so harness credentials cannot leak into output, `env`, or spill files. Temp/spill files use a private (0700) dir, random names, and exclusive owner-only opens (`'wx'`, `0o600`) — predictable world-readable paths invite symlink races and disclosure. - -## Unlink link-shaped paths - -A path that may be a symlink or Windows junction is removed with `lstatSync().isSymbolicLink()` then `unlinkSync`: unlink deletes only the link and refuses a real directory, so it never follows the link into its target. Windows `rmSync(link)` throws `ERR_FS_EISDIR` on a junction; recursive deletion may descend through one into its target. Reserve recursive `rmSync` for known real directories. diff --git a/docs/defensive-patterns.zh.md b/docs/defensive-patterns.zh.md deleted file mode 100644 index c21a87cb28..0000000000 --- a/docs/defensive-patterns.zh.md +++ /dev/null @@ -1,35 +0,0 @@ -# 防御性模式 - -[English](defensive-patterns.md) | 中文 - -来之不易的缺陷类别规则:下面每条模式都是本项目实际发布或差点发布的一类缺陷,以防止其复发的规则形式陈述。在编写生命周期、并发、子进程或清理代码之前请先阅读本文。测试层面的对应规则(真实入口路径、验证实际结果、资源归属)见 [testing.md](testing.zh.md)。 - -## 正交结果独立上报 - -一个结果可以同时具有多种性质:进程可能已经超时,却仍以退出码 0 结束,因为它捕获了终止信号。每个独立事实(`timedOut`、`signal`、`exitCode`)都应单独上报;切勿把一个标志的上报嵌套在另一个标志的分支中,否则调用方可能把提前终止的运行误判为正常成功。 - -## 公共约定两侧都要遵守 - -当一个实现收到同一结果的多种表示时,应在通过公共 API 返回前将其规范化。`LlmAdapter.stream()` 的实现可以抛出异常或发出 `finish {kind:'error'|'aborted'}`,但 `LlmRuntime.stream()` 只会通过终止型 finish 分片暴露模型请求失败;middleware 缺陷与消费方缺陷仍会以异常形式抛出。这使消费方不必猜测捕获的异常究竟来自提供方、包装层、分片日志记录还是自身组装逻辑。请在类型定义处记录规范化后的约定;通过真实消费方覆盖每种来源形式。 - -## 异步状态不是同步状态 - -`agent.followup()` 没有逐消息的完成状态或结果;后台任务的完成与轮次边界存在竞争;`reader.close()` 在 EOF 和 dispose(资源释放)两种情况下都会触发。切勿把 `agent/status` 或 `whenIdle()` 当作某次 `followup()` 的结果:多条已排队的后续消息、steering(中途引导)和注入工作可能共用同一个 `running` 区间,而取消或资源释放可能丢弃尚未启动的项。真正拥有一次运行的自动化调用方必须显式定义其区间——例如从消息的持久 inbox 回执到整个 agent(智能体)下一次进入 `idle`——并将选取的任何输出描述为整个区间的输出,而不是把因果关系归于该消息。这条守则是双向的:如果等待的转换永远不会发生,等待就会挂起,因此应显式处理「无需等待」的分支。 - - - -## dispose 必须达到完全停稳,而不仅仅是请求停止 - -如果清理流程只发出终止或中止信号便返回,而不等待工作真正停止,就会留下孤儿进程。清理逻辑应采用异步流程,并等待子进程退出(发出终止信号后等待 `done`);还应在终止进程前关闭监听器注册表和通知注册表,使迟到的完成事件保持静默。 - -## 在分发器中隔离回调异常 - -逐个捕获并报告监听器的异常,不让分发 promise 被 reject,也不让后续监听器失去执行机会。监听器的所有者必须按[错误处理规范](../.agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop)处置其修改的状态;仅捕获异常不会恢复状态。 - -## 绝不将环境变量或可预测路径暴露给不可信输出 - -启动的命令应使用经过清理的环境变量,移除名称匹配 `*KEY*`、`*SECRET*`、`*TOKEN*` 或 `*PASSWORD*` 的项,防止 harness 凭证通过命令输出、`env` 或 spill 文件泄漏。临时文件和 spill 文件应放在权限为 0700 的私有目录中,使用随机文件名,并以独占且仅所有者可访问的方式打开(`'wx'`、`0o600`);可预测且全局可读的路径会引发符号链接竞态和信息泄露。 - -## 用 unlink 删除链接形态的路径 - -可能是符号链接或 Windows junction 的路径,应先用 `lstatSync().isSymbolicLink()` 判断,再用 `unlinkSync` 删除:unlink 只删除链接本身并拒绝真实目录,因此绝不会跟随链接进入其目标。Windows 上对 junction 调用 `rmSync(link)` 会抛 `ERR_FS_EISDIR`;递归删除可能穿过 junction 进入其目标。真实目录才使用带 `recursive` 的 `rmSync`。 diff --git a/docs/defensive-patterns/README.i18n.yaml b/docs/defensive-patterns/README.i18n.yaml new file mode 100644 index 0000000000..79e3b6cd15 --- /dev/null +++ b/docs/defensive-patterns/README.i18n.yaml @@ -0,0 +1,10 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/defensive-patterns/README.md +/defensive-patterns: + en: 7229c49e920aa5b3 + zh: 1dd52db6b4d84952 +/defensive-patterns/why-these-rules: + en: 7c012071b5af8c98 + zh: 298aaba83625c7a0 diff --git a/docs/defensive-patterns/README.md b/docs/defensive-patterns/README.md new file mode 100644 index 0000000000..c74d1a4c29 --- /dev/null +++ b/docs/defensive-patterns/README.md @@ -0,0 +1,25 @@ +# Defensive patterns + +English | [中文](README.zh.md) + +Hard-won rules: each pattern in this directory is a requirement this repository enforces in review, stated as the rule and the defect it prevents. Every rule states what must hold, the condition a reviewer judges it by, its boundary and who approves an exception, and a correct and a wrong example. Read the page for the artifact you are about to change, before you change it. + +## Why these rules + +Five habits cover most of what follows, and each page is their application to one artifact: + +- **Make correctness explicit.** Write it into the structure — named call points, explicit lifecycles, explicit conditions and types — rather than compensating for it afterwards with timing. +- **Keep one source of truth.** One read path for a piece of data, one home for a fact, one owner for shared state. +- **Extend through the registered seam.** A new capability registers; an existing carrier stops taking new logic instead of growing a branch inside it. +- **Keep the change face equal to the review face.** A change carries only the lines its stated behavior change needs, a migration moves code rather than rewriting it, and a performance-sensitive change carries its measurement. +- **Require evidence.** A claim is falsifiable and recomputable — measured before and after, or checked by a gate — rather than kept in sync by hand. + +| Changing | Read | +|---|---| +| Package exports, package shape, build faces, dependency declarations | [package-surface.md](package-surface.md) | +| Remote services, `@Remote` methods, API dispatch, business ownership at the API layer | [remote-and-api.md](remote-and-api.md) | +| Client components, slots, stores, hooks, effects | [client-components.md](client-components.md) | +| Session reads, retention, conversation nodes, renderers | [conversation-and-session.md](conversation-and-session.md) | +| Timing, state representation, shared ownership, decentralization, refactors, migrations, performance evidence, disposal, callbacks, subprocesses | [general.md](general.md) | + +Type definitions and per-subsystem semantics live in [subsystems/](../subsystems/README.md); this directory carries the rules, and the semantics pages carry what the types mean. [dsh-code-review](../../.agents/skills/dsh-code-review/SKILL.md) reads this directory when judging a pull request, and Development routes through the same table from [AGENTS.md](../../AGENTS.md). diff --git a/docs/defensive-patterns/README.zh.md b/docs/defensive-patterns/README.zh.md new file mode 100644 index 0000000000..38d4c617d2 --- /dev/null +++ b/docs/defensive-patterns/README.zh.md @@ -0,0 +1,27 @@ +# 防御性模式 + +[English](README.md) | 中文 + +来之不易的规则:本目录中每条模式都是本仓库在评审中执行的**要求**,以「规则 + 它所防止的缺陷」的形式陈述。每条规则都写明:必须成立什么、评审据什么判定、边界在哪、例外由谁批准,以及一个正例与一个反例。动手修改某类制品之前,先读对应那一页。 + + + +## 这些规则背后的思想 + +下面五条习惯覆盖了绝大部分内容,每一页都是它们在某类制品上的落地: + +- **把正确性显式化。** 把它写进结构——具名调用点、显式生命周期、显式条件与类型——而不是事后用时序去补偿。 +- **只留一个真相。** 一份数据一条读取路径,一个事实一个正家,共享状态一个所有者。 +- **走注册面扩展。** 新能力靠注册接入;既有载体不再承接新逻辑,而不是在它内部长出分支。 +- **把改动面压成评审面。** 改动只包含其声明的行为变化所需的行;迁移是搬代码而不是重写;涉及性能的改动附带测量。 +- **要求可证伪、可复算。** 口径能被改动前后的实测或门禁证明/否证,而不是靠人肉同步。 + +| 你在改什么 | 读哪篇 | +|---|---| +| 包导出面、包形态、构建面、依赖声明 | [package-surface.zh.md](package-surface.zh.md) | +| 远程服务、`@Remote` 方法、API 分发、API 层的业务归属 | [remote-and-api.zh.md](remote-and-api.zh.md) | +| 客户端组件、slots、store、hooks、effect | [client-components.zh.md](client-components.zh.md) | +| Session 读取、持有、会话节点、renderer | [conversation-and-session.zh.md](conversation-and-session.zh.md) | +| 时序、状态表示、共享归属、去中心化、重构、迁移、性能证据、清理、回调、子进程 | [general.zh.md](general.zh.md) | + +类型定义与各子系统语义见 [subsystems/](../subsystems/README.zh.md);本目录承载**规则**,语义页承载**类型的含义**。[dsh-code-review](../../.agents/skills/dsh-code-review/SKILL.md) 在评审 pull request 时读本目录,日常修改经 [AGENTS.md](../../AGENTS.md) 路由到同一张表。 diff --git a/docs/defensive-patterns/client-components.i18n.yaml b/docs/defensive-patterns/client-components.i18n.yaml new file mode 100644 index 0000000000..753df9d6a8 --- /dev/null +++ b/docs/defensive-patterns/client-components.i18n.yaml @@ -0,0 +1,46 @@ +# Bilingual-pair consistency record for client-components.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/defensive-patterns/client-components.md +/client-component-rules: + en: a6e8a87976040c04 + zh: 08b59ad3c14fe250 +/client-component-rules/state-arrives-through-injection: + en: f8abfaf951119c64 + zh: be91a98d3a53b082 +/client-component-rules/props-carry-data-and-callbacks-not-react-nodes: + en: 253f05568dd7e26f + zh: fa12565ff5afb8bd +/client-component-rules/a-slot-registration-is-a-stable-function-component: + en: 36fa33b28a889aa6 + zh: 93ecb1d415d47ad1 +/client-component-rules/components-never-receive-a-cordis-context: + en: 8bb102b178615c03 + zh: 93cb177a578a1373 +/client-component-rules/context-comes-from-the-current-scope: + en: 652ec94d13ee51c9 + zh: b47c39e96c53cfac +/client-component-rules/resource-consumers-go-through-useresource: + en: edb2be9bbfa1a53b + zh: 414bf824c80286ed +/client-component-rules/store-usage-is-narrow-and-explicit: + en: 9dc1bad38c435976 + zh: effaa4ae9ba0e4e7 +/client-component-rules/identity-and-initial-state-are-deliberate: + en: a34c30b8f7c415d4 + zh: cbd0c0cf0c0db57c +/client-component-rules/uselayouteffect-is-not-a-default: + en: f53f17846a8a89b2 + zh: 94d205c4d85f1de9 +/client-component-rules/effects-never-push-render-derived-data-to-a-parent: + en: 580441bd6cce9ee9 + zh: a5f093d8e7dec2ee +/client-component-rules/build-and-style-follow-their-owners: + en: 561df1e1709a004c + zh: 89ca6eb4533648b8 +/client-component-rules/a-key-states-what-it-identifies: + en: 1d6f9bdc2b267fef + zh: cf4d579ca877c422 +/client-component-rules/each-shared-layer-keeps-its-own-isolation-level: + en: 3faec81a6a7c9fdd + zh: aa512c089b5f9afc diff --git a/docs/defensive-patterns/client-components.md b/docs/defensive-patterns/client-components.md new file mode 100644 index 0000000000..da75280f69 --- /dev/null +++ b/docs/defensive-patterns/client-components.md @@ -0,0 +1,480 @@ +# Client component rules + +English | [中文](client-components.zh.md) + +Rules for client components, their state, and their effects. [packages/client/AGENTS.md](../../packages/client/AGENTS.md) carries the detailed discipline; [slots.md](../subsystems/slots.md) owns the Slot design and [web-styling.md](../web-styling.md) the styling rules. Each section below states the requirement, how a reviewer judges it, where its boundary and exception sit, and a correct and a wrong example. + +## State arrives through injection + +A Slot's component receives everything it renders through the Injection face bound at its render site — owner props, hook seats, and actions — and never reads one large global state at the top of the tree to hand values down. Keeping every live value on that face is what makes a prop that did not change keep its identity, and what lets a component subscribe only to the sub-state it reads. Without it any unrelated field change re-renders the whole subtree, which is how a long session under streaming events loses frames while the user scrolls or types. + +- Judged by: at every `slots.render` site the author must be able to name which sub-states the rendered component subscribes to and which of its incoming props keep a stable identity across renders. Watch the mutability of every prop: a value rebuilt each render — a fresh object, array, or inline callback — propagates re-renders even when nothing in it changed. +- Not covered: the component's own local state (`useState` for a fold, a hover, a draft) is not injection content, and a component that subscribes to nothing outside React needs no new seat. +- Exception: a new injection face or hook seat changes the Slot contract, so that change states its impact — which components subscribe to what — in review; using an existing face needs no per-component approval. +- Fix: narrow the injection to what the view renders, expose one field per read through a hook seat, and pass a narrow action set instead of a store or service handle. [Component inputs](../subsystems/slots.md#component-inputs) owns the inject factory, the standard hook seats, and how each becomes a prop. + +The render site injects one hook seat and a narrow action set, and the component reads only the field it renders: + +```tsx +// Render site: plain owner data, one hook seat, a narrow action set. +slots.render('sidebar.right', { + props: { id }, + useHooks: SidebarHooks, + action: { rename, archive }, +}) + +function SidebarRight({ id, useInfo, action }: Props) { + const { title } = useInfo() // subscribes to title only + return +} +``` + +The top-level component reads the whole view store and hands it down as one prop, so the render site can no longer answer either question above: + +```tsx +function Sidebar() { + const view = useViewStore() // one top-level global read + return // the whole store travels down +} + +function SidebarRight({ view }: { view: ViewStore }) { + return {view.activePanel.title} +} +``` + +Every field change in that store re-renders the whole sidebar subtree, and the component's subscription set is invisible to the site that bound it. + +## Props carry data and callbacks, not React nodes + +A prop is data or a callback; a React node travels through a declared slot. Passing an element as a prop value or an injected member hides a second composition path that the Slot contract does not describe, moves render control from the registration surface to the call site, and lets one package assemble another package's markup. New node-valued props or injected members are never added; a location that needs host-supplied markup is declared as a child slot instead. + +- Judged by: `ReactNode`, `ReactElement`, or a `() => JSX.Element` in a component's props type, in an inject factory's return value, or in an owner-props object at a render site. +- Not covered: node-valued fields that already shipped keep working. The rule triggers when a change touches one, and that change converts it rather than extending it. +- Exception: when the conversion cannot happen in the same change, the owning domain expert confirms the deferral and the change records that confirmation; the author never self-approves. +- Fix: declare the location in the parent registration's `children`, render it with `renderSlot`, and pass data through the child's props. [Extension rules](../subsystems/slots.md#extension-rules) own which package may declare and render which slot. + +The header location is a declared child slot, so the host passes data and the registered component owns its markup: + +```tsx +// The card declares the header location; the host passes data only. +ctx.slots.register( + { + name: 'tool.call.toolview', + children: { header: { kind: 'single', scope: 'session' } }, + }, + ToolCard, +) + +function ToolCard({ title, renderSlot }: Props) { + return
{renderSlot('header', { title })}
+} +``` + +A React node crosses the boundary as a prop value, so the composition path it travels is not declared anywhere: + +```tsx +type ToolCardProps = { + header?: React.ReactNode + footer?: React.ReactNode +} + +// The call site assembles another package's markup. +} /> +``` + +The card's Slot contract stops describing what it renders, the call site keeps render control, and the badge's package becomes a runtime reference from whoever passes it. + +## A slot registration is a stable function component + +The value registered into a slot is a stable function component declared at module scope, or a plain string when the seat renders fixed text. A component function created during render is a new component type on every pass, and React treats a changed type as a different component: it unmounts the subtree and mounts a fresh one, which resets expanded rows, input focus, and scroll position. Registration-time parameters reach the component through props rather than by closing over render-time variables. + +- Judged by: where the registered value is created. An inline arrow in the registration call, a component defined inside a render body, and a `useCallback` wrapper around an inline component all fail; a module-scope `function` declaration or a string passes. +- Not covered: the rule constrains the identity of the registered value, not its complexity. A stable component may still read injected props, hooks, and callbacks, and a fixed-text seat may stay a string. +- Exception: creating a component during render is correct only when the caller wants the remount, and an ordinary change needs no separate approval; a change to the form of the Slot contract follows the injection-face review described under State arrives through injection. +- Fix: move the component to module scope, type its props from the registration's shares, and pass the varying value through the inject face instead of the closure. + +The registration holds one stable reference to a module-scope component, and the varying value arrives injected: + +```tsx +function PanelTitle({ title, count }: Props) { + return {title} ({count}) +} + +// The registration holds one stable reference to the module-scope component. +ctx.slots.registerFactory( + { + name: 'panel', + slots: { title: PanelTitle }, + inject: () => ({ title: 'Sessions', count: 3 }), + }, + Panel, +) +``` + +An inline arrow inside the registration call creates a new component type whenever the registration runs: + +```tsx +// A new component type each time this registration runs. +ctx.slots.registerFactory( + { name: 'panel', slots: { title: (p) => {p.title} } }, + Panel, +) +``` + +React sees a different type than the previous registration, remounts the seat, and resets its local state — expanded, focused, or scrolled position — on an otherwise unrelated update. + +## Components never receive a Cordis context + +`ctx` belongs to the apply world: the plugin body and the `inject` factories closed over it. A component never receives a Cordis context, never imports a service class to poke it, and never reads a React context, because business components see zero contexts — the renderer's binding contexts are internal to it. A bare observable reaches a component only after Injection wraps it in a hook; a component that subscribes directly owns a lifecycle that nothing on the Injection face releases. + +- Judged by: `ctx` or `Context` in a component's parameter or props type; a component body reading `observable.value`, calling `subscribe`, or wiring `useSyncExternalStore`; a service class imported into a feature `.tsx` module. +- Not covered: a component-internal behavioral hook that subscribes to nothing outside React (a timer, a media query) is not injection content and stays in the component. +- Exception: none. The direct subscription still present in `TabSlot` is remediation work owned by that entry's owner, not a precedent for new code. +- Fix: move the fact into the registration's `inject` — plain data and callbacks, with bare observables in the reserved `hooks` compartment — or into a declared store, and read it through the derived seat. + +Injection binds the observable, and the component reads one derived hook whose subscription the renderer owns: + +```tsx +// The inject factory is the only place that closes over ctx. +const inject = () => ({ + hooks: { tab: tabStore.observable }, + action: { openTab }, +}) + +function TabView({ useTab, action }: Props) { + const { loaded } = useTab() // the renderer owns the subscription + return +} +``` + +The whole view store is injected for the component to pick fields from, and a multi-instance store is given one shared persistence key: + +```tsx +// The component receives the store and picks its own fields. +const inject = () => ({ viewStore }) + +function SidebarHeader({ viewStore }: Props) { + return +} + +// One key for several pane instances. +createPaneStore({ persistKey: 'pane' }) +``` + +The component's dependency face stops being auditable, and the shared key makes two pane instances overwrite each other's state on hydrate. + +## Identity and initial state are deliberate + +Switching state does not remount a control or replace its DOM node: the instance and its DOM identity stay the same across a state change, so focus, selection, and an in-progress draft survive it. Initial state is ready when the first flow runs — the same path prepares the data and establishes the state — instead of being filled in later by an effect. A component receives hooks, selectors, and action callbacks rather than a whole service. + +- Judged by: after a state change, whether the control instance and its DOM node keep their identity; an unmount followed by a mount is the violation. The initialization path is judged the same way: state established inside the first flow passes, state written from an effect fails. +- Dependency face: hooks read, selectors pick a sub-state, and action callbacks write back. A whole service passed as a prop or an injected member fails. +- Scope: input and command controls that hold an internal instance and local state, and business views created by a factory. +- Exception: a genuinely required remount — switching to a data set whose instance state cannot migrate — is explained in review together with the state migration plan; the reviewer of a change that affects a control's instance lifetime accepts it. +- Fix: derive the initial value where the first flow builds its state, keep the layout node mounted and vary its props, and replace a service prop with the three narrow shares. + +The draft exists with the session and the composer node stays mounted while only its props change: + +```tsx +// The draft is built by the first flow; nothing fills it in later. +const draft = useDraftState(sessionId) +const { canSend } = useComposerSelectors(draft) + +// The node stays mounted; state changes reach it as props. +return ( +
+ {draft.text} +
+) +``` + +Initial state arrives one commit late, and the keyed control is rebuilt whenever the session changes: + +```tsx +// The draft is filled in after the first commit. +useEffect(() => { setDraftState(initialDraft) }, []) + +// The keyed composer unmounts on every session switch. + +``` + +The first frame renders an empty draft, and every session switch drops focus, selection, and whatever the user had typed. + +## `useLayoutEffect` is not a default + +`useLayoutEffect` is not used by default, and replacing it with `useEffect` is not a fix, because the two differ in timing rather than in what the code is doing. A layout measurement first answers why it happens here, why CSS cannot express it, and why it must be a pixel measurement; only then does it move into an injected measurement hook with the owning domain expert's sign-off. An effect of either kind never records state or binds logic, because that belongs in Injection. + +- Judged by purpose, not by hook name: which measurement or which binding the effect exists for. A state-recording or logic-binding effect returns to Injection as a Provider or an injected hook; only a measurement that survived the three questions stays, and its result is consumed as a declarative layout parameter. +- Not covered: the timing difference between the two effects, which `@types/react` documents for `useLayoutEffect` as synchronous after DOM mutation and before paint, is background fact and not a license to rewrite one as the other. +- Exception: any retained `useLayoutEffect` needs the owning domain expert's confirmation, and the change records that confirmation. +- Fix: express the layout in CSS — grid, `aspect-ratio`, a container query — or collect the measurement inside the injected hook and expose one value. + +Layout is declared in CSS, and the one measurement that survived the questions lives in an injected hook: + +```tsx +// Fix 1 — express the layout in CSS and delete the measurement. +// .card { display: grid; grid-template-columns: minmax(0, 1fr) auto; aspect-ratio: 16 / 9; } + +// Fix 2 — the approved measurement is injected and returns one value. +function CardBase({ useLayoutMeasurements }: Props) { + const ref = useRef(null) + const { gutterWidth } = useLayoutMeasurements(ref) + return
+} +``` + +Both of the first two effects below answer the wrong question — which effect to use — and the third parks a binding in an effect: + +```tsx +// A synchronous pixel measurement the design did not need. +useLayoutEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// The same measurement with the hook name swapped. +useEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// Logic binding parked in an effect instead of Injection. +useEffect(() => { bindShortcut(handler) }, []) +``` + +The rename leaves the layout problem in place, the measured height now depends on which effect was chosen, and the shortcut binds one render late instead of through Injection. + +## Effects never push render-derived data to a parent + +An effect body never calls a setter that arrived through props or slot props to push data back to a parent when that data could be decided during render from props or state the component already has. Such a push costs a second render, leaves the parent without the value on its first frame, and turns any later state change into a render cascade. The value is decided during render, the host takes it through a render-time channel, or a user gesture updates its own state in its handler. + +- Judged by: a setter from props or slot props called inside an effect, whose argument derives from the current props or state, with no external event or subscription callback driving it. A cleanup `return () => setX(undefined)` is part of the same violation. +- Consequences to name in review: the extra render pass; the parent's first frame missing the value; a dependency array that goes stale when a member is omitted; the effect → parent state → render cascade; and a child lifecycle entangled with parent state. +- Not covered: an effect that reacts to a genuine external event — a subscription callback, a socket frame, a user gesture — is not this pattern, and an event handler may update state directly. +- Exception: none by default; any exception needs the owning domain expert's confirmation. +- Fix, in order: render the UI where the state already is; if the host must render it, hand the value over during render; if the state is shared across entries, move it to the inject face or a declared store. + +The control is rendered where its state already lives, and the shared variant is read during render while the write stays in the gesture handler: + +```tsx +// 1. Render it where the state already lives; no channel is needed. +return + +// 2. The host renders it: the flag is declared state, read during render +// and written only from the gesture handler. +const { showOriginal } = useStore() +const { toggleOriginal } = actions +return +``` + +`label` and `disabled` are render-derivable, so calling the parent's setter from an effect makes the parent render twice and still lack the header on its first frame: + +```tsx +useEffect(() => { + setHeaderAction({ label, disabled, onClick }) // render-derivable data pushed up + return () => { setHeaderAction(undefined) } +}, [label, disabled, setHeaderAction]) +``` + +The parent renders twice for data it could have had on the first pass, the header appears a frame late or flashes, and the hand-written dependency list decides when it is published. + +## Build and style follow their owners + +Every build adjustment for a client package goes through the tsdown plugin for that package, and a package does not grow its own build branch. Styling goes through CSS Modules, and only images, GIFs, and SVG are inlined — inlined into CSS rather than into JSX. Large text never appears inline in TSX, and a `style` object holds only runtime-computed values, because static values and style variants belong to CSS Module class names. + +- Judged by: a new build branch inside a package instead of the tsdown plugin; a literal color, a component library, or Tailwind in feature styling; base64 data or large text in TSX; and a `style` object carrying static values or a variant switch. +- Not covered: a runtime-computed value such as a measured gutter or a progress percentage may enter `style`, and a component-local custom property may carry a layout value. [Component rules](../web-styling.md#component-rules) own the tokens, CSS Module, and class-name rules. +- Exception: a new build branch or a new inline form is explained in review before it lands, and the owning package's rules decide whether it stays. +- Fix: move the variant into a CSS Module class switched by `className`, keep base64 in CSS produced by the build chain, and delete the large text constant from the TSX module. + +The component switches class names and data attributes, and the CSS Module owns the presentation: + +```tsx +import s from './card.module.css' + +// Style variants are class names, not style-object branches. +export function Card({ active, tone, children }: Props) { + return ( +
+ {children} +
+ ) +} +``` + +Large text and inlined binary data enter the module, and the `style` object encodes a variant the theme cannot override: + +```tsx +const HUGE = '...several KB of text...' // large text inline in the module + +// A variant switch and an inlined asset both sit in the style object. +
+``` + +The bundle carries text and binary data that belong in CSS and assets, diffs carry unreadable blobs, and a theme override can no longer reach that colour. + +## A key states what it identifies + +Pass a `key` only when it names which entity or instance an element represents, and state that identity — a `turnId`, for example, is unique inside one session. Most lists already have a stable business id and need no extra key. A key invented to silence a warning or to encode render order states an identity the data does not have, and an array index is never that identity, because an insert or delete shifts every following item onto a different element. + +- Judged by: whether the item's identity can be expressed by position or by a stable id. When a key is passed, the change states what makes it unique, and `key={index}` over a mutable list fails. +- Not covered: React's own requirement that a list's items carry keys still applies; that key is the item's stable business id and not a second key beside it. +- Exception: none. An ordinary change needs no sign-off, while the key semantics of a shared component are stated in review. +- Fix: use the entity's stable id, and when two rows genuinely share one id, fix the id source instead of mixing an index into the key. + +The key is the turn's own id, whose uniqueness inside a session is the identity the element represents: + +```tsx +// turnId is unique inside a session; the id is the identity. +export function TurnList({ turns }: Props) { + return ( +
    + {turns.map((turn) => )} +
+ ) +} +``` + +The index stands in for identity, so every following row changes identity when the list changes: + +```tsx +// The index stands in for identity. +{items.map((item, index) => ( + +))} +``` + +After an insert or a delete, each following row keeps its previous state on new data, so an expanded row or an in-progress edit appears on the wrong item. + +## Each shared layer keeps its own isolation level + +A feature absorbs its requirement in its own package, and how much separation it must keep from shared code depends on which shared layer that code belongs to. The violation to look for is a feature-specific concept placed in a shared layer, because every other consumer then has to understand a concept that is not theirs and the branch is hard to withdraw. + +| Shared code | Isolation a feature keeps | +|---|---| +| `ui-primitives`, the catalogued controls | Consume the catalogued control. A new control starts in the feature package and is promoted into the shared catalog only when a second consumer needs it. | +| `ui-layout` and the shell layout | Consume it; adapt in the feature package with a wrapper, an overridden style, or an added layer. | +| `ui-renderer` and the other render machinery | No value dependency from business code; extend only through the documented registration seams — slots, provide/inject-bound hooks, declared stores. | +| Another feature plugin | No runtime import and no re-export of its values. UI crosses through slots and behavior through injected services; shared runtime code lives in a narrow static owner such as `client/store`, `ui-primitives`, or a browser-safe utility package. | +| The data object layer (`client/connection`, `session-controller/client`, `client/store`) | Read through the documented surface; a feature's own concepts do not enter these objects or their stores. | +| The feature's own package | Unrestricted — the requirement is absorbed here, including its own rows, ordering, and presentation. | + +- Judged by: whether the diff puts a feature-specific branch, field, or concept into any layer but the feature's own package. +- Not covered: code the feature owns, and a change to a shared layer that is genuinely general rather than one feature's need. +- Exception: a shared-layer change carries the owning domain expert's confirmation and regresses every consumer; a GUI change runs the minimum check in [packages/client/AGENTS.md](../../packages/client/AGENTS.md). +- Fix: absorb the requirement in the feature package, or, when the need is genuinely general, promote it to the shared layer in its own change with the owner's sign-off. + +The feature owns its row rendering and its ordering rule, and the base component is consumed unchanged: + +```tsx +// The feature owns its rows; the base is consumed, not edited. +// packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx +export function WorkspaceBrowser({ rows, onArchive }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return ( +
    + {ordered.map((row) => )} +
+ ) +} +``` + +A base component learns one feature's ordering rule, so every consumer inherits a concept that is not theirs: + +```tsx +// ui-layout: the base learns one feature's ordering rule. +export function BrowserList({ rows, ...rest }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return
    {ordered.map((row) => )}
+} +``` + +Every other consumer of `ui-layout` now has to understand an archive concept that only one feature has, and withdrawing the branch means auditing all of them. diff --git a/docs/defensive-patterns/client-components.zh.md b/docs/defensive-patterns/client-components.zh.md new file mode 100644 index 0000000000..a63392b876 --- /dev/null +++ b/docs/defensive-patterns/client-components.zh.md @@ -0,0 +1,482 @@ +# 客户端组件规则 + +[English](client-components.md) | 中文 + +关于客户端组件、其状态与 effect 的规则。详细纪律见 [packages/client/AGENTS.md](../../packages/client/AGENTS.md);Slot 设计正家是 [slots.zh.md](../subsystems/slots.zh.md),样式规则正家是 [web-styling.zh.md](../web-styling.zh.md)。以下每一节给出要求、评审判定方式、边界与例外,以及一正一反两个例子。 + +## 状态经 Injection 到达 + +Slot 的组件经其渲染点绑定的 Injection 面获得它渲染所需的一切——owner props、hook 席位与 action——绝不先在顶层读一棵大全局状态再逐层手工传下去。把每个活值都放在这个面上,props 才能在没变时保持引用不变,组件也才能只订阅自己读取的那部分子状态。缺了这条,任何一个无关字段变化都会重渲整棵子树——长会话在流式事件下的掉帧、滚动与输入卡顿就是这么来的。 + +- 判定方式:每个 `slots.render` 点上的作者都必须能回答两件事——被渲染组件订阅了哪些子状态,以及它收到的哪些 props 在多次渲染之间保持引用稳定。要盯住每个 prop 的可变性:每次渲染都重建的值(新对象、新数组、内联回调)即使内容没变也会向下传播重渲。 +- 不在范围内:组件自己的局部状态(折叠、悬停、草稿用的 `useState`)不属于注入内容;不订阅 React 之外任何东西的组件也不需要新席位。 +- 例外:新增注入面或 hook 席位会改动 Slot 契约,因此该改动要在 review 中说明影响面——哪些组件订阅什么;使用既有注入面不需要逐组件批准。 +- 修法:把注入收窄到该视图真正渲染的内容,每个读取项经一个 hook 席位暴露一个字段,用窄 action 集合取代 store 或 service 句柄。[组件输入](../subsystems/slots.zh.md#component-inputs) 正家负责 inject 工厂、标准 hook 席位,以及它们各自如何成为 prop。 + +渲染点只注入一个 hook 席位与一组窄 action,组件只读它渲染的那个字段: + +```tsx +// Render site: plain owner data, one hook seat, a narrow action set. +slots.render('sidebar.right', { + props: { id }, + useHooks: SidebarHooks, + action: { rename, archive }, +}) + +function SidebarRight({ id, useInfo, action }: Props) { + const { title } = useInfo() // subscribes to title only + return +} +``` + +顶层组件读了整个 view store 并把它作为一个 prop 传下去,于是渲染点再也回答不了上面两个问题: + +```tsx +function Sidebar() { + const view = useViewStore() // one top-level global read + return // the whole store travels down +} + +function SidebarRight({ view }: { view: ViewStore }) { + return {view.activePanel.title} +} +``` + +该 store 里任何字段变化都会重渲整个侧栏子树,而且绑定它的渲染点完全看不到这个组件订阅了什么。 + +## props 承载数据与回调,不承载 React 节点 + +prop 是数据或回调;React 节点经声明的 slot 传递。把元素作为 prop 值或注入成员传下去,会藏起一条 Slot 契约没有描述的第二条组合路径,把渲染控制权从注册面挪到调用点,并让一个包去拼装另一个包的标记。新增的节点型 prop 或注入成员一律禁止;需要宿主提供标记的位置,改为声明一个 child slot。 + +- 判定方式:组件的 props 类型、inject 工厂的返回值、或渲染点的 owner props 对象里出现 `ReactNode`、`ReactElement` 或 `() => JSX.Element`。 +- 不在范围内:已经发布的节点型字段继续可用。规则在改动波及它时触发,该改动把它改掉,而不是继续扩展它。 +- 例外:同一改动内无法完成改造时,由对应领域专家确认延期,且改动中记录该确认;作者不得自行确认。 +- 修法:在父级注册的 `children` 中声明该位置,用 `renderSlot` 渲染它,数据经子组件的 props 传入。[扩展规则](../subsystems/slots.zh.md#extension-rules) 正家负责哪个包可以声明和渲染哪个 slot。 + +头部位置是一个声明的 child slot,因此宿主只传数据,标记由注册组件自己决定: + +```tsx +// The card declares the header location; the host passes data only. +ctx.slots.register( + { + name: 'tool.call.toolview', + children: { header: { kind: 'single', scope: 'session' } }, + }, + ToolCard, +) + +function ToolCard({ title, renderSlot }: Props) { + return
{renderSlot('header', { title })}
+} +``` + +React 节点作为 prop 值越过边界,于是它所走的组合路径没有任何地方声明过: + +```tsx +type ToolCardProps = { + header?: React.ReactNode + footer?: React.ReactNode +} + +// The call site assembles another package's markup. +} /> +``` + +卡片的 Slot 契约不再描述它渲染什么,调用点继续握着渲染控制权,而徽章所在的包变成了传节点方的运行时引用。 + +## slot 注册物是稳定的 function component + +注册进 slot 的值是在模块作用域声明的稳定 function component;席位渲染固定文本时也可以是纯字符串。渲染期创建的组件函数每一轮都是新的组件类型,而 React 把变化的类型当作另一个组件:它卸载这棵子树并挂载一棵新的,展开的行、输入焦点与滚动位置随之重置。注册期参数经 props 到达组件,而不是靠闭包捕获渲染期变量。 + +- 判定方式:注册物在哪里创建。注册调用里的内联箭头、渲染函数体内定义的组件、以及用 `useCallback` 包住内联组件的写法都不合格;模块作用域的 `function` 声明或字符串合格。 +- 不在范围内:本条约束的是注册物的身份,不是它的复杂度。稳定组件照样可以读取注入的 props、hooks 与回调,固定文本席位也可以保持为字符串。 +- 例外:只有调用方确实想要这次重挂载时,渲染期创建组件才是对的,普通改动无需单独批准;Slot 契约形态的变更按「状态经 Injection 到达」一节描述的注入面 review 走。 +- 修法:把组件移到模块作用域,用注册面的各个 share 给它的 props 定型,让变化的值经 inject 面传入而不是走闭包。 + +注册物持有对模块作用域组件的稳定引用,变化的值经注入到达: + +```tsx +function PanelTitle({ title, count }: Props) { + return {title} ({count}) +} + +// The registration holds one stable reference to the module-scope component. +ctx.slots.registerFactory( + { + name: 'panel', + slots: { title: PanelTitle }, + inject: () => ({ title: 'Sessions', count: 3 }), + }, + Panel, +) +``` + +注册调用里的内联箭头会在注册每次运行时产生新的组件类型: + +```tsx +// A new component type each time this registration runs. +ctx.slots.registerFactory( + { name: 'panel', slots: { title: (p) => {p.title} } }, + Panel, +) +``` + +React 看到的类型与上一次注册不同,于是重挂载该席位,并在一次无关更新中重置它的局部状态——展开态、焦点或滚动位置。 + +## 组件绝不接收 Cordis context + +`ctx` 属于 apply 世界:插件主体与闭包持有它的 `inject` 工厂。组件不接收 Cordis context、不导入 service 类去戳它、也不读 React context,因为业务组件看不到任何 context——渲染器的 binding context 是它内部的。裸 observable 只有在 Injection 把它包成 hook 之后才到达组件;直接自行订阅的组件持有一份 Injection 面上无人释放的生命周期。 + +- 判定方式:组件的参数或 props 类型里出现 `ctx` 或 `Context`;组件体内读 `observable.value`、调用 `subscribe`、或接 `useSyncExternalStore`;feature 的 `.tsx` 模块里导入 service 类。 +- 不在范围内:组件内部、不订阅 React 之外任何东西的行为 hook(计时器、媒体查询)不是注入内容,留在组件里。 +- 例外:无。`TabSlot` 里现存的直接订阅是该席位 owner 的整改工作,不是新代码的先例。 +- 修法:把该事实移进注册的 `inject`——纯数据与回调,裸 observable 放进保留的 `hooks` 隔间——或移进声明的 store,再经派生的席位读取。 + +Injection 绑定 observable,组件读一个派生的 hook,订阅生命周期由渲染器持有: + +```tsx +// The inject factory is the only place that closes over ctx. +const inject = () => ({ + hooks: { tab: tabStore.observable }, + action: { openTab }, +}) + +function TabView({ useTab, action }: Props) { + const { loaded } = useTab() // the renderer owns the subscription + return +} +``` + +整个 view store 被注入给组件自行挑选字段,多实例 store 又被赋了一个共享的持久化键: + +```tsx +// The component receives the store and picks its own fields. +const inject = () => ({ viewStore }) + +function SidebarHeader({ viewStore }: Props) { + return +} + +// One key for several pane instances. +createPaneStore({ persistKey: 'pane' }) +``` + +组件的依赖面不再可审计,而共享的键会让两个 pane 实例在 hydrate 时互相覆盖状态。 + +## 身份与初始状态都是刻意的 + +状态切换不重建控件、也不替换其 DOM 节点:实例与其 DOM 身份在状态变化之间保持同一,焦点、选中与进行中的草稿因此得以保留。初始状态在首个流程运行时即就绪——同一条路径既准备数据也建立状态——而不是之后由 effect 回填。组件接收 hooks、选择器与 action 回调,而不是整个 service。 + +- 判定方式:状态变化之后,控件实例与其 DOM 节点是否保持同一身份;出现卸载再挂载即违反。初始化路径同样判定:状态在首个流程内建立合格,从 effect 写入不合格。 +- 依赖面:hooks 读取、选择器选中子状态、action 回调写回。整个 service 作为 prop 或注入成员传入即不合格。 +- 范围:带内部实例与本地状态的输入与命令控件,以及由 factory 创建的业务视图。 +- 例外:确需重挂载(切换的数据集其实例状态不可迁移)时,在 review 中连同状态迁移方案一并说明;由评审该控件实例生命周期改动的评审者接受。 +- 修法:在首个流程建立状态的地方派生初始值,保持布局节点挂载、只变化其 props,并用三个窄 share 取代 service prop。 + +草稿随会话一起建立,composer 节点保持挂载,只有 props 随状态变化: + +```tsx +// The draft is built by the first flow; nothing fills it in later. +const draft = useDraftState(sessionId) +const { canSend } = useComposerSelectors(draft) + +// The node stays mounted; state changes reach it as props. +return ( +
+ {draft.text} +
+) +``` + +初始状态迟一个提交到达,带 key 的控件在每次会话切换时被重建: + +```tsx +// The draft is filled in after the first commit. +useEffect(() => { setDraftState(initialDraft) }, []) + +// The keyed composer unmounts on every session switch. + +``` + +首帧渲染出空草稿,每次会话切换都会丢掉焦点、选中,以及用户已经输入的内容。 + +## `useLayoutEffect` 不是默认选项 + +`useLayoutEffect` 默认不用,换成 `useEffect` 也不算修好,因为二者的差别在时序,而不在代码在做什么。布局测量先回答三个问题——为何在此处发生、为何 CSS 无法表达、为何必须是像素测量;只有回答完,才收进注入的测量 hook 并取得对应领域专家的确认。两类 effect 都不承担状态记录或逻辑绑定,那是 Injection 的职责。 + +- 判定依据是用途而不是 hook 名字:这个 effect 为哪次测量或哪次绑定而存在。状态记录或逻辑绑定的 effect 回到 Injection——Provider 或注入 hook;只有通过三问的测量才留下,其结果作为声明式布局参数消费。 +- 不在范围内:两个 effect 的时序差异(`@types/react` 记载 `useLayoutEffect` 在 DOM 变更后同步触发、绘制前刷出)是背景事实,不是把其一改写为另一的许可。 +- 例外:任何保留下来的 `useLayoutEffect` 都要经对应领域专家确认,改动中记录该确认。 +- 修法:用 CSS 表达布局——grid、`aspect-ratio`、容器查询——或把测量收进注入 hook 并暴露一个值。 + +布局用 CSS 声明,唯一通过三问的测量住在注入 hook 里: + +```tsx +// Fix 1 — express the layout in CSS and delete the measurement. +// .card { display: grid; grid-template-columns: minmax(0, 1fr) auto; aspect-ratio: 16 / 9; } + +// Fix 2 — the approved measurement is injected and returns one value. +function CardBase({ useLayoutMeasurements }: Props) { + const ref = useRef(null) + const { gutterWidth } = useLayoutMeasurements(ref) + return
+} +``` + +下面前两个 effect 回答的是错的问题——该用哪个 effect——第三个把绑定停在 effect 里: + +```tsx +// A synchronous pixel measurement the design did not need. +useLayoutEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// The same measurement with the hook name swapped. +useEffect(() => { setHeight(ref.current.getBoundingClientRect().height) }, []) + +// Logic binding parked in an effect instead of Injection. +useEffect(() => { bindShortcut(handler) }, []) +``` + +改名并不能解决布局问题,量到的高度从此取决于选了哪个 effect,而快捷键绑定迟一轮渲染生效,没有回到 Injection。 + +## effect 绝不把渲染期可派生的数据推给父层 + +effect 体内绝不调用经 props 或 slot props 传来的 setter,把本可在渲染期由组件已有的 props / state 决定的数据推回父层。这种推送要多付一轮渲染、让父层首帧拿不到值,并把之后任何一次状态抖动放大成渲染级联。该值在渲染期决定,宿主经渲染期通道取得,或由用户手势在其处理器内更新自己的状态。 + +- 判定方式:effect 体内调用了 props 或 slot props 传来的 setter,其入参由当前 props / state 派生,且没有外部事件或订阅回调驱动它。清理函数 `return () => setX(undefined)` 属于同一违规。 +- review 中要点名的后果:多一轮渲染;父层首帧缺值;依赖数组漏项即 stale;effect → 父 state → 再渲染的级联;子组件生命周期与父层状态纠缠。 +- 不在范围内:响应真实外部事件的 effect——订阅回调、socket 帧、用户手势——不是本形态;事件处理器可以直接更新状态。 +- 例外:默认无例外;任何例外都要经对应领域专家确认。 +- 修法按顺序:状态在哪里就让 UI 在哪里渲染;必须由宿主渲染时,在渲染期把值交出去;跨条目共享的状态移进注入面或声明的 store。 + +控件在状态所在处渲染,共享的开关在渲染期读取,写回只发生在手势处理器里: + +```tsx +// 1. Render it where the state already lives; no channel is needed. +return + +// 2. The host renders it: the flag is declared state, read during render +// and written only from the gesture handler. +const { showOriginal } = useStore() +const { toggleOriginal } = actions +return +``` + +`label` 与 `disabled` 都是渲染期可派生的,从 effect 调用父层 setter 让父层渲染两轮、首帧仍然没有头部动作: + +```tsx +useEffect(() => { + setHeaderAction({ label, disabled, onClick }) // render-derivable data pushed up + return () => { setHeaderAction(undefined) } +}, [label, disabled, setHeaderAction]) +``` + +父层为本来第一轮就能拿到的数据渲染两轮,头部迟一帧出现或闪烁,而发布时间由手写的依赖数组决定。 + +## 构建与样式各归其主 + +客户端包的每项构建调整都经该包的 tsdown 插件完成,包内不新开自己的构建分支。样式走 CSS Module,只有图像、GIF 与 SVG 需要内联——且内联到 CSS 而不是 JSX。TSX 里绝不内联大文本,`style` 对象只放运行期计算的值,因为静态值与多样式切换属于 CSS Module 的 class name。 + +- 判定方式:包内新开构建分支而不是走 tsdown 插件;feature 样式里出现字面颜色、组件库或 Tailwind;TSX 里出现 base64 数据或大文本;`style` 对象承载静态值或样式切换。 +- 不在范围内:运行期计算的值(量到的 gutter、进度百分比)可以进 `style`,组件局部自定义属性也可以承载布局值。[组件规则](../web-styling.zh.md#component-rules) 正家负责 token、CSS Module 与 class name 规则。 +- 例外:新增构建分支或新的内联形态在落地前于 review 中说明理由,由所属包的规则决定是否保留。 +- 修法:把样式切换移进用 `className` 切换的 CSS Module class,base64 交给构建链写进 CSS,并从 TSX 模块里删掉大文本常量。 + +组件切换 class name 与 data 属性,呈现由 CSS Module 负责: + +```tsx +import s from './card.module.css' + +// Style variants are class names, not style-object branches. +export function Card({ active, tone, children }: Props) { + return ( +
+ {children} +
+ ) +} +``` + +大文本与内联二进制数据进了模块,`style` 对象还编码了主题无法覆盖的样式切换: + +```tsx +const HUGE = '...several KB of text...' // large text inline in the module + +// A variant switch and an inlined asset both sit in the style object. +
+``` + +包里带上了本该属于 CSS 与资源的文本和二进制数据,diff 里躺着无法阅读的 blob,主题覆盖也再够不到那个颜色。 + +## 传 key 就要说明它标识什么 + +只有当 `key` 指明元素代表哪个实体或实例时才传它,并把这份身份说清楚——例如 `turnId` 在一个 session 内唯一。多数列表本就有稳定的业务 id,不需要额外的 key。为消除警告或编码渲染顺序而造的 key,声明的是一份数据并不具备的身份;数组下标从来不是这份身份,因为插入或删除会把后面每一项挪到另一个元素上。 + +- 判定方式:条目的身份能否由位置或稳定 id 表达。传 key 时,改动要说明它因何唯一,而可变列表上的 `key={index}` 不合格。 +- 不在范围内:React 要求列表项带 key 这条规则依然成立;那个 key 就是条目的稳定业务 id,不是它旁边的第二个 key。 +- 例外:无。普通改动无需批准,公共组件的 key 语义要在 review 中说明。 +- 修法:使用实体的稳定 id;两行确实共用一个 id 时,修 id 的来源,而不是往 key 里掺下标。 + +key 就是 turn 自己的 id,它在 session 内唯一,正是元素所代表的身份: + +```tsx +// turnId is unique inside a session; the id is the identity. +export function TurnList({ turns }: Props) { + return ( +
    + {turns.map((turn) => )} +
+ ) +} +``` + +下标冒充身份,于是列表一变,后面每一行的身份都跟着变: + +```tsx +// The index stands in for identity. +{items.map((item, index) => ( + +))} +``` + +插入或删除之后,后面每一行都会把先前的状态带到新数据上,展开的行或编辑中的内容会出现在错误的条目上。 + +## 每层共享代码各有自己的隔离度 + +功能把诉求吸收在自己的包里;它需要与共享代码保持多大隔离,取决于那段代码属于哪一层共享。要盯的违规形态是把业务专属概念放进共享层,因为此后每个使用方都得理解一个不属于自己的概念,而这个分支很难撤回。 + +| 共享代码 | 功能应保持的隔离度 | +|---|---| +| `ui-primitives`,目录中的控件 | 消费目录中的控件。新控件先在功能包内落地,只有出现第二个使用方时才提升进共享目录。 | +| `ui-layout` 与 shell 布局 | 消费它;在功能包内通过 wrapper、覆盖样式或加一层来适配。 | +| `ui-renderer` 及其他渲染机制 | 业务代码不产生值依赖;只经文档化的注册面扩展——slots、provide/inject 绑定的 hooks、声明的 store。 | +| 另一个功能插件 | 不运行时导入、也不重新导出它的值。UI 经 slots 跨越,行为经注入的服务跨越;共享运行时代码住在窄的静态正家,如 `client/store`、`ui-primitives` 或浏览器安全的工具包。 | +| 数据对象层(`client/connection`、`session-controller/client`、`client/store`) | 经文档化接口读取;功能自己的概念不进入这些对象及其 store。 | +| 功能自己的包 | 不受限——诉求在这里被吸收,包括它自己的行、排序与呈现。 | + +- 判定方式:diff 是否把业务专属的分支、字段或概念放进了功能自己包以外的任何一层。 +- 不在范围内:功能自己拥有的代码;以及确实属于通用需求、而不是某一个功能需要的共享层改动。 +- 例外:共享层的改动要带上所属领域专家的确认,并回归所有使用方;GUI 改动按 [packages/client/AGENTS.md](../../packages/client/AGENTS.md) 的最低检查自验。 +- 修法:把诉求吸收进功能包;确属通用需求时,在独立改动中连同 owner 的确认一起提升到共享层。 + +功能自己拥有行渲染与排序规则,基座组件按原样消费: + +```tsx +// The feature owns its rows; the base is consumed, not edited. +// packages/client/ui-workspace/src/client/rows/WorkspaceBrowser.tsx +export function WorkspaceBrowser({ rows, onArchive }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return ( +
    + {ordered.map((row) => )} +
+ ) +} +``` + +基座组件学会某一个功能的排序规则,于是每个使用方都继承了一个不属于自己的概念: + +```tsx +// ui-layout: the base learns one feature's ordering rule. +export function BrowserList({ rows, ...rest }: Props) { + const ordered = [...rows].sort((a, b) => Number(b.archived) - Number(a.archived)) + return
    {ordered.map((row) => )}
+} +``` + +`ui-layout` 的每个其他使用方从此都要理解只有那一个功能才有的归档概念,撤回该分支意味着把它们全部审一遍。 diff --git a/docs/defensive-patterns/conversation-and-session.i18n.yaml b/docs/defensive-patterns/conversation-and-session.i18n.yaml new file mode 100644 index 0000000000..acb90ee210 --- /dev/null +++ b/docs/defensive-patterns/conversation-and-session.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for conversation-and-session.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/defensive-patterns/conversation-and-session.md +/conversation-and-session-rules: + en: 499609ba1c6822d8 + zh: 7429eabcce7d7c14 +/conversation-and-session-rules/projection-is-the-only-read-and-compute-path: + en: 9fa9a332c93ba386 + zh: ce01ccb47dfa5df7 +/conversation-and-session-rules/cold-reads-are-the-last-resort: + en: 32991da738e47f7f + zh: b138910f8c16d103 +/conversation-and-session-rules/retention-follows-one-lifecycle-rule: + en: 580a3a11e97a6c49 + zh: d19fed1195d08ee6 +/conversation-and-session-rules/node-computation-is-incremental-and-streaming-publication-is-batched: + en: edce17b7d760152b + zh: 3f6caec6e6c27c30 +/conversation-and-session-rules/the-node-build-and-grouping-engine-carries-no-business-rule: + en: a588f4abbbc27166 + zh: 7601dd70d9845c59 +/conversation-and-session-rules/the-node-list-and-seat-components-carry-no-business-branch: + en: f69c4c16f472adcc + zh: 4570a62aa3d934fb +/conversation-and-session-rules/the-markdown-pipeline-carries-no-business-branch: + en: bc01d9cf17d3273c + zh: 0400c59c648ccfda +/conversation-and-session-rules/the-user-message-model-and-rendering-carry-no-business-field: + en: 8f97bbeaba14be0d + zh: cfad05711395cbd2 diff --git a/docs/defensive-patterns/conversation-and-session.md b/docs/defensive-patterns/conversation-and-session.md new file mode 100644 index 0000000000..bd040e462f --- /dev/null +++ b/docs/defensive-patterns/conversation-and-session.md @@ -0,0 +1,312 @@ +# Conversation and Session rules + +English | [中文](conversation-and-session.zh.md) + +Rules for reading a Session, holding one, computing conversation nodes, and rendering them. The data model and per-type semantics live in [session-projection.md](../subsystems/session-projection.md) and [conversation.md](../subsystems/conversation.md). + +## Projection is the only read and compute path + +Session data is read and computed through Projection. A client reads a projection value instead of pulling the Session log, and a computation that belongs to the Session runs as a registered projection unit that publishes its result instead of being recomputed on demand. Two answers to the same question — one pulled, one pushed — drift apart, so a render can show a value the Session log no longer supports. + +- Judged condition: every Session-derived value a client renders arrives through a projection read at the render position, and every new in-Session computation is registered as a unit whose result reaches clients as a published value. A component that fetches Session data itself, or a computation a reader triggers on demand, is the violation. +- State and View: a unit folds host-side State and declares the client-visible View over it, and the registration states that division. The `ProjectionDefinition` fields and the registry that drives them belong to [session-projection.md](../subsystems/session-projection.md#ctxsessionprojections--sessionprojectionregistry). +- Version: `stateVersion` starts at 1 and is bumped whenever the serialized state fields or the fold semantics change, compatible or not. Prefer a compatible change where one exists, but still bump; registering one key twice with different `stateVersion` values throws instead of merging. +- Compute strategy: units compute in full by default. Narrowing what a unit computes needs the owning domain expert's confirmation, never the implementer's own decision. +- Boundary: a partial projection view may serve interface availability for individual keys, such as a cached block drawn before the connected Session answers. It never decides an externally visible result, which waits for the standard projection value. + +A component that reads at its render position, and a computation that registers instead of being pulled, both comply: + +```tsx +// The client reads the published value; it never fetches Session data itself. +function PlanChip({ useProjection }: PlanChipProps) { + const plan = useProjection('plan') + return plan === undefined ? null : +} + +// The computation is a registered unit; the registry drives it and publishes changes. +const planDefinition: ProjectionDefinition<'plan'> = { + key: 'plan', + stateVersion: 1, + init: () => emptyPlan, + apply: (state, event) => foldPlan(state, event), + wire: { viewSchema: planSchema, view: planView }, +} +``` + +A component that pulls the same value over its own request breaks the single read path: + +```tsx +function PlanChip() { + const [plan, setPlan] = useState() + useEffect(() => { + void fetchSessionPlan(sessionId).then(setPlan) // a second read path beside Projection + }, [sessionId]) + return plan === undefined ? null : +} +``` + +The pulled copy and the pushed value disagree, and no version check can tell which one the Session currently holds. + +## Cold reads are the last resort + +Read an available cache before the original log, and reach for a cold read only when no projection covers the data. The "small Session may be read in full" exception is removed and is not reconsidered. When cached and official data are not equivalent, a missing or stale row produces an explicit outcome instead of silently switching onto the slow path. + +- Judged condition: a Session read consults the projection cache first, and an absent row leaves an explicit state for the caller; a cache test whose `else` branch opens the complete log is the violation. +- Fallback semantics: the caller decides what a miss means and states it in the returned value. There is no cache-size or Session-size exception, and no approver for one. +- Boundary: this restriction is the client's. An absolute "never fork a cold read" on the host is not required, because the host may need to open a log the client cannot. + +The stored projection rows are read first, and a miss stays a state the caller renders: + +```ts ignore-check +// The listing reads stored projection rows; a miss remains an explicit state. +type ListingView = + | { kind: 'cached'; snapshot: ProjectionSnapshot } + | { kind: 'unknown' } + +function readListing(header: SessionHeader, keys: readonly ProjectionKey[]): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header, keys) + return cached === undefined ? { kind: 'unknown' } : { kind: 'cached', snapshot: cached } +} +// Opening the complete log is a separate operation the caller names, never this fallback. +``` + +A cache test that falls through to the complete log turns the slow path into the ordinary one: + +```ts ignore-check +function readListing(header: SessionHeader, session: Session): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header) + if (cached !== undefined) return { kind: 'cached', snapshot: cached } + return coldReadCompleteLog(session) // every miss pays the full-log read +} +``` + +Every miss now reads the whole log in the foreground, so a slow Session is slow on every listing rather than only on the path that asks for it. + +## Retention follows one lifecycle rule + +A client holds a Session through an explicit reference (`SessionReference`), and the reference count reaching zero releases it. Idle reclamation follows the one lifecycle rule — no references and nothing in flight — and never enumerates which Sessions may be reclaimed from business state, because that list has to be maintained by every feature that adds one. An implicit holder is invisible, so reclamation cannot tell who still uses the Session. + +- Judged condition: the predicate is `refCount == 0 && inflight == 0`. Does the code hold the Session across its acquire → use window through a reference that retain and release can be audited against? A module-level Session object or a global current id is the violation. +- Current design, not a hard requirement: reference count zero releases the Session today, and that is the rule in force, but the exact release trigger is checked by hand and is not by itself a rejection reason. The enforced parts are the unified predicate and the absence of business-state enumeration. +- Backend status: Session references are not implemented on the backend yet; once they exist they use the same explicit references and lifecycle management. Code that assumes an implicit backend hold is premature. +- Evidence: the predicate is recorded as secondary evidence, so re-read the retention contract before citing it. Do not weaken the two parts it does establish — an explicit reference, and no business-state enumeration. +- Ownership: `retain`, `release`, `ready`, and teardown ordering belong to [the Session Controller's client references](../../packages/api/session-controller/README.md#client-references). A source-session mention carried in a message is a different type, owned by [session-reference.md](../subsystems/session-reference.md). + +A view that retains through an explicit reference and releases it on teardown complies: + +```ts ignore-check +class SidebarSessionView implements Disposable { + private readonly reference: SessionReference + + constructor(readonly id: SessionId, sessions: ISessions) { + this.reference = sessions.retain(id, { source: 'sidebarView' }) + void this.reference.ready.catch((error: unknown) => { console.error('opening failed:', error) }) + } + + [Symbol.dispose](): void { + this.reference.release() // the last reference releases the Session + } +} +``` + +Module state that keeps the Session object hides every holder from the reclaimer: + +```ts ignore-check +let currentSessionId: SessionId | undefined +const sessionCache = new Map() + +export function remember(session: Session): void { + currentSessionId = session.id + sessionCache.set(session.id, session) +} + +export function reclaimIdle(): void { + if (state === 'idle' || state === 'closed') reclaim() // a newly added state is missed +} +``` + +Nobody can count who still uses the Session, and the next state added to the Session escapes the enumeration and is never reclaimed. + +## Node computation is incremental and streaming publication is batched + +A new node computation states its complexity, and high-frequency streaming chunks never publish immediately and never recompute in full. A per-chunk full rebuild published at once puts the whole node collection on the frame budget, and the transcript stalls behind the stream. The append-path cost — with `D` registered Definitions, `D` matches and one constant-time Context-key lookup — and the publication vocabulary (`none`, `animation-frame`, `immediate`) are owned by [conversation.md](../subsystems/conversation.md#definition-and-typed-chat-payload). + +- Judged condition: how much one chunk computes — the increment on the affected subtree, not the event window — and when its result is published — a batching policy, not one publication per chunk. +- Development requirement, not a review rejection: the implementation must follow this rule; a reviewer does not reject a change for its cadence alone. +- Forbidden on the high-frequency path: `immediate` publication, and a full recomputation per chunk. +- Boundary: a structural or terminal change may publish `immediate`, because the cadence is chosen per publication. Only the high-frequency delta path is bound to batching. + +A chunk that updates one Context and asks for a coalesced publication complies: + +```ts ignore-check +const assistantDefinition: ConversationNodeDefinition = { + kind: 'assistant-step', + target: 'chat', + match: event => matchAssistant(event), + start: (_context, match) => initialState(match), + update: (context, match) => appendChunk(context.state, match.event), // increment, not the window + publication: () => 'animation-frame', // high-frequency deltas coalesce; never immediate + buildViewNode: context => assistantNode(context), +} +``` + +Rebuilding the whole node collection for every chunk and publishing it immediately: + +```ts ignore-check +function onChunk(chunk: AssistantLiveChunk): void { + const nodes = buildNodesFromCompleteWindow(session) // full recompute per chunk + target.publish(nodes, { publication: 'immediate' }) // and an immediate publish +} +``` + +Each chunk costs a full-window rebuild inside the frame budget, so grouping and rendering stall behind the stream. + +## The node build and grouping engine carries no business rule + +Business rules never enter the grouping engine, and a business requirement never reshapes the built payload. `ProcessState`, the group product hierarchy, and the set of group semantics in `conversation-nodes/process-groups.ts` are infrastructure: the engine understands enum placement values such as grouped, standalone, and reply, and the caller computes which one applies. A special case inside the engine changes the produced structure for every consumer and puts a business condition on the group computation path. + +- Judged condition: does the engine contain a business condition? A diff that adds a `ProcessState` field, adds or removes a group level, or changes group semantics for one business fails; the placement decision belongs to the caller that computes the enum value. +- Design status: the build and grouping design cannot be substantially reworked. The layering, its cost, and existing business expectations are the reason. +- Boundary: a new enum value carrying a new placement meaning is the supported extension, wherever the caller computes it. +- Exception and approver: none by default. A change to this infrastructure needs the corresponding domain expert's confirmation. [conversation.md](../subsystems/conversation.md#group-definitions) owns the group Definition types. + +The caller decides the business meaning and passes the placement enum the engine places by: + +```ts ignore-check +// Business judgment stays in the caller. +function placementOf(command: CommandView): NodePlacement { + return isHandoff(command) ? 'reply' : 'grouped' +} + +// The engine consumes the enum as data; it reads no business condition. +function groupEntries(commands: readonly CommandView[]): readonly NodePlacement[] { + return commands.map(placementOf) +} +``` + +A business condition inside the engine's own computation: + +```ts ignore-check +// The grouping engine asks what a node means, not where it goes. +function placeProcessNode(node: ChatConversationViewNode): GroupPlacement { + if (node.kind === 'command' && isRagMessage(node)) return 'rag' // business special case + return 'grouped' +} +``` + +The produced structure now carries one business's meaning, so every consumer and the group computation follow that feature. + +## The node list and seat components carry no business branch + +`ChatNodeList`, `ChatNodeSeat`, and `ChatGroupSeat` are infrastructure. They carry no business condition and no business-specific field, and a single business never changes the list traversal or the seat selection. A new node shape contributes its kind to `ChatNodeDataMap` and its renderer through the kind registration surface, so the list keeps dispatching on kind while business semantics stay in the business module. A branch added for one feature makes every node's rendering depend on that feature. + +- Judged condition: a business branch in a list or seat component, a business-only field on its props, or a traversal or seat-selection change that serves one business. +- Correct outlet: the business package merges its own key into `ChatNodeDataMap` and registers a renderer for the node kind; the seat renders the registered component for the node's kind. The registration discipline is owned by [slots.md](../subsystems/slots.md#extension-rules). +- Boundary: a rendering change that applies to every business — ordering, virtualization, accessibility — is not a business modification. +- Exception and approver: none by default; the corresponding domain expert confirms any exception. + +A business package that declares its kind and registers its renderer leaves the shared list untouched: + +```tsx +// The business declares its kind and registers its renderer; the shared list is untouched. +declare module '@deepseek-ai/dsh-client-ui-chat/client' { + interface ChatNodeDataMap { handoff: HandoffData } +} + +const HandoffNodeView = memo(function HandoffNodeView({ node, t }: ChatNodeOwnerProps<'handoff'>) { + return +}) + +ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( + { name: 'conversation.chat.node', key: 'handoff', locale: NS }, HandoffNodeView)) +``` + +A business branch and a business field inside the shared seat: + +```tsx +export const ChatNodeSeat = memo(function ChatNodeSeat({ node, handoffFlag }: ChatNodeSeatProps) { + if (node.kind === 'user' && handoffFlag) return // business dispatch + return
{renderByKind(node)}
+}) +``` + +One feature's condition now decides how every node renders, and the shared seat must change again for the next feature. + +## The Markdown pipeline carries no business branch + +`AssistantMarkdown` and its rendering pipeline are infrastructure: no business condition enters the Markdown render path, and no business rewrites the node mapping or the style injection rules. A presentation need registers a renderer on the existing chain or expresses itself in the data, and the official default content participates in that same registration surface rather than existing as an optional renderer with a host-side inline fallback. A pipeline that hosts business special cases can no longer be reviewed or optimized on its own. + +- Judged condition: a business branch inside `AssistantMarkdown` or its block mapping — for example `if (isXxxBusiness) renderXxx()` — or a style injection rule keyed on one business. +- Correct outlet: a renderer registered on the existing chain, or a semantic field in the data that the generic renderer reads. The Component Factory registration is owned by the [ui-renderer README](../../packages/client/ui-renderer/README.md). +- Wrapping: a wrapper that needs the standard rendering calls the official entry and keeps its fallback; it never re-renders the slot and never imports the private React component across packages. +- Responsibility: the host owns position and invocation; the plugin owns its own state, cleanup, and controls, and the official host carries no business action for a contribution. +- `labels`: an optional complete `MarkdownLabels` object is used whole, with no field-level merge against the default; omitting it uses the official default. `variant="compact"` is fixed by the Factory. +- Boundary: generic Markdown capability — syntax support, performance — is not a business modification. +- Exception and approver: none by default; the corresponding domain expert confirms any exception. + +A contribution that registers on the existing chain, and a host that keeps the official fallback: + +```tsx +// The business registers a renderer; AssistantMarkdown itself stays generic. +ctx.slots.inject('conversation.chat.reasoning-body', () => ctx.slots.register( + { name: 'conversation.chat.reasoning-body', locale: NS, select: owner => owner }, + ({ text, running }) => , +)) + +// The host invokes the chain at the position it owns and keeps the official fallback. +{renderReasoningBody('conversation.chat.reasoning-body', { text, running, setHeaderAction }, + { fallback: })} +``` + +A business branch inside the shared Markdown pipeline: + +```tsx +export const AssistantMarkdown = memo(function AssistantMarkdown({ blocks, ...props }: AssistantMarkdownProps) { + return <>{blocks.map(block => ( + isHandoffBlock(block) + ? // a business special case in the pipeline + : renderBlock(block, props) + ))} +}) +``` + +Every business special case lands in one shared pipeline, and Markdown rendering can no longer change or be measured without the businesses it now carries. + +## The user message model and rendering carry no business field + +`UserMessage` and the UI's `user` kind rendering are infrastructure: no business-only field on the message model, and no business branch in the user message renderer. A business difference travels in the message payload — its own merge-extensible source kind or a content field — or through a registered renderer. A field added for one business is handled by every consumer of the model, and the next business adds another branch to the same shared renderer. + +- Judged condition: a business-named field on `UserMessage`, or a business condition in the rendering of the `user` kind. +- Correct outlet: expression in the payload. `MessageSourceMap` is declaration-merge extensible, so a producer declares its own source kind instead of widening `UserMessage`; the message model is documented in [session.md](../subsystems/session.md). +- Boundary: a generic message capability — attachments, quotes, edit state — is not a business modification. +- Exception and approver: none by default; the corresponding domain expert confirms any exception. + +A producer that declares its own source kind keeps the business difference in the payload: + +```ts ignore-check +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + handoff: { kind: 'handoff'; sessionId: SessionId } + } +} + +const message = createUserMessage({ + role: 'user', + content: [{ type: 'text', text: prompt }], + source: { kind: 'handoff', sessionId: source.id }, +}) +``` + +A business field on the shared model, and the branch it forces into the shared renderer: + +```ts ignore-check +interface UserMessage extends MessageBase { + readonly role: 'user' + readonly handoffKind?: 'handoff' | 'rag' // one business's field on the shared model +} + +// ...and the renderer branches on it. +if (message.handoffKind === 'handoff') return +``` + +Every consumer of the message model handles one business's field, and the shared renderer grows a branch for each business that follows. diff --git a/docs/defensive-patterns/conversation-and-session.zh.md b/docs/defensive-patterns/conversation-and-session.zh.md new file mode 100644 index 0000000000..8df0fdff15 --- /dev/null +++ b/docs/defensive-patterns/conversation-and-session.zh.md @@ -0,0 +1,312 @@ +# 会话与 Session 规则 + +[English](conversation-and-session.md) | 中文 + +关于读取 Session、持有 Session、计算会话节点与渲染它们的规则。数据模型与各类型语义见 [session-projection.zh.md](../subsystems/session-projection.zh.md) 与 [conversation.zh.md](../subsystems/conversation.zh.md)。 + +## Projection 是唯一的读取与计算路径 + +Session 数据一律经 Projection 读取与计算。客户端读投影值,而不是拉 Session 日志;属于该会话的计算以注册单元的形式运行并**推送**结果,而不是按需重算。同一个问题若有两个答案——一个拉取、一个推送——两者就会分叉,渲染可能显示出 Session 日志已不再支持的值。 + +- 判定条件:客户端渲染的每个 Session 派生值都在渲染位置经投影读取取得,每个新增的会话内计算都注册为单元、其结果以已发布值的形式到达客户端。组件自己拉取 Session 数据、或读者按需触发一次计算,都属违规。 +- State 与 View:单元折叠 host 侧 State,并在其上声明客户端可见的 View,二者分工写在注册里。`ProjectionDefinition` 的字段与驱动它们的注册表归 [session-projection.zh.md](../subsystems/session-projection.zh.md#ctxsessionprojections--sessionprojectionregistry)。 +- 版本:`stateVersion` 从 1 起,只要序列化 state 字段或折叠语义变化就自增,兼容与否都一样。存在兼容改法时优先兼容,但版本仍要自增;同一 key 以不同 `stateVersion` 注册两次会抛错,而不是合并。 +- 计算策略:单元默认全量计算。收窄某个单元的计算范围需要对应领域专家确认,绝不能由实现者自行决定。 +- 边界:非完全 projection 渲染可用于某些 key 的界面可用性展示,例如在连接中的 Session 应答之前先画缓存块。它绝不参与对外可见结果的判定,那些结果等标准 projection 值。 + +在渲染位置读取、并以注册代替拉取,两者都合规: + +```tsx +// The client reads the published value; it never fetches Session data itself. +function PlanChip({ useProjection }: PlanChipProps) { + const plan = useProjection('plan') + return plan === undefined ? null : +} + +// The computation is a registered unit; the registry drives it and publishes changes. +const planDefinition: ProjectionDefinition<'plan'> = { + key: 'plan', + stateVersion: 1, + init: () => emptyPlan, + apply: (state, event) => foldPlan(state, event), + wire: { viewSchema: planSchema, view: planView }, +} +``` + +自行发请求拉取同一个值,就破坏了唯一读面: + +```tsx +function PlanChip() { + const [plan, setPlan] = useState() + useEffect(() => { + void fetchSessionPlan(sessionId).then(setPlan) // a second read path beside Projection + }, [sessionId]) + return plan === undefined ? null : +} +``` + +拉取到的副本与推送值互相矛盾,版本检查也无法说明 Session 当前持有的是哪一个。 + +## 冷读是最后手段 + +可用的缓存要先于原始日志被读取;只有没有任何投影覆盖该数据时才走冷读。「小会话可以全读」这一例外已移除、不再考虑。当缓存与正式数据不完全对等时,缺失或过期要产出显式结果,而不是静默改走重路径。 + +- 判定条件:Session 读取先查 projection 缓存,行缺失时为调用方留下显式状态;缓存判断的 `else` 分支直接打开完整日志,即属违规。 +- 回退语义:缺失意味着什么由调用方决定,并写进返回值。不存在按缓存大小或 Session 大小开出的例外,也没有对应的批准人。 +- 边界:这条限制是前端的。host 侧「禁止 fork 冷读」的绝对化表述不成立,因为 host 可能需要打开前端打不开的日志。 + +先读已存储的投影行,缺失仍是一个由调用方渲染的状态: + +```ts ignore-check +// The listing reads stored projection rows; a miss remains an explicit state. +type ListingView = + | { kind: 'cached'; snapshot: ProjectionSnapshot } + | { kind: 'unknown' } + +function readListing(header: SessionHeader, keys: readonly ProjectionKey[]): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header, keys) + return cached === undefined ? { kind: 'unknown' } : { kind: 'cached', snapshot: cached } +} +// Opening the complete log is a separate operation the caller names, never this fallback. +``` + +缓存判断落回完整日志,就等于把慢路径变成常规路径: + +```ts ignore-check +function readListing(header: SessionHeader, session: Session): ListingView { + const cached = ctx.sessionProjectionCache.cachedSnapshot(header) + if (cached !== undefined) return { kind: 'cached', snapshot: cached } + return coldReadCompleteLog(session) // every miss pays the full-log read +} +``` + +现在每次缺失都在前台读完整日志,于是慢会话在每次列表读取时都慢,而不只是在那条主动请求它的路径上慢。 + +## 持有与回收遵循同一条生命周期判据 + +客户端经显式引用(`SessionReference`)持有 Session,引用计数归零即释放。闲置回收只看那一条生命周期判据——零引用且无在途——绝不按业务状态枚举「哪些 Session 可以回收」,因为那份清单要靠每个新增状态的业务功能自己去维护。隐式持有者不可见,回收便判断不了谁还在使用该 Session。 + +- 判定条件:判据 = `refCount == 0 && inflight == 0`。代码是否在「获取 → 使用」的时间窗口内通过一份可审计 retain / release 的引用来持有 Session?模块级 Session 对象或全局 current id 都属违规。 +- 现行设计,非硬性要求:引用计数归零即释放 Session,这是当前生效的规则,但确切释放时机靠人工检查,本身不作为打回理由。被强制执行的是统一判据与「不按业务状态枚举」这两点。 +- 后端状态:后端 session reference 尚未实现;实现后一律走同样的显式 reference 与生命周期管理。假定后端存在隐式持有的代码为时过早。 +- 证据强度:该判据属次要证据,引用前须回读 retainer 契约。它确实确立的两点不得弱化——显式引用,以及不按业务状态枚举。 +- 归口:`retain`、`release`、`ready` 与 teardown 顺序归 [Session Controller 的 client references](../../packages/api/session-controller/README.zh.md#client-references)。消息里携带的 source session mention 是另一种类型,归 [session-reference.zh.md](../subsystems/session-reference.zh.md)。 + +经显式引用持有并在 teardown 释放的视图合规: + +```ts ignore-check +class SidebarSessionView implements Disposable { + private readonly reference: SessionReference + + constructor(readonly id: SessionId, sessions: ISessions) { + this.reference = sessions.retain(id, { source: 'sidebarView' }) + void this.reference.ready.catch((error: unknown) => { console.error('opening failed:', error) }) + } + + [Symbol.dispose](): void { + this.reference.release() // the last reference releases the Session + } +} +``` + +模块状态缓存 Session 对象,会把所有持有者对回收器隐藏: + +```ts ignore-check +let currentSessionId: SessionId | undefined +const sessionCache = new Map() + +export function remember(session: Session): void { + currentSessionId = session.id + sessionCache.set(session.id, session) +} + +export function reclaimIdle(): void { + if (state === 'idle' || state === 'closed') reclaim() // a newly added state is missed +} +``` + +没有人能数清谁仍在使用该 Session,下一个新增的 Session 状态也会漏出枚举、永远不被回收。 + +## 节点计算是增量的,流式发布是合批的 + +新增节点计算要说明其复杂度;高频流式 chunk 绝不立即发布、也不做全量计算。每个 chunk 全量重算并立即发布,等于把整个节点集合压进帧预算,转写区便会堵在流后面。追加速路径的开销——在 `D` 个已注册 Definition 下执行 `D` 次匹配与一次常量级 Context key 查找——以及发布节拍取值(`none`、`animation-frame`、`immediate`)归 [conversation.zh.md](../subsystems/conversation.zh.md#definition-and-typed-chat-payload)。 + +- 判定条件:单个 chunk 计算了多少——受影响子树的增量,而不是事件窗口——以及结果何时发布——合批策略,而不是每个 chunk 发布一次。 +- 属开发要求,不作 review 打回依据:实现必须遵守本条;评审不单凭节拍选择打回改动。 +- 高频路径上禁止:`immediate` 发布,以及每个 chunk 做一次全量重算。 +- 边界:结构性或终态变化可以 `immediate` 发布,因为节拍是按单次发布选择的。只有高频 delta 路径受合批约束。 + +只更新一个 Context 并请求合批发布的 chunk 合规: + +```ts ignore-check +const assistantDefinition: ConversationNodeDefinition = { + kind: 'assistant-step', + target: 'chat', + match: event => matchAssistant(event), + start: (_context, match) => initialState(match), + update: (context, match) => appendChunk(context.state, match.event), // increment, not the window + publication: () => 'animation-frame', // high-frequency deltas coalesce; never immediate + buildViewNode: context => assistantNode(context), +} +``` + +每个 chunk 重建整个节点集合并立即发布: + +```ts ignore-check +function onChunk(chunk: AssistantLiveChunk): void { + const nodes = buildNodesFromCompleteWindow(session) // full recompute per chunk + target.publish(nodes, { publication: 'immediate' }) // and an immediate publish +} +``` + +每个 chunk 都要在帧预算内做一次全窗口重建,于是分组与渲染都堵在流后面。 + +## 节点构建与分组引擎不承载业务规则 + +业务规则绝不进入分组引擎,业务诉求也绝不改变构建产物的形态。`ProcessState`、分组产物层级,以及 `conversation-nodes/process-groups.ts` 里的分组语义集合都属基础设施:引擎只认枚举化的落位语义(如成组 / 独立 / 回复),由调用方算出该用哪一个。引擎内的业务特判会改变所有使用方共享的产物结构,并把业务条件带上分组计算路径。 + +- 判定条件:引擎内部是否存在业务条件?新增 `ProcessState` 字段、增删分组产物层级、为某个业务改变分组语义,都属违规;落位判定归算出枚举值的调用方。 +- 设计状态:当前构建与分组设计不能大改。架构分层、其开销与既有业务预期就是原因。 +- 边界:携带新落位含义的新枚举值才是受支持的扩展,无论调用方在哪里算出它。 +- 例外与批准人:无默认例外。改动该基础设施须经对应领域专家确认。分组 Definition 类型归 [conversation.zh.md](../subsystems/conversation.zh.md#group-definitions)。 + +调用方决定业务含义,并把引擎据以落位的枚举值传进去: + +```ts ignore-check +// Business judgment stays in the caller. +function placementOf(command: CommandView): NodePlacement { + return isHandoff(command) ? 'reply' : 'grouped' +} + +// The engine consumes the enum as data; it reads no business condition. +function groupEntries(commands: readonly CommandView[]): readonly NodePlacement[] { + return commands.map(placementOf) +} +``` + +业务条件写进引擎自己的计算过程: + +```ts ignore-check +// The grouping engine asks what a node means, not where it goes. +function placeProcessNode(node: ChatConversationViewNode): GroupPlacement { + if (node.kind === 'command' && isRagMessage(node)) return 'rag' // business special case + return 'grouped' +} +``` + +产物从此承载某一个业务的含义,所有使用方与分组计算都要跟着该功能走。 + +## 节点列表与席位组件不承载业务分支 + +`ChatNodeList`、`ChatNodeSeat` 与 `ChatGroupSeat` 属基础设施。它们不承载业务判断,也不承载业务专用字段;单一业务绝不改变列表遍历或席位选择。新的节点形态把自己的 kind 贡献给 `ChatNodeDataMap`,并经 kind 注册面注册 renderer,于是列表继续按 kind 分发,业务语义留在业务模块内。为某个功能加的分支,会让每个节点的渲染都依赖该功能。 + +- 判定条件:在列表或席位组件里加业务分支、给其 props 加业务专用字段,或为单一业务改变列表遍历与席位选择。 +- 正确出路:业务包把自己的 key merge 进 `ChatNodeDataMap`,并为该节点 kind 注册 renderer;席位渲染该 kind 已注册的组件。注册纪律归 [slots.zh.md](../subsystems/slots.zh.md#extension-rules)。 +- 边界:对所有业务生效的渲染增强——排序、虚拟化、可访问性——不属于为业务诉求修改。 +- 例外与批准人:无默认例外;任何例外须经对应领域专家确认。 + +声明自己的 kind 并注册 renderer 的业务包,不改动共享列表: + +```tsx +// The business declares its kind and registers its renderer; the shared list is untouched. +declare module '@deepseek-ai/dsh-client-ui-chat/client' { + interface ChatNodeDataMap { handoff: HandoffData } +} + +const HandoffNodeView = memo(function HandoffNodeView({ node, t }: ChatNodeOwnerProps<'handoff'>) { + return +}) + +ctx.slots.inject('conversation.chat.node', () => ctx.slots.register( + { name: 'conversation.chat.node', key: 'handoff', locale: NS }, HandoffNodeView)) +``` + +把业务分支与业务字段写进共享席位: + +```tsx +export const ChatNodeSeat = memo(function ChatNodeSeat({ node, handoffFlag }: ChatNodeSeatProps) { + if (node.kind === 'user' && handoffFlag) return // business dispatch + return
{renderByKind(node)}
+}) +``` + +某个功能的条件从此决定每个节点怎么渲染,下一个功能还得再改一次共享席位。 + +## Markdown 管线不承载业务分支 + +`AssistantMarkdown` 及其渲染管线属基础设施:Markdown 渲染路径里不得出现业务条件,也不得按业务改写节点映射或样式注入规则。展示需求要么在既有链上注册 renderer,要么在数据里表达;官方默认内容也参与同一个注册面,而不是做成「可选 renderer + 宿主内联 fallback」。承载业务特判的管线,再也无法单独评审或单独优化。 + +- 判定条件:`AssistantMarkdown` 或其 block 映射里出现业务分支——例如 `if (isXxxBusiness) renderXxx()`——或按某个业务注入样式规则。 +- 正确出路:在既有链上注册 renderer,或在数据里带上语义字段、由通用 renderer 读取。Component Factory 的注册归 [ui-renderer README](../../packages/client/ui-renderer/README.zh.md)。 +- 包装展示:需要标准渲染的包装组件调用官方入口并保留其 fallback;绝不重复渲染 Slot,也绝不跨包导入官方私有 React 组件。 +- 权责边界:宿主只负责位置与调用;插件的状态、清理、控件归插件自己,官方宿主不为某个 contribution 承载业务动作。 +- `labels`:可选传入完整 `MarkdownLabels`,**传入即整体使用**、不与默认值做字段级合并;省略则用官方默认。`variant="compact"` 由 Factory 固定。 +- 边界:通用 Markdown 能力——语法支持、性能优化——不属于为业务诉求修改。 +- 例外与批准人:无默认例外;任何例外须经对应领域专家确认。 + +在既有链上注册的 contribution,与保留官方 fallback 的宿主: + +```tsx +// The business registers a renderer; AssistantMarkdown itself stays generic. +ctx.slots.inject('conversation.chat.reasoning-body', () => ctx.slots.register( + { name: 'conversation.chat.reasoning-body', locale: NS, select: owner => owner }, + ({ text, running }) => , +)) + +// The host invokes the chain at the position it owns and keeps the official fallback. +{renderReasoningBody('conversation.chat.reasoning-body', { text, running, setHeaderAction }, + { fallback: })} +``` + +业务分支写进共享 Markdown 管线: + +```tsx +export const AssistantMarkdown = memo(function AssistantMarkdown({ blocks, ...props }: AssistantMarkdownProps) { + return <>{blocks.map(block => ( + isHandoffBlock(block) + ? // a business special case in the pipeline + : renderBlock(block, props) + ))} +}) +``` + +每个业务特判都落进同一条共享管线,Markdown 渲染再也无法脱离它如今承载的这些业务去改动或度量。 + +## 用户消息模型与渲染不承载业务字段 + +`UserMessage` 与 UI 侧 `user` kind 渲染属基础设施:消息模型上不得有业务专用字段,用户消息渲染里不得有业务分支。业务差异经消息 payload 传递——自己可 merge 扩展的 source kind 或某个 content 字段——或经注册的 renderer 表达。为某个业务加的字段,所有消息模型使用方都要处理;下一个业务还会往同一个共享 renderer 里再加一条分支。 + +- 判定条件:`UserMessage` 上出现业务命名字段,或 `user` kind 的渲染里出现业务条件。 +- 正确出路:在 payload 里表达。`MessageSourceMap` 可经 declaration merging 扩展,因此生产者声明自己的 source kind,而不是加宽 `UserMessage`;消息模型见 [session.zh.md](../subsystems/session.zh.md)。 +- 边界:通用消息能力——附件、引用、编辑态——不属于为业务诉求修改。 +- 例外与批准人:无默认例外;任何例外须经对应领域专家确认。 + +声明自己的 source kind 的生产者,把业务差异留在 payload 里: + +```ts ignore-check +declare module '@deepseek-ai/dsh-llm' { + interface MessageSourceMap { + handoff: { kind: 'handoff'; sessionId: SessionId } + } +} + +const message = createUserMessage({ + role: 'user', + content: [{ type: 'text', text: prompt }], + source: { kind: 'handoff', sessionId: source.id }, +}) +``` + +共享模型上的业务字段,以及它逼进共享 renderer 的分支: + +```ts ignore-check +interface UserMessage extends MessageBase { + readonly role: 'user' + readonly handoffKind?: 'handoff' | 'rag' // one business's field on the shared model +} + +// ...and the renderer branches on it. +if (message.handoffKind === 'handoff') return +``` + +消息模型的每个使用方都要处理某一个业务的字段,共享 renderer 则随每个后续业务再长一条分支。 diff --git a/docs/defensive-patterns/general.i18n.yaml b/docs/defensive-patterns/general.i18n.yaml new file mode 100644 index 0000000000..371ec98879 --- /dev/null +++ b/docs/defensive-patterns/general.i18n.yaml @@ -0,0 +1,52 @@ +# Bilingual-pair consistency record for general.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/defensive-patterns/general.md +/defensive-patterns: + en: 324de84cf5239e89 + zh: b3bdfb17d01e5a6c +/defensive-patterns/report-orthogonal-outcomes-independently: + en: c16f636f8f522db4 + zh: 94c523b536df786d +/defensive-patterns/honor-public-contracts-on-both-sides: + en: 656746d485640b3a + zh: f75cd0333dc5bc9b +/defensive-patterns/async-state-is-not-synchronous-state: + en: f58b3f3fb047f434 + zh: daea224503617808 +/defensive-patterns/timing-does-not-carry-correctness: + en: 5778664b676a0079 + zh: e99aeabf0631f647 +/defensive-patterns/optional-inputs-state-both-behaviors: + en: 243e275fee74f54e + zh: a58e04b6e3ac0e7a +/defensive-patterns/one-value-states-one-fact: + en: a3b0f6585a381a1d + zh: 6fd57b2181e3009a +/defensive-patterns/a-new-active-current-singleton-is-refused: + en: 8bf36acf96fa4c33 + zh: bb6db31a63bcf383 +/defensive-patterns/shared-state-has-one-owner: + en: 053e2c485eec2613 + zh: 2817da00572c789f +/defensive-patterns/a-business-capability-owns-itself: + en: 7588b8dba9279dac + zh: 2760468ede60220c +/defensive-patterns/changes-carry-performance-evidence: + en: 8ec0e26abfb13e8f + zh: ad5cfda4ffe2ec9a +/defensive-patterns/migrations-preserve-behavior: + en: 6213e051f51437b8 + zh: 853580b3a4fec100 +/defensive-patterns/dispose-must-reach-quiescence-not-just-request-it: + en: eeb9fe3158484618 + zh: 97187d4dbe4d75ee +/defensive-patterns/contain-callback-exceptions-in-the-dispatcher: + en: ae2332afa54cb253 + zh: db51fedb070d9a83 +/defensive-patterns/never-hand-untrusted-output-the-ambient-environment-or-predictable-paths: + en: 6fb7938f5197f520 + zh: 01eb670a852f24e6 +/defensive-patterns/unlink-link-shaped-paths: + en: 35944dc084b41ded + zh: 0e59beebd9fb6d22 diff --git a/docs/defensive-patterns/general.md b/docs/defensive-patterns/general.md new file mode 100644 index 0000000000..ffc4271e6f --- /dev/null +++ b/docs/defensive-patterns/general.md @@ -0,0 +1,218 @@ +# Defensive patterns + +English | [中文](general.zh.md) + +Hard-won bug-class rules: each pattern below is a class of defect that actually shipped or nearly shipped here, stated as the rule that prevents its recurrence. Read this before writing lifecycle, concurrency, subprocess, or teardown code. Test-tier counterparts (real entry path, world-verification, resource ownership) are in [testing.md](../testing.md); the type-level definitions these rules refer to live in [subsystems/](../subsystems/README.md). + +## Report orthogonal outcomes independently + +A result can be several things at once — a process can time out AND exit 0 because it trapped the signal. Surface each independent fact (`timedOut`, `signal`, `exitCode`) on its own; never nest one flag's report inside another's branch, or a caller reads a cut-short run as a clean success. + +A reviewer checks the reporting shape rather than the killing mechanism: can each fact be true independently, and is each one readable without entering another condition's branch? The boundary is the report — how the process is signalled or how long it is given is a separate decision. + +## Honor public contracts on BOTH sides + +When an implementation receives several representations of one outcome, normalize them before returning through the public API. `LlmAdapter.stream()` implementations may throw or emit `finish {kind:'error'|'aborted'}`, but `LlmRuntime.stream()` exposes model-request failures only as terminal finish chunks; middleware and consumer defects remain thrown. This keeps consumers from guessing whether a caught exception came from the provider, a wrapper, chunk logging, or their own assembly. Document the normalized contract where the type is defined; exercise every source form through the real consumer. + +The judged condition is whether a consumer can name the source of a failure from the public API alone. Internal helpers stay free to throw: the requirement binds the boundary the consumer crosses, not every function behind it. + +## Async state is not synchronous state + +`agent.followup()` has no per-message completion or result; a background job's completion races turn boundaries; `reader.close()` fires for both EOF and disposal. Never treat `agent/status` or `whenIdle()` as the result of one follow-up: several queued follow-ups, steering, and injected work may share one `running` interval, while cancellation or disposal can discard unstarted items. An automation caller that truly owns a run must define its interval explicitly—for example, from its message's durable inbox receipt through the next whole-agent `idle`—and describe any selected output as interval-wide rather than causally attributed to that message. The guard cuts both ways: if the awaited transition can never occur, the wait hangs, so handle the "nothing to wait for" branch explicitly. + +The judged condition is whether an agent can observe a per-unit completion the API does not define. Where the interval genuinely belongs to the caller, it is the caller that states the interval and the output scope; a shared `running` flag is never that statement. + +## Timing does not carry correctness + +Correctness comes from explicit call points and explicit state, never from where a callback lands in the event loop. A `microtask`, `setTimeout`, or `queueMicrotask` that decides whether work is correct races the rest of the program: it holds under a light load and silently fails under a busy one or when batching changes. React code follows the same rule — an effect never supplies a "just after render" ordering that the design should have made explicit. + +The judged condition is whether correctness depends on "that callback already ran" instead of on a named call point or state machine. Two boundaries: a test's timeout budget waits for a failure and is not timing-dependent correctness, and a deliberate delay that only paces user-visible work is not this rule. There is no developer-side exception; a genuine need for a timing technique goes to the domain owner. + +```ts +// The order is written into the code: dispose the old store, then build its successor. +declare let store: { dispose(): void } +declare function createStore(scopeKey: string): { dispose(): void } +declare const scopeKey: string + +store.dispose() +store = createStore(scopeKey) +``` + +```ts ignore-check +queueMicrotask(() => { if (!ready) refresh() }) // assumes the microtask runs before the next frame +setTimeout(() => setMounted(true), 0) // waits for a render that was never sequenced +``` + +The wrong form fails intermittently: a dropped refresh or a state that never syncs, reproducing only under load. + +## Optional inputs state both behaviors + +An optional parameter states what the callee does when it is present and when it is absent, so a caller reads both behaviors from the contract instead of inferring one from a defensive operator. Accumulating `?.` is the signal: each one substitutes for a decision about whether the field should exist at all. + +The judged condition is whether `?.` replaces a determination that a field exists rather than handling a genuinely optional hop on a known value. The requirement binds the interface contract: both branches state their return value and their side effects, and the contract is where the caller reads them. There is no exception channel — a call site that cannot state both behaviors is a review blocker, not a style preference. + +```ts +// Both behaviors are in the contract: no options object means "unknown", not "skip". +interface ResolveInput { options?: readonly string[] } +type Resolution = { kind: 'unknown' } | { kind: 'value'; value: string } + +function resolve(input: ResolveInput): Resolution { + if (input.options === undefined) return { kind: 'unknown' } + return { kind: 'value', value: input.options.join(',') } +} +``` + +```ts ignore-check +const value = a?.b?.c?.d ?? fallback // four layers of fallback hide whether d should exist +``` + +The wrong form keeps the contract vague and swallows the error, so the next caller adds another fallback on top. + +## One value states one fact + +An unknown value, an empty collection or string, and a genuinely absent field are three different facts and take three representations. One `undefined` or `null` never stands for several of them, and a consumer that must act differently on each discriminates explicitly instead of collapsing them at the boundary. + +The judged condition is whether a single "no value" carries more than one semantic: not yet queried, queried and empty, and cannot be determined. A discriminated union or an explicit enum value is the ordinary implementation, documented where the type is defined in [core.md](../subsystems/core.md#repo-wide-type-patterns). One named exception: `catalog` membership reporting is a specific development requirement, not a general pattern to copy. + +```ts +type ValueState = { kind: 'unknown' } | { kind: 'empty' } | { kind: 'value'; value: T } +``` + +```ts ignore-check +return null // means "not queried", "queried, nothing there", and "cannot tell", all at once +``` + +The wrong form leaves the caller unable to distinguish the cases, so UI states, cache policy, and retry decisions all go wrong. + +## A new active/current singleton is refused + +No new global `active` or `current` singleton is introduced, and existing ones are migrated out. A globally unique selection is a design statement this codebase does not make: several views of one piece of data each hold their own reference or key. + +The judged condition is whether the change introduces a globally unique selected-state field. The replacement shape is one piece of data with several views over it, each view carrying its own reference. There is no default exception; where the concept genuinely exists once per service, a service or instance field expressed through `inject` carries it, never a module-level field. + +```ts ignore-check +// Each view holds the key it renders; nothing global decides what is "current". +function ConversationView({ sessionKey }: { sessionKey: SessionKey }) { /* … */ } +``` + +```ts ignore-check +let activeTabId: TabId | undefined // module-level; every component reads the same one +``` + +The wrong form makes independent instances interfere with each other, and no reviewer can audit which view owns the focus. + +## Shared state has one owner + +Shared state hangs on a service or an instance, so its owner is a named object with a lifecycle. A module-level cache, a singleton, a global `WeakMap`, or a `Symbol.for` / `globalThis` / `window.__X__` bypass hides that owner and outlives every teardown. + +The judged condition: name the service or instance that owns the value; if no owner can be named, the owner is decided before the implementation. The boundary is that a field on a service or instance may be read by any number of injected consumers, and passing that value across domains goes through the existing interface rather than a global namespace. There is no default exception; a genuine need for a global lookup key goes to the domain owner together with its reclamation policy. + +```ts +// The shared value hangs on the session service instance; consumers inject it. +interface Sessions { readonly current: string } +declare const ctx: { get(name: 'sessions'): Sessions } + +const sessions = ctx.get('sessions') // one owner, lifetime tied to the service +``` + +```ts ignore-check +globalThis.__dshCache = new Map() // shared across instances, reclaimed never +``` + +The wrong form lets instances overwrite each other, makes reclamation timing unknowable, and leaks state between tests. + +## A business capability owns itself + +A business capability lives in its own package and attaches through a registration surface — a registry, `slots.inject`, a waterfall, or an event subscription. A runtime, controller, manager, or gateway carries generic orchestration: it may hold the registry structure and the disposal lifecycle, while the entries are written by the packages that own them, and it never hardcodes a central table of business rows. + +The judged condition is whether the capability declares and registers itself, with the center layer only forwarding and managing lifetime rather than making business decisions. The boundary is that the center layer holds the registry structure and the disposal lifecycle while the entries come from the owning packages. One exception: pure infrastructure — logging, transport, storage — does not attach through a business registration surface. A new branch in a center layer must explain why it cannot live in the owning package. + +```ts +// The business package registers its own slot and handlers in its apply. +interface Slots { + inject(name: string, register: () => void): void + register(name: string): void +} +interface Context { readonly slots: Slots } + +export function apply(ctx: Context): void { + ctx.slots.inject('conversation.footer', () => ctx.slots.register('conversation.footer')) +} +``` + +```ts ignore-check +if (pluginName === 'ui-attachment') { /* business branch inside the manager */ } +``` + +The wrong form makes every new capability edit the center layer, which becomes the change bottleneck and the conflict hotspot. + +## Changes carry performance evidence + +A change that can move the cost of a hot path measures the code it touched before and after and reports the numbers with their conditions. The three metrics are runtime, peak memory, and steady-state memory, measured in one environment on one input; the granularity is the changed path, not a whole-machine score. Reporting that "nothing got slower overall" is not evidence, and a path that improved elsewhere does not excuse a regression here — an optimised first paint still has to answer for `append`. + +The baseline is the native implementation with no hook attached, not the previous implementation. Comparing old against new with the same hook attached on both sides dilutes the difference until it disappears: both sides pay the same overhead, so the measurement reports "no change" while both are slow. CI benchmark output is an alert, not a pass — a regression there is located by profiling segments locally to find which part slowed and which change introduced it. + +Boundaries: edits that touch no runtime path — comments, documentation, test-only code — need no measurement, and production performance code is not benchmark instrumentation to be deleted opportunistically (`performance.now()` and `scheduler.yield()` are part of production decode and encode chunk scheduling). An architectural change that genuinely costs performance states the measured cost and the reason, and the domain owner approves it; "the layering needed it" is not a self-service reason. Record the command, the numbers, the environment, and the input size so the baseline can be rebuilt. + +The judged condition: under one environment and one input, any of the three metrics is significantly worse on the changed path. + +```sh +# Before and after, same environment and input; the numbers go into the PR. +pnpm run bench --filter -- --scenario +``` + +```text +CI benchmark reported green, so the change is accepted as performance-neutral. +``` + +That form ships a real regression in a path the benchmark does not model. + +## Migrations preserve behavior + +A migration or a package split keeps externally observable behavior equal: error codes, diagnostics, data-flow order, and UI timing are compared item by item. Moving code is preferred over deleting and rewriting it; a rewrite suits code whose semantics are changing anyway, and then the change lists its differences. A package or export-path change is a carrier change rather than a behavior change, and a behavior change is its own change. + +The judged condition is the item-by-item comparison of observable behavior before and after. Where full equality is impossible, the change states the differing items and how each is verified, and the domain owner approves. A defect found during a migration is fixed as its own change rather than folded into the move. + +```sh +# The move keeps paths and error codes; the reference updates are the whole diff. +git mv packages/old/src/endpoint.ts packages/new/src/endpoint.ts +``` + +```ts ignore-check +// The migration silently upgrades the error handling it was only supposed to move. +throw new EndpointError('not found') // was: return { ok: false, code: 'not_found' } +``` + +The wrong form buries behavior changes inside a move, so review cannot separate the relocation from the semantics and regressions cannot be localized. + +## Dispose must reach quiescence, not just request it + +A teardown that issues kills/aborts but returns before the work stops leaves orphans. Make cleanup async and await the children's exit (kill → await `done`), and close listener/notification registries BEFORE killing so late completions stay silent. + +The judged condition is whether teardown awaits actual quiescence or only requests it. The boundary is work with no owner to await — a detached, unobserved task — which the teardown is not obliged to track; anything the component started and can still observe must be awaited before it reports completion. + +## Contain callback exceptions in the dispatcher + +Catch and report each listener's exception without rejecting the dispatch promise or starving later listeners. The listener's owner must handle state it mutates under the [error-handling rules](../../.agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop); catching alone does not restore state. + +The judged condition is whether a throwing listener can reject the dispatch promise or prevent later listeners from running. The boundary is the caller's own await: an error the dispatcher deliberately propagates to the operation that requested it is not a containment failure. + +```ts +async function dispatch(listeners: ((event: string) => Promise)[], event: string): Promise { + for (const listener of listeners) { + try { await listener(event) } catch (error) { console.warn('listener failed', error) } + } +} +``` + +## Never hand untrusted output the ambient environment or predictable paths + +Spawned commands get a scrubbed env (drop `*KEY*`/`*SECRET*`/`*TOKEN*`/`*PASSWORD*`) so harness credentials cannot leak into output, `env`, or spill files. Temp/spill files use a private (0700) dir, random names, and exclusive owner-only opens (`'wx'`, `0o600`) — predictable world-readable paths invite symlink races and disclosure. + +The judged condition is whether spawned processes inherit the ambient environment or write somewhere another process can predict and replace. The boundary is trusted, in-process code with no external input, which the rule does not govern. + +## Unlink link-shaped paths + +A path that may be a symlink or Windows junction is removed with `lstatSync().isSymbolicLink()` then `unlinkSync`: unlink deletes only the link and refuses a real directory, so it never follows the link into its target. Windows `rmSync(link)` throws `ERR_FS_EISDIR` on a junction; recursive deletion may descend through one into its target. Reserve recursive `rmSync` for known real directories. + +The judged condition is whether the removal primitive can follow a link into its target. The boundary is a path the code created itself in a directory it owns, where a plain recursive removal is already known to be safe. diff --git a/docs/defensive-patterns/general.zh.md b/docs/defensive-patterns/general.zh.md new file mode 100644 index 0000000000..46074f7c99 --- /dev/null +++ b/docs/defensive-patterns/general.zh.md @@ -0,0 +1,248 @@ +# 防御性模式 + +[English](general.md) | 中文 + +来之不易的缺陷类别规则:下面每条模式都是本项目实际发布或差点发布的一类缺陷,以防止其复发的规则形式陈述。在编写生命周期、并发、子进程或清理代码之前请先阅读本文。测试层面的对应规则(真实入口路径、验证实际结果、资源归属)见 [testing.zh.md](../testing.zh.md);这些规则引用的类型定义正家见 [subsystems/](../subsystems/README.zh.md)。 + + + +## 正交结果独立上报 + +一个结果可以同时具有多种性质:进程可能已经超时,却仍以退出码 0 结束,因为它捕获了终止信号。每个独立事实(`timedOut`、`signal`、`exitCode`)都应单独上报;切勿把一个标志的上报嵌套在另一个标志的分支中,否则调用方可能把提前终止的运行误判为正常成功。 + +评审看的是**上报形态**而不是终止机制:每个事实能否独立为真,以及能否不进入另一个条件分支就读到它?边界就是这个上报本身——如何发信号、给多长时间是另一个决定。 + + + +## 公共约定两侧都要遵守 + +当一个实现收到同一结果的多种表示时,应在通过公共 API 返回前将其规范化。`LlmAdapter.stream()` 的实现可以抛出异常或发出 `finish {kind:'error'|'aborted'}`,但 `LlmRuntime.stream()` 只会通过终止型 finish 分片暴露模型请求失败;middleware 缺陷与消费方缺陷仍会以异常形式抛出。这使消费方不必猜测捕获的异常究竟来自提供方、包装层、分片日志记录还是自身组装逻辑。请在类型定义处记录规范化后的约定;通过真实消费方覆盖每种来源形式。 + +判定条件是:消费方能否仅凭公共 API 说出故障的来源。内部 helper 仍可自由抛错:这条要求约束的是消费方跨越的那个边界,而不是它背后的每个函数。 + + + +## 异步状态不是同步状态 + +`agent.followup()` 没有逐消息的完成状态或结果;后台任务的完成与轮次边界存在竞争;`reader.close()` 在 EOF 和 dispose(资源释放)两种情况下都会触发。切勿把 `agent/status` 或 `whenIdle()` 当作某次 `followup()` 的结果:多条已排队的后续消息、steering(中途引导)和注入工作可能共用同一个 `running` 区间,而取消或资源释放可能丢弃尚未启动的项。真正拥有一次运行的自动化调用方必须显式定义其区间——例如从消息的持久 inbox 回执到整个 agent(智能体)下一次进入 `idle`——并将选取的任何输出描述为整个区间的输出,而不是把因果关系归于该消息。这条守则是双向的:如果等待的转换永远不会发生,等待就会挂起,因此应显式处理「无需等待」的分支。 + +判定条件是:调用方是否观察到一个 API 并未定义的逐单元完成态。区间确实属于调用方时,就由调用方声明区间与输出范围;共享的 `running` 标志永远不是这份声明。 + + + +## 时序不承载正确性 + +正确性来自显式调用点与显式状态,而不是回调落在事件循环的哪个位置。用 `microtask`、`setTimeout` 或 `queueMicrotask` 决定某项工作是否正确,是在与程序其余部分竞争:轻负载下成立,重负载或合批行为一变就静默失效。React 代码同理——effect 绝不提供那种本应由设计显式给出的「渲染之后」次序。 + +判定条件是:正确性是否依赖「那个回调已经跑过」,而不是具名调用点或状态机。两条边界:测试的 timeout 预算是在等失败,不属于靠时序保正确性;纯粹为可见工作 pacing 的延迟也不属本条。开发者一侧没有例外通道,确需时序技巧须经对应领域专家确认。 + +```ts +// The order is written into the code: dispose the old store, then build its successor. +declare let store: { dispose(): void } +declare function createStore(scopeKey: string): { dispose(): void } +declare const scopeKey: string + +store.dispose() +store = createStore(scopeKey) +``` + +```ts ignore-check +queueMicrotask(() => { if (!ready) refresh() }) // assumes the microtask runs before the next frame +setTimeout(() => setMounted(true), 0) // waits for a render that was never sequenced +``` + +反例的失效是间歇性的:偶发丢刷新,或状态永远没同步,只在压力大时复现。 + + + +## 可选输入要写明两种行为 + +可选参数要写明被调用方在**传入**与**不传入**两种情况下各自的行为,调用方从契约里读到两种行为,而不是靠防御性运算符去猜其中一种。堆积 `?.` 就是这个信号:每一个都在替代「这个字段到底应不应该存在」的判断。 + +判定条件是:`?.` 是否被用来替代「该字段存在」的判定,而不是在处理一个已知值上真正可选的一跳。这条要求约束接口契约:两个分支都要写明返回值与副作用,并由调用方从契约处读到。没有例外通道——无法说清两种行为的调用点属于评审打回项,不是风格偏好。 + +```ts +// Both behaviors are in the contract: no options object means "unknown", not "skip". +interface ResolveInput { options?: readonly string[] } +type Resolution = { kind: 'unknown' } | { kind: 'value'; value: string } + +function resolve(input: ResolveInput): Resolution { + if (input.options === undefined) return { kind: 'unknown' } + return { kind: 'value', value: input.options.join(',') } +} +``` + +```ts ignore-check +const value = a?.b?.c?.d ?? fallback // four layers of fallback hide whether d should exist +``` + +反例让契约持续含糊、错误被静默吞掉,于是下一个调用方又叠一层兜底。 + + + +## 一个值只表达一个事实 + +未知值、空集合或空字符串、以及字段真的不存在,是三件不同的事实,用三种不同的表示。一个 `undefined` 或 `null` 绝不代表其中多个;需要在三者上分别处理的消费方显式判别,而不是在边界处把它们压平。 + +判定条件是:同一个「无值」是否承载了多种语义——**未查询**、**查到为空**、**无法判定**。通常的实现是可辨识联合或显式枚举值,并在类型定义处记录(见 [core.zh.md](../subsystems/core.zh.md#repo-wide-type-patterns))。一条具名例外:`catalog` membership 的上报属特定开发要求,不作为可照搬的通则。 + +```ts +type ValueState = { kind: 'unknown' } | { kind: 'empty' } | { kind: 'value'; value: T } +``` + +```ts ignore-check +return null // means "not queried", "queried, nothing there", and "cannot tell", all at once +``` + +反例让调用方无法区分这些情况,UI 状态、缓存策略与重试判断都会跟着做错。 + + + +## 新增 active/current 单例一律禁止 + +不得新增全局的 `active` 或 `current` 单例,存量逐步迁出。全局唯一选中态是本仓库不做出的设计声明:同一份数据的多个视图各自持有自己的引用或键。 + +判定条件是:该改动是否引入了全局唯一的选中态字段。替代形态是**一份数据、多份视图**,每个视图带自己的引用。没有默认例外;确实每个服务只有一份的概念由服务或实例的字段承载并经 `inject` 取得,绝不落成模块级字段。 + +```ts ignore-check +// Each view holds the key it renders; nothing global decides what is "current". +function ConversationView({ sessionKey }: { sessionKey: SessionKey }) { /* … */ } +``` + +```ts ignore-check +let activeTabId: TabId | undefined // module-level; every component reads the same one +``` + +反例让彼此独立的实例互相串台,也没有人能审计焦点与状态归谁。 + + + +## 共享状态只有一个所有者 + +共享状态挂在服务或实例上,因此它的所有者是一个有生命周期的具名对象。模块级缓存、单例、全局 `WeakMap`,以及 `Symbol.for` / `globalThis` / `window.__X__` 旁路都会把这个所有者藏起来,并活得比任何一次清理都久。 + +判定条件:说出拥有该值的服务或实例;说不出所有者时,先定所有者再实现。边界是:服务或实例上的字段可以被任意多个注入方读取,跨域传递走既有接口而不是全局命名空间。没有默认例外;确需全局检索键时须经对应领域专家确认,并一并给出回收策略。 + +```ts +// The shared value hangs on the session service instance; consumers inject it. +interface Sessions { readonly current: string } +declare const ctx: { get(name: 'sessions'): Sessions } + +const sessions = ctx.get('sessions') // one owner, lifetime tied to the service +``` + +```ts ignore-check +globalThis.__dshCache = new Map() // shared across instances, reclaimed never +``` + +反例让实例之间互相覆盖、回收时机不可控,并让状态在测试之间泄漏。 + + + +## 业务能力自己拥有自己 + +业务能力住在自己的包里,经注册面接入——registry、`slots.inject`、waterfall 或事件订阅。runtime、controller、manager、gateway 承载通用编排:它可以持有注册表结构与 disposal 生命周期,但条目由拥有它们的包写入,且绝不硬编码一张业务中心表。 + +判定条件是:该能力是否由业务包自己声明并注册,中心层只做转发与生命周期管理、不做业务判定。边界是:中心层持有注册表结构与 disposal 生命周期,条目来自拥有它们的包。一条例外:纯基础设施能力——日志、传输、存储——不经业务注册面接入。中心层新增分支必须说明它为何无法下沉到业务包。 + +```ts +// The business package registers its own slot and handlers in its apply. +interface Slots { + inject(name: string, register: () => void): void + register(name: string): void +} +interface Context { readonly slots: Slots } + +export function apply(ctx: Context): void { + ctx.slots.inject('conversation.footer', () => ctx.slots.register('conversation.footer')) +} +``` + +```ts ignore-check +if (pluginName === 'ui-attachment') { /* business branch inside the manager */ } +``` + +反例让每个新能力都要改中心层,中心层随即成为变更瓶颈与冲突热点。 + + + +## 改动要附带性能证据 + +可能改变热点路径成本的改动,要测量它所触及的代码在改动前后的表现,并把数字与测量条件一并给出。三项指标是运行耗时、内存峰值与稳态内存,在同一环境、同一输入下测量;粒度是**被改动的那条路径**,不是整机跑分。只报「整体没变慢」不算证据,别处变快也不能抵消这里的倒退——优化了首屏,仍然要回答 `append` 是否倒退。 + +基线是**完全不挂 hook 的原生实现**,不是旧实现。新旧两侧挂着同一个 hook、共同开销把真实差值稀释掉,测量就会报告「没变化」,而实际上两边一起慢。CI benchmark 输出是报警而不是通过依据——CI 出现退化时,靠本地分段 profile 定位是哪一段变慢、哪次变更引入。 + +边界:不触碰运行路径的改动——注释、文档、仅测试代码——不需要测量;生产性能代码不是可以顺手删掉的 benchmark instrumentation(`performance.now()`、`scheduler.yield()` 属于生产 decode/encode 分片调度的一部分)。架构调整确实要付出性能代价时,写明实测代价与理由,并由对应领域专家确认;「分层需要」不是自助理由。命令、数字、环境与输入规模都要落账,以便返工时重建同一基线。 + +判定条件:同一环境、同一输入下,改动后那条路径的三项指标中任一项显著变差。 + +```sh +# Before and after, same environment and input; the numbers go into the PR. +pnpm run bench --filter -- --scenario +``` + +```text +CI benchmark reported green, so the change is accepted as performance-neutral. +``` + +这种写法会把 benchmark 未建模路径上的真实退化直接放行。 + + + +## 迁移保持行为 + +迁移或拆包保持对外可观测行为全等:错误码、诊断信息、数据流顺序与 UI 时机逐项比对。优先搬运代码而不是删了重写;重写适用于本来就要改语义的代码,且此时要在改动里列出差异。包或导出路径变化属于载体变化而非行为变化,行为变化则是独立的一刀。 + +判定条件是改动前后可观测行为的逐项比对。无法做到完全全等时,改动要写明差异项与各自的验收方式,并由对应领域专家确认。迁移过程中发现的缺陷按其自身另开一刀,不并入这次搬运。 + +```sh +# The move keeps paths and error codes; the reference updates are the whole diff. +git mv packages/old/src/endpoint.ts packages/new/src/endpoint.ts +``` + +```ts ignore-check +// The migration silently upgrades the error handling it was only supposed to move. +throw new EndpointError('not found') // was: return { ok: false, code: 'not_found' } +``` + +反例把行为变化埋进搬运里,评审无法把位置移动与语义变化分开,回归也就无法定位。 + + + +## dispose 必须达到完全停稳,而不仅仅是请求停止 + +如果清理流程只发出终止或中止信号便返回,而不等待工作真正停止,就会留下孤儿进程。清理逻辑应采用异步流程,并等待子进程退出(发出终止信号后等待 `done`);还应在终止进程前关闭监听器注册表和通知注册表,使迟到的完成事件保持静默。 + +判定条件是清理是否等待到真正停稳,而不只是发出请求。边界是没有可等待归属的工作——无人观察的游离任务——清理逻辑没有义务追踪它;但组件自己启动、且仍能观察到的工作,必须在它报告完成之前等待完毕。 + + + +## 在分发器中隔离回调异常 + +逐个捕获并报告监听器的异常,不让分发 promise 被 reject,也不让后续监听器失去执行机会。监听器的所有者必须按[错误处理规范](../../.agents/skills/dsh-error-handling/SKILL.md#catch-recover-or-stop)处置其修改的状态;仅捕获异常不会恢复状态。 + +判定条件是:抛异常的监听器是否能让分发 promise 被 reject,或让其后的监听器不再运行。边界是调用方自己的 await——分发器有意抛给发起该操作的那条路径的错误,不属于隔离失败。 + +```ts +async function dispatch(listeners: ((event: string) => Promise)[], event: string): Promise { + for (const listener of listeners) { + try { await listener(event) } catch (error) { console.warn('listener failed', error) } + } +} +``` + + + +## 绝不将环境变量或可预测路径暴露给不可信输出 + +启动的命令应使用经过清理的环境变量,移除名称匹配 `*KEY*`、`*SECRET*`、`*TOKEN*` 或 `*PASSWORD*` 的项,防止 harness 凭证通过命令输出、`env` 或 spill 文件泄漏。临时文件和 spill 文件应放在权限为 0700 的私有目录中,使用随机文件名,并以独占且仅所有者可访问的方式打开(`'wx'`、`0o600`);可预测且全局可读的路径会引发符号链接竞态和信息泄露。 + +判定条件是:启动的进程是否继承环境变量,或是否写入别人可以预测并替换的位置。边界是不接受外部输入的受信进程内代码,本条不约束它。 + + + +## 用 unlink 删除链接形态的路径 + +可能是符号链接或 Windows junction 的路径,应先用 `lstatSync().isSymbolicLink()` 判断,再用 `unlinkSync` 删除:unlink 只删除链接本身并拒绝真实目录,因此绝不会跟随链接进入其目标。Windows 上对 junction 调用 `rmSync(link)` 会抛 `ERR_FS_EISDIR`;递归删除可能穿过 junction 进入其目标。真实目录才使用带 `recursive` 的 `rmSync`。 + +判定条件是:所用的删除原语是否可能跟随链接进入其目标。边界是代码在自己拥有的目录里自行创建的路径,那里已知普通递归删除是安全的。 diff --git a/docs/defensive-patterns/package-surface.i18n.yaml b/docs/defensive-patterns/package-surface.i18n.yaml new file mode 100644 index 0000000000..024c8a7877 --- /dev/null +++ b/docs/defensive-patterns/package-surface.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for package-surface.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/defensive-patterns/package-surface.md +/package-surface-rules: + en: 28d4c2d7da24269f + zh: d723b807815401d7 +/package-surface-rules/a-plugin-package-exports-the-loader-four: + en: 34e91aa4d00d75b0 + zh: e1fc49160591fda2 +/package-surface-rules/two-package-shapes-and-both-are-dynamic-plugin-packages: + en: eb8289ca36b97f3b + zh: 3370e3bc05783dcd +/package-surface-rules/package-json-exports-uses-the-standard-key-set: + en: eb2734c4b6df6772 + zh: adb8d592e12d3030 +/package-surface-rules/dependency-declarations-and-version-consistency-are-enforced-by-the-dependency-scan: + en: e68bfcde70f845b4 + zh: 73e5c4fb067c4fa1 +/package-surface-rules/internal-dependency-syntax-follows-the-package-family: + en: d0cbaf0a92d4b601 + zh: 9e6c7239fd87e730 +/package-surface-rules/a-new-resolve-hook-is-refused-outright: + en: b420ae3e228432d5 + zh: 0c49c4a9c3a5262c diff --git a/docs/defensive-patterns/package-surface.md b/docs/defensive-patterns/package-surface.md new file mode 100644 index 0000000000..39b2f4b7fe --- /dev/null +++ b/docs/defensive-patterns/package-surface.md @@ -0,0 +1,224 @@ +# Package surface rules + +English | [中文](package-surface.zh.md) + +Rules for what a package exports, how it is built, and how it declares dependencies. [development.md](../development.md#typescript-project-layout) describes the layout itself; [packages/AGENTS.md](../../packages/AGENTS.md) carries the standing orders. + +## A plugin package exports the Loader four + +A plugin package's entry point exports `name`, `inject`, `Config`, and `apply`, and no other value; `name`, `inject`, and `apply` are lower-case, while `Config` is upper-case and appears both as an `interface` and as its Schemastery schema value. Cross-package references carry types only, so a new import of a value from another package is not allowed. A same-package test reaches internals directly through a relative `../src/...` path or the `./src/*` subpath, so a test-only need never becomes a permanent export. The rule stops a test convenience from freezing into published API and stops value references from spreading across package boundaries, where every later refactor has to follow them. + +- The Loader four and its exact form are defined in [cordis-primer.md](../cordis-primer.md#loader-configuration). +- Judged condition: the plugin entry (`src/index.ts`) exports an entity beyond the four; a cross-package import names a value instead of a type; a fixture reaches another package by relative path. +- Boundary: only Loader plugin entry points are constrained. Internal modules, helper functions, and hooks keep exporting values, and a test fixture stays inside its own package — a relative path into another package's `src` bypasses the `exports` map and the package-boundary checks. +- Exception: none by default; an exception that is genuinely needed requires the domain owner's confirmation. + +The compliant entry — the four exports, with the same-package test path recorded as a comment rather than as a fifth export. + +```ts +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' + +// The plugin entry: the Loader four, and no fifth value +export const name = 'web-app' +export const inject = ['webServer'] +export interface Config { /* … */ } +export const Config = z.object({ /* … */ }) +export function apply(ctx: Context, config: Config): void { /* … */ } + +// A same-package test imports '../src/internal/header.ts' instead of this entry +``` + +Three ways the entry gains an export it must not have; all three are visible in the diff. + +```ts ignore-check +// The entry widened so a test could reach one helper +export { isHeaderLine } from './internal/header.ts' + +// A value imported across packages +import { deriveEventMessage } from '@deepseek-ai/dsh-session' + +// A fixture reaching into another package by relative path +import { isSurfaceEligibleType } from '../../core/session/src/surface.ts' +``` + +## Two package shapes, and both are dynamic plugin packages + +A package is either a Host package or a Host + Client package, and both are dynamic plugin packages; a new package takes one of those two forms, with no third form and no exception. Only a genuine both-face package splits its compiler faces, build output goes to `lib`, and the `include`, `external`, and roster lists are derived by scanning the workspace rather than hand-written. A hand-written list or an invented compiler face makes build output and the manifest disagree, and every later package would have to maintain its own list. + +- Judged condition: a new package built as anything but a dynamic plugin package (static-link bundling, a hand-written all-external list); a third `tsconfig` variant; a hand-written `include`, `external`, or roster list. +- Census over `packages/*/*`: 330 packages carry a `tsconfig.json`, 24 are both-face (`tsconfig.json` plus `tsconfig.client.json` and `tsconfig.host.json`), 75 declare `dsh.client`, 87 export `./client`, and 330 point `main` at `lib/`. +- Boundary: a both-face package may appear in `include` or `exclude`. +- Exception: none; there is no approval path. A change to a package's shape or compiler faces starts with the owning documents and needs the domain owner's confirmation. +- Owners: [development.md](../development.md#typescript-project-layout) for the compiler faces, [packages/README.md](../../packages/README.md) for the package groups, and [adding-a-package.md](../cookbook/adding-a-package.md) for the steps. + +A package in one of the two shapes, with the standard manifest fields and no hand-written external list. + +```json +{ + "name": "@deepseek-ai/dsh-example", + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" } + } +} +``` + +A hand-written `external` list — and a `tsconfig.foo.json` invented beside it for one package — leaves the scans nothing to derive, so build output and manifest stop agreeing. + +```json +{ "name": "@deepseek-ai/dsh-example", "external": ["@deepseek-ai/*"] } +``` + +## `package.json` `exports` uses the standard key set + +A `package.json` `exports` map uses only the standard key set, in which every key already has one meaning across the repository, and a package never opens a key for its own local purpose. A key that only a handful of packages use without a documenting owner is not a precedent: formalizing a key, including one of the undocumented keys below, means changing the owning document and the check in the same change. The small shared key set is what lets a consumer infer a key's purpose from its name and lets a scan judge the export map at all. + +- Standard keys, with the number of packages using each across `packages/*/*/package.json` and `apps/*/package.json`: `.` (330, the package entry), `./package.json` (332, toolchain access, not a semantic export), `./src/*` (315, source passthrough for tests and tools, whose documented status is still open), `./client` (87, the browser entry, paired with the `dsh.client` declaration), `./types` (64, the type entry), `./typert` (28, the typert type runtime), `./remote` (28, the `@Remote` call surface), `./locale/*.json` (26, locale resources), `./cordis.patch.yml` (19, the bundle patch layer declared by `dsh.bundle`). +- Keys outside that set (`./brand` in 5 packages, `./worker` in 4, `./startup`, `./runner`, and `./protocol` in 2 each, plus many one-off keys) have no documented meaning; they are pending review, not a pattern to copy. +- Judged condition: does a change add an export key outside the standard set? +- Exception: none by default; a new key changes the owning document and the check first, with the domain owner's confirmation. +- Recompute the distribution: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update(json.load(open(p)).get('exports',{}).keys()) for p in glob.glob('packages/*/*/package.json')+glob.glob('apps/*/package.json') if isinstance(json.load(open(p)).get('exports'),dict)]; print(c.most_common())" +``` + +The compliant map — three standard keys used with their repo-wide meanings, in a package that also declares its client entry. + +```json +{ + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./types": { "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" }, + "./src/*": "./src/*", + "./package.json": "./package.json" + } +} +``` + +Keys opened for one package's local purposes — here `./brand` and `./worker`, whose documented status is pending — turn the export map into a per-package convention that neither a consumer nor a scan can read. + +```json +{ + "exports": { + ".": "./lib/index.js", + "./brand": "./lib/brand.js", + "./worker": "./lib/worker.js" + } +} +``` + +## Dependency declarations and version consistency are enforced by the dependency scan + +Dependency declarations and version consistency are guaranteed mechanically by the dependency scan; this page repeats neither the `devDependencies` and `peerDependencies` field rules nor a package admission list of its own. When the scan fails, reproduce it locally and fix the manifest it names, because the scan and its policy file own the rules. Editing the scan or relaxing its policy so that a change can land is not a normal edit and needs the domain owner's confirmation. + +- Entry point: [verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts), run as `pnpm run verify-package-dependencies`, by `scripts/run-gates.ts` as the `package-dependencies` gate, and directly by `.github/workflows/release.yml`. +- Policy owner: [package-dependency-policy.ts](../../scripts/package-dependency-policy.ts) exports `PACKAGE_DEPENDENCY_POLICY`; the declaration sections, version forms, and exemptions are defined there, with package-level context in [packages/README.md](../../packages/README.md). +- Boundary: this page lists no packages, field rules, or thresholds; it points at the owning file instead. +- Find the wiring: `grep -rn "verify-package-dependencies" package.json .github/workflows scripts/run-gates.ts`. +- Exception: a change to the scan or to the policy requires the domain owner's confirmation and the reason recorded on the change. + +The repeatable procedure: reproduce, read the diagnostic, and fix the manifest it names. + +```sh +# 1. Reproduce what CI reports +pnpm run verify-package-dependencies + +# 2. The diagnostic names the manifest, the section, the dependency, and the expected range +# packages/example/package.json: dependencies.@deepseek-ai/dsh-base must use workspace:*, found workspace:~ + +# 3. The fix goes into the manifest, never into the policy file or the scan +# "dependencies": { "@deepseek-ai/dsh-base": "workspace:*" } + +# 4. Re-run the scan until every package matches the published policy +pnpm run verify-package-dependencies +``` + +Two ways to lose the mechanical guarantee: change the check instead of the manifest, or restate the rule here so that it drifts from its owner. + +```text +Relaxing PACKAGE_DEPENDENCY_POLICY, or dropping the scanned section that fails, to go green +Restating a required-devDependency package list or the field rules on this page instead of linking the policy file +``` + +## Internal dependency syntax follows the package family + +Internal dependency syntax follows the package family: `@deepseek-ai/dsh` and `@deepseek-ai/dsh-*` use `workspace:*`, every other internal package uses `workspace:~`, and `workspace:^` has retired. The same dependency name is written the same way in every workspace, and a mismatch is a hard scan failure rather than a warning a reviewer can waive. The uniform syntax keeps one resolution path and prevents duplicate instances of a dependency and the resolution differences that follow them. + +- Judged by `workspaceRange()` in [verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts): the `@deepseek-ai/dsh` and `@deepseek-ai/dsh-*` families get `workspace:*`, every other internal package gets `workspace:~`; the scan walks the managed manifests and compares every declaration of the same dependency name. +- Boundary: a same-namespace package that is not a workspace member declares an ordinary third-party range and is outside the family rule — `@deepseek-ai/libreoffice-kit` is declared `^0.1.5` in `apps/desktop-host/package.json` (dependencies), `packages/bundle/web-app/package.json` (devDependencies), `packages/document/office-to-pdf/package.json` (dependencies), and `packages/skill/skill-office/package.json` (dependencies). +- Distribution (the command below prints the current numbers): `workspace:*` 4216, `workspace:~` 1034, `workspace:^` 0, plus the four `^0.1.5` declarations above. +- Exception: the scan decides mechanically; a genuine exception means changing the scan and the policy file with the domain owner's confirmation and the reason on the change. +- Recompute: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update([r]) for p in glob.glob('apps/*/package.json')+glob.glob('packages/*/*/package.json')+glob.glob('vendor/*/package.json') for s in ('dependencies','devDependencies','optionalDependencies','peerDependencies') for n,r in (json.load(open(p)).get(s) or {}).items() if n.startswith('@deepseek-ai/')]; print(c.most_common())" +``` + +Each family in its form, with the non-member exception left as an ordinary version range. + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:*", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/libreoffice-kit": "^0.1.5" + }, + "devDependencies": { + "@deepseek-ai/dsh-typert-registry": "workspace:*" + } +} +``` + +A `dsh-*` package on `workspace:~` and a workspace member pinned to an external range — each is a hard scan failure, and the retired rule of pinning exact versions is not available as an alternative. + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:~", + "@deepseek-ai/cordis": "^4.0.0" + } +} +``` + +## A new resolve hook is refused outright + +A new `resolve` hook is refused by default — a definite prohibition, not a preference to avoid one. A genuine need has two preconditions together: re-auditing the resolve strategy as a whole rather than patching the specifier that motivated the change, and the domain owner's confirmation before anything lands. An author's own judgment that this case is special is not a confirmation. + +- Judged condition: does the change add a `resolve` hook, including a wrapper around an existing hook that rewrites the same specifiers? +- Boundary: this rule decides whether a hook may be added at all; the separation of resolution, hot reload, and plugin management responsibilities is governed separately and does not permit a new hook. +- The one resolution path is the tsx ESM hook registered by the `dsh` source launch, whose rationale is in the [source-launch Agent Note](../../.agents/notes/implemented/architecture/2026-07-29-dsh-source-launch-tsx-esm.md). +- Exception: only the two preconditions above, both recorded on the change. + +The compliant path when new resolution behavior is genuinely needed, in order. + +```text +A new resolve hook is allowed only after both preconditions hold: + +1. Re-audit the resolve strategy as a whole — resolution, hot reload, and plugin + management responsibilities together, not only the specifier at hand. +2. Record the domain owner's confirmation on the change. +3. Only then add the hook, linking both records from the change. + +Until both hold, the answer is no; "this case is special" is the author's judgment, +not a confirmation. +``` + +A hook added so that one specifier lands where this package expects it, or the equivalent wrapper around the existing hook — the resolution path gains a branch, and what the resolver returns no longer matches `node_modules`. + +```ts ignore-check +// Added so one specifier resolves to the local source copy +export async function resolve(specifier: string, parentURL: string, importAttributes: object) { + if (specifier === '@deepseek-ai/dsh-example') return { url: localSourceUrl, shortCircuit: true } + return defaultResolve(specifier, parentURL, importAttributes) +} + +// The equivalent shape: wrapping the hook that already exists +const previous = hooks.resolve +hooks.resolve = (specifier, context, next) => + pinned.has(specifier) ? pinned.get(specifier) : previous(specifier, context, next) +``` diff --git a/docs/defensive-patterns/package-surface.zh.md b/docs/defensive-patterns/package-surface.zh.md new file mode 100644 index 0000000000..462e639f42 --- /dev/null +++ b/docs/defensive-patterns/package-surface.zh.md @@ -0,0 +1,224 @@ +# 包面规则 + +[English](package-surface.md) | 中文 + +关于包导出什么、怎么构建、如何声明依赖的规则。布局本身见 [development.zh.md](../development.zh.md#typescript-project-layout);常设条款见 [packages/AGENTS.md](../../packages/AGENTS.md)。 + +## 插件包导出 Loader 四件套 + +插件包的入口导出 `name`、`inject`、`Config`、`apply`,没有第五个值;`name`、`inject`、`apply` 全小写,`Config` 首字母大写,且同时以 `interface` 与 Schemastery schema 值两种形态出现。跨包引用只携带类型,因此不允许从其他包新增实体值的 import。同包测试通过相对 `../src/...` 路径或 `./src/*` 子路径直接触达内部,测试专用的需要因此永远不会变成常驻导出。这条规则既阻止测试便利被固化成对外 API,也阻止实体值引用跨包扩散——后者会让此后每一次重构都必须跟着它们走。 + +- Loader 四件套及其准确形态见 [cordis-primer.zh.md](../cordis-primer.zh.md#loader-configuration)。 +- 判定条件:插件入口(`src/index.ts`)导出了四件套以外的实体;跨包 import 引用的是实体值而不是类型;fixture 用相对路径引用其他包。 +- 边界:只约束 Loader 插件入口。内部模块、工具函数与 hooks 照常导出值;测试 fixture 也留在本包内——用相对路径伸进别的包的 `src` 会绕过 `exports` 映射与包边界检查。 +- 例外:无默认例外;确需破例须经对应领域专家确认。 + +合规的入口——四件套,同包测试路径以注释记录,而不是加出第五个导出。 + +```ts +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' + +// The plugin entry: the Loader four, and no fifth value +export const name = 'web-app' +export const inject = ['webServer'] +export interface Config { /* … */ } +export const Config = z.object({ /* … */ }) +export function apply(ctx: Context, config: Config): void { /* … */ } + +// A same-package test imports '../src/internal/header.ts' instead of this entry +``` + +三种写法都会让入口多出不该有的导出;三种都能在 diff 里看到。 + +```ts ignore-check +// The entry widened so a test could reach one helper +export { isHeaderLine } from './internal/header.ts' + +// A value imported across packages +import { deriveEventMessage } from '@deepseek-ai/dsh-session' + +// A fixture reaching into another package by relative path +import { isSurfaceEligibleType } from '../../core/session/src/surface.ts' +``` + +## 包只有两类,且两类都是动态插件包 + +包要么是 Host 包,要么是 Host + Client 包,两类都是动态插件包;新增包只能取这两种形态之一,没有第三种形态,也没有例外。只有真正的双面包才拆编译面,生成物进 `lib`,`include`、`external` 与 roster 清单由扫描 workspace 得出,不手写。手写清单或新造编译面会让构建产物与清单不再一致,此后每个新增包都得各自维护清单。 + +- 判定条件:新增包未按动态插件包形态构建(static link 打包、手写的全 external 清单);出现第三种 `tsconfig` 变体;手写 `include`、`external` 或 roster 清单。 +- 对 `packages/*/*` 的实查:330 个包带 `tsconfig.json`,24 个是双面包(`tsconfig.json` 加 `tsconfig.client.json` 与 `tsconfig.host.json`),75 个声明 `dsh.client`,87 个导出 `./client`,330 个把 `main` 指向 `lib/`。 +- 边界:双面包允许被 `include` 或 `exclude`。 +- 例外:无;没有审批通道。包的形态或编译面变更须先改正家文档,并须经对应领域专家确认。 +- 正家:[development.zh.md](../development.zh.md#typescript-project-layout) 管编译面,[packages/README.zh.md](../../packages/README.zh.md) 管包分组,[adding-a-package.zh.md](../cookbook/adding-a-package.zh.md) 管步骤。 + +属于两类之一的包:使用标准清单字段,没有手写 external 清单。 + +```json +{ + "name": "@deepseek-ai/dsh-example", + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" } + } +} +``` + +手写的 `external` 清单——以及在它旁边为单个包新造的 `tsconfig.foo.json`——让扫描无从推导,构建产物与清单随之不再一致。 + +```json +{ "name": "@deepseek-ai/dsh-example", "external": ["@deepseek-ai/*"] } +``` + +## `package.json` `exports` 使用标准键集合 + +`package.json` 的 `exports` 只使用标准键集合,集合中每个键在全仓已经只有一个含义,包不得为自己的局部用途开键。只有少数几个包在用、又没有文档正家的键不构成先例:把某个键正式化(包括下面那些未记录在案的键)意味着在同一次改动里改正家文档与检查。键集合小且共享,消费者才能从键名推断用途,扫描也才有可能判定导出映射。 + +- 标准键及各键在 `packages/*/*/package.json` 与 `apps/*/package.json` 中的包数:`.`(330,包主入口)、`./package.json`(332,工具链读取清单,非语义 export)、`./src/*`(315,测试与工具用的源码直出,其文档地位仍待定)、`./client`(87,浏览器入口,与 `dsh.client` 声明配对)、`./types`(64,类型入口)、`./typert`(28,typert 类型运行时)、`./remote`(28,`@Remote` 调用面)、`./locale/*.json`(26,多语言资源)、`./cordis.patch.yml`(19,`dsh.bundle` 声明的组合包 patch 层)。 +- 集合之外的键(`./brand` 5 个包、`./worker` 4 个、`./startup`、`./runner`、`./protocol` 各 2 个,另有大量一次性键)没有文档含义,属待核项,不是可照抄的先例。 +- 判定条件:改动是否新增了标准集合以外的 export 键? +- 例外:无默认例外;新增键须先改正家文档与检查,并取得对应领域专家确认。 +- 复算分布: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update(json.load(open(p)).get('exports',{}).keys()) for p in glob.glob('packages/*/*/package.json')+glob.glob('apps/*/package.json') if isinstance(json.load(open(p)).get('exports'),dict)]; print(c.most_common())" +``` + +合规的映射——三个标准键各按全仓含义使用,该包同时声明了 client 入口。 + +```json +{ + "exports": { + ".": { "types": "./lib/types/index.d.ts", "default": "./lib/index.js" }, + "./client": { "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./types": { "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" }, + "./src/*": "./src/*", + "./package.json": "./package.json" + } +} +``` + +为单个包的局部用途开的键——这里是文档地位待核的 `./brand` 与 `./worker`——让导出映射退化为各包自便的约定,消费者与扫描都读不懂。 + +```json +{ + "exports": { + ".": "./lib/index.js", + "./brand": "./lib/brand.js", + "./worker": "./lib/worker.js" + } +} +``` + +## 依赖声明与版本一致性由依赖扫描门禁保证 + +依赖声明与版本一致性由依赖扫描机械保证;本页既不复述 `devDependencies` 与 `peerDependencies` 的字段规则,也不另立包准入清单。扫描失败时,在本地复现并修正它指名的清单,因为规则的正家是扫描与其策略文件。为了让改动落地而修改扫描或放宽策略不属于常规改动,须经对应领域专家确认。 + +- 入口:[verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts),以 `pnpm run verify-package-dependencies` 运行,被 `scripts/run-gates.ts` 作为 `package-dependencies` 门禁调用,`.github/workflows/release.yml` 也直接运行它。 +- 策略正家:[package-dependency-policy.ts](../../scripts/package-dependency-policy.ts) 导出 `PACKAGE_DEPENDENCY_POLICY`;声明面、版本形态与豁免都在该文件定义,包级背景见 [packages/README.zh.md](../../packages/README.zh.md)。 +- 边界:本页不列包清单、字段规则或阈值,只指向正家文件。 +- 查接线:`grep -rn "verify-package-dependencies" package.json .github/workflows scripts/run-gates.ts`。 +- 例外:修改扫描或策略须经对应领域专家确认,并在改动上记录理由。 + +可重复的流程:复现、读诊断、修正它指名的清单。 + +```sh +# 1. Reproduce what CI reports +pnpm run verify-package-dependencies + +# 2. The diagnostic names the manifest, the section, the dependency, and the expected range +# packages/example/package.json: dependencies.@deepseek-ai/dsh-base must use workspace:*, found workspace:~ + +# 3. The fix goes into the manifest, never into the policy file or the scan +# "dependencies": { "@deepseek-ai/dsh-base": "workspace:*" } + +# 4. Re-run the scan until every package matches the published policy +pnpm run verify-package-dependencies +``` + +失去机械保证的两种做法:改检查而不改清单,或者把规则复述到本页、从此与正家漂移。 + +```text +Relaxing PACKAGE_DEPENDENCY_POLICY, or dropping the scanned section that fails, to go green +Restating a required-devDependency package list or the field rules on this page instead of linking the policy file +``` + +## 内部依赖写法按包族保证 + +内部依赖写法按包族决定:`@deepseek-ai/dsh` 与 `@deepseek-ai/dsh-*` 用 `workspace:*`,其余内部包用 `workspace:~`,`workspace:^` 已退出。同一个依赖名在所有 workspace 内写法一致,不一致是扫描硬失败,不是评审可以放行的警告。写法统一才能保持一条解析路径,避免同一个依赖出现重复实例以及随之而来的解析差异。 + +- 判定在 [verify-package-dependencies.ts](../../scripts/verify-package-dependencies.ts) 的 `workspaceRange()`:`@deepseek-ai/dsh` 与 `@deepseek-ai/dsh-*` 包族取 `workspace:*`,其余内部包取 `workspace:~`;扫描遍历受管清单,比对同一依赖名的每一处声明。 +- 边界:同命名空间但不是 workspace 成员的包按普通第三方版本范围声明,不受包族规则约束——`@deepseek-ai/libreoffice-kit` 在 `apps/desktop-host/package.json`(dependencies)、`packages/bundle/web-app/package.json`(devDependencies)、`packages/document/office-to-pdf/package.json`(dependencies)、`packages/skill/skill-office/package.json`(dependencies)中声明为 `^0.1.5`。 +- 分布(下面的命令打印当前数字):`workspace:*` 4216 处、`workspace:~` 1034 处、`workspace:^` 0 处,另有上面四处 `^0.1.5` 声明。 +- 例外:门禁机械判定;确需例外意味着修改扫描与策略文件,并须经对应领域专家确认、在改动上说明理由。 +- 复算: + +```sh +python3 -c "import json,glob,collections; c=collections.Counter(); [c.update([r]) for p in glob.glob('apps/*/package.json')+glob.glob('packages/*/*/package.json')+glob.glob('vendor/*/package.json') for s in ('dependencies','devDependencies','optionalDependencies','peerDependencies') for n,r in (json.load(open(p)).get(s) or {}).items() if n.startswith('@deepseek-ai/')]; print(c.most_common())" +``` + +每个包族各用其写法,非成员的例外保持普通版本范围。 + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:*", + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/libreoffice-kit": "^0.1.5" + }, + "devDependencies": { + "@deepseek-ai/dsh-typert-registry": "workspace:*" + } +} +``` + +`dsh-*` 包写成 `workspace:~`,以及把 workspace 成员钉到外部版本范围——两者都是扫描硬失败,已退出的「一律钉精确版本」旧口径不能作为替代写法。 + +```json +{ + "dependencies": { + "@deepseek-ai/dsh-base": "workspace:~", + "@deepseek-ai/cordis": "^4.0.0" + } +} +``` + +## 新增 resolve 钩子直接禁止 + +新增 `resolve` 钩子默认被拒——这是确定性禁止,不是「尽量不」。确有需要时,两个前置条件必须同时成立:整体重审 resolve 策略,而不是给触发本次改动的那个 specifier 打补丁;以及在任何内容落地之前取得对应领域专家的确认。开发者自行判断「这次特殊」不构成确认。 + +- 判定条件:改动是否新增 `resolve` 钩子,包括包装既有钩子、改写同一批 specifier 的等价写法? +- 边界:本条只管能否新增钩子;解析、热更新与插件管理三者的职责划分另行治理,并不因此允许新增钩子。 +- 唯一的解析路径是 `dsh` 源码启动注册的 tsx ESM 钩子,其理由见[源码启动 Agent Note](../../.agents/notes/implemented/architecture/2026-07-29-dsh-source-launch-tsx-esm.zh.md)。 +- 例外:只有上述两个前置条件,且都要记录在改动上。 + +确有新的解析需求时的合规路径,按顺序。 + +```text +A new resolve hook is allowed only after both preconditions hold: + +1. Re-audit the resolve strategy as a whole — resolution, hot reload, and plugin + management responsibilities together, not only the specifier at hand. +2. Record the domain owner's confirmation on the change. +3. Only then add the hook, linking both records from the change. + +Until both hold, the answer is no; "this case is special" is the author's judgment, +not a confirmation. +``` + +为了让某个 specifier 落到本包期望的位置而加的钩子,或包装既有钩子达到同样效果的等价写法——解析路径多出一个分支,resolver 的返回与 `node_modules` 实况不再对应。 + +```ts ignore-check +// Added so one specifier resolves to the local source copy +export async function resolve(specifier: string, parentURL: string, importAttributes: object) { + if (specifier === '@deepseek-ai/dsh-example') return { url: localSourceUrl, shortCircuit: true } + return defaultResolve(specifier, parentURL, importAttributes) +} + +// The equivalent shape: wrapping the hook that already exists +const previous = hooks.resolve +hooks.resolve = (specifier, context, next) => + pinned.has(specifier) ? pinned.get(specifier) : previous(specifier, context, next) +``` diff --git a/docs/defensive-patterns/remote-and-api.i18n.yaml b/docs/defensive-patterns/remote-and-api.i18n.yaml new file mode 100644 index 0000000000..d3147327c4 --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for remote-and-api.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/defensive-patterns/remote-and-api.md +/remote-and-api-rules: + en: 26fb6e92d16925b0 + zh: 72d13c0481fc61e9 +/remote-and-api-rules/a-new-remote-capability-gets-its-own-service: + en: 12b1bb62563bd0f8 + zh: 62465fbe91a4d2af +/remote-and-api-rules/remote-marks-capability-methods: + en: ad35b0223f7e3ea9 + zh: e04d59e75730758a +/remote-and-api-rules/packages-api-carries-generic-orchestration-only: + en: 12a964b9c04fccf9 + zh: cf804f8044535727 diff --git a/docs/defensive-patterns/remote-and-api.md b/docs/defensive-patterns/remote-and-api.md new file mode 100644 index 0000000000..31542468a8 --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.md @@ -0,0 +1,114 @@ +# Remote and API rules + +English | [中文](remote-and-api.zh.md) + +Rules for the `packages/api` layer and the remote methods it exposes. [api-gateway.md](../api-gateway.md) describes the call model itself. Each section below states the requirement, how a reviewer judges it, what it does not cover, which exception applies and who approves it, and a correct and a wrong example. + +## A new remote capability gets its own service + +A new remote business capability is a new service — its own package or its own object — and `@Remote` marks that service's concrete methods. Growing an existing large service one method at a time leaves one object answering for auth, Session, workspace, and event carriage at once, mixes per-domain activation policy with history pagination, and makes every later change to one capability touch all of them. Split by business boundary, not by caller count: a capability with a single caller today still gets its own service, and an endpoint that changes owners moves to its new owner instead of joining the object it is leaving. + +- Judged by: which object holds the new remote method. A method for a new business line added to a service that already owns another line is the defect; the fix is a service named for the new capability, with `@Remote` on its concrete methods. A migration is judged the same way — the moved method appears on its new owner, as `SubagentRuntime` does in `packages/subagent/subagent`, not on the object it left. +- Not covered: a service whose methods all serve one business boundary stays whole, and a new private helper of that capability belongs on it. Data that needs its own protocol does not become a Remote method on the new service either; session event streams, pagination, incremental reduce, projection, and entity substreams keep their separate registration model ([gateway boundaries](../api-gateway.md#boundaries)). +- Exception: none recorded; a single caller is not a reason to merge. Where the business boundary itself is contested, the domain owner (对应领域专家) settles it as an architecture question before the change lands. +- Fix: create the capability's own service object or package, put `@Remote` on its concrete methods, and let callers reach it through `ctx.remote.`. + +The subagent capability owns its own service, and every remote method is a concrete method of that service: + +```ts ignore-check +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' + +interface SubagentList { ids: string[] } +interface PromptRequest { text: string } +interface PromptResult { accepted: boolean } + +class SubagentRuntime extends TypertRemoteService { + @Remote list(): SubagentList { return { ids: [] } } + @Remote prompt(request: PromptRequest): PromptResult { + return { accepted: request.text !== '' } + } + @Remote interruptByParent(id: string): void { } +} +``` + +The wrong version adds the same capability to the object that already carries other domains: + +```text +class ApiProxy { + @Remote goalList(): GoalList // goal domain + @Remote subagentPrompt(request): ... // subagent domain +} +``` + +One object then answers for both domains, so a change to either capability's activation policy, pagination, or event handling lands in the same place, and neither capability can move without the other. + +## `@Remote` marks capability methods + +`@Remote` carries four disciplines that a reviewer checks separately: it marks the concrete method that performs a capability; client-facing types come from the existing definitions through the generator instead of a hand-written copy; the payload is JSON and the remote method performs no output-side decode; and existing method and field names are additive. Each discipline removes a different failure — a wrapper hides which operation is exposed, a second hand-written type set drifts from the generated one, an output-side decode adds a second result path beside the codec the Gateway already runs, and a rename breaks every caller in the same change. + +- **Capability methods.** The annotation goes on the concrete method that performs the operation (`list`, `prompt`, `interruptByParent`), never on a wrapper that forwards to the real implementation. Judged by the decorated method's body: a body that only delegates means the annotation is on the wrong method. +- **Types from inference.** Client-facing types are aliased from what the generator produces — `type SessionRemote = TypertClientRemote['session']` — instead of being written a second time. Judged by a hand-written declaration whose fields repeat a generated Client type; [typert.md](../subsystems/typert.md) owns the generated maps and their declaration merges. +- **JSON only, no output-side decode.** A Remote parameter and result are JSON, with binary content expressed field-level. `@Remote` performs no decode on the way out; the generated codec and the Gateway validate the result. Judged by a decode, a stream reassembly, or a whole non-JSON value on a method carrying the decorator; [programming model](../api-gateway.md#programming-model) owns what may cross a Remote method. +- **Existing names are additive.** A migration does not rename a remote method or field that a Client already calls; a new semantic gets a new entry, and a rename is its own change with its own review. Judged by a diff that renames or removes a name already exposed through `ctx.remote.`. +- **Not covered.** A method without the decorator stays an ordinary service method with in-process callers; the four disciplines govern what becomes a Remote method, not what a service may implement. +- **Exception.** A rename or a new decode path states its benefit and the impact on existing callers first and needs the domain owner's confirmation (对应领域专家); the author never self-approves. + +The generated map is the only source for Client-facing types, the decorator sits on the concrete method, and the payload stays JSON: + +```ts ignore-check +import { Remote, TypertRemoteService, type TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' + +// Client-facing types come from the generated map, never from a second hand-written set. +type SessionRemote = TypertClientRemote['session'] + +class SessionController extends TypertRemoteService { + @Remote('rename') + rename(id: string, title: string): SessionRenameValue { + return this.applyRename(id, title) + } +} +``` + +A hand-written second type set, a rename of a shipped name, and an output-side decode each break a different discipline: + +```text +type SessionRemote = { list(): ...; rename(id: string): ... } // hand-written copy +@Remote('renameSession') rename(...) // shipped name changed +@Remote decode(payload: Uint8Array): Result // output-side decode +``` + +The hand-written copy drifts from the generated type without failing a build, the rename breaks every existing Client call at once, and the decode replaces the generated codec with a second, unchecked result path. + +## `packages/api` carries generic orchestration only + +The packages under `packages/api` — the controllers, `gateway`, and `remotes` — carry transport, call shape, Session lifecycle, and other generic orchestration. A business branch never aggregates there: a decision that depends on concrete business state, handling bound to one feature, or a per-feature filter belongs in its own package or module and reaches this layer as projected data or through a registration surface. The criterion is where the logic belongs, not where the file sits, so a branch that only makes sense for one feature is a defect even when the file holding it is generic. + +- Judged by: where the branch reads its condition. An `if` or `switch` over feature state, a per-feature filter, or a helper named for one feature inside `packages/api` is the defect; the same decision taken in the owning package and consumed here as projected data or a registered entry is not. The package census shows the impact: `packages/api` holds nine packages — `account-controller`, `gateway`, `job-controller`, `remotes`, `session-controller`, `settings-controller`, `terminal-controller`, `workspace-controller`, `workspace-files` — and `session-controller` is the largest at 34 `src` files (terminal-controller 12, gateway 11, workspace-controller 10, workspace-files 8, job-controller 8, remotes 4, settings-controller 3, account-controller 2). +- Not covered: generic Session lifecycle, transport, and storage abstraction stay — `gateway` dispatch, `remotes` selection, and shared session-list and catalog reads are infrastructure, not business logic. [Business ownership](../api-gateway.md#business-ownership) states the same split from the Gateway side. +- Exception: none by default. Adding a business branch here needs an independent-package review, and that review answers why the logic cannot live in the package that owns the feature. +- Fix: move the decision into the owning package, publish its result as projected data or register it on a registry this layer already injects, and leave only the orchestration that reads it. + +The owning package decides and registers its unit, and the controller only reads the projected value: + +```ts ignore-check +// packages/workspace//src/index.ts: the rule lives with the feature it serves. +ctx.sessionProjections.register({ + key: 'durablePage', + stateSchema: durablePageState, + init: () => ({ durable: false }), + apply: applyDurablePage, + stateVersion: 1, +}) + +// packages/api/session-controller: generic orchestration reads the projected value. +const { durable } = ctx.sessionProjections.stateOf(session, 'durablePage') +``` + +The wrong version decides the rule inside the shared layer: + +```text +// packages/api/session-controller: a feature branch inside the shared layer +if (session.page.transport === 'durable') { /* durable-transport handling */ } +``` + +The rule then has a second home, and every later change to it has to find both while the shared layer keeps carrying one feature's semantics. diff --git a/docs/defensive-patterns/remote-and-api.zh.md b/docs/defensive-patterns/remote-and-api.zh.md new file mode 100644 index 0000000000..0808f5d48a --- /dev/null +++ b/docs/defensive-patterns/remote-and-api.zh.md @@ -0,0 +1,114 @@ +# 远程与 API 规则 + +[English](remote-and-api.md) | 中文 + +`packages/api` 层及其对外远程方法的规则。调用模型本身见 [api-gateway.zh.md](../api-gateway.zh.md)。以下每条规则都给出要求、审查者的判定方式、不覆盖的内容、例外与批准人,以及一个正例与一个反例。 + +## 新的远程能力要有自己的 service + +新的远程业务能力就是一个新的 service——独立包或独立对象——`@Remote` 标在它的具体方法上。往既有的大 service 上一个方法一个方法地加,会让同一个对象同时承担 auth、Session、workspace 与事件载体,把逐领域的激活策略与历史分页混在一起,并让之后对任一能力的变更都要动所有这些面。按业务边界切,而不是按调用方数量切:当前只有一个调用方的能力也建独立 service;端点迁移是搬到新归属,而不是并进它正要离开的那个对象。 + +- 判定:新远程方法最终落在哪个对象上。把属于新业务线的方法加到已经承担另一条业务线的 service 上即为违反;修法是为新能力建一个以它命名的 service,并把 `@Remote` 标在它的具体方法上。迁移按同一标准判定——被搬走的方法出现在新归属上(如 `packages/subagent/subagent` 的 `SubagentRuntime`),而不是留在它离开的那个对象上。 +- 不覆盖:所有方法都服务同一条业务边界的 service 保持完整,该能力新增的私有辅助方法就属于它。需要独立协议的数据也不会变成新 service 上的 Remote 方法;会话事件流、分页、增量 reduce、projection 与实体子流保持各自独立的注册模型([gateway 边界](../api-gateway.zh.md#boundaries))。 +- 例外:无。只有一个调用方不构成合并的理由;业务边界本身有争议时,由对应领域专家作为架构问题先行裁定,再落地。 +- 修法:为新能力建独立 service 对象或包,把 `@Remote` 标在它的具体方法上,调用方经 `ctx.remote.` 使用。 + +subagent 能力拥有自己的 service,它的每个远程方法都是该 service 的具体方法: + +```ts ignore-check +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' + +interface SubagentList { ids: string[] } +interface PromptRequest { text: string } +interface PromptResult { accepted: boolean } + +class SubagentRuntime extends TypertRemoteService { + @Remote list(): SubagentList { return { ids: [] } } + @Remote prompt(request: PromptRequest): PromptResult { + return { accepted: request.text !== '' } + } + @Remote interruptByParent(id: string): void { } +} +``` + +反例把同一能力加到已经在承担其他领域的对象上: + +```text +class ApiProxy { + @Remote goalList(): GoalList // goal domain + @Remote subagentPrompt(request): ... // subagent domain +} +``` + +于是一个对象同时为两个领域作答:任一能力的激活策略、分页或事件处理变更都落在同一处,两个能力也无法各自搬迁。 + +## `@Remote` 标在能力方法上 + +`@Remote` 有四项纪律,审查者分别核对:标注执行能力的具体方法;面向 Client 的类型经生成器来自既有定义,而不是手写第二份;载荷只承载 JSON,远程方法不做输出侧 decode;既有的方法与字段名只增不改。每项纪律消除一类不同的缺陷——壳方法藏起真正暴露的是哪个操作,手写的第二份类型会与生成结果漂移,输出侧 decode 在 Gateway 已有的 codec 之外再造一条结果路径,改名则让所有调用方在同一次变更里一起断掉。 + +- **标能力方法。** 标注落在执行该操作的具体方法上(`list`、`prompt`、`interruptByParent`),绝不落在转发给真正实现的壳方法上。判定看被标注方法的函数体:函数体只做转发,标注就标错了方法。 +- **类型靠推断。** 面向 Client 的类型从生成结果取别名——`type SessionRemote = TypertClientRemote['session']`——而不是重写一份。判定看是否出现字段与生成的 Client 类型重复的手写声明;生成映射及其声明合并的正家是 [typert.zh.md](../subsystems/typert.zh.md)。 +- **只 JSON、不做输出侧 decode。** Remote 的参数与结果都是 JSON,二进制在字段级表达。`@Remote` 不做输出侧 decode;结果由生成的 codec 与 Gateway 校验。判定看带该标注的方法上是否出现 decode、流重组或整体非 JSON 值;可跨越 Remote 方法的内容正家是 [编程模型](../api-gateway.zh.md#programming-model)。 +- **存量名只增不改。** 迁移不改 Client 已在调用的远程方法名或字段名;新语义新增条目,改名是独立的一刀、单独评审。判定看 diff 是否改名或删除了已经经 `ctx.remote.` 暴露的名字。 +- **不覆盖。** 不带该标注的方法仍是有进程内调用者的普通 service 方法;这四项纪律约束的是什么成为 Remote 方法,而不是 service 可以实现什么。 +- **例外。** 确需改名或新增 decode 路径,须先说明收益与对既有调用方的影响,并取得对应领域专家的确认;作者不得自行批准。 + +生成的映射是面向 Client 类型的唯一来源,标注落在具体方法上,载荷保持 JSON: + +```ts ignore-check +import { Remote, TypertRemoteService, type TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol' + +// Client-facing types come from the generated map, never from a second hand-written set. +type SessionRemote = TypertClientRemote['session'] + +class SessionController extends TypertRemoteService { + @Remote('rename') + rename(id: string, title: string): SessionRenameValue { + return this.applyRename(id, title) + } +} +``` + +手写第二份类型、改名已发布的名字、在远程方法上做输出侧 decode,各自破坏一项纪律: + +```text +type SessionRemote = { list(): ...; rename(id: string): ... } // hand-written copy +@Remote('renameSession') rename(...) // shipped name changed +@Remote decode(payload: Uint8Array): Result // output-side decode +``` + +手写的副本会与生成类型漂移而不会让构建失败,改名一次性打断所有既有 Client 调用,decode 则用第二条未经校验的结果路径替换生成的 codec。 + +## `packages/api` 只承载通用编排 + +`packages/api` 下的包——各 controller、`gateway`、`remotes`——承载传输、调用形态、Session 生命周期等通用编排。业务分支绝不在其中聚合:依赖具体业务状态的判断、与单个功能绑定的处理、逐功能的过滤,都归独立包或模块,并作为投影数据或经注册面接入本层。判据是逻辑的归属,而不是文件的位置,所以只对一个功能成立的业务分支即使放在通用文件里也是缺陷。 + +- 判定:分支的条件从哪里读取。在 `packages/api` 内对功能状态做 `if` 或 `switch`、写逐功能的过滤、或以某个功能命名的辅助方法,即为缺陷;同样的判断由归属包做出、在本层作为投影数据或注册条目消费,则不是。包普查是影响面的证据:`packages/api` 共 9 个包——`account-controller`、`gateway`、`job-controller`、`remotes`、`session-controller`、`settings-controller`、`terminal-controller`、`workspace-controller`、`workspace-files`——其中 `session-controller` 以 34 个 `src` 文件为最多(terminal-controller 12、gateway 11、workspace-controller 10、workspace-files 8、job-controller 8、remotes 4、settings-controller 3、account-controller 2)。 +- 不覆盖:通用 Session 生命周期、传输与存储抽象留下——`gateway` 的分发、`remotes` 的选择、共享的会话列表与目录读取属于基础设施,不是业务逻辑。[业务所有权](../api-gateway.zh.md#business-ownership)从 Gateway 一侧给出同一个划分。 +- 例外:默认无例外。在此新增业务分支须走独立包评审,评审要回答这些逻辑为什么不能住在拥有该功能的包里。 +- 修法:把判断移进归属包,将其结果作为投影数据发布、或注册到本层本就注入的注册表上,这里只留下读取它的编排。 + +归属包做出判断并注册自己的单元,controller 只读取投影值: + +```ts ignore-check +// packages/workspace//src/index.ts: the rule lives with the feature it serves. +ctx.sessionProjections.register({ + key: 'durablePage', + stateSchema: durablePageState, + init: () => ({ durable: false }), + apply: applyDurablePage, + stateVersion: 1, +}) + +// packages/api/session-controller: generic orchestration reads the projected value. +const { durable } = ctx.sessionProjections.stateOf(session, 'durablePage') +``` + +反例把这条规则的决定放进共享层: + +```text +// packages/api/session-controller: a feature branch inside the shared layer +if (session.page.transport === 'durable') { /* durable-transport handling */ } +``` + +这条规则于是有了第二个家,之后每次变更都要同时找到两处,而共享层继续承载某一个功能的语义。 diff --git a/docs/development.i18n.yaml b/docs/development.i18n.yaml index 2a08605a85..a2ad16d37b 100644 --- a/docs/development.i18n.yaml +++ b/docs/development.i18n.yaml @@ -22,7 +22,7 @@ zh: 29f166be6a5c04d9 /development-guide/contributor-reference/typescript-project-layout: en: e3327c5492a593cb - zh: d43a5edcb11523ae + zh: 9de38778c76a5f0d /development-guide/contributor-reference/environment-variables: en: dba2c72ee6ffa930 zh: b65c27fbb9129ec8 diff --git a/docs/development.zh.md b/docs/development.zh.md index 3154c4d988..4494917361 100644 --- a/docs/development.zh.md +++ b/docs/development.zh.md @@ -109,6 +109,8 @@ pnpm run build `pnpm run hygiene` 包含 `publint`(用构建出的 `lib/*.js` 文件校验包入口点)和 `verify-node-next-types`(用一个临时的 NodeNext 消费方校验构建出的声明文件)。新 worktree 在 `pnpm run build` 运行之前没有打包的 JS 和声明文件;普通提交和推送无需构建,除非所选检查会使用这些产物。 + + ### 环境变量 真实的 DeepSeek 适配器和需要密钥的 agent 演示从环境变量或仓库根目录一个被 gitignore 的 `.env` 文件读取凭证: diff --git a/docs/subsystems/conversation.i18n.yaml b/docs/subsystems/conversation.i18n.yaml index b8f7380bbf..d53eb92d3b 100644 --- a/docs/subsystems/conversation.i18n.yaml +++ b/docs/subsystems/conversation.i18n.yaml @@ -16,7 +16,7 @@ zh: 787ad4d04b79adaf /conversation-assembly/replayable-event-families: en: c216e2df128b8cb9 - zh: e61312f1f280332d + zh: c039cf84b0d86ad8 /conversation-assembly/definition-and-typed-chat-payload: en: 5f24557a050d1df0 zh: 47735627f802b6fa diff --git a/docs/subsystems/conversation.zh.md b/docs/subsystems/conversation.zh.md index 7115bb90b8..7678e2b78c 100644 --- a/docs/subsystems/conversation.zh.md +++ b/docs/subsystems/conversation.zh.md @@ -71,6 +71,8 @@ Group 存储在安装前校验完整提交结果:根 Group 引用与记录一 实时 Assistant delta 作为 Client-only `assistant/live-chunk` event 到达。重连 baseline 会把活跃的进程内紧凑 stream 展开为相同的瞬态 event,持久 `assistant/message` 与 `assistant/attempt` event 则嵌入完整紧凑 stream 供历史回放。瞬态 event 可以初始化 Context。每条工具 delta 和后续 `tool/call` 都可以按同一个 callId 匹配为 start,即使名称尚未到达;只有最早的 Match 调用 `start()`,后续 Match 调用 `update()`。准备态 Tool 节点只有在名称可用后才显示。历史分页不把已结束消息展开为实时 delta。消费 Assistant 输出的 Definition 通过同一组匹配和更新接口处理 live chunk 与持久 settlement,其他 Definition 直接返回 `null`,无需展开 stream。 + + ## Definition 与类型化 Chat payload 为了完整展示关联关系,下面把生产方声明和 Client 贡献写在同一个代码块里。实际的包族中,branded id 与 `SessionEventMap` 声明留在事件生产方,Definition、Chat data 合并与 renderer 留在 Client 插件。 diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index c4c106c066..94bed76054 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -25,7 +25,7 @@ zh: d0f66664ac85ae64 /core/tooldefinition: en: d926a9b80aada2e5 - zh: e34e6f43bdfd8920 + zh: 7e191ba5dab904df /core/repo-wide-type-patterns: en: 057db6d8bf356c0f zh: 1441b39e5142b0bf diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 582a817f1f..beb65f2c60 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -363,6 +363,8 @@ type SessionStartSource = 'startup' | 'resume' | 'clear' | 'compact' 其完整字段、`defineTool`/`ValueSchemaSpec`/`ParameterSchemaSpec` 类型化 schema DSL、`ToolExecution`/`ToolExecutionResult` waterfall 类型,以及工具展示 UI 类型都在 **[tools.md](tools.zh.md)** 中。 + + ## 全仓通用类型模式 两个模式在每个子系统中反复出现,只在此处记录一次。 diff --git a/docs/subsystems/ptc-runtime.i18n.yaml b/docs/subsystems/ptc-runtime.i18n.yaml index 4ad1978544..e4031e772d 100644 --- a/docs/subsystems/ptc-runtime.i18n.yaml +++ b/docs/subsystems/ptc-runtime.i18n.yaml @@ -12,8 +12,8 @@ en: 182147ddf388c600 zh: c0a7d77602c78bcd /ptc-runtime/captured-output-and-the-failure-taxonomy: - en: e5431173436c00c2 - zh: 4ba58e259bbadbc8 + en: 8eb1607888ab6efc + zh: 580c852d17b9413f /ptc-runtime/the-service: en: a82f828fa006c7e9 zh: 2279d36867335b57 diff --git a/docs/subsystems/ptc-runtime.md b/docs/subsystems/ptc-runtime.md index efab5bcefa..c0bf80b405 100644 --- a/docs/subsystems/ptc-runtime.md +++ b/docs/subsystems/ptc-runtime.md @@ -168,12 +168,12 @@ type PtcBindingFunction = (args: unknown) => Promise Logs are plain strings. Each source channel preserves emission order, while interleaving across independent channels is backend-dependent because channel metadata is not part of the seam. The runtime captures the program's console and stream output, and consumers render only the text. Implementations cap the serialized outer log-array plus completion-value or failure-message payload; fixed result-envelope syntax and consumer presentation whitespace are not part of that variable-payload ledger. Overflow is an explicit failure rather than in-band value substitution. -Failure kinds are **orthogonal outcomes reported independently** (per [defensive-patterns](../defensive-patterns.md)): a budget expiry is not an exception, an abort is not a timeout, and a substrate death (e.g. OOM) is neither: +Failure kinds are **orthogonal outcomes reported independently** (per [defensive-patterns](../defensive-patterns/general.md)): a budget expiry is not an exception, an abort is not a timeout, and a substrate death (e.g. OOM) is neither: ```ts type-equiv /** * Why a run failed. The kinds are orthogonal outcomes reported independently - * (per docs/defensive-patterns.md): a budget expiry is not an exception, an + * (per docs/defensive-patterns/general.md): a budget expiry is not an exception, an * abort is not a timeout, and a substrate death is neither. * * - `'exception'` — the program threw or failed to parse/transform. diff --git a/docs/subsystems/ptc-runtime.zh.md b/docs/subsystems/ptc-runtime.zh.md index f35c5bd84d..3896ffc61d 100644 --- a/docs/subsystems/ptc-runtime.zh.md +++ b/docs/subsystems/ptc-runtime.zh.md @@ -168,12 +168,12 @@ type PtcBindingFunction = (args: unknown) => Promise 日志是纯字符串。每个来源通道保留自身的发出顺序;由于通道元数据不属于 seam,相互独立的通道如何交错由后端决定。运行时捕获程序的 console 与流输出,Consumer 只渲染文本。实现会对序列化后的外层日志数组,以及完成值或失败消息的组合载荷设置上限;固定的结果封装语法与 Consumer 展示空白不计入这份可变载荷计量。超限会显式失败,而不会在值中插入替代内容。 -失败类型是**正交的结果,独立报告**(见 [defensive-patterns](../defensive-patterns.zh.md)):预算耗尽不是异常,中止不是超时,基底崩溃(如 OOM)也不是二者中的任何一个: +失败类型是**正交的结果,独立报告**(见 [defensive-patterns](../defensive-patterns/general.zh.md)):预算耗尽不是异常,中止不是超时,基底崩溃(如 OOM)也不是二者中的任何一个: ```ts type-equiv /** * Why a run failed. The kinds are orthogonal outcomes reported independently - * (per docs/defensive-patterns.md): a budget expiry is not an exception, an + * (per docs/defensive-patterns/general.md): a budget expiry is not an exception, an * abort is not a timeout, and a substrate death is neither. * * - `'exception'` — the program threw or failed to parse/transform. diff --git a/docs/subsystems/scope.i18n.yaml b/docs/subsystems/scope.i18n.yaml index bce762d85d..f5dd6f8a73 100644 --- a/docs/subsystems/scope.i18n.yaml +++ b/docs/subsystems/scope.i18n.yaml @@ -4,7 +4,7 @@ # pnpm run verify-translation-pairing --write docs/subsystems/scope.md /scoped-registration: en: b786b68190a93d3f - zh: 8ea0fb2fac9a1529 + zh: d487dc4263d61a53 /scoped-registration/identity-and-dispatch-carrier: en: f4e1bdd96c43a845 zh: c74409f7f81bd0e0 diff --git a/docs/subsystems/scope.zh.md b/docs/subsystems/scope.zh.md index db791a407f..c48858d6ba 100644 --- a/docs/subsystems/scope.zh.md +++ b/docs/subsystems/scope.zh.md @@ -6,6 +6,8 @@ 源码:[`packages/core/scope/src/index.ts`](../../packages/core/scope/src/index.ts) 与 [`packages/core/scope/src/store.ts`](../../packages/core/scope/src/store.ts)。 + + ## 身份标识与分发载体 `ScopeKey` 是一个不透明的对象身份标识。已交付的 agent loop(智能体循环)使用活跃的 `Agent` 对象作为自身的 key,但该原语从不检视该对象。 diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index aec206af8c..9aa254ff44 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -10,7 +10,7 @@ zh: 441ed13ff3f81d2a /web-client-slots/cardinality-and-scope: en: 5b0ada069239576b - zh: 7e71ced7f17d78a6 + zh: 84e1e6b253d1461e /web-client-slots/component-inputs: en: 9cb70abb2e39b958 zh: cd4b6f1705d90e17 @@ -22,7 +22,7 @@ zh: b961f792052b4ce5 /web-client-slots/current-hierarchy: en: 8a4cc4b8608ce0f6 - zh: 21281dcf047503b2 + zh: 7dcc51b213782a40 /web-client-slots/extension-rules: en: b2cce357141883ee zh: 278080a5fb941189 diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 3689583543..d51825c579 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -61,6 +61,8 @@ Slot 声明固定两个相互独立的维度。 对于 `single`、`list` 和 `keyed` cell,`priority` 是遮蔽优先级;对于 `chain`,它是选举顺序。数值越小越先运行或渲染。普通增量贡献应选用新的 list `id` 或 keyed `key`;复用已有 cell 表示有意替换其展示。 + + ## 组件输入 注册组件会在 binding 位置收到组装后的输入。组件应从这些类型推导 props,不要重新抄写成员。 @@ -195,6 +197,8 @@ root 生成的 Client inspect catalog 是每个 key 的完整参考,包含 cardinality、scope、owner props、标准 props、当前 occupant、声明 owner 与替换风险。运行中的动态包可以用 `cordis_inspect what:"client"` 查询实时树与某个精确 key;源码 catalog 由 `pnpm run gen-client-catalog` 根据 `SlotMap` 声明和 `slots.register()` 调用点生成。 + + ## 扩展规则 - 另一个功能包只能通过 `import type` 引入声明;绝不导入或转发它的运行时值。 diff --git a/packages/AGENTS.md b/packages/AGENTS.md index 8c071dac2e..50f203586c 100644 --- a/packages/AGENTS.md +++ b/packages/AGENTS.md @@ -10,6 +10,8 @@ These package-specific rules supplement the repo-wide [conventions](../AGENTS.md - **Design Service Definitions for all current Consumers.** Keep tool-schema, Loader, UI, transport, and provider-specific behavior in the Consumer or provider; do not let one Consumer dictate the service contract ([capability-seam rationale](../.agents/notes/implemented/architecture/2026-06-13-capability-seams.md)). Inverse smell: a public service method with one internal caller — pass a private capability closure instead (`RunCodeBridgeOptions`). - **Require a current owner and need.** Tie each abstraction, state machine, option, defensive copy, and compatibility path to a current contract or production consumer, and keep behavior in its owning plugin or service. - **Require evidence for public choices.** Configurability does not justify an unsupported default, public operation set, format, or imported external concept. Use current-consumer evidence or relevant prior art; otherwise require an explicit value or defer the choice. +- **Give shared state an owner.** Hang shared state on a service or instance. A module-level cache, a singleton, a global `WeakMap`, or a `Symbol.for` / `globalThis` / `window.__X__` bypass hides that owner; add no new global `current`, `active`, or `selection` singleton, and derive context from the current scope instead. +- **Keep business rules in their own package.** A runtime, controller, manager, gateway, or API dispatch layer carries generic orchestration; a business branch belongs to an independent package and attaches through a registration surface or projected data ([where new behavior goes](../docs/architecture.md#where-new-behavior-goes)). - **Write model-facing contracts from the model's perspective.** Prompts, tool schemas, results, and diagnostics contain only task-relevant concepts, not UI, transport, or implementation vocabulary. Pin stable model-visible text verbatim and dynamic behavior through snapshots or end-to-end coverage. - **Enforce a decision in the operation that makes it.** Schema omission, prompt filtering, facades, wrappers, and listener order are not enforcement when direct or alternate callers can bypass them; test denial through the executor. - **Publish state only at its commit point.** Emit each notification and update derived state only after the operation succeeds; derive caches, prompts, UI echoes, replay, and query views from one authoritative source. diff --git a/packages/client/AGENTS.md b/packages/client/AGENTS.md index c6f92acce6..ddaad3c866 100644 --- a/packages/client/AGENTS.md +++ b/packages/client/AGENTS.md @@ -16,6 +16,7 @@ The [Slots reference](../../docs/subsystems/slots.md) owns the current design; t 6. **Stores: read `props.useStore`, write `props.actions.*`** — the declared actions are the complete mutation API. Write the store as an exported `createXXXStore()` factory (module-level handles are forbidden — de-facto singletons); share by passing one handle to registrations inside `apply`. A Factory may instead receive the factory itself to create one handle per committed render position. Production code never calls the factory or `.create()` outside registration; tests do (that is the sanctioned zero-machinery path). 7. **inject returns plain data and callbacks** from the apply closure's own ctx — no hand-made hooks, no ReactNode producers, no whole-service objects. A registrant-private reactive fact uses the reserved `hooks` compartment (bare observables the renderer binds to `use`; components never see the sources). The plugin may use only the dependencies named by its `inject` declaration; there is no wider ctx to reach for. 8. **Factory local Components keep stable identities**: pass module-level function Components through `renderFactorySlot(..., { slots })`. Creating a Component function during render intentionally remounts that local subtree and resets its local state; the caller owns that behavior. +9. **A `key` states identity**: pass one when it names which entity or instance the element represents. A key that only silences a warning, or that encodes render order, misstates identity and makes a later remount or reuse decision wrong. ## Reactive read and contract-currency discipline @@ -27,6 +28,8 @@ How live data reaches render code, and what UI domains may share: 4. **UI domains share JSON-compatible data and callbacks.** Owner props, injected values, store state, and provide contributions use these values. Tool `args` may carry the [lazy argument reader](../../.agents/notes/implemented/architecture/2026-09-24-preparing-tool-arguments.md); its Definition republishes the block when an observed answer changes. Transient file-read and document-preview content may also carry `Uint8Array`: published buffers are borrowed read-only, copied before Worker transfer, and never persisted in layout or Session JSON. The injected `hooks` compartment is the only place for bare observables, and components never receive those sources directly. Route ReactNode content through a slot; do not add ReactNode-valued owner props or injected members (the composer's existing `accessory`/`overlay`/`leftItems`/`rightItems` fields remain until they move to slots). 5. **An observable source keeps two identities stable**: the source object itself (hook binding is cached per source), and its snapshot between changes (`getSnapshot` returns the same reference until the fact moves). 6. **Whoever rebuilds a published value republishes it through the same source in the same step**, and a registration path that can run after consumers exist notifies the live consumers as part of registering. +7. **Resource consumers go through `useResource`.** An element showing a resource reads it through the injected `useResource` hook, and a domain wrapper composes its own hook over it rather than reimplementing the fetch, cache, or polling below. Wrapping is free at the business layer as long as the bottom layer is not rebuilt ([client resources](../../docs/subsystems/client-resources.md)). +8. **Effects do not synchronize state.** `useLayoutEffect` is not a default and `useEffect` is not the fix: a layout measurement answers why it happens here, why CSS cannot express it, and why it must be pixel-based, then takes an injected measurement hook. An effect never pushes render-derivable data back to a parent through a props setter; decide it during render, give the host a render-time channel, or move it to the inject face. ## Export discipline (client plugin packages) diff --git a/packages/experimental/hooks-codex/src/index.ts b/packages/experimental/hooks-codex/src/index.ts index 8dc76fef58..139a99de6d 100644 --- a/packages/experimental/hooks-codex/src/index.ts +++ b/packages/experimental/hooks-codex/src/index.ts @@ -106,7 +106,7 @@ export function apply(ctx: Context, config: Config): void { // SessionStart is the one emit-shaped (detached) point Codex has: track its // run chains so disposal aborts a still-running hook process and drains the - // continuation (docs/defensive-patterns.md: dispose must reach quiescence). + // continuation (docs/defensive-patterns/general.md: dispose must reach quiescence). const detached = createDetachedRuns() ctx.effect(() => () => detached.drain(), 'hooks-codex: drain detached hook runs') diff --git a/packages/experimental/ptc-runtime-python/src/index.ts b/packages/experimental/ptc-runtime-python/src/index.ts index f8a3c15df9..2785958fe0 100644 --- a/packages/experimental/ptc-runtime-python/src/index.ts +++ b/packages/experimental/ptc-runtime-python/src/index.ts @@ -1124,7 +1124,7 @@ export class PythonPtcRuntime extends PtcRuntime { // child can dispatch. `namespace.functions` is caller-supplied, so it may // expose members through getters or a Proxy; reading one of them inside // the fd-3 `data` callback would throw OUTSIDE the dispatcher's try and - // terminate the host (defensive-patterns contain-callback-exceptions). + // terminate the host (docs/defensive-patterns/general.md contain-callback-exceptions). // Reading every member here, in run()'s synchronous validation segment, // turns that throw into the seam-misuse rejection run() reserves for // malformed bindings. The snapshot is also the single key set the boot diff --git a/packages/ptc-runtime/ptc-runtime/src/types.ts b/packages/ptc-runtime/ptc-runtime/src/types.ts index a6f061b2ea..b5309b26a5 100644 --- a/packages/ptc-runtime/ptc-runtime/src/types.ts +++ b/packages/ptc-runtime/ptc-runtime/src/types.ts @@ -117,7 +117,7 @@ export interface PtcRunSandbox { /** * Why a run failed. The kinds are orthogonal outcomes reported independently - * (per docs/defensive-patterns.md): a budget expiry is not an exception, an + * (per docs/defensive-patterns/general.md): a budget expiry is not an exception, an * abort is not a timeout, and a substrate death is neither. * * - `'exception'` — the program threw or failed to parse/transform. diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 2eba3f4c17..3e43fbe50a 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -1,10 +1,9 @@ { "AGENTS.md": 1960, - "docs/AGENTS.md": 1320, + "docs/AGENTS.md": 1430, "docs/architecture.md": 2410, "docs/cordis-primer.md": 600, - "docs/defensive-patterns.md": 550, "docs/testing.md": 1350, - "packages/AGENTS.md": 750, + "packages/AGENTS.md": 810, "packages/README.md": 994 }