@acryldev/plugin-context 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/LICENSE +21 -0
  2. package/docs/README.md +160 -0
  3. package/docs/delivery/local-live.md +113 -0
  4. package/docs/delivery/marketplace.md +16 -0
  5. package/docs/docs.json +2836 -0
  6. package/docs/extending/agent-preset.md +37 -0
  7. package/docs/extending/chat-command.md +28 -0
  8. package/docs/extending/client-slot.md +135 -0
  9. package/docs/extending/config-schema.md +7 -0
  10. package/docs/extending/cordis-core.md +63 -0
  11. package/docs/extending/desktop-app.md +53 -0
  12. package/docs/extending/desktop-main.md +25 -0
  13. package/docs/extending/event-hook.md +14 -0
  14. package/docs/extending/host-route.md +33 -0
  15. package/docs/extending/llm-adapter.md +38 -0
  16. package/docs/extending/packaging.md +53 -0
  17. package/docs/extending/prompt-contribution.md +9 -0
  18. package/docs/extending/service.md +13 -0
  19. package/docs/extending/skill-provider.md +9 -0
  20. package/docs/extending/state-and-persistence.md +71 -0
  21. package/docs/extending/three-role-capability.md +33 -0
  22. package/docs/extending/tool-plugin.md +24 -0
  23. package/docs/extending/tui-command.md +8 -0
  24. package/docs/extending/tui-components.md +61 -0
  25. package/docs/extending/ui-branding.md +43 -0
  26. package/docs/extending/ui-components.md +56 -0
  27. package/docs/extending/ui-customization.md +41 -0
  28. package/docs/extending/ui-library.md +66 -0
  29. package/docs/extending/ui-theme.md +55 -0
  30. package/docs/extending/workspace-tab.md +50 -0
  31. package/docs/maps/events.md +108 -0
  32. package/docs/maps/mount-points.md +154 -0
  33. package/docs/maps/slot-contracts.md +3376 -0
  34. package/docs/maps/taxonomy.md +306 -0
  35. package/docs/maps/theme-tokens.md +115 -0
  36. package/docs/maps/ui-components.md +26 -0
  37. package/docs/reference/cookbook/adding-a-package.md +174 -0
  38. package/docs/reference/cookbook/adding-a-remote-api.md +199 -0
  39. package/docs/reference/cookbook/adding-a-settings-card.md +74 -0
  40. package/docs/reference/cookbook/adding-a-tool.md +103 -0
  41. package/docs/reference/cookbook/adding-an-llm-adapter.md +45 -0
  42. package/docs/reference/cookbook/extension-cookbook.md +134 -0
  43. package/docs/reference/cordis-api/context.md +366 -0
  44. package/docs/reference/cordis-api/events.md +209 -0
  45. package/docs/reference/cordis-api/fiber.md +377 -0
  46. package/docs/reference/cordis-api/inherited.md +40 -0
  47. package/docs/reference/cordis-api/registry.md +154 -0
  48. package/docs/reference/cordis-api/service.md +104 -0
  49. package/docs/reference/cordis-guides/cordis-usage-cheatsheet.md +167 -0
  50. package/docs/reference/cordis-guides/cordis_system_guide_for_coding_agents.md +4666 -0
  51. package/docs/reference/cordis-guides/development-canvas-plugin.md +109 -0
  52. package/docs/reference/cordis-guides/hello-world-plugin-guide.md +517 -0
  53. package/docs/reference/harness/agent-lifecycle.md +93 -0
  54. package/docs/reference/harness/architecture.md +168 -0
  55. package/docs/reference/harness/capability-seams.md +675 -0
  56. package/docs/reference/harness/config-catalog.md +4523 -0
  57. package/docs/reference/harness/cordis-primer.md +47 -0
  58. package/docs/reference/harness/defensive-patterns.md +35 -0
  59. package/docs/reference/harness/event-producer-consumer.md +111 -0
  60. package/docs/reference/harness/glossary.md +47 -0
  61. package/docs/reference/harness/tool-catalog.md +2721 -0
  62. package/docs/reference/harness/tool-execution-pipeline.md +67 -0
  63. package/docs/reference/subsystems/README.md +75 -0
  64. package/docs/reference/subsystems/agent-team.md +233 -0
  65. package/docs/reference/subsystems/approval.md +172 -0
  66. package/docs/reference/subsystems/attachment.md +363 -0
  67. package/docs/reference/subsystems/boot.md +324 -0
  68. package/docs/reference/subsystems/browser-use.md +69 -0
  69. package/docs/reference/subsystems/client-modules.md +186 -0
  70. package/docs/reference/subsystems/client-resources.md +94 -0
  71. package/docs/reference/subsystems/commands.md +225 -0
  72. package/docs/reference/subsystems/compaction.md +286 -0
  73. package/docs/reference/subsystems/computer-use.md +58 -0
  74. package/docs/reference/subsystems/conversation.md +287 -0
  75. package/docs/reference/subsystems/core.md +1107 -0
  76. package/docs/reference/subsystems/credentials.md +497 -0
  77. package/docs/reference/subsystems/deliverables.md +180 -0
  78. package/docs/reference/subsystems/extensions.md +386 -0
  79. package/docs/reference/subsystems/feedback.md +402 -0
  80. package/docs/reference/subsystems/filesystem.md +532 -0
  81. package/docs/reference/subsystems/goal.md +315 -0
  82. package/docs/reference/subsystems/invariants.md +90 -0
  83. package/docs/reference/subsystems/jobs.md +501 -0
  84. package/docs/reference/subsystems/llm-streaming.md +1131 -0
  85. package/docs/reference/subsystems/lsp.md +204 -0
  86. package/docs/reference/subsystems/mcp.md +141 -0
  87. package/docs/reference/subsystems/office-to-pdf.md +89 -0
  88. package/docs/reference/subsystems/otel.md +46 -0
  89. package/docs/reference/subsystems/permission-presets.md +169 -0
  90. package/docs/reference/subsystems/persistence.md +418 -0
  91. package/docs/reference/subsystems/plan.md +89 -0
  92. package/docs/reference/subsystems/product-telemetry.md +81 -0
  93. package/docs/reference/subsystems/ptc-runtime.md +234 -0
  94. package/docs/reference/subsystems/sandbox.md +223 -0
  95. package/docs/reference/subsystems/schedule.md +545 -0
  96. package/docs/reference/subsystems/scope.md +61 -0
  97. package/docs/reference/subsystems/session-projection.md +358 -0
  98. package/docs/reference/subsystems/session-query.md +511 -0
  99. package/docs/reference/subsystems/session-reference.md +226 -0
  100. package/docs/reference/subsystems/session-telemetry.md +214 -0
  101. package/docs/reference/subsystems/session-title.md +206 -0
  102. package/docs/reference/subsystems/session.md +1300 -0
  103. package/docs/reference/subsystems/settings.md +157 -0
  104. package/docs/reference/subsystems/shell.md +316 -0
  105. package/docs/reference/subsystems/sidebar-right.md +160 -0
  106. package/docs/reference/subsystems/skills.md +354 -0
  107. package/docs/reference/subsystems/slots.md +201 -0
  108. package/docs/reference/subsystems/spill.md +126 -0
  109. package/docs/reference/subsystems/ssh.md +137 -0
  110. package/docs/reference/subsystems/storage.md +262 -0
  111. package/docs/reference/subsystems/subagent.md +762 -0
  112. package/docs/reference/subsystems/subprocess.md +323 -0
  113. package/docs/reference/subsystems/system-prompt.md +226 -0
  114. package/docs/reference/subsystems/terminal.md +186 -0
  115. package/docs/reference/subsystems/todo.md +34 -0
  116. package/docs/reference/subsystems/token-meter.md +108 -0
  117. package/docs/reference/subsystems/tools.md +749 -0
  118. package/docs/reference/subsystems/typert.md +489 -0
  119. package/docs/reference/subsystems/user-questions.md +309 -0
  120. package/docs/reference/subsystems/voice-input.md +166 -0
  121. package/docs/reference/subsystems/web-client.md +102 -0
  122. package/docs/reference/subsystems/web-server.md +228 -0
  123. package/docs/reference/subsystems/web.md +208 -0
  124. package/docs/reference/subsystems/webhook.md +72 -0
  125. package/docs/reference/subsystems/workflow.md +280 -0
  126. package/docs/reference/subsystems/workspace.md +661 -0
  127. package/docs/start-here/blueprints.md +33 -0
  128. package/docs/start-here/this-runtime.md +84 -0
  129. package/docs/start-here/troubleshooting.md +29 -0
  130. package/docs/start-here/trust-and-safety.md +39 -0
  131. package/docs/start-here/verify-before-done.md +46 -0
  132. package/example-plugins/README.md +45 -0
  133. package/example-plugins/packages/agent-preset-reviewer/agent.cordis.yml +18 -0
  134. package/example-plugins/packages/agent-preset-reviewer/preset.yml +3 -0
  135. package/example-plugins/packages/capability-swap-consumer/cordis.patch.yml +3 -0
  136. package/example-plugins/packages/capability-swap-consumer/index.js +14 -0
  137. package/example-plugins/packages/capability-swap-consumer/package.json +25 -0
  138. package/example-plugins/packages/capability-swap-provider-loud/cordis.patch.yml +3 -0
  139. package/example-plugins/packages/capability-swap-provider-loud/index.js +20 -0
  140. package/example-plugins/packages/capability-swap-provider-loud/package.json +25 -0
  141. package/example-plugins/packages/capability-swap-provider-quiet/cordis.patch.yml +3 -0
  142. package/example-plugins/packages/capability-swap-provider-quiet/index.js +20 -0
  143. package/example-plugins/packages/capability-swap-provider-quiet/package.json +25 -0
  144. package/example-plugins/packages/chat-command-basic/cordis.patch.yml +3 -0
  145. package/example-plugins/packages/chat-command-basic/index.js +26 -0
  146. package/example-plugins/packages/chat-command-basic/package.json +25 -0
  147. package/example-plugins/packages/client-chat-message-action/client.js +46 -0
  148. package/example-plugins/packages/client-chat-message-action/cordis.patch.yml +3 -0
  149. package/example-plugins/packages/client-chat-message-action/index.js +9 -0
  150. package/example-plugins/packages/client-chat-message-action/package.json +31 -0
  151. package/example-plugins/packages/client-slot-header-action/client.js +57 -0
  152. package/example-plugins/packages/client-slot-header-action/cordis.patch.yml +3 -0
  153. package/example-plugins/packages/client-slot-header-action/index.js +13 -0
  154. package/example-plugins/packages/client-slot-header-action/package.json +31 -0
  155. package/example-plugins/packages/client-slot-sidebar-tab/client.js +57 -0
  156. package/example-plugins/packages/client-slot-sidebar-tab/cordis.patch.yml +3 -0
  157. package/example-plugins/packages/client-slot-sidebar-tab/index.js +9 -0
  158. package/example-plugins/packages/client-slot-sidebar-tab/package.json +32 -0
  159. package/example-plugins/packages/client-theme-override/client.js +52 -0
  160. package/example-plugins/packages/client-theme-override/cordis.patch.yml +3 -0
  161. package/example-plugins/packages/client-theme-override/index.js +9 -0
  162. package/example-plugins/packages/client-theme-override/package.json +30 -0
  163. package/example-plugins/packages/client-tool-view/client.js +47 -0
  164. package/example-plugins/packages/client-tool-view/cordis.patch.yml +3 -0
  165. package/example-plugins/packages/client-tool-view/index.js +24 -0
  166. package/example-plugins/packages/client-tool-view/package.json +34 -0
  167. package/example-plugins/packages/client-ui-components/client.js +77 -0
  168. package/example-plugins/packages/client-ui-components/cordis.patch.yml +3 -0
  169. package/example-plugins/packages/client-ui-components/index.js +9 -0
  170. package/example-plugins/packages/client-ui-components/package.json +31 -0
  171. package/example-plugins/packages/client-ui-library/client.js +715 -0
  172. package/example-plugins/packages/client-ui-library/cordis.patch.yml +3 -0
  173. package/example-plugins/packages/client-ui-library/index.js +9 -0
  174. package/example-plugins/packages/client-ui-library/package.json +37 -0
  175. package/example-plugins/packages/client-workspace-tab/client.js +72 -0
  176. package/example-plugins/packages/client-workspace-tab/cordis.patch.yml +3 -0
  177. package/example-plugins/packages/client-workspace-tab/index.js +9 -0
  178. package/example-plugins/packages/client-workspace-tab/package.json +30 -0
  179. package/example-plugins/packages/config-schema-basic/cordis.patch.yml +3 -0
  180. package/example-plugins/packages/config-schema-basic/index.js +19 -0
  181. package/example-plugins/packages/config-schema-basic/package.json +25 -0
  182. package/example-plugins/packages/desktop-main-profile-info/cordis.patch.yml +3 -0
  183. package/example-plugins/packages/desktop-main-profile-info/index.js +22 -0
  184. package/example-plugins/packages/desktop-main-profile-info/package.json +25 -0
  185. package/example-plugins/packages/event-hook-basic/cordis.patch.yml +3 -0
  186. package/example-plugins/packages/event-hook-basic/index.js +17 -0
  187. package/example-plugins/packages/event-hook-basic/package.json +22 -0
  188. package/example-plugins/packages/generated-capability-template/cordis.patch.yml +3 -0
  189. package/example-plugins/packages/generated-capability-template/index.js +16 -0
  190. package/example-plugins/packages/generated-capability-template/package.json +42 -0
  191. package/example-plugins/packages/host-route-basic/cordis.patch.yml +3 -0
  192. package/example-plugins/packages/host-route-basic/index.js +20 -0
  193. package/example-plugins/packages/host-route-basic/package.json +29 -0
  194. package/example-plugins/packages/lifecycle-function-basic/cordis.patch.yml +3 -0
  195. package/example-plugins/packages/lifecycle-function-basic/index.js +12 -0
  196. package/example-plugins/packages/lifecycle-function-basic/package.json +15 -0
  197. package/example-plugins/packages/lifecycle-function-hot-shim/cordis.patch.yml +3 -0
  198. package/example-plugins/packages/lifecycle-function-hot-shim/impl.js +5 -0
  199. package/example-plugins/packages/lifecycle-function-hot-shim/index.js +18 -0
  200. package/example-plugins/packages/lifecycle-function-hot-shim/package.json +23 -0
  201. package/example-plugins/packages/lifecycle-hooks-observer/cordis.patch.yml +3 -0
  202. package/example-plugins/packages/lifecycle-hooks-observer/index.js +23 -0
  203. package/example-plugins/packages/lifecycle-hooks-observer/package.json +22 -0
  204. package/example-plugins/packages/llm-adapter-echo/cordis.patch.yml +3 -0
  205. package/example-plugins/packages/llm-adapter-echo/index.js +42 -0
  206. package/example-plugins/packages/llm-adapter-echo/package.json +25 -0
  207. package/example-plugins/packages/prompt-assemble-hook/cordis.patch.yml +3 -0
  208. package/example-plugins/packages/prompt-assemble-hook/index.js +22 -0
  209. package/example-plugins/packages/prompt-assemble-hook/package.json +22 -0
  210. package/example-plugins/packages/prompt-contribution-basic/cordis.patch.yml +3 -0
  211. package/example-plugins/packages/prompt-contribution-basic/index.js +18 -0
  212. package/example-plugins/packages/prompt-contribution-basic/package.json +22 -0
  213. package/example-plugins/packages/service-consumer-greeter/cordis.patch.yml +3 -0
  214. package/example-plugins/packages/service-consumer-greeter/index.js +14 -0
  215. package/example-plugins/packages/service-consumer-greeter/package.json +22 -0
  216. package/example-plugins/packages/service-provider-greeter/cordis.patch.yml +3 -0
  217. package/example-plugins/packages/service-provider-greeter/index.js +22 -0
  218. package/example-plugins/packages/service-provider-greeter/package.json +25 -0
  219. package/example-plugins/packages/settings-section-basic/cordis.patch.yml +3 -0
  220. package/example-plugins/packages/settings-section-basic/index.js +34 -0
  221. package/example-plugins/packages/settings-section-basic/package.json +26 -0
  222. package/example-plugins/packages/skill-provider-basic/cordis.patch.yml +3 -0
  223. package/example-plugins/packages/skill-provider-basic/index.js +31 -0
  224. package/example-plugins/packages/skill-provider-basic/package.json +22 -0
  225. package/example-plugins/packages/state-host-store/client.js +57 -0
  226. package/example-plugins/packages/state-host-store/cordis.patch.yml +3 -0
  227. package/example-plugins/packages/state-host-store/index.js +90 -0
  228. package/example-plugins/packages/state-host-store/package.json +31 -0
  229. package/example-plugins/packages/state-workspace-file/cordis.patch.yml +3 -0
  230. package/example-plugins/packages/state-workspace-file/index.js +52 -0
  231. package/example-plugins/packages/state-workspace-file/package.json +25 -0
  232. package/example-plugins/packages/tool-basic/cordis.patch.yml +3 -0
  233. package/example-plugins/packages/tool-basic/index.js +25 -0
  234. package/example-plugins/packages/tool-basic/package.json +25 -0
  235. package/example-plugins/packages/tool-policy-hook/cordis.patch.yml +3 -0
  236. package/example-plugins/packages/tool-policy-hook/index.js +28 -0
  237. package/example-plugins/packages/tool-policy-hook/package.json +25 -0
  238. package/example-plugins/packages/tui-command-basic/cordis.patch.yml +3 -0
  239. package/example-plugins/packages/tui-command-basic/index.js +24 -0
  240. package/example-plugins/packages/tui-command-basic/package.json +22 -0
  241. package/example-plugins/packages/tui-overlay-themed/cordis.patch.yml +3 -0
  242. package/example-plugins/packages/tui-overlay-themed/index.js +65 -0
  243. package/example-plugins/packages/tui-overlay-themed/package.json +25 -0
  244. package/example-plugins/packages/tui-ui-library/cordis.patch.yml +3 -0
  245. package/example-plugins/packages/tui-ui-library/index.js +73 -0
  246. package/example-plugins/packages/tui-ui-library/package.json +29 -0
  247. package/example-plugins/packages/web-page-branding/cordis.patch.yml +3 -0
  248. package/example-plugins/packages/web-page-branding/index.js +31 -0
  249. package/example-plugins/packages/web-page-branding/package.json +22 -0
  250. package/example-plugins/scenarios.json +11 -0
  251. package/index.js +384 -0
  252. package/lib/blend-apply.js +107 -0
  253. package/lib/blend-capture.js +249 -0
  254. package/lib/blend-ledger.js +76 -0
  255. package/lib/contract.js +5 -0
  256. package/lib/install.js +516 -0
  257. package/lib/lookup.js +67 -0
  258. package/lib/manifest.js +56 -0
  259. package/lib/pack-root.js +22 -0
  260. package/lib/provenance.js +110 -0
  261. package/lib/publish.js +64 -0
  262. package/lib/reconcile.js +83 -0
  263. package/lib/router.js +55 -0
  264. package/lib/scopes.js +82 -0
  265. package/lib/skills.js +54 -0
  266. package/lib/stage.js +157 -0
  267. package/lib/verify.js +77 -0
  268. package/package.json +56 -3
  269. package/scripts/lib/indexes.mjs +45 -0
  270. package/scripts/lib/manifest.mjs +127 -0
  271. package/scripts/lib/maps.mjs +482 -0
  272. package/skills/acryl-add-provider-or-capability/SKILL.md +12 -0
  273. package/skills/acryl-add-ui/SKILL.md +18 -0
  274. package/skills/acryl-build-plugin/SKILL.md +21 -0
  275. package/skills/acryl-change-plugin/SKILL.md +16 -0
  276. package/skills/acryl-desktop-shell/SKILL.md +12 -0
  277. package/skills/acryl-diagnose-plugin/SKILL.md +10 -0
  278. package/skills/acryl-fix-plugin/SKILL.md +12 -0
  279. package/skills/acryl-improve-ui/SKILL.md +10 -0
  280. package/skills/acryl-remove-plugin/SKILL.md +11 -0
  281. package/skills/acryl-restyle-ui/SKILL.md +14 -0
  282. package/skills/acryl-share-plugin/SKILL.md +23 -0
  283. package/skills/acryl-tui-ui/SKILL.md +12 -0
  284. package/README.md +0 -3
@@ -0,0 +1,4666 @@
1
+ <!-- Synced from acryl:docs/cordis/cordis_system_guide_for_coding_agents.md @ 592736f2a2. Do not edit; run scripts/sync-corpus.mjs. Relative links inside may not resolve here. -->
2
+
3
+ # Cordis System Guide for Coding Agents
4
+
5
+ > **End-to-end practical handbook for building on Cordis and DeepSeek Harness (`dsh`)**
6
+ > **Target:** DeepSeek Harness vendored `@deepseek-ai/cordis` and its Harness capability layer
7
+ > **Audience:** coding agents and engineers modifying, extending, or designing a Cordis-based agent harness
8
+ > **Research snapshot:** 2026-08-24
9
+ > **Primary implementation target:** this repository's pinned
10
+ > `deepseek-harness/` checkout at
11
+ > `b150a551b8d465e31e418e1b2eaf5e79bbb7d28e`, including its vendored Cordis
12
+ > source snapshot and local lifecycle/Loader patches. Public `master` is a
13
+ > comparison source, not authority for code in this checkout.
14
+
15
+ ---
16
+
17
+ **Path convention:** Unless an ACRYL/root path is written explicitly, paths such
18
+ as `docs/...`, `packages/...`, and `vendor/...` in this guide are relative to
19
+ the pinned `deepseek-harness/` submodule.
20
+
21
+ ## 0. Purpose of this document
22
+
23
+ This is a **single, operational A-to-Z tutorial**. It is designed so that a coding agent can read one file and then safely implement Cordis-style components without repeatedly rediscovering the architecture.
24
+
25
+ It explains:
26
+
27
+ - what Cordis is and is not;
28
+ - how the formal ideas in *A Programming Paradigm for Spatiotemporal Composability* map to real TypeScript code;
29
+ - how `Context`, `Fiber`, `Service`, `Registry`, effects, disposers, coeffects, injection, events, configuration, isolation, interception, Loader reconciliation, and HMR actually work;
30
+ - how DeepSeek Harness builds agent semantics on top of Cordis;
31
+ - how `tools`, `llm`, sessions, agents, prompt assembly, jobs, shell, filesystem, sandbox, and other capability seams fit together;
32
+ - how to build plugins, services, providers, consumers, tools, LLM adapters, event hooks, and policy wrappers;
33
+ - how to compose and hot-swap those pieces from `cordis.yml`;
34
+ - how to diagnose `PENDING`, failed, stale, leaking, or incorrectly wired plugins;
35
+ - how a coding agent should decide **which Cordis primitive to use** for a requested feature;
36
+ - which design rules are mandatory if we want components to be safely replaceable at runtime.
37
+
38
+ This is intentionally **not** a prose-only conceptual introduction. Every important concept has a concrete coding pattern, implementation rule, or diagnostic recipe.
39
+
40
+ ---
41
+
42
+ # Part I - Read this first: the mental model
43
+
44
+ ## 1. Cordis in one sentence
45
+
46
+ **Cordis is a runtime meta-framework that turns application capabilities into dynamically mountable components whose dependencies are tracked and whose in-process contributions have owned cleanup.**
47
+
48
+ In DeepSeek Harness, this becomes:
49
+
50
+ ```text
51
+ DeepSeek Harness / dsh
52
+ │
53
+ │ domain semantics: agents, LLMs, tools, sessions, prompts, policies, UI
54
+ ▼
55
+ Cordis
56
+ │
57
+ │ composition semantics: plugins, services, injection, effects, events,
58
+ │ fibers, scopes, configuration, reconciliation, HMR
59
+ ▼
60
+ Node.js / OS / external systems
61
+ ```
62
+
63
+ The most important architectural statement in Harness is:
64
+
65
+ > **The product is a plugin tree.**
66
+
67
+ The LLM adapter is a plugin. The tool registry is a plugin. The agent loop is a plugin. Session storage is a plugin. Sandbox behavior is a plugin. UI/surface bundles are plugins and configuration layers.
68
+
69
+ Cordis itself does **not** know what an LLM, agent, chat, Bash command, or session means. That is why it is a **meta-framework** rather than an agent framework.
70
+
71
+ ---
72
+
73
+ ## 2. The five ideas to keep in working memory
74
+
75
+ When editing a Cordis system, reduce almost everything to these five ideas:
76
+
77
+ 1. **Plugin = lifecycle unit.**
78
+ A plugin is something Cordis can mount, suspend/reload, and dispose.
79
+
80
+ 2. **Context = scoped capability environment.**
81
+ `ctx` is how a plugin sees services and registers owned behavior.
82
+
83
+ 3. **`inject` = live dependency contract.**
84
+ It is not only startup DI. A consumer activates only while required service implementations exist. Provider identity changes can reactivate the consumer.
85
+
86
+ 4. **Registration = effect = ownership.**
87
+ If a plugin registers a listener, tool, provider, timer, watcher, or other contribution, that contribution must belong to the plugin's Fiber and have cleanup.
88
+
89
+ 5. **`cordis.yml` = desired composition.**
90
+ Configuration expresses the plugin tree. Stable entry IDs let Loader reconcile edits, provider swaps, configuration changes, and HMR without treating the whole process as disposable.
91
+
92
+ If a feature cannot be explained with these five ideas, inspect the owning subsystem before adding another abstraction.
93
+
94
+ ---
95
+
96
+ ## 3. The object model: do not confuse these terms
97
+
98
+ ```text
99
+ Plugin definition
100
+ │ ctx.plugin(plugin)
101
+ ▼
102
+ Fiber ← one mounted runtime instance
103
+ │ owns
104
+ ├── child Context ← scoped view of capabilities
105
+ ├── effect disposers
106
+ ├── dependency snapshot
107
+ ├── child Fibers
108
+ └── lifecycle state
109
+
110
+ Context
111
+ ├── resolves Services by stable names
112
+ ├── registers effects/listeners/plugins
113
+ ├── dispatches typed Events
114
+ ├── carries isolation/intercept scope
115
+ └── exposes Registry + current Fiber
116
+
117
+ Service provider plugin
118
+ └── provides ctx.<serviceName>
119
+
120
+ Consumer plugin
121
+ └── injects <serviceName>
122
+ ```
123
+
124
+ ### Plugin
125
+ A **definition** or mountable callback/class/object. It may have zero, one, or many live Fibers.
126
+
127
+ ### Fiber
128
+ A **runtime instance** of a plugin. The Fiber owns activation state and cleanup. A Fiber is not a thread, coroutine, React Fiber, or process.
129
+
130
+ ### Context
131
+ The scoped interface passed into the plugin. It behaves like a dynamic service environment plus lifecycle-aware registration surface.
132
+
133
+ ### Service
134
+ A named capability exposed on `ctx`, e.g. `ctx.tools`, `ctx.llm`, `ctx.sessions`, or a custom `ctx.myCap`.
135
+
136
+ ### Registry
137
+ Tracks plugin runtimes and Fibers. Useful for introspection and diagnostics.
138
+
139
+ ### Effect
140
+ A lifecycle-owned environmental contribution with a cleanup operation.
141
+
142
+ ### Coeffect / `inject`
143
+ A declaration of contextual requirements. In Cordis, these requirements are reactive to live provider changes.
144
+
145
+ ---
146
+
147
+ # Part II - The theory translated into engineering
148
+
149
+ ## 4. Why “spatiotemporal composability” matters
150
+
151
+ The Cordis paper separates dynamic composition into two orthogonal problems.
152
+
153
+ ### 4.1 Temporal composability
154
+
155
+ Question:
156
+
157
+ > Can a component withdraw its own in-process contributions later without leaving stale state or deleting independent contributions from other components?
158
+
159
+ Example problem:
160
+
161
+ ```text
162
+ Plugin A registers tool A
163
+ Plugin B registers tool B
164
+ Plugin A registers event listener A
165
+ Plugin A starts timer A
166
+
167
+ later: unload A
168
+ ```
169
+
170
+ Correct result:
171
+
172
+ ```text
173
+ Tool A removed
174
+ Listener A removed
175
+ Timer A stopped
176
+ Tool B remains
177
+ Everything B owns remains
178
+ ```
179
+
180
+ This is what **revertible effects** are for.
181
+
182
+ ### 4.2 Spatial composability
183
+
184
+ Question:
185
+
186
+ > Can components stay valid while the live dependency graph changes?
187
+
188
+ Example:
189
+
190
+ ```text
191
+ consumer injects 'llm'
192
+ │
193
+ └── currently resolved to Provider A
194
+
195
+ Provider A disappears
196
+ Provider B appears
197
+ ```
198
+
199
+ The consumer must not keep a stale reference to A. Cordis reacts to the dependency change, unloads the consumer's active episode, and runs it again against the new provider when requirements are satisfied.
200
+
201
+ This is what **reactive coeffects** are for.
202
+
203
+ ### 4.3 Why both are required
204
+
205
+ Dependency rebinding without cleanup leaves old registrations alive.
206
+
207
+ Cleanup without dependency rebinding leaves consumers calling dead providers.
208
+
209
+ Cordis combines both dimensions inside one `Context`/Fiber runtime.
210
+
211
+ ---
212
+
213
+ ## 5. Revertible effects
214
+
215
+ A revertible effect is conceptually:
216
+
217
+ ```text
218
+ acquire / contribute
219
+ ↓
220
+ environment changed
221
+ ↓
222
+ disposer
223
+ ↓
224
+ contribution withdrawn
225
+ ```
226
+
227
+ Canonical Cordis form:
228
+
229
+ ```ts
230
+ ctx.effect(() => {
231
+ const timer = setInterval(doWork, 1000)
232
+
233
+ return () => {
234
+ clearInterval(timer)
235
+ }
236
+ })
237
+ ```
238
+
239
+ ### Rule
240
+
241
+ **If Cordis does not already own the resource, acquire it inside `ctx.effect()` and return cleanup.**
242
+
243
+ Bad:
244
+
245
+ ```ts
246
+ export function apply(ctx: Context) {
247
+ setInterval(doWork, 1000)
248
+ }
249
+ ```
250
+
251
+ The timer outlives the plugin.
252
+
253
+ Good:
254
+
255
+ ```ts
256
+ export function apply(ctx: Context) {
257
+ ctx.effect(() => {
258
+ const timer = setInterval(doWork, 1000)
259
+ return () => clearInterval(timer)
260
+ })
261
+ }
262
+ ```
263
+
264
+ ---
265
+
266
+ ## 6. Disposer
267
+
268
+ A **disposer** is the concrete cleanup function.
269
+
270
+ Examples:
271
+
272
+ ```ts
273
+ () => clearTimeout(timer)
274
+ () => socket.close()
275
+ () => watcher.close()
276
+ () => registry.delete(key)
277
+ () => abortController.abort()
278
+ ```
279
+
280
+ A disposer may also be asynchronous:
281
+
282
+ ```ts
283
+ ctx.effect(async () => {
284
+ const connection = await openConnection()
285
+
286
+ return async () => {
287
+ await connection.flush()
288
+ await connection.close()
289
+ }
290
+ })
291
+ ```
292
+
293
+ The Fiber waits for owned asynchronous cleanup to reach quiescence before disposal settles.
294
+
295
+ ### Important implementation nuance
296
+
297
+ Current vendored Cordis allows effect setup to produce:
298
+
299
+ - one disposer;
300
+ - a promise of a disposer;
301
+ - an iterable of disposers;
302
+ - an async iterable of disposers.
303
+
304
+ Do not reach for generator effects unless they simplify a real incremental-acquisition case. A single effect with explicit cleanup is easier to audit.
305
+
306
+ ---
307
+
308
+ ## 7. Twisted composition and LIFO cleanup
309
+
310
+ The formal idea is that forward operations compose in acquisition order while inverses compose in reverse order.
311
+
312
+ ```text
313
+ forward: A → B → C
314
+ cleanup: C⁻¹ → B⁻¹ → A⁻¹
315
+ ```
316
+
317
+ Practical example:
318
+
319
+ ```ts
320
+ ctx.effect(() => {
321
+ const socket = openSocket()
322
+ const subscription = socket.subscribe('events')
323
+
324
+ return async () => {
325
+ // reverse dependency order
326
+ await subscription.unsubscribe()
327
+ await socket.close()
328
+ }
329
+ })
330
+ ```
331
+
332
+ ### Cordis teardown nuance
333
+
334
+ At the Fiber level, multiple top-level effects may be cleaned concurrently. Therefore:
335
+
336
+ > **If teardown operations have a required sequence, keep them inside one effect disposer and await them in the required order.**
337
+
338
+ Do not rely on timing between two independent asynchronous top-level effects.
339
+
340
+ Bad:
341
+
342
+ ```ts
343
+ ctx.effect(() => {
344
+ const db = openDb()
345
+ return async () => db.close()
346
+ })
347
+
348
+ ctx.effect(() => {
349
+ const writer = createWriter(/* depends on db */)
350
+ return async () => writer.flush()
351
+ })
352
+ ```
353
+
354
+ If ordering matters, combine ownership:
355
+
356
+ ```ts
357
+ ctx.effect(() => {
358
+ const db = openDb()
359
+ const writer = createWriter(db)
360
+
361
+ return async () => {
362
+ await writer.flush()
363
+ await writer.close()
364
+ await db.close()
365
+ }
366
+ })
367
+ ```
368
+
369
+ ---
370
+
371
+ ## 8. Left inverse
372
+
373
+ The mathematical ideal is:
374
+
375
+ ```text
376
+ g(f(c)) = c
377
+ ```
378
+
379
+ where:
380
+
381
+ - `c` = starting context/environment;
382
+ - `f` = effect;
383
+ - `g` = cleanup/inverse.
384
+
385
+ In real systems this does **not** mean time travel.
386
+
387
+ You cannot un-send a network packet or erase an external observer's memory.
388
+
389
+ The coding rule is narrower:
390
+
391
+ > Make the plugin's **owned in-process contribution** disappear so the rest of the running system behaves as if that contribution were no longer mounted.
392
+
393
+ ---
394
+
395
+ ## 9. Observational equivalence
396
+
397
+ Recovery does not require every memory bit to become identical to an earlier snapshot.
398
+
399
+ The useful target is:
400
+
401
+ > After withdrawal, subsequent supported operations cannot distinguish the environment from one in which that component's contribution is absent, except for effects that are inherently external/irreversible and explicitly outside the recovery model.
402
+
403
+ This distinction is crucial for agent systems:
404
+
405
+ - a persisted session event cannot be “unhappened” by plugin disposal;
406
+ - an HTTP request already sent cannot be recalled;
407
+ - a file mutation may need a domain-specific compensation strategy;
408
+ - process-local registrations **can** and should be removed exactly.
409
+
410
+ Do not sell `ctx.effect()` as a transaction manager. It is lifecycle ownership, not distributed rollback.
411
+
412
+ ---
413
+
414
+ ## 10. Reactive coeffects
415
+
416
+ A coeffect expresses what a component needs from its environment.
417
+
418
+ In Cordis:
419
+
420
+ ```ts
421
+ export const inject = ['tools', 'llm']
422
+
423
+ export function apply(ctx: Context) {
424
+ // During this activation episode, both are available.
425
+ ctx.tools
426
+ ctx.llm
427
+ }
428
+ ```
429
+
430
+ The key word is **reactive**.
431
+
432
+ Cordis continually ties activation to the implementations that satisfy the injection set.
433
+
434
+ Conceptually:
435
+
436
+ ```text
437
+ missing dependency
438
+ ↓
439
+ PENDING
440
+ ↓ provider appears
441
+ LOADING
442
+ ↓
443
+ ACTIVE
444
+ ↓ provider disappears/replaced
445
+ UNLOADING
446
+ ↓
447
+ PENDING
448
+ ↓ new provider appears
449
+ LOADING
450
+ ↓
451
+ ACTIVE
452
+ ```
453
+
454
+ This is more than a one-time dependency container lookup.
455
+
456
+ ---
457
+
458
+ ## 11. Dependency identity matters, not just dependency name
459
+
460
+ Suppose a plugin injects `shell`.
461
+
462
+ ```text
463
+ 'shell' → LocalShell#fiber-15
464
+ ```
465
+
466
+ Then configuration replaces it with:
467
+
468
+ ```text
469
+ 'shell' → RemoteShell#fiber-29
470
+ ```
471
+
472
+ Even though the **name** is still `shell`, the provider Fiber identity changed.
473
+
474
+ Cordis tracks the implementation episode. A dependent plugin can be reactivated so it no longer holds references captured from the former provider.
475
+
476
+ This is one of the most important reasons to use stable service names and avoid importing concrete provider implementations into consumers.
477
+
478
+ ---
479
+
480
+ ## 12. Theory-to-code mapping
481
+
482
+ | Formal / conceptual notion | Cordis mechanism | Coding-agent rule |
483
+ |---|---|---|
484
+ | Component | Plugin + mounted Fiber | Put independently replaceable behavior behind a plugin boundary |
485
+ | Effect | `ctx.effect()` or lifecycle-aware registration | Every contribution must have an owner |
486
+ | Revertible effect | acquisition + disposer | Acquire and clean up in the same lifecycle scope |
487
+ | Disposer | returned cleanup function | Make it idempotent/safe and await real cleanup |
488
+ | Reactive coeffect | `inject` + service resolver | Declare hard dependencies instead of assuming load order |
489
+ | Context | `ctx` proxy and scope | Resolve capabilities through stable service names |
490
+ | Dependency topology | service providers + injection graph | Consumers depend on interfaces/capabilities, not concrete providers |
491
+ | Temporal withdrawal | Fiber unload | Expect every owned registration to disappear |
492
+ | Spatial rebind | provider identity change → reactivation | Never cache provider references outside the owning activation episode |
493
+ | Observational recovery | complete removal of owned live contributions | Test absence of stale tool/listener/provider/handle state |
494
+ | Composition | `ctx.plugin()` and Loader tree | Make desired runtime structure explicit |
495
+ | Dynamic reconciliation | Loader/HMR | Stable IDs + reversible plugin design are mandatory |
496
+
497
+ ---
498
+
499
+ # Part III - The actual Cordis runtime
500
+
501
+ ## 13. Target the right Cordis
502
+
503
+ There are two closely related targets:
504
+
505
+ ### Upstream
506
+
507
+ ```text
508
+ cordiverse/cordis
509
+ npm: cordis
510
+ ```
511
+
512
+ ### DeepSeek Harness vendored/rescoped line
513
+
514
+ ```text
515
+ deepseek-ai/deepseek-harness/vendor/cordis
516
+ package: @deepseek-ai/cordis
517
+ ```
518
+
519
+ At the inspected 2026-08-24 Harness snapshot, the vendor manifest records the
520
+ upstream source provenance:
521
+
522
+ ```text
523
+ @deepseek-ai/cordis
524
+ upstream package: cordis
525
+ upstream version snapshot: 4.0.0-rc.7
526
+ upstream commit: 56b3d4f725681cf4556c1a8695a709cc3b6eed74
527
+ ```
528
+
529
+ The rescoped package published by this pinned Harness checkout is currently
530
+ `@deepseek-ai/cordis` `4.0.1`. The upstream snapshot version documents source
531
+ provenance; the rescoped package version is the dependency/runtime version ACRYL
532
+ must satisfy.
533
+
534
+ Harness also carries local changes, including lifecycle hardening, lazy config resolution, and transactional Loader/Include reconciliation.
535
+
536
+ ### Coding-agent rule
537
+
538
+ **When working inside DeepSeek Harness, treat its vendored source and generated Harness docs/types as authoritative.**
539
+
540
+ Do not copy an upstream Cordis example blindly if its API or Loader behavior differs.
541
+
542
+ Before implementing a nontrivial feature, inspect locally:
543
+
544
+ ```text
545
+ vendor/cordis/src/
546
+ vendor/loader/src/
547
+ vendor/include/src/
548
+ vendor/hmr/src/
549
+ docs/cordis-primer.md
550
+ docs/cordis-tutorial/
551
+ docs/subsystems/
552
+ ```
553
+
554
+ ---
555
+
556
+ ## 14. Creating the root Context
557
+
558
+ Pure Cordis can start with:
559
+
560
+ ```ts
561
+ import { Context } from '@deepseek-ai/cordis'
562
+
563
+ const root = new Context()
564
+ ```
565
+
566
+ The root Context creates core runtime machinery including:
567
+
568
+ ```text
569
+ ctx.events
570
+ ctx.logger
571
+ ctx.reflect
572
+ ctx.registry
573
+ ctx.fiber
574
+ ctx.root
575
+ ```
576
+
577
+ Harness normally creates the composition for you, so ordinary Harness plugins receive `ctx` rather than constructing another root.
578
+
579
+ ### Rule
580
+
581
+ **Do not create random root Contexts inside feature plugins.**
582
+
583
+ A second root is a second dependency universe. Use child/scoped contexts only when isolation is intentional.
584
+
585
+ ---
586
+
587
+ ## 15. What `ctx` really is
588
+
589
+ The current Context is a Proxy-backed scoped environment.
590
+
591
+ It serves four jobs simultaneously:
592
+
593
+ 1. **capability lookup** - `ctx.llm`, `ctx.tools`, `ctx.myService`;
594
+ 2. **lifecycle ownership** - `ctx.effect`, `ctx.plugin`, `ctx.on`;
595
+ 3. **event dispatch** - `ctx.emit`, `ctx.waterfall`, etc.;
596
+ 4. **scope definition** - isolation/intercept behavior and current Fiber.
597
+
598
+ You should think:
599
+
600
+ ```text
601
+ ctx = “the world this plugin is currently allowed to see and modify”
602
+ ```
603
+
604
+ not:
605
+
606
+ ```text
607
+ ctx = “a bag of global singleton objects”
608
+ ```
609
+
610
+ ---
611
+
612
+ ## 16. Context API: core practical surface
613
+
614
+ Common public operations:
615
+
616
+ ```ts
617
+ ctx.plugin(plugin, config?)
618
+ ctx.inject(dependencies, callback)
619
+ ctx.effect(effectBody)
620
+
621
+ ctx.on(event, listener, options?)
622
+ ctx.once(event, listener, options?)
623
+ ctx.emit(event, ...args)
624
+ ctx.parallel(event, ...args)
625
+ ctx.serial(event, ...args)
626
+ ctx.bail(event, ...args)
627
+ ctx.waterfall(event, ...args, next)
628
+
629
+ ctx.get('serviceName')
630
+
631
+ ctx.extend(meta?)
632
+ ctx.isolate('serviceName', label?)
633
+ ctx.intercept('serviceName', config)
634
+
635
+ ctx.registry
636
+ ctx.fiber
637
+ ctx.logger
638
+ ctx.root
639
+ ```
640
+
641
+ Exact package-specific additions come through TypeScript declaration merging. In Harness, importing the package that owns a service/event surface is often required for types.
642
+
643
+ ---
644
+
645
+ ## 17. `extend()` - make a scoped child view
646
+
647
+ `extend(meta)` creates a child Context that prototypically inherits its parent and can carry extra metadata.
648
+
649
+ ```ts
650
+ const child = ctx.extend({ requestId: 'r-123' })
651
+ ```
652
+
653
+ The parent is not mutated.
654
+
655
+ Use this when a subsystem intentionally propagates scoped metadata.
656
+
657
+ Do **not** use `extend` as an arbitrary global state mechanism.
658
+
659
+ ---
660
+
661
+ ## 18. `isolate()` - create a separate service realm
662
+
663
+ ```ts
664
+ const isolated = ctx.isolate('shell')
665
+ ```
666
+
667
+ Below this child context, the named service resolves in a different isolation realm.
668
+
669
+ This is what allows two plugin groups to each have their own `shell` implementation under the same service name.
670
+
671
+ Conceptual example:
672
+
673
+ ```text
674
+ root
675
+ ├── group A isolate(shell=A)
676
+ │ ├── LocalShell(timeout=5s)
677
+ │ └── agent A → ctx.shell = A's shell
678
+ │
679
+ └── group B isolate(shell=B)
680
+ ├── LocalShell(timeout=60s)
681
+ └── agent B → ctx.shell = B's shell
682
+ ```
683
+
684
+ ### Important
685
+
686
+ Service isolation is **not a security sandbox**.
687
+
688
+ It changes Cordis resolution scope; it does not stop plugin code from using Node APIs directly.
689
+
690
+ ---
691
+
692
+ ## 19. `intercept()` - scoped service configuration
693
+
694
+ A service can expose interceptable configuration. A child context may provide an override:
695
+
696
+ ```ts
697
+ const child = ctx.intercept('someService', {
698
+ timeoutMs: 5000,
699
+ })
700
+ ```
701
+
702
+ The service resolves config by combining intercept layers according to its contract.
703
+
704
+ This is advanced. Prefer ordinary plugin configuration until a service explicitly supports scoped interception and there is a real need for per-subtree behavior.
705
+
706
+ ---
707
+
708
+ ## 20. There is no generic `ctx.fork()` in current public Context API
709
+
710
+ The term **fork** is overloaded in architecture discussions.
711
+
712
+ Do not invent:
713
+
714
+ ```ts
715
+ ctx.fork() // not the generic public Context API described by current source
716
+ ```
717
+
718
+ Use the correct mechanism:
719
+
720
+ - mount a child lifecycle → `ctx.plugin(...)`;
721
+ - derive child context metadata → `ctx.extend(...)`;
722
+ - create a service realm → `ctx.isolate(...)`;
723
+ - alter scoped service config → `ctx.intercept(...)`;
724
+ - fork a **Harness session** → the session subsystem's `ctx.sessions.fork(...)` API, which is a completely different domain concept.
725
+
726
+ A coding agent must distinguish **context scope** from **session history fork**.
727
+
728
+ ---
729
+
730
+ # Part IV - Plugins and Fibers
731
+
732
+ ## 21. The three plugin shapes
733
+
734
+ Cordis accepts three practical forms.
735
+
736
+ ### 21.1 Function plugin - default choice
737
+
738
+ ```ts
739
+ import type { Context } from '@deepseek-ai/cordis'
740
+
741
+ export const name = 'hello'
742
+
743
+ export function apply(ctx: Context) {
744
+ console.log('hello')
745
+ }
746
+ ```
747
+
748
+ A function itself can also be mounted:
749
+
750
+ ```ts
751
+ function heartbeat(ctx: Context) {
752
+ // ...
753
+ }
754
+
755
+ ctx.plugin(heartbeat)
756
+ ```
757
+
758
+ ### 21.2 Object plugin
759
+
760
+ ```ts
761
+ export const plugin = {
762
+ name: 'object-plugin',
763
+ inject: ['tools'],
764
+ apply(ctx: Context) {
765
+ // ...
766
+ },
767
+ }
768
+ ```
769
+
770
+ ### 21.3 Class plugin / Service subclass
771
+
772
+ ```ts
773
+ import { Service, type Context } from '@deepseek-ai/cordis'
774
+
775
+ export class MyService extends Service {
776
+ constructor(ctx: Context) {
777
+ super(ctx, 'myService')
778
+ }
779
+ }
780
+ ```
781
+
782
+ Use class form when the plugin naturally **provides a service** or benefits from a service object's public methods/state.
783
+
784
+ ### Default decision
785
+
786
+ ```text
787
+ Need lifecycle only? → function plugin
788
+ Need structured object form? → object plugin
789
+ Need to provide service API? → Service class
790
+ ```
791
+
792
+ ---
793
+
794
+ ## 22. Plugin metadata
795
+
796
+ Current plugin runtime understands metadata such as:
797
+
798
+ ```ts
799
+ export const name = 'my-plugin'
800
+ export const inject = ['tools', 'llm']
801
+ export const Config = /* Standard Schema */
802
+ ```
803
+
804
+ At the underlying runtime type level there are also concepts such as `provide` and `intercept` metadata. Ordinary Harness authors should follow subsystem examples instead of manually manipulating low-level metadata without need.
805
+
806
+ ---
807
+
808
+ ## 23. `ctx.plugin()`
809
+
810
+ ```ts
811
+ const fiber = ctx.plugin(myPlugin, config)
812
+ ```
813
+
814
+ This:
815
+
816
+ 1. resolves the plugin shape;
817
+ 2. creates/reuses a plugin runtime record;
818
+ 3. creates a child Fiber;
819
+ 4. creates a child Context bound to that Fiber;
820
+ 5. normalizes injection declarations;
821
+ 6. waits for requirements;
822
+ 7. validates configuration when activation is possible;
823
+ 8. executes the plugin;
824
+ 9. tracks all owned effects;
825
+ 10. returns a Fiber-like thenable.
826
+
827
+ You can await initial settlement:
828
+
829
+ ```ts
830
+ const fiber = await ctx.plugin(myPlugin)
831
+ ```
832
+
833
+ Or keep the handle:
834
+
835
+ ```ts
836
+ const fiber = ctx.plugin(myPlugin)
837
+ await fiber.await()
838
+ ```
839
+
840
+ ---
841
+
842
+ ## 24. `ctx.inject()` shorthand
843
+
844
+ For localized dependency-gated behavior:
845
+
846
+ ```ts
847
+ ctx.inject(['tools'], (ctx) => {
848
+ // active only while tools exists
849
+ })
850
+ ```
851
+
852
+ Conceptually it is shorthand for mounting a plugin with that injection declaration.
853
+
854
+ This is useful when a larger service/class needs one method or sub-behavior to come alive only under additional dependencies.
855
+
856
+ Do not use it to hide the primary dependencies of a top-level plugin. Those should remain visible in the plugin's `inject` metadata.
857
+
858
+ ---
859
+
860
+ ## 25. Fiber state machine - actual current states
861
+
862
+ The current vendored implementation exposes:
863
+
864
+ ```text
865
+ PENDING
866
+ LOADING
867
+ ACTIVE
868
+ FAILED
869
+ UNLOADING
870
+ DISPOSED
871
+ ```
872
+
873
+ Useful transition model:
874
+
875
+ ```text
876
+ apply/config error
877
+ ┌───────► FAILED
878
+ │
879
+ PENDING ──deps ready────► LOADING ─────► ACTIVE
880
+ ▲ │
881
+ │ │ dependency/provider change
882
+ │ │ restart/update/HMR
883
+ │ ▼
884
+ └────────────────────────────── UNLOADING
885
+ │
886
+ ├── still mounted, requirements absent
887
+ │ → PENDING
888
+ │
889
+ ├── requirements already satisfied/new epoch
890
+ │ → LOADING
891
+ │
892
+ └── explicit permanent disposal
893
+ → DISPOSED
894
+ ```
895
+
896
+ ### Important correction: `INACTIVE`
897
+
898
+ Some conceptual explanations use the word **inactive**, but current `FiberState` does not export an `INACTIVE` enum member.
899
+
900
+ Treat “inactive” as a conceptual condition, not an enum constant.
901
+
902
+ ### Important correction: temporary dependency loss ≠ permanent disposal
903
+
904
+ A service disappearing does not necessarily destroy the Fiber forever.
905
+
906
+ The active episode unloads. The mounted Fiber may settle back into `PENDING` and reactivate later.
907
+
908
+ `DISPOSED` means the Fiber's runtime identity has been explicitly removed and it cannot restart normally.
909
+
910
+ ---
911
+
912
+ ## 26. `PENDING` is not an error
913
+
914
+ A plugin in `PENDING` is saying:
915
+
916
+ ```text
917
+ “I am mounted, but my declared environment does not currently exist.”
918
+ ```
919
+
920
+ This is a valid state because a provider may appear later.
921
+
922
+ Therefore this can exit silently:
923
+
924
+ ```ts
925
+ export const inject = ['doesNotExist']
926
+
927
+ export function apply(ctx: Context) {
928
+ console.log('never prints while missing')
929
+ }
930
+ ```
931
+
932
+ If nothing else keeps Node alive, the process can even exit cleanly.
933
+
934
+ ### Diagnostic rule
935
+
936
+ When a plugin “does nothing,” inspect Fiber state before assuming its `apply()` is broken.
937
+
938
+ ---
939
+
940
+ ## 27. Fiber methods a coding agent should know
941
+
942
+ ### Await stable initial state
943
+
944
+ ```ts
945
+ await fiber.await()
946
+ ```
947
+
948
+ Startup/config errors are rethrown.
949
+
950
+ ### Permanently dispose mounted instance
951
+
952
+ ```ts
953
+ await fiber.dispose()
954
+ ```
955
+
956
+ Waits for owned cleanup and children.
957
+
958
+ ### Restart current plugin
959
+
960
+ ```ts
961
+ await fiber.restart()
962
+ ```
963
+
964
+ Unload and activate again using current configuration/dependencies.
965
+
966
+ ### Update config
967
+
968
+ ```ts
969
+ await fiber.update(newConfig)
970
+ ```
971
+
972
+ Validation/reconciliation hooks can participate.
973
+
974
+ ### Inspect effects
975
+
976
+ Current Fiber provides diagnostic metadata for live effects:
977
+
978
+ ```ts
979
+ fiber.getEffects()
980
+ ```
981
+
982
+ This can be valuable when hunting lifecycle leaks.
983
+
984
+ ---
985
+
986
+ ## 28. The Registry
987
+
988
+ Every Context exposes the plugin registry:
989
+
990
+ ```ts
991
+ ctx.registry
992
+ ```
993
+
994
+ Diagnostic example:
995
+
996
+ ```ts
997
+ import { FiberState, type Context } from '@deepseek-ai/cordis'
998
+
999
+ export function apply(ctx: Context) {
1000
+ for (const runtime of ctx.registry.values()) {
1001
+ for (const fiber of runtime.fibers) {
1002
+ console.log({
1003
+ name: fiber.name,
1004
+ state: FiberState[fiber.state],
1005
+ uid: fiber.uid,
1006
+ })
1007
+ }
1008
+ }
1009
+ }
1010
+ ```
1011
+
1012
+ Depending on TS enum emission/const-enum setup, direct reverse lookup may not be available in every build; the tutorial's robust check is comparing to `FiberState.PENDING` and logging the name.
1013
+
1014
+ ### Use Registry for
1015
+
1016
+ - diagnostics;
1017
+ - runtime introspection tooling;
1018
+ - developer panels;
1019
+ - HMR/debugging tests.
1020
+
1021
+ ### Do not use Registry for
1022
+
1023
+ - ordinary cross-plugin business calls;
1024
+ - searching for a concrete provider instead of defining a service dependency;
1025
+ - creating hidden load-order coupling.
1026
+
1027
+ ---
1028
+
1029
+ # Part V - Effects: the non-negotiable lifecycle discipline
1030
+
1031
+ ## 29. What is already an effect
1032
+
1033
+ Many Cordis/Harness registration APIs already attach cleanup to the current Fiber.
1034
+
1035
+ Examples include:
1036
+
1037
+ ```ts
1038
+ ctx.on(...)
1039
+ ctx.once(...)
1040
+ ctx.plugin(...)
1041
+ ```
1042
+
1043
+ And Harness registries are designed similarly:
1044
+
1045
+ ```ts
1046
+ ctx.tools.register(...)
1047
+ ctx.llm.registerAdapter(...)
1048
+ ```
1049
+
1050
+ Service provisioning is also lifecycle-owned.
1051
+
1052
+ Therefore you should not wrap every Cordis helper in another `ctx.effect()` mechanically.
1053
+
1054
+ ---
1055
+
1056
+ ## 30. When to write `ctx.effect()` yourself
1057
+
1058
+ Use it for resources Cordis does not know how to clean up.
1059
+
1060
+ Common cases:
1061
+
1062
+ ```text
1063
+ setTimeout / setInterval
1064
+ filesystem watcher
1065
+ WebSocket / TCP connection
1066
+ message-broker subscription
1067
+ child process not owned by another Harness service
1068
+ third-party event emitter registration
1069
+ temporary file / lock
1070
+ native handle
1071
+ background queue worker
1072
+ external SDK subscription
1073
+ ```
1074
+
1075
+ Example watcher:
1076
+
1077
+ ```ts
1078
+ ctx.effect(() => {
1079
+ const watcher = watch(directory, onChange)
1080
+ return () => watcher.close()
1081
+ })
1082
+ ```
1083
+
1084
+ Example emitter:
1085
+
1086
+ ```ts
1087
+ ctx.effect(() => {
1088
+ emitter.on('data', onData)
1089
+ return () => emitter.off('data', onData)
1090
+ })
1091
+ ```
1092
+
1093
+ ---
1094
+
1095
+ ## 31. Effect anti-pattern: acquire outside the effect
1096
+
1097
+ Risky:
1098
+
1099
+ ```ts
1100
+ const socket = openSocket()
1101
+
1102
+ export function apply(ctx: Context) {
1103
+ ctx.effect(() => {
1104
+ return () => socket.close()
1105
+ })
1106
+ }
1107
+ ```
1108
+
1109
+ The resource does not have a clean one-to-one relation to the plugin activation episode.
1110
+
1111
+ Preferred:
1112
+
1113
+ ```ts
1114
+ export function apply(ctx: Context) {
1115
+ ctx.effect(() => {
1116
+ const socket = openSocket()
1117
+ return () => socket.close()
1118
+ })
1119
+ }
1120
+ ```
1121
+
1122
+ This keeps acquisition and release inside one owner scope.
1123
+
1124
+ ---
1125
+
1126
+ ## 32. Effect anti-pattern: fire-and-forget asynchronous setup
1127
+
1128
+ Bad:
1129
+
1130
+ ```ts
1131
+ export function apply(ctx: Context) {
1132
+ void connect().then(connection => {
1133
+ // Now who owns this if the plugin unloaded before connect resolved?
1134
+ })
1135
+ }
1136
+ ```
1137
+
1138
+ Better:
1139
+
1140
+ ```ts
1141
+ export function apply(ctx: Context) {
1142
+ ctx.effect(async () => {
1143
+ const connection = await connect()
1144
+ return () => connection.close()
1145
+ })
1146
+ }
1147
+ ```
1148
+
1149
+ Harness's vendored Cordis includes lifecycle hardening specifically around re-entrant/async setup and disposal. Use the framework path instead of rebuilding ownership yourself.
1150
+
1151
+ ---
1152
+
1153
+ ## 33. Effect anti-pattern: cleanup creates new long-lived effects
1154
+
1155
+ During unload, the owner is leaving. Do not register replacement listeners/timers from a disposer unless the owning architecture explicitly creates a new Fiber elsewhere.
1156
+
1157
+ Current vendored lifecycle hardening rejects effect creation while a Fiber is `UNLOADING`.
1158
+
1159
+ This is a useful invariant:
1160
+
1161
+ ```text
1162
+ cleanup removes ownership
1163
+ cleanup does not secretly extend ownership
1164
+ ```
1165
+
1166
+ ---
1167
+
1168
+ ## 34. Effect audit checklist
1169
+
1170
+ For every plugin, a coding agent should ask:
1171
+
1172
+ ```text
1173
+ [ ] What does apply() add to the process?
1174
+ [ ] Which additions are already lifecycle-aware APIs?
1175
+ [ ] Which additions need ctx.effect()?
1176
+ [ ] Can asynchronous setup complete after unload begins?
1177
+ [ ] Does the framework own that race, or did I create a detached promise?
1178
+ [ ] Does each disposer fully quiesce its resource?
1179
+ [ ] Does cleanup depend on another cleanup ordering?
1180
+ [ ] If yes, are those steps inside one disposer?
1181
+ [ ] Does any callback retain ctx/service references after unload?
1182
+ [ ] Can an external irreversible side effect occur? If so, is that consciously outside rollback semantics?
1183
+ ```
1184
+
1185
+ ---
1186
+
1187
+ # Part VI - Services and live dependency injection
1188
+
1189
+ ## 35. What a Service is
1190
+
1191
+ A Service is a named capability.
1192
+
1193
+ Examples in Harness:
1194
+
1195
+ ```ts
1196
+ ctx.tools
1197
+ ctx.llm
1198
+ ctx.agents
1199
+ ctx.sessions
1200
+ ctx.systemPrompt
1201
+ ctx.shell
1202
+ ctx.fs
1203
+ ctx.sandbox
1204
+ ctx.jobs
1205
+ ```
1206
+
1207
+ A consumer should depend on the **capability name/interface**, not on the concrete provider package.
1208
+
1209
+ ---
1210
+
1211
+ ## 36. Provide a custom service
1212
+
1213
+ ```ts
1214
+ import { Service, type Context } from '@deepseek-ai/cordis'
1215
+
1216
+ declare module '@deepseek-ai/cordis' {
1217
+ interface Context {
1218
+ greeter: GreeterService
1219
+ }
1220
+ }
1221
+
1222
+ export class GreeterService extends Service {
1223
+ constructor(ctx: Context) {
1224
+ super(ctx, 'greeter')
1225
+ }
1226
+
1227
+ greet(name: string) {
1228
+ return `Hello, ${name}!`
1229
+ }
1230
+ }
1231
+
1232
+ export const name = 'greeter-provider'
1233
+
1234
+ export function apply(ctx: Context) {
1235
+ ctx.plugin(GreeterService)
1236
+ }
1237
+ ```
1238
+
1239
+ Two independent things happen:
1240
+
1241
+ ### Runtime
1242
+
1243
+ ```ts
1244
+ super(ctx, 'greeter')
1245
+ ```
1246
+
1247
+ provides the service in the current Cordis scope.
1248
+
1249
+ ### Compile time
1250
+
1251
+ ```ts
1252
+ declare module '@deepseek-ai/cordis' {
1253
+ interface Context {
1254
+ greeter: GreeterService
1255
+ }
1256
+ }
1257
+ ```
1258
+
1259
+ teaches TypeScript that `ctx.greeter` exists.
1260
+
1261
+ Declaration merging alone does **not** provide anything at runtime.
1262
+
1263
+ ---
1264
+
1265
+ ## 37. Consume a required service with `inject`
1266
+
1267
+ ```ts
1268
+ import type { Context } from '@deepseek-ai/cordis'
1269
+ import type {} from './greeter-provider.ts'
1270
+
1271
+ export const name = 'greeter-consumer'
1272
+ export const inject = ['greeter']
1273
+
1274
+ export function apply(ctx: Context) {
1275
+ console.log(ctx.greeter.greet('Ada'))
1276
+ }
1277
+ ```
1278
+
1279
+ The contract is:
1280
+
1281
+ ```text
1282
+ apply() runs only while greeter is available in this service scope
1283
+ ```
1284
+
1285
+ Do not duplicate runtime checks inside `apply()` for a hard dependency.
1286
+
1287
+ ---
1288
+
1289
+ ## 38. Required vs optional dependencies
1290
+
1291
+ ### Required
1292
+
1293
+ ```ts
1294
+ export const inject = ['metrics']
1295
+
1296
+ export function apply(ctx: Context) {
1297
+ ctx.metrics.record('loaded', 1)
1298
+ }
1299
+ ```
1300
+
1301
+ Plugin should not run without the capability.
1302
+
1303
+ ### Optional
1304
+
1305
+ ```ts
1306
+ export function apply(ctx: Context) {
1307
+ const metrics = ctx.get('metrics')
1308
+ metrics?.record('loaded', 1)
1309
+ }
1310
+ ```
1311
+
1312
+ Plugin remains useful without the capability.
1313
+
1314
+ ### Decision rule
1315
+
1316
+ Ask:
1317
+
1318
+ > If this service does not exist, is the plugin's behavior still valid and complete?
1319
+
1320
+ - no → `inject`;
1321
+ - yes → optional lookup or a separate dependency-gated sub-plugin.
1322
+
1323
+ ---
1324
+
1325
+ ## 39. Never use YAML order as dependency order
1326
+
1327
+ Wrong assumption:
1328
+
1329
+ ```yaml
1330
+ - name: './provider.ts'
1331
+ - name: './consumer.ts'
1332
+ ```
1333
+
1334
+ Therefore provider loads first.
1335
+
1336
+ That is **not** the Cordis contract. Entries may start concurrently.
1337
+
1338
+ Correct dependency:
1339
+
1340
+ ```ts
1341
+ export const inject = ['myService']
1342
+ ```
1343
+
1344
+ `cordis.yml` says **what exists**. `inject` says **what must be ready before activation**.
1345
+
1346
+ ---
1347
+
1348
+ ## 40. Dynamic provider replacement
1349
+
1350
+ Suppose provider A and B implement the same service definition.
1351
+
1352
+ Consumer:
1353
+
1354
+ ```ts
1355
+ export const inject = ['translator']
1356
+
1357
+ export function apply(ctx: Context) {
1358
+ ctx.on('document/received', doc => {
1359
+ void ctx.translator.translate(doc.text)
1360
+ })
1361
+ }
1362
+ ```
1363
+
1364
+ Swap provider A for B in configuration.
1365
+
1366
+ Correct Cordis behavior:
1367
+
1368
+ ```text
1369
+ 1. old provider leaves
1370
+ 2. consumer's active episode unloads
1371
+ 3. consumer-owned listener disappears
1372
+ 4. new provider activates
1373
+ 5. consumer reactivates
1374
+ 6. listener is registered again against the new dependency environment
1375
+ ```
1376
+
1377
+ No stale provider reference survives if the plugin follows ownership rules.
1378
+
1379
+ ---
1380
+
1381
+ ## 41. Service definition / provider / consumer = capability seam
1382
+
1383
+ For a capability intended to have replaceable implementations, use three roles.
1384
+
1385
+ ```text
1386
+ Service Definition
1387
+ interface + request/result
1388
+ / \
1389
+ / \
1390
+ Provider Consumer
1391
+ implementation tool/feature/etc.
1392
+ ```
1393
+
1394
+ DeepSeek Harness's Bash family is the canonical pattern:
1395
+
1396
+ ```text
1397
+ dsh-shell → definition
1398
+
1399
+ dsh-bash-local → provider
1400
+
1401
+ dsh-tool-bash → consumer/model-facing tool
1402
+ ```
1403
+
1404
+ Provider and consumer depend on the definition. They should not depend on each other.
1405
+
1406
+ ---
1407
+
1408
+ ## 42. Do not split every tiny feature into three packages
1409
+
1410
+ Capability seams are valuable when implementations need to vary independently.
1411
+
1412
+ For a one-off tool whose implementation is unlikely to be replaced, this is enough:
1413
+
1414
+ ```text
1415
+ one plugin
1416
+ └── registers one tool
1417
+ ```
1418
+
1419
+ Split when you need:
1420
+
1421
+ - multiple providers;
1422
+ - environment-specific execution;
1423
+ - independent security/policy boundary;
1424
+ - independent API evolution;
1425
+ - multiple different consumers;
1426
+ - per-agent or per-group provider selection.
1427
+
1428
+ Architecture is not improved by package count alone.
1429
+
1430
+ ---
1431
+
1432
+ # Part VII - Events
1433
+
1434
+ ## 43. Service call vs event
1435
+
1436
+ Use a **Service method** when the caller knows which capability it wants and needs a result.
1437
+
1438
+ ```ts
1439
+ await ctx.shell.execute(request)
1440
+ ```
1441
+
1442
+ Use an **Event** when behavior is open to observers/interceptors and the producer should not know the consumers.
1443
+
1444
+ ```ts
1445
+ ctx.emit('stats/report', data)
1446
+ ```
1447
+
1448
+ Or:
1449
+
1450
+ ```ts
1451
+ await ctx.waterfall('policy/request', request, defaultHandler)
1452
+ ```
1453
+
1454
+ ---
1455
+
1456
+ ## 44. Declare typed events
1457
+
1458
+ ```ts
1459
+ import type { Context } from '@deepseek-ai/cordis'
1460
+
1461
+ declare module '@deepseek-ai/cordis' {
1462
+ interface Events {
1463
+ 'stats/report'(name: string, count: number): void
1464
+ }
1465
+ }
1466
+ ```
1467
+
1468
+ Then:
1469
+
1470
+ ```ts
1471
+ ctx.on('stats/report', (name, count) => {
1472
+ console.log(name, count)
1473
+ })
1474
+
1475
+ ctx.emit('stats/report', 'tool_call', 1)
1476
+ ```
1477
+
1478
+ The declaration merge gives compile-time typing. It does not automatically emit or register anything.
1479
+
1480
+ ---
1481
+
1482
+ ## 45. Event dispatch modes
1483
+
1484
+ ### `emit` - synchronous broadcast
1485
+
1486
+ ```ts
1487
+ ctx.emit('feature/changed', payload)
1488
+ ```
1489
+
1490
+ - listeners invoked synchronously;
1491
+ - values ignored;
1492
+ - returned promises not awaited.
1493
+
1494
+ Use for cheap observation/notification where asynchronous completion is not part of the producer contract.
1495
+
1496
+ ### `parallel` - await all listeners concurrently
1497
+
1498
+ ```ts
1499
+ await ctx.parallel('feature/flush', payload)
1500
+ ```
1501
+
1502
+ Use when all listeners must finish but do not depend on each other's order/results.
1503
+
1504
+ Current core aggregates failures after concurrent settlement.
1505
+
1506
+ ### `serial` - ordered async short-circuit
1507
+
1508
+ ```ts
1509
+ const result = await ctx.serial('feature/check', input)
1510
+ ```
1511
+
1512
+ Listeners run in registration order and are awaited. First value other than `null`, `false`, or `undefined` bails out.
1513
+
1514
+ ### `bail` - synchronous short-circuit
1515
+
1516
+ ```ts
1517
+ const result = ctx.bail('feature/check-sync', input)
1518
+ ```
1519
+
1520
+ Same bail condition, synchronous.
1521
+
1522
+ ### `waterfall` - around-middleware
1523
+
1524
+ ```ts
1525
+ const result = await ctx.waterfall(
1526
+ 'feature/transform',
1527
+ input,
1528
+ async () => defaultResult,
1529
+ )
1530
+ ```
1531
+
1532
+ Listeners wrap downstream behavior.
1533
+
1534
+ ---
1535
+
1536
+ ## 46. Waterfall: the most dangerous event mode to misuse
1537
+
1538
+ Example:
1539
+
1540
+ ```ts
1541
+ ctx.on('demo/transform', async (input, next) => {
1542
+ const result = await next()
1543
+ return result.trim()
1544
+ })
1545
+ ```
1546
+
1547
+ Another listener can intentionally intercept:
1548
+
1549
+ ```ts
1550
+ ctx.on('demo/transform', async (input, next) => {
1551
+ if (input.includes('blocked')) {
1552
+ return 'blocked'
1553
+ }
1554
+
1555
+ return next()
1556
+ })
1557
+ ```
1558
+
1559
+ ### Absolute rule
1560
+
1561
+ > A waterfall listener that is only observing, logging, measuring, or annotating must call `next()`.
1562
+
1563
+ Bad logger:
1564
+
1565
+ ```ts
1566
+ ctx.on('agent/request', async (req, next) => {
1567
+ console.log(req)
1568
+ // forgot next() - downstream model request is swallowed
1569
+ })
1570
+ ```
1571
+
1572
+ Correct:
1573
+
1574
+ ```ts
1575
+ ctx.on('agent/request', async (req, next) => {
1576
+ console.log(req)
1577
+ return next()
1578
+ })
1579
+ ```
1580
+
1581
+ Missing `next()` is a deliberate veto, not an innocent omission.
1582
+
1583
+ ---
1584
+
1585
+ ## 47. Event listeners are effects
1586
+
1587
+ ```ts
1588
+ ctx.on('tools/result', handler)
1589
+ ```
1590
+
1591
+ belongs to the current Fiber and is removed automatically when that Fiber unloads.
1592
+
1593
+ Do not add manual global listener cleanup around ordinary `ctx.on()` unless you are intentionally disposing the listener earlier than plugin lifetime.
1594
+
1595
+ ---
1596
+
1597
+ ## 48. Cordis events vs durable Harness session events
1598
+
1599
+ This distinction prevents many architectural mistakes.
1600
+
1601
+ ### Live Cordis events
1602
+
1603
+ Examples:
1604
+
1605
+ ```text
1606
+ agent/request
1607
+ tools/result
1608
+ approval/request
1609
+ session/event
1610
+ ```
1611
+
1612
+ These are runtime dispatch surfaces.
1613
+
1614
+ ### Durable session-event records
1615
+
1616
+ Examples:
1617
+
1618
+ ```text
1619
+ turn/start
1620
+ step/start
1621
+ user/message
1622
+ assistant/chunk
1623
+ assistant/message
1624
+ tool/call
1625
+ tool/result
1626
+ turn/end
1627
+ ```
1628
+
1629
+ These are facts stored in the session log.
1630
+
1631
+ Do not assume a durable event type automatically has a same-named Cordis event.
1632
+
1633
+ To observe the durable stream, listen to the session subsystem's runtime event and inspect record type:
1634
+
1635
+ ```ts
1636
+ ctx.on('session/event', event => {
1637
+ if (event.type === 'tool/result') {
1638
+ // durable session fact
1639
+ }
1640
+ })
1641
+ ```
1642
+
1643
+ ### Rule
1644
+
1645
+ **If model-visible or replay-critical state must survive reload, it belongs in durable session history-not only in a transient Cordis event.**
1646
+
1647
+ ---
1648
+
1649
+ # Part VIII - Plugin configuration
1650
+
1651
+ ## 49. Config type + runtime schema
1652
+
1653
+ Recommended pattern:
1654
+
1655
+ ```ts
1656
+ import type { Context } from '@deepseek-ai/cordis'
1657
+ import Schema from '@deepseek-ai/schemastery'
1658
+
1659
+ export interface Config {
1660
+ greeting: string
1661
+ maxRetries: number
1662
+ verbose: boolean
1663
+ }
1664
+
1665
+ export const Config: Schema<Config> = Schema.object({
1666
+ greeting: Schema.string().default('Hello'),
1667
+ maxRetries: Schema.number().default(3),
1668
+ verbose: Schema.boolean().default(false),
1669
+ })
1670
+
1671
+ export function apply(ctx: Context, config: Config) {
1672
+ console.log(config.greeting)
1673
+ }
1674
+ ```
1675
+
1676
+ A TypeScript interface is compile-time only.
1677
+
1678
+ The exported runtime `Config` schema validates input before activation.
1679
+
1680
+ ---
1681
+
1682
+ ## 50. Fail before partial activation
1683
+
1684
+ Bad configuration should prevent `apply()` from running.
1685
+
1686
+ This is desirable:
1687
+
1688
+ ```text
1689
+ raw config
1690
+ ↓
1691
+ validate + defaults
1692
+ ↓ invalid
1693
+ FAILED
1694
+ ```
1695
+
1696
+ rather than:
1697
+
1698
+ ```text
1699
+ apply half starts
1700
+ opens resources
1701
+ then discovers bad config
1702
+ then tries to recover manually
1703
+ ```
1704
+
1705
+ Use schema constraints for self-contained validation.
1706
+
1707
+ Use dependency-aware validation for resource/provider names that can only be resolved once services are active.
1708
+
1709
+ ---
1710
+
1711
+ ## 51. Tunable deployment values belong in config
1712
+
1713
+ Bad:
1714
+
1715
+ ```ts
1716
+ const TIMEOUT_MS = 30_000
1717
+ ```
1718
+
1719
+ if deployments may legitimately differ.
1720
+
1721
+ Better:
1722
+
1723
+ ```ts
1724
+ export interface Config {
1725
+ timeoutMs: number
1726
+ }
1727
+
1728
+ export const Config = Schema.object({
1729
+ timeoutMs: Schema.number().default(30_000),
1730
+ })
1731
+ ```
1732
+
1733
+ Rule:
1734
+
1735
+ > If two deployments may need different values, `cordis.yml` should be able to change it without editing source.
1736
+
1737
+ ---
1738
+
1739
+ ## 52. `!!js` computed configuration in Harness Loader
1740
+
1741
+ Harness's Loader/Include layer supports computed values in `config`:
1742
+
1743
+ ```yaml
1744
+ - id: demo
1745
+ name: './demo.ts'
1746
+ config:
1747
+ apiKey: !!js process.env.DEMO_API_KEY
1748
+ ```
1749
+
1750
+ And computed `disabled`:
1751
+
1752
+ ```yaml
1753
+ - id: platform-feature
1754
+ name: './platform-feature.ts'
1755
+ disabled: !!js process.platform !== 'darwin'
1756
+ ```
1757
+
1758
+ Important behavior in the current Harness patches:
1759
+
1760
+ - plugin `config` expressions are resolved lazily when declared injections are active, against that plugin context;
1761
+ - `disabled` is evaluated at mount decisions against Loader context;
1762
+ - other entry metadata stays literal;
1763
+ - nested Include rows preserve expressions until the owning row activates.
1764
+
1765
+ Do not assume arbitrary YAML fields execute JavaScript.
1766
+
1767
+ ---
1768
+
1769
+ ## 53. Config update and HMR
1770
+
1771
+ A config edit can cause the plugin's old activation episode to unload and the new one to activate.
1772
+
1773
+ That is why lifecycle-clean registrations matter even when source code never changes.
1774
+
1775
+ The test is:
1776
+
1777
+ ```text
1778
+ change config 20 times
1779
+ ```
1780
+
1781
+ and confirm there is still:
1782
+
1783
+ ```text
1784
+ one listener
1785
+ one tool registration
1786
+ one timer
1787
+ one provider
1788
+ ```
1789
+
1790
+ not 20 of each.
1791
+
1792
+ ---
1793
+
1794
+ # Part IX - `cordis.yml`, Loader, reconciliation, and HMR
1795
+
1796
+ ## 54. Minimal composition
1797
+
1798
+ ```yaml
1799
+ - name: './hello.ts'
1800
+ ```
1801
+
1802
+ Each row is a plugin entry.
1803
+
1804
+ A better long-lived config uses stable IDs:
1805
+
1806
+ ```yaml
1807
+ - id: hello
1808
+ name: './hello.ts'
1809
+ ```
1810
+
1811
+ ---
1812
+
1813
+ ## 55. Stable IDs are operationally important
1814
+
1815
+ Without a stable `id`, Loader may not be able to identify a row across configuration rereads as the same logical entry.
1816
+
1817
+ Use explicit IDs for application-level rows that should be reconciled rather than treated as unrelated removals/additions.
1818
+
1819
+ Good:
1820
+
1821
+ ```yaml
1822
+ - id: llm-provider
1823
+ name: './providers/deepseek.ts'
1824
+
1825
+ - id: my-tools
1826
+ name: './tools/index.ts'
1827
+ ```
1828
+
1829
+ ---
1830
+
1831
+ ## 56. `disabled`
1832
+
1833
+ Keep a row but prevent mounting:
1834
+
1835
+ ```yaml
1836
+ - id: experimental-feature
1837
+ name: './experimental.ts'
1838
+ disabled: true
1839
+ ```
1840
+
1841
+ Flip to false and dependency-gated consumers can activate as services appear.
1842
+
1843
+ This is preferable to commenting random pieces in and out when you want stable identity and patchability.
1844
+
1845
+ ---
1846
+
1847
+ ## 57. Groups and isolation
1848
+
1849
+ Harness docs show group-style composition for separate service realms.
1850
+
1851
+ Conceptual configuration:
1852
+
1853
+ ```yaml
1854
+ - id: group-a
1855
+ name: '@deepseek-ai/cordis-plugin-group'
1856
+ group: true
1857
+ isolate:
1858
+ shell: true
1859
+ config:
1860
+ - id: shell-a
1861
+ name: '@deepseek-ai/dsh-bash-local'
1862
+ config:
1863
+ timeoutMs: 5000
1864
+ - id: consumer-a
1865
+ name: './consumer-a.ts'
1866
+
1867
+ - id: group-b
1868
+ name: '@deepseek-ai/cordis-plugin-group'
1869
+ group: true
1870
+ isolate:
1871
+ shell: true
1872
+ config:
1873
+ - id: shell-b
1874
+ name: '@deepseek-ai/dsh-bash-local'
1875
+ config:
1876
+ timeoutMs: 60000
1877
+ - id: consumer-b
1878
+ name: './consumer-b.ts'
1879
+ ```
1880
+
1881
+ Both consumers inject `shell`, but service resolution is scoped.
1882
+
1883
+ ---
1884
+
1885
+ ## 58. HMR composition
1886
+
1887
+ Tutorial setup:
1888
+
1889
+ ```yaml
1890
+ - id: logger
1891
+ name: '@deepseek-ai/cordis-plugin-logger-console'
1892
+
1893
+ - id: timer
1894
+ name: '@deepseek-ai/cordis-plugin-timer'
1895
+
1896
+ - id: hmr
1897
+ name: '@deepseek-ai/cordis-plugin-hmr'
1898
+ config:
1899
+ root: ['.']
1900
+
1901
+ - id: hello
1902
+ name: './hello.ts'
1903
+ ```
1904
+
1905
+ HMR itself has dependencies. In the tutorial it needs the timer service for debounce and logs via Cordis logger.
1906
+
1907
+ This is a good illustration of Cordis philosophy: even the reload machinery participates in the same dependency system.
1908
+
1909
+ ---
1910
+
1911
+ ## 59. Harness-specific transactional reconciliation
1912
+
1913
+ DeepSeek Harness's vendored Loader/Include layer contains local hardening beyond the plain conceptual tutorial.
1914
+
1915
+ Its vendor manifest explicitly describes transactional behavior such as:
1916
+
1917
+ - import a changed candidate before disposing a working entry when possible;
1918
+ - await lifecycle settlement;
1919
+ - restore previous plugin/config when candidate application fails;
1920
+ - reconcile grouped changes and undo partial changes on failure;
1921
+ - validate Include candidate content before committing cached state;
1922
+ - serialize Include child-tree mutation;
1923
+ - keep failed dependencies `PENDING` rather than corrupting the live tree.
1924
+
1925
+ ### Why this matters
1926
+
1927
+ HMR safety depends on two layers:
1928
+
1929
+ ```text
1930
+ Loader reconciliation correctness
1931
+ +
1932
+ plugin effect/disposer correctness
1933
+ ```
1934
+
1935
+ Transactional Loader logic cannot save a plugin that leaked an unmanaged global timer or mutated an external singleton irreversibly.
1936
+
1937
+ ---
1938
+
1939
+ ## 60. HMR mental model
1940
+
1941
+ For a changed plugin:
1942
+
1943
+ ```text
1944
+ old code ACTIVE
1945
+ │
1946
+ ▼
1947
+ unload old activation
1948
+ │ cleanup effects
1949
+ ▼
1950
+ load candidate code
1951
+ │ validate/configure
1952
+ ▼
1953
+ ACTIVE new code
1954
+ ```
1955
+
1956
+ With Harness reconciliation, failed candidate application can be contained/restored in more cases.
1957
+
1958
+ ### Coding-agent requirement
1959
+
1960
+ A plugin must be written as if `apply()` can happen many times in one process.
1961
+
1962
+ If that assumption breaks the implementation, it is not HMR-safe.
1963
+
1964
+ ---
1965
+
1966
+ # Part X - DeepSeek Harness: Cordis becomes an agent runtime
1967
+
1968
+ ## 61. Agent Harness definition
1969
+
1970
+ An agent harness is the surrounding execution environment that turns a model into an operational agent.
1971
+
1972
+ It supplies things such as:
1973
+
1974
+ ```text
1975
+ system prompts
1976
+ model providers
1977
+ model-tool loop
1978
+ tools
1979
+ sessions/history
1980
+ permissions/approval
1981
+ storage
1982
+ filesystem/shell
1983
+ sandboxing
1984
+ background jobs
1985
+ agent coordination
1986
+ UI/CLI surfaces
1987
+ telemetry
1988
+ ```
1989
+
1990
+ Cordis manages composition. Harness defines these domain capabilities.
1991
+
1992
+ ---
1993
+
1994
+ ## 62. Important built-in Harness service names
1995
+
1996
+ The exact generated subsystem docs and TypeScript types are authoritative, but major current services include:
1997
+
1998
+ | Capability | Typical `ctx` key | Purpose |
1999
+ |---|---|---|
2000
+ | Session log/runtime | `ctx.sessions` | durable session event store, fork/resume primitives |
2001
+ | System prompt | `ctx.systemPrompt` | assembled prompt sections and tool schema contribution |
2002
+ | Tool runtime | `ctx.tools` | model-visible tool registry and guarded execution pipeline |
2003
+ | Live agents | `ctx.agents` | active agent handles and agent events |
2004
+ | Agent loop | `ctx.agentLoop` | default turn/step driver |
2005
+ | LLM | `ctx.llm` | provider-neutral generation and adapter routing |
2006
+ | Shell | `ctx.shell` | shell capability seam |
2007
+ | Filesystem | `ctx.fs` | filesystem capability seam |
2008
+ | Sandbox | `ctx.sandbox` | process/file confinement integration |
2009
+ | Jobs | `ctx.jobs` | durable-ish runtime ownership of background work |
2010
+ | Commands | `ctx.commands` | human/runtime commands that do not require model tool selection |
2011
+
2012
+ Before using any service, inspect its owning subsystem docs and package declarations because Harness is evolving quickly.
2013
+
2014
+ ---
2015
+
2016
+ ## 63. Turn and Step
2017
+
2018
+ Current Harness architecture defines:
2019
+
2020
+ ### Step
2021
+
2022
+ One model request plus the tool executions caused by the response.
2023
+
2024
+ ### Turn
2025
+
2026
+ Zero or more steps that drain one accepted input until no additional work is owed.
2027
+
2028
+ Simplified flow:
2029
+
2030
+ ```text
2031
+ turn/start
2032
+ claim input
2033
+ assemble prompt + tool schemas
2034
+ agent/pre-step
2035
+ step/start
2036
+ persist user/message
2037
+ derive model history
2038
+ agent/request
2039
+ llm/stream
2040
+ assistant/chunk*
2041
+ assistant/message
2042
+ tool/call*
2043
+ tools/pre-execute
2044
+ tools/execute
2045
+ tools/post-execute
2046
+ tool/result*
2047
+ step/end
2048
+ maybe another step
2049
+ agent/turn-stopping
2050
+ turn/end
2051
+ ```
2052
+
2053
+ ### “Round”
2054
+
2055
+ Do not treat `round` as a universal Cordis runtime primitive.
2056
+
2057
+ Where a strategy/outer-loop package uses “round,” follow that package's contract. In the current core architecture, **Turn** and **Step** are the primary loop terms.
2058
+
2059
+ ---
2060
+
2061
+ ## 64. “Everything is a plugin” does not mean “everything is a separate package”
2062
+
2063
+ It means major runtime capabilities can be mounted and replaced through the composition model.
2064
+
2065
+ Good plugin boundary:
2066
+
2067
+ ```text
2068
+ LLM provider
2069
+ filesystem provider
2070
+ permission policy
2071
+ tool family
2072
+ memory/context system
2073
+ agent loop strategy
2074
+ UI surface
2075
+ ```
2076
+
2077
+ Usually bad plugin boundary:
2078
+
2079
+ ```text
2080
+ one tiny pure helper function
2081
+ one constant
2082
+ one local data transform with no lifecycle/config/replacement need
2083
+ ```
2084
+
2085
+ Make a unit a plugin when lifecycle, replacement, configuration, ownership, or dependency topology matters.
2086
+
2087
+ ---
2088
+
2089
+ # Part XI - Tools: from Cordis plugin to model-callable capability
2090
+
2091
+ ## 65. A Tool is not a Cordis primitive
2092
+
2093
+ This distinction is fundamental.
2094
+
2095
+ Cordis provides:
2096
+
2097
+ ```text
2098
+ plugin
2099
+ service
2100
+ inject
2101
+ effect
2102
+ event
2103
+ scope
2104
+ fiber
2105
+ loader
2106
+ ```
2107
+
2108
+ Harness provides a **`tools` Service**.
2109
+
2110
+ A model-facing tool is registered into that service:
2111
+
2112
+ ```ts
2113
+ ctx.tools.register(...)
2114
+ ```
2115
+
2116
+ So a tool plugin is ordinary Cordis composition plus a Harness-specific registry operation.
2117
+
2118
+ ---
2119
+
2120
+ ## 66. Minimal tool
2121
+
2122
+ ```ts
2123
+ import type { Context } from '@deepseek-ai/cordis'
2124
+ import { defineTool } from '@deepseek-ai/dsh-tools'
2125
+
2126
+ export const name = 'greet-tool'
2127
+ export const inject = ['tools']
2128
+
2129
+ export function apply(ctx: Context) {
2130
+ ctx.tools.register(defineTool({
2131
+ name: 'greet',
2132
+ description: 'Greet someone by name.',
2133
+
2134
+ parameters: {
2135
+ name: {
2136
+ type: 'string',
2137
+ required: true,
2138
+ description: 'The name to greet',
2139
+ },
2140
+ },
2141
+
2142
+ output: {
2143
+ schema: { type: 'string' },
2144
+ render: (_args, value) => [
2145
+ { type: 'text', text: value },
2146
+ ],
2147
+ },
2148
+
2149
+ async execute(args) {
2150
+ return `Hello, ${args.name}!`
2151
+ },
2152
+ }))
2153
+ }
2154
+ ```
2155
+
2156
+ What happens:
2157
+
2158
+ ```text
2159
+ inject tools
2160
+ ↓
2161
+ plugin waits until ToolRuntime exists
2162
+ ↓
2163
+ register tool definition
2164
+ ↓
2165
+ registration becomes owned by plugin Fiber
2166
+ ↓
2167
+ Tool schema joins model-visible tool set
2168
+ ↓
2169
+ plugin unload
2170
+ ↓
2171
+ tool unregisters automatically
2172
+ ```
2173
+
2174
+ ---
2175
+
2176
+ ## 67. Tool definition anatomy
2177
+
2178
+ ```text
2179
+ name
2180
+ stable model-visible operation name
2181
+
2182
+ description
2183
+ tells model what the operation does
2184
+
2185
+ parameters
2186
+ validates and types model-supplied arguments
2187
+
2188
+ output.schema
2189
+ canonical programmatic value contract
2190
+
2191
+ execute(args, exec)
2192
+ does the real work
2193
+
2194
+ output.render(args, value)
2195
+ converts canonical value to model-facing Native content
2196
+
2197
+ presentation metadata / presenters (optional)
2198
+ UI replay/card concern, separate from canonical return
2199
+ ```
2200
+
2201
+ ---
2202
+
2203
+ ## 68. The canonical-value rule
2204
+
2205
+ A production tool should return a structured canonical value, not prose that other code must parse.
2206
+
2207
+ Bad:
2208
+
2209
+ ```ts
2210
+ return `Created file at ${path} with id ${id}`
2211
+ ```
2212
+
2213
+ if downstream code needs both fields.
2214
+
2215
+ Better:
2216
+
2217
+ ```ts
2218
+ output: {
2219
+ schema: {
2220
+ type: 'object',
2221
+ properties: {
2222
+ path: { type: 'string' },
2223
+ id: { type: 'string' },
2224
+ },
2225
+ required: ['path', 'id'],
2226
+ },
2227
+ render: (_args, value) => [{
2228
+ type: 'text',
2229
+ text: `Created ${value.path}`,
2230
+ }],
2231
+ },
2232
+
2233
+ async execute(args) {
2234
+ return { path, id }
2235
+ }
2236
+ ```
2237
+
2238
+ Programmatic truth belongs in the canonical value. Human/model formatting belongs in the renderer.
2239
+
2240
+ ---
2241
+
2242
+ ## 69. Tool argument validation
2243
+
2244
+ `defineTool` validates the model-generated arguments according to its parameter DSL before `execute()`.
2245
+
2246
+ Inside `execute`, TypeScript can infer argument types.
2247
+
2248
+ You still must validate semantic constraints not represented by the schema.
2249
+
2250
+ Example:
2251
+
2252
+ ```ts
2253
+ parameters: {
2254
+ limit: { type: 'number', required: true },
2255
+ }
2256
+
2257
+ async execute(args) {
2258
+ if (!Number.isInteger(args.limit) || args.limit <= 0) {
2259
+ throw new Error('limit must be a positive integer')
2260
+ }
2261
+ }
2262
+ ```
2263
+
2264
+ Do not assume a primitive type check expresses every business invariant.
2265
+
2266
+ ---
2267
+
2268
+ ## 70. Honor cancellation
2269
+
2270
+ Production tool:
2271
+
2272
+ ```ts
2273
+ async execute(args, exec) {
2274
+ return await readFile(args.path, {
2275
+ encoding: 'utf8',
2276
+ signal: exec.signal,
2277
+ })
2278
+ }
2279
+ ```
2280
+
2281
+ If a downstream API supports `AbortSignal`, pass `exec.signal`.
2282
+
2283
+ If it does not, write an adapter that cooperates with cancellation as far as possible.
2284
+
2285
+ Ignoring cancellation creates teardown and session-stopping problems.
2286
+
2287
+ ---
2288
+
2289
+ ## 71. Tool identity is runtime-owned
2290
+
2291
+ The tool execution runtime protects identity fields such as:
2292
+
2293
+ ```text
2294
+ callId
2295
+ name
2296
+ arguments
2297
+ agent
2298
+ token
2299
+ signal
2300
+ optional parent execution identity
2301
+ ```
2302
+
2303
+ Treat arguments as read-only input.
2304
+
2305
+ Do not mutate the registered tool definition after registration. To replace behavior, let the owning effect/plugin dispose and register a replacement.
2306
+
2307
+ That is the Cordis way:
2308
+
2309
+ ```text
2310
+ replace component
2311
+ not mutate hidden shared definition in place
2312
+ ```
2313
+
2314
+ ---
2315
+
2316
+ ## 72. Tool error behavior
2317
+
2318
+ Infrastructure failure should throw.
2319
+
2320
+ A domain-successful but nonideal outcome should often remain a valid canonical value.
2321
+
2322
+ Example Bash:
2323
+
2324
+ ```text
2325
+ process exited code 2
2326
+ ```
2327
+
2328
+ can still be a successfully executed tool whose canonical result contains `exitCode: 2`, rather than an infrastructure exception.
2329
+
2330
+ Use exceptions for failure of the tool execution contract itself.
2331
+
2332
+ ---
2333
+
2334
+ ## 73. Tool execution policy extension points
2335
+
2336
+ Harness exposes a pipeline around tool execution.
2337
+
2338
+ Conceptually:
2339
+
2340
+ ```text
2341
+ tool call
2342
+ ↓
2343
+ tools/pre-execute
2344
+ ↓
2345
+ tools/execute ← around-dispatch wrappers
2346
+ ↓
2347
+ actual tool body
2348
+ ↓
2349
+ tools/post-execute
2350
+ ↓
2351
+ normalized result
2352
+ ↓
2353
+ tools/result ← observation
2354
+ ```
2355
+
2356
+ Typical uses:
2357
+
2358
+ ### `tools/pre-execute`
2359
+
2360
+ - permission decision;
2361
+ - allow/deny/ask policy;
2362
+ - argument policy.
2363
+
2364
+ ### `ctx.tools.guard()`
2365
+
2366
+ A final monotonic deny mechanism where appropriate. A later extension should not be able to undo the denial.
2367
+
2368
+ ### `tools/execute`
2369
+
2370
+ Around behavior:
2371
+
2372
+ - timeout;
2373
+ - tracing;
2374
+ - metrics;
2375
+ - retry when semantically safe;
2376
+ - execution wrapping.
2377
+
2378
+ Remember waterfall semantics: delegate with `next()` unless intentionally replacing/vetoing.
2379
+
2380
+ ### `tools/post-execute`
2381
+
2382
+ - presentation adjustment;
2383
+ - attach model context;
2384
+ - confidentiality filtering;
2385
+ - result transformation under the subsystem contract.
2386
+
2387
+ ### `tools/result`
2388
+
2389
+ Observe normalized immutable outcome.
2390
+
2391
+ Good for:
2392
+
2393
+ - telemetry;
2394
+ - logs;
2395
+ - counters;
2396
+ - analytics;
2397
+ - non-mutating observers.
2398
+
2399
+ ---
2400
+
2401
+ ## 74. Tool observer example
2402
+
2403
+ ```ts
2404
+ import type { Context } from '@deepseek-ai/cordis'
2405
+ import type {} from '@deepseek-ai/dsh-tools'
2406
+
2407
+ export const name = 'tool-logger'
2408
+ export const inject = ['tools']
2409
+
2410
+ export function apply(ctx: Context) {
2411
+ ctx.on('tools/result', (exec, result) => {
2412
+ const text = result.content
2413
+ .map(block => block.type === 'text' ? block.text : '')
2414
+ .join('')
2415
+
2416
+ console.log(`[tool] ${exec.name} -> ${text.slice(0, 120)}`)
2417
+ })
2418
+ }
2419
+ ```
2420
+
2421
+ Because `ctx.on()` is an effect, HMR does not accumulate duplicate observers.
2422
+
2423
+ ---
2424
+
2425
+ ## 75. Code Mode
2426
+
2427
+ Harness can expose registered visible tools programmatically through Code Mode, conceptually:
2428
+
2429
+ ```ts
2430
+ await tools.some_tool(args)
2431
+ ```
2432
+
2433
+ The key architecture property is that the call re-enters the normal tool pipeline rather than bypassing policy/lifecycle.
2434
+
2435
+ Code Mode receives the canonical value, not the rendered prose content.
2436
+
2437
+ Therefore canonical output schemas are APIs, not only display metadata.
2438
+
2439
+ ---
2440
+
2441
+ ## 76. Background work
2442
+
2443
+ Long-running work should not be implemented by returning from a tool while a detached promise keeps mutating state.
2444
+
2445
+ Harness provides a jobs capability for published background work.
2446
+
2447
+ Follow the jobs subsystem pattern so:
2448
+
2449
+ - work has an owner;
2450
+ - it has an ID;
2451
+ - cancellation semantics are explicit;
2452
+ - owner disposal can clean it;
2453
+ - output/read lifecycle is bounded;
2454
+ - the tool returns a canonical handle.
2455
+
2456
+ The outer tool's `exec.signal` is appropriate for foreground work. Once background work is formally published, its task-owned cancellation lifecycle takes over according to the jobs contract.
2457
+
2458
+ ---
2459
+
2460
+ # Part XII - LLM adapters
2461
+
2462
+ ## 77. LLM adapter role
2463
+
2464
+ The LLM subsystem is another capability seam.
2465
+
2466
+ A provider adapter translates:
2467
+
2468
+ ```text
2469
+ Harness GenerateOptions
2470
+ ↓
2471
+ provider-specific API request
2472
+ ↓
2473
+ provider stream
2474
+ ↓
2475
+ Harness StreamChunk protocol
2476
+ ```
2477
+
2478
+ The agent loop should not know provider SDK details.
2479
+
2480
+ ---
2481
+
2482
+ ## 78. Minimal adapter skeleton
2483
+
2484
+ ```ts
2485
+ import type { Context } from '@deepseek-ai/cordis'
2486
+ import Schema from '@deepseek-ai/schemastery'
2487
+ import {
2488
+ LlmAdapter,
2489
+ type GenerateOptions,
2490
+ type StreamChunk,
2491
+ } from '@deepseek-ai/dsh-llm'
2492
+
2493
+ class MyAdapter extends LlmAdapter {
2494
+ constructor(private apiKey: string) {
2495
+ super()
2496
+ }
2497
+
2498
+ async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
2499
+ // 1. translate options -> provider request
2500
+ // 2. stream provider response
2501
+ // 3. yield valid Harness chunks
2502
+ }
2503
+ }
2504
+
2505
+ export interface Config {
2506
+ apiKey: string
2507
+ providers: string[]
2508
+ }
2509
+
2510
+ export const Config: Schema<Config> = Schema.object({
2511
+ apiKey: Schema.string().required(),
2512
+ providers: Schema.array(Schema.string()).required(),
2513
+ })
2514
+
2515
+ export const name = 'my-llm-adapter'
2516
+ export const inject = ['llm']
2517
+
2518
+ export function apply(ctx: Context, config: Config) {
2519
+ const adapter = new MyAdapter(config.apiKey)
2520
+ ctx.llm.registerAdapter(config.providers, adapter)
2521
+ }
2522
+ ```
2523
+
2524
+ The registration belongs to the adapter plugin's Fiber.
2525
+
2526
+ ---
2527
+
2528
+ ## 79. StreamChunk protocol
2529
+
2530
+ Canonical text stream:
2531
+
2532
+ ```ts
2533
+ async function* stream(): AsyncIterable<StreamChunk> {
2534
+ yield {
2535
+ type: 'block-start',
2536
+ index: 0,
2537
+ blockType: 'text',
2538
+ }
2539
+
2540
+ yield {
2541
+ type: 'text-delta',
2542
+ index: 0,
2543
+ text: 'Hello',
2544
+ }
2545
+
2546
+ yield {
2547
+ type: 'text-delta',
2548
+ index: 0,
2549
+ text: ' world',
2550
+ }
2551
+
2552
+ yield {
2553
+ type: 'block-end',
2554
+ index: 0,
2555
+ block: {
2556
+ type: 'text',
2557
+ text: 'Hello world',
2558
+ },
2559
+ }
2560
+
2561
+ yield {
2562
+ type: 'usage',
2563
+ usage: {
2564
+ inputTokens: 100,
2565
+ outputTokens: 2,
2566
+ },
2567
+ }
2568
+
2569
+ yield {
2570
+ type: 'finish',
2571
+ reason: { kind: 'stop' },
2572
+ }
2573
+ }
2574
+ ```
2575
+
2576
+ Tool-call block pattern:
2577
+
2578
+ ```ts
2579
+ yield {
2580
+ type: 'block-start',
2581
+ index: 1,
2582
+ blockType: 'tool-call',
2583
+ }
2584
+
2585
+ yield {
2586
+ type: 'tool-call-delta',
2587
+ index: 1,
2588
+ id: CallId('call-123'),
2589
+ name: 'greet',
2590
+ argumentsDelta: '{"name":"Ada"}',
2591
+ }
2592
+
2593
+ yield {
2594
+ type: 'block-end',
2595
+ index: 1,
2596
+ block: {
2597
+ type: 'tool-call',
2598
+ id: CallId('call-123'),
2599
+ name: 'greet',
2600
+ arguments: '{"name":"Ada"}',
2601
+ },
2602
+ }
2603
+
2604
+ yield {
2605
+ type: 'finish',
2606
+ reason: { kind: 'tool-calls' },
2607
+ }
2608
+ ```
2609
+
2610
+ Rules:
2611
+
2612
+ ```text
2613
+ [ ] block-start has matching block-end
2614
+ [ ] index identifies content-block order
2615
+ [ ] tool-call argumentsDelta is raw JSON text
2616
+ [ ] usage precedes finish
2617
+ [ ] finish is the final chunk
2618
+ ```
2619
+
2620
+ ---
2621
+
2622
+ ## 80. Adapter errors and cancellation
2623
+
2624
+ Provider failures should become stable Harness LLM errors, not arbitrary silent fallbacks.
2625
+
2626
+ Pattern:
2627
+
2628
+ ```ts
2629
+ import {
2630
+ attributionHeaders,
2631
+ LlmAdapter,
2632
+ LlmError,
2633
+ } from '@deepseek-ai/dsh-llm'
2634
+
2635
+ class HttpAdapter extends LlmAdapter {
2636
+ async *stream(options: GenerateOptions) {
2637
+ const response = await fetch(this.endpoint, {
2638
+ method: 'POST',
2639
+ headers: {
2640
+ 'content-type': 'application/json',
2641
+ ...attributionHeaders(),
2642
+ },
2643
+ body: JSON.stringify({
2644
+ model: options.model,
2645
+ messages: options.messages,
2646
+ }),
2647
+ signal: options.signal,
2648
+ })
2649
+
2650
+ if (!response.ok) {
2651
+ throw new LlmError(
2652
+ `Provider API error: ${response.status}`,
2653
+ 'PROVIDER_HTTP_ERROR',
2654
+ )
2655
+ }
2656
+
2657
+ // parse stream...
2658
+ }
2659
+ }
2660
+ ```
2661
+
2662
+ ### Rule
2663
+
2664
+ If Harness supplies cancellation, forward it to the provider SDK/request.
2665
+
2666
+ Do not silently drop unsupported explicit generation fields. Follow the adapter contract and fail with a meaningful stable error when the provider cannot honor a required option.
2667
+
2668
+ ---
2669
+
2670
+ # Part XIII - An end-to-end hands-on Cordis mini-system
2671
+
2672
+ ## 81. Goal
2673
+
2674
+ Build a small replaceable capability from scratch:
2675
+
2676
+ ```text
2677
+ TextTransform service definition
2678
+ │
2679
+ ├── Uppercase provider
2680
+ └── Lowercase provider
2681
+
2682
+ Transform tool consumer
2683
+
2684
+ Metrics observer
2685
+
2686
+ cordis.yml chooses provider
2687
+
2688
+ HMR/provider swap demonstrates reactivity
2689
+ ```
2690
+
2691
+ This example intentionally mirrors a real agent capability seam while remaining keyless and deterministic.
2692
+
2693
+ ---
2694
+
2695
+ ## 82. Setup against DeepSeek Harness checkout
2696
+
2697
+ From repository root:
2698
+
2699
+ ```sh
2700
+ pnpm install
2701
+ mkdir -p tmp/cordis-system-guide
2702
+ cd tmp/cordis-system-guide
2703
+ ```
2704
+
2705
+ Run tutorial compositions with:
2706
+
2707
+ ```sh
2708
+ node --import tsx ../../vendor/cordis/bin.js
2709
+ ```
2710
+
2711
+ The launcher creates the root Context, mounts Loader, and reads `./cordis.yml`.
2712
+
2713
+ ---
2714
+
2715
+ ## 83. Step 1 - first plugin
2716
+
2717
+ Create `hello.ts`:
2718
+
2719
+ ```ts
2720
+ import type { Context } from '@deepseek-ai/cordis'
2721
+
2722
+ export const name = 'hello'
2723
+
2724
+ export function apply(ctx: Context) {
2725
+ console.log('[hello] active')
2726
+ }
2727
+ ```
2728
+
2729
+ `cordis.yml`:
2730
+
2731
+ ```yaml
2732
+ - id: hello
2733
+ name: './hello.ts'
2734
+ ```
2735
+
2736
+ Run:
2737
+
2738
+ ```sh
2739
+ node --import tsx ../../vendor/cordis/bin.js
2740
+ ```
2741
+
2742
+ Expected:
2743
+
2744
+ ```text
2745
+ [hello] active
2746
+ ```
2747
+
2748
+ ---
2749
+
2750
+ ## 84. Step 2 - add an owned effect
2751
+
2752
+ Create `heartbeat.ts`:
2753
+
2754
+ ```ts
2755
+ import type { Context } from '@deepseek-ai/cordis'
2756
+
2757
+ export const name = 'heartbeat'
2758
+
2759
+ export function apply(ctx: Context) {
2760
+ ctx.effect(() => {
2761
+ const timer = setInterval(() => {
2762
+ console.log('[heartbeat] tick')
2763
+ }, 1000)
2764
+
2765
+ return () => {
2766
+ clearInterval(timer)
2767
+ console.log('[heartbeat] disposed')
2768
+ }
2769
+ })
2770
+ }
2771
+ ```
2772
+
2773
+ Add it:
2774
+
2775
+ ```yaml
2776
+ - id: heartbeat
2777
+ name: './heartbeat.ts'
2778
+ ```
2779
+
2780
+ Now HMR/disabling this plugin can stop the timer cleanly.
2781
+
2782
+ ---
2783
+
2784
+ ## 85. Step 3 - define the service contract
2785
+
2786
+ Create `transform-service.ts`:
2787
+
2788
+ ```ts
2789
+ import { Service, type Context } from '@deepseek-ai/cordis'
2790
+
2791
+ export interface TransformRequest {
2792
+ text: string
2793
+ }
2794
+
2795
+ export interface TransformResult {
2796
+ text: string
2797
+ provider: string
2798
+ }
2799
+
2800
+ declare module '@deepseek-ai/cordis' {
2801
+ interface Context {
2802
+ textTransform: TextTransformService
2803
+ }
2804
+ }
2805
+
2806
+ export abstract class TextTransformService extends Service {
2807
+ constructor(ctx: Context) {
2808
+ super(ctx, 'textTransform')
2809
+ }
2810
+
2811
+ abstract transform(
2812
+ request: TransformRequest,
2813
+ ): Promise<TransformResult>
2814
+ }
2815
+ ```
2816
+
2817
+ This file defines the **stable capability API**.
2818
+
2819
+ It does not choose an implementation.
2820
+
2821
+ ---
2822
+
2823
+ ## 86. Step 4 - provider A
2824
+
2825
+ Create `transform-uppercase.ts`:
2826
+
2827
+ ```ts
2828
+ import type { Context } from '@deepseek-ai/cordis'
2829
+ import {
2830
+ TextTransformService,
2831
+ type TransformRequest,
2832
+ type TransformResult,
2833
+ } from './transform-service.ts'
2834
+
2835
+ class UppercaseTransform extends TextTransformService {
2836
+ async transform(
2837
+ request: TransformRequest,
2838
+ ): Promise<TransformResult> {
2839
+ return {
2840
+ text: request.text.toUpperCase(),
2841
+ provider: 'uppercase',
2842
+ }
2843
+ }
2844
+ }
2845
+
2846
+ export const name = 'transform-uppercase'
2847
+
2848
+ export function apply(ctx: Context) {
2849
+ ctx.plugin(UppercaseTransform)
2850
+ }
2851
+ ```
2852
+
2853
+ Add:
2854
+
2855
+ ```yaml
2856
+ - id: transform-provider
2857
+ name: './transform-uppercase.ts'
2858
+ ```
2859
+
2860
+ ---
2861
+
2862
+ ## 87. Step 5 - direct service consumer
2863
+
2864
+ Create `transform-consumer.ts`:
2865
+
2866
+ ```ts
2867
+ import type { Context } from '@deepseek-ai/cordis'
2868
+ import type {} from './transform-service.ts'
2869
+
2870
+ export const name = 'transform-consumer'
2871
+ export const inject = ['textTransform']
2872
+
2873
+ export function apply(ctx: Context) {
2874
+ void ctx.textTransform
2875
+ .transform({ text: 'Cordis' })
2876
+ .then(result => {
2877
+ console.log('[consumer]', result)
2878
+ })
2879
+ }
2880
+ ```
2881
+
2882
+ Add:
2883
+
2884
+ ```yaml
2885
+ - id: transform-consumer
2886
+ name: './transform-consumer.ts'
2887
+ ```
2888
+
2889
+ Load order does not matter. `inject` is the dependency.
2890
+
2891
+ ---
2892
+
2893
+ ## 88. Step 6 - declare an event
2894
+
2895
+ Add to `transform-service.ts`:
2896
+
2897
+ ```ts
2898
+ declare module '@deepseek-ai/cordis' {
2899
+ interface Context {
2900
+ textTransform: TextTransformService
2901
+ }
2902
+
2903
+ interface Events {
2904
+ 'text-transform/result'(result: TransformResult): void
2905
+ }
2906
+ }
2907
+ ```
2908
+
2909
+ Update provider:
2910
+
2911
+ ```ts
2912
+ class UppercaseTransform extends TextTransformService {
2913
+ async transform(request: TransformRequest): Promise<TransformResult> {
2914
+ const result = {
2915
+ text: request.text.toUpperCase(),
2916
+ provider: 'uppercase',
2917
+ }
2918
+
2919
+ this.ctx.emit('text-transform/result', result)
2920
+ return result
2921
+ }
2922
+ }
2923
+ ```
2924
+
2925
+ Because `ctx` in `Service` is protected, the subclass can use it.
2926
+
2927
+ ---
2928
+
2929
+ ## 89. Step 7 - event observer
2930
+
2931
+ Create `transform-metrics.ts`:
2932
+
2933
+ ```ts
2934
+ import type { Context } from '@deepseek-ai/cordis'
2935
+ import type {} from './transform-service.ts'
2936
+
2937
+ export const name = 'transform-metrics'
2938
+
2939
+ export function apply(ctx: Context) {
2940
+ let count = 0
2941
+
2942
+ ctx.on('text-transform/result', result => {
2943
+ count += 1
2944
+ console.log(
2945
+ `[metrics] count=${count} provider=${result.provider}`,
2946
+ )
2947
+ })
2948
+ }
2949
+ ```
2950
+
2951
+ Add:
2952
+
2953
+ ```yaml
2954
+ - id: transform-metrics
2955
+ name: './transform-metrics.ts'
2956
+ ```
2957
+
2958
+ The observer does not need to know provider or consumer packages.
2959
+
2960
+ ---
2961
+
2962
+ ## 90. Step 8 - make provider configurable
2963
+
2964
+ Update `transform-uppercase.ts`:
2965
+
2966
+ ```ts
2967
+ import Schema from '@deepseek-ai/schemastery'
2968
+
2969
+ export interface Config {
2970
+ prefix: string
2971
+ }
2972
+
2973
+ export const Config: Schema<Config> = Schema.object({
2974
+ prefix: Schema.string().default(''),
2975
+ })
2976
+
2977
+ class UppercaseTransform extends TextTransformService {
2978
+ constructor(
2979
+ ctx: Context,
2980
+ private prefix: string,
2981
+ ) {
2982
+ super(ctx)
2983
+ }
2984
+
2985
+ async transform(request: TransformRequest): Promise<TransformResult> {
2986
+ const result = {
2987
+ text: this.prefix + request.text.toUpperCase(),
2988
+ provider: 'uppercase',
2989
+ }
2990
+
2991
+ this.ctx.emit('text-transform/result', result)
2992
+ return result
2993
+ }
2994
+ }
2995
+
2996
+ export function apply(ctx: Context, config: Config) {
2997
+ ctx.plugin(class Provider extends UppercaseTransform {
2998
+ constructor(childCtx: Context) {
2999
+ super(childCtx, config.prefix)
3000
+ }
3001
+ })
3002
+ }
3003
+ ```
3004
+
3005
+ For production code, prefer a simpler named provider class/factory structure rather than an anonymous class if diagnostics/type ergonomics suffer. The point is that deployment-specific values come from validated config.
3006
+
3007
+ YAML:
3008
+
3009
+ ```yaml
3010
+ - id: transform-provider
3011
+ name: './transform-uppercase.ts'
3012
+ config:
3013
+ prefix: '[UP] '
3014
+ ```
3015
+
3016
+ ---
3017
+
3018
+ ## 91. Step 9 - add the Harness Tool consumer
3019
+
3020
+ Create `transform-tool.ts`:
3021
+
3022
+ ```ts
3023
+ import type { Context } from '@deepseek-ai/cordis'
3024
+ import { defineTool } from '@deepseek-ai/dsh-tools'
3025
+ import type {} from './transform-service.ts'
3026
+
3027
+ export const name = 'transform-tool'
3028
+ export const inject = ['tools', 'textTransform']
3029
+
3030
+ export function apply(ctx: Context) {
3031
+ ctx.tools.register(defineTool({
3032
+ name: 'transform_text',
3033
+ description: 'Transform text using the configured text-transform provider.',
3034
+
3035
+ parameters: {
3036
+ text: {
3037
+ type: 'string',
3038
+ required: true,
3039
+ description: 'Text to transform',
3040
+ },
3041
+ },
3042
+
3043
+ output: {
3044
+ schema: {
3045
+ type: 'object',
3046
+ properties: {
3047
+ text: { type: 'string' },
3048
+ provider: { type: 'string' },
3049
+ },
3050
+ required: ['text', 'provider'],
3051
+ },
3052
+
3053
+ render: (_args, value) => [{
3054
+ type: 'text',
3055
+ text: `${value.text}\n(provider: ${value.provider})`,
3056
+ }],
3057
+ },
3058
+
3059
+ async execute(args, exec) {
3060
+ if (exec.signal.aborted) {
3061
+ throw exec.signal.reason ?? new Error('aborted')
3062
+ }
3063
+
3064
+ return ctx.textTransform.transform({
3065
+ text: args.text,
3066
+ })
3067
+ },
3068
+ }))
3069
+ }
3070
+ ```
3071
+
3072
+ This plugin requires two independent services:
3073
+
3074
+ ```text
3075
+ tools
3076
+ textTransform
3077
+ ```
3078
+
3079
+ It activates only while both are present.
3080
+
3081
+ ---
3082
+
3083
+ ## 92. Step 10 - compose with real Harness tool runtime
3084
+
3085
+ Minimal keyless tool-pipeline composition from the official tutorial requires system prompt + tools:
3086
+
3087
+ ```yaml
3088
+ - id: system-prompt
3089
+ name: '@deepseek-ai/dsh-system-prompt'
3090
+
3091
+ - id: tools
3092
+ name: '@deepseek-ai/dsh-tools'
3093
+
3094
+ - id: transform-provider
3095
+ name: './transform-uppercase.ts'
3096
+ config:
3097
+ prefix: '[UP] '
3098
+
3099
+ - id: transform-metrics
3100
+ name: './transform-metrics.ts'
3101
+
3102
+ - id: transform-tool
3103
+ name: './transform-tool.ts'
3104
+ ```
3105
+
3106
+ Why `system-prompt`?
3107
+
3108
+ The tools service contributes schemas to system-prompt assembly and therefore has its own injection requirements.
3109
+
3110
+ When a subsystem stays `PENDING`, inspect **its dependencies too**, not only your plugin's.
3111
+
3112
+ ---
3113
+
3114
+ ## 93. Step 11 - provider B
3115
+
3116
+ Create `transform-lowercase.ts`:
3117
+
3118
+ ```ts
3119
+ import type { Context } from '@deepseek-ai/cordis'
3120
+ import {
3121
+ TextTransformService,
3122
+ type TransformRequest,
3123
+ type TransformResult,
3124
+ } from './transform-service.ts'
3125
+
3126
+ class LowercaseTransform extends TextTransformService {
3127
+ async transform(
3128
+ request: TransformRequest,
3129
+ ): Promise<TransformResult> {
3130
+ const result = {
3131
+ text: request.text.toLowerCase(),
3132
+ provider: 'lowercase',
3133
+ }
3134
+
3135
+ this.ctx.emit('text-transform/result', result)
3136
+ return result
3137
+ }
3138
+ }
3139
+
3140
+ export const name = 'transform-lowercase'
3141
+
3142
+ export function apply(ctx: Context) {
3143
+ ctx.plugin(LowercaseTransform)
3144
+ }
3145
+ ```
3146
+
3147
+ Now change only the provider row:
3148
+
3149
+ ```yaml
3150
+ - id: transform-provider
3151
+ name: './transform-lowercase.ts'
3152
+ ```
3153
+
3154
+ The service name stays:
3155
+
3156
+ ```text
3157
+ textTransform
3158
+ ```
3159
+
3160
+ but provider identity changes.
3161
+
3162
+ Consumers injecting it are reconciled to the new capability environment.
3163
+
3164
+ That is spatial composability in practical form.
3165
+
3166
+ ---
3167
+
3168
+ ## 94. Step 12 - deliberately remove the provider
3169
+
3170
+ Disable it:
3171
+
3172
+ ```yaml
3173
+ - id: transform-provider
3174
+ name: './transform-lowercase.ts'
3175
+ disabled: true
3176
+ ```
3177
+
3178
+ Expected conceptual state:
3179
+
3180
+ ```text
3181
+ transform-provider → not active
3182
+ transform-consumer → PENDING
3183
+ transform-tool → PENDING because textTransform missing
3184
+ metrics observer → can remain ACTIVE because it does not require textTransform
3185
+ ```
3186
+
3187
+ Re-enable provider and consumers can reactivate.
3188
+
3189
+ ---
3190
+
3191
+ ## 95. Step 13 - verify no duplicate registrations
3192
+
3193
+ With HMR running, edit provider/tool several times.
3194
+
3195
+ Verify:
3196
+
3197
+ ```text
3198
+ [ ] transform_text appears once
3199
+ [ ] metrics listener runs once per result
3200
+ [ ] no old provider is called
3201
+ [ ] no old timer/watch survives
3202
+ [ ] provider swap changes output immediately after reconciliation
3203
+ ```
3204
+
3205
+ If duplicate behavior appears, find the unmanaged effect.
3206
+
3207
+ ---
3208
+
3209
+ # Part XIV - Three-role capability design for real systems
3210
+
3211
+ ## 96. Package layout
3212
+
3213
+ For a mature capability:
3214
+
3215
+ ```text
3216
+ packages/
3217
+ my-cap/
3218
+ definition/
3219
+ src/index.ts
3220
+ provider-local/
3221
+ src/index.ts
3222
+ provider-remote/
3223
+ src/index.ts
3224
+ tool-my-cap/
3225
+ src/index.ts
3226
+ ```
3227
+
3228
+ Definition:
3229
+
3230
+ ```text
3231
+ service class/interface
3232
+ request/result types
3233
+ shared stable domain vocabulary
3234
+ ```
3235
+
3236
+ Provider:
3237
+
3238
+ ```text
3239
+ implementation
3240
+ environment-specific config
3241
+ resource ownership
3242
+ ```
3243
+
3244
+ Consumer:
3245
+
3246
+ ```text
3247
+ tool
3248
+ agent behavior
3249
+ UI bridge
3250
+ workflow
3251
+ ```
3252
+
3253
+ ---
3254
+
3255
+ ## 97. The Definition owns the contract
3256
+
3257
+ Bad dependency graph:
3258
+
3259
+ ```text
3260
+ tool imports local provider
3261
+ remote provider imports tool types
3262
+ ```
3263
+
3264
+ Good:
3265
+
3266
+ ```text
3267
+ provider-local ─┐
3268
+ provider-remote ├──► definition
3269
+ consumer-tool ──┘
3270
+ ```
3271
+
3272
+ This is what makes replacement credible rather than nominal.
3273
+
3274
+ ---
3275
+
3276
+ ## 98. Resolve defaults explicitly
3277
+
3278
+ For a complex capability, do not smear fallback logic throughout execution:
3279
+
3280
+ ```ts
3281
+ const timeout = req.timeout ?? config.timeout ?? 30_000
3282
+ const cwd = req.cwd ?? config.cwd ?? process.cwd()
3283
+ ```
3284
+
3285
+ Prefer an explicit resolution phase:
3286
+
3287
+ ```ts
3288
+ interface ResolvedSpec {
3289
+ timeoutMs: number
3290
+ cwd: string
3291
+ }
3292
+
3293
+ function resolveRequest(
3294
+ request: Request,
3295
+ config: Config,
3296
+ ): ResolvedSpec {
3297
+ return {
3298
+ timeoutMs: request.timeoutMs ?? config.timeoutMs,
3299
+ cwd: request.cwd ?? config.cwd,
3300
+ }
3301
+ }
3302
+ ```
3303
+
3304
+ Then execution uses the resolved spec.
3305
+
3306
+ This improves testability, diagnostics, and provider parity.
3307
+
3308
+ ---
3309
+
3310
+ # Part XV - Profiles, bundles, patches, and publishing
3311
+
3312
+ ## 99. Bundle vs Profile
3313
+
3314
+ ### Bundle
3315
+
3316
+ An npm package that contributes a configuration layer.
3317
+
3318
+ Manifest:
3319
+
3320
+ ```json
3321
+ {
3322
+ "dsh": {
3323
+ "bundle": {
3324
+ "patch": "./cordis.patch.yml"
3325
+ }
3326
+ }
3327
+ }
3328
+ ```
3329
+
3330
+ Answers:
3331
+
3332
+ ```text
3333
+ “What does this package contribute to a composition?”
3334
+ ```
3335
+
3336
+ ### Profile
3337
+
3338
+ A runnable named composition under Harness home.
3339
+
3340
+ Manifest concept:
3341
+
3342
+ ```json
3343
+ {
3344
+ "dsh": {
3345
+ "profile": {
3346
+ "bundles": [
3347
+ "@deepseek-ai/dsh-base",
3348
+ "my-bundle"
3349
+ ]
3350
+ }
3351
+ }
3352
+ }
3353
+ ```
3354
+
3355
+ Answers:
3356
+
3357
+ ```text
3358
+ “Which bundles compose this runtime, in what layer order?”
3359
+ ```
3360
+
3361
+ A bundle and a profile are different roles.
3362
+
3363
+ ---
3364
+
3365
+ ## 100. Bundle structure
3366
+
3367
+ Example:
3368
+
3369
+ ```text
3370
+ my-plugin/
3371
+ ├── package.json
3372
+ ├── cordis.patch.yml
3373
+ └── index.js
3374
+ ```
3375
+
3376
+ `package.json`:
3377
+
3378
+ ```json
3379
+ {
3380
+ "name": "dsh-my-plugin",
3381
+ "version": "0.1.0",
3382
+ "type": "module",
3383
+ "main": "index.js",
3384
+ "files": ["index.js", "cordis.patch.yml"],
3385
+ "dsh": {
3386
+ "bundle": {
3387
+ "patch": "./cordis.patch.yml"
3388
+ }
3389
+ }
3390
+ }
3391
+ ```
3392
+
3393
+ `cordis.patch.yml`:
3394
+
3395
+ ```yaml
3396
+ - insert:
3397
+ - id: my-plugin
3398
+ name: dsh-my-plugin
3399
+ ```
3400
+
3401
+ ---
3402
+
3403
+ ## 101. Install into a profile
3404
+
3405
+ ```sh
3406
+ dsh plugin --profile demo add ./my-plugin
3407
+ ```
3408
+
3409
+ Inspect effective config:
3410
+
3411
+ ```sh
3412
+ dsh --profile demo --dump-config
3413
+ ```
3414
+
3415
+ Run:
3416
+
3417
+ ```sh
3418
+ dsh --profile demo
3419
+ ```
3420
+
3421
+ Remove:
3422
+
3423
+ ```sh
3424
+ dsh plugin --profile demo remove dsh-my-plugin
3425
+ ```
3426
+
3427
+ ---
3428
+
3429
+ ## 102. Layer precedence
3430
+
3431
+ Current docs describe effective configuration layers in this order:
3432
+
3433
+ ```text
3434
+ 1. bundle patches in profile bundle order
3435
+ 2. profile cordis.patch.yml
3436
+ 3. $DSH_HOME/cordis.patch.yml
3437
+ 4. each --patch overlay in argv order
3438
+ ```
3439
+
3440
+ Later layers win.
3441
+
3442
+ Important:
3443
+
3444
+ > A patch replacing an entry's `config` replaces that row's whole config value; do not assume arbitrary deep merge.
3445
+
3446
+ When overriding an earlier row, restate all required configuration keys.
3447
+
3448
+ ---
3449
+
3450
+ ## 103. Git install build-script warning
3451
+
3452
+ Installing from Git can fetch source without prebuilt artifacts.
3453
+
3454
+ For TypeScript packages, authors may need a self-contained `prepare` build.
3455
+
3456
+ Modern pnpm may require users to explicitly allow install-time builds.
3457
+
3458
+ Treat that permission as a security decision:
3459
+
3460
+ ```text
3461
+ allowing build scripts = allowing package code to execute at install time
3462
+ ```
3463
+
3464
+ Prefer pinned commits and trusted source.
3465
+
3466
+ For lower-friction distribution, publish built artifacts to npm or ship a tarball.
3467
+
3468
+ ---
3469
+
3470
+ # Part XVI - Coding-agent decision framework
3471
+
3472
+ ## 104. Given a feature request, choose the Cordis mechanism
3473
+
3474
+ | Need | Prefer |
3475
+ |---|---|
3476
+ | Independently mount/unmount behavior | plugin |
3477
+ | Direct callable capability | Service |
3478
+ | Hard dependency on capability | `inject` |
3479
+ | Optional capability | `ctx.get()` or dependency-gated sub-plugin |
3480
+ | Raw resource with cleanup | `ctx.effect()` |
3481
+ | Observe a runtime occurrence | event listener |
3482
+ | Multiple async observers must complete | `parallel` event |
3483
+ | Ordered decision chain | `serial` / `bail` |
3484
+ | Around-policy / interception | `waterfall` |
3485
+ | Model-callable operation | `ctx.tools.register(defineTool(...))` |
3486
+ | New model provider | `ctx.llm.registerAdapter(...)` |
3487
+ | Replaceable implementation family | Definition + Provider + Consumer seam |
3488
+ | Per-subtree provider | service isolation |
3489
+ | Per-subtree service config | intercept mechanism if service supports it |
3490
+ | Runtime composition change | Loader config / patch |
3491
+ | Source hot-swap | HMR + reversible plugin |
3492
+ | Durable model-visible fact | session event/log, not only live event |
3493
+ | Background task | jobs subsystem, not detached promise |
3494
+
3495
+ ---
3496
+
3497
+ ## 105. Coding-agent implementation algorithm
3498
+
3499
+ When asked to add a feature:
3500
+
3501
+ ```text
3502
+ 1. Identify the owning domain/capability.
3503
+ 2. Search generated subsystem docs and package types.
3504
+ 3. Decide whether this is:
3505
+ - service capability,
3506
+ - provider,
3507
+ - consumer,
3508
+ - tool,
3509
+ - event hook,
3510
+ - policy wrapper,
3511
+ - configuration composition.
3512
+ 4. List required services.
3513
+ 5. Put hard dependencies in inject.
3514
+ 6. List every side effect created during activation.
3515
+ 7. Make each effect lifecycle-owned.
3516
+ 8. Add validated config for deployment-specific values.
3517
+ 9. Use stable config entry IDs.
3518
+ 10. Test initial activation.
3519
+ 11. Test missing dependencies → PENDING.
3520
+ 12. Test provider removal/replacement.
3521
+ 13. Test plugin disposal.
3522
+ 14. Test config reload/HMR.
3523
+ 15. Assert no duplicate/stale registrations.
3524
+ 16. If model-visible behavior changed, test durable session/replay implications.
3525
+ ```
3526
+
3527
+ ---
3528
+
3529
+ # Part XVII - Debugging
3530
+
3531
+ ## 106. Plugin prints nothing
3532
+
3533
+ Check in this order:
3534
+
3535
+ ```text
3536
+ 1. Is the row in effective config?
3537
+ dsh --profile <name> --dump-config
3538
+
3539
+ 2. Is module path/name resolvable?
3540
+
3541
+ 3. Is row disabled?
3542
+
3543
+ 4. What is Fiber state?
3544
+
3545
+ 5. Is it PENDING because an injected service is absent?
3546
+
3547
+ 6. Is the provider itself PENDING on another service?
3548
+
3549
+ 7. Did Config validation fail?
3550
+
3551
+ 8. Is a logger exporter present for the diagnostic path?
3552
+
3553
+ 9. Did a source/HMR candidate fail and get rolled back?
3554
+ ```
3555
+
3556
+ Do not add sleep/retry hacks before understanding the dependency graph.
3557
+
3558
+ ---
3559
+
3560
+ ## 107. Diagnose PENDING Fibers
3561
+
3562
+ Tutorial pattern:
3563
+
3564
+ ```ts
3565
+ import { FiberState, type Context } from '@deepseek-ai/cordis'
3566
+
3567
+ export const name = 'diagnose'
3568
+
3569
+ export function apply(ctx: Context) {
3570
+ ctx.effect(() => {
3571
+ const timer = setTimeout(() => {
3572
+ for (const runtime of ctx.registry.values()) {
3573
+ for (const fiber of runtime.fibers) {
3574
+ if (fiber.state === FiberState.PENDING) {
3575
+ console.log(
3576
+ `${fiber.name} is PENDING - check required services`,
3577
+ )
3578
+ }
3579
+ }
3580
+ }
3581
+ }, 500)
3582
+
3583
+ return () => clearTimeout(timer)
3584
+ })
3585
+ }
3586
+ ```
3587
+
3588
+ Notice that even the diagnostic timer is lifecycle-owned.
3589
+
3590
+ ---
3591
+
3592
+ ## 108. Duplicate tool/listener after HMR
3593
+
3594
+ Symptom:
3595
+
3596
+ ```text
3597
+ one save → handler fires twice
3598
+ second save → three times
3599
+ ```
3600
+
3601
+ Likely cause:
3602
+
3603
+ ```text
3604
+ registration happened outside Cordis effect ownership
3605
+ ```
3606
+
3607
+ Audit:
3608
+
3609
+ ```text
3610
+ ctx.on → already owned
3611
+ ctx.tools.register → should be owned by tools registry
3612
+ ctx.llm.register... → should be owned
3613
+ raw emitter.on → must wrap
3614
+ setInterval → must wrap
3615
+ third-party callback → likely must wrap
3616
+ module-scope mutable singleton → suspicious
3617
+ ```
3618
+
3619
+ ---
3620
+
3621
+ ## 109. Provider swap causes stale calls
3622
+
3623
+ Likely causes:
3624
+
3625
+ - consumer did not declare `inject`;
3626
+ - provider object copied into module-global state;
3627
+ - asynchronous work escaped the activation lifecycle;
3628
+ - callback registered outside Fiber ownership;
3629
+ - optional lookup was cached forever.
3630
+
3631
+ Correct pattern:
3632
+
3633
+ ```ts
3634
+ export const inject = ['provider']
3635
+
3636
+ export function apply(ctx: Context) {
3637
+ // capture ctx.provider only inside resources owned by this activation
3638
+ }
3639
+ ```
3640
+
3641
+ ---
3642
+
3643
+ ## 110. Waterfall suddenly stops core behavior
3644
+
3645
+ Inspect every listener on that waterfall.
3646
+
3647
+ Find one that logs/annotates but does not:
3648
+
3649
+ ```ts
3650
+ return next()
3651
+ ```
3652
+
3653
+ This is one of the highest-value Cordis debugging heuristics.
3654
+
3655
+ ---
3656
+
3657
+ ## 111. Plugin fails only after config edit
3658
+
3659
+ Check:
3660
+
3661
+ - schema mismatch;
3662
+ - patch replaced whole config instead of deep-merging;
3663
+ - `!!js` expression evaluates only after required injections and now sees a different provider/context;
3664
+ - stable row ID missing;
3665
+ - HMR candidate import/build error;
3666
+ - provider change triggered a consumer restart that reveals an unmanaged global.
3667
+
3668
+ ---
3669
+
3670
+ ## 112. Cleanup hangs
3671
+
3672
+ Look for:
3673
+
3674
+ - async disposer waiting forever;
3675
+ - work not observing abort signal;
3676
+ - disposer waiting on an event emitted only by already-disposed child;
3677
+ - circular cleanup dependency between independent effects;
3678
+ - detached background work not managed by jobs;
3679
+ - external SDK close/flush without timeout semantics.
3680
+
3681
+ If cleanup order is important, consolidate it in one effect.
3682
+
3683
+ ---
3684
+
3685
+ # Part XVIII - Anti-pattern catalog
3686
+
3687
+ ## 113. Importing concrete providers in consumers
3688
+
3689
+ Bad:
3690
+
3691
+ ```ts
3692
+ import { LocalShell } from '@my/local-shell'
3693
+ ```
3694
+
3695
+ inside a tool that should work with any shell implementation.
3696
+
3697
+ Better:
3698
+
3699
+ ```ts
3700
+ export const inject = ['shell']
3701
+
3702
+ export function apply(ctx: Context) {
3703
+ return ctx.shell.execute(...)
3704
+ }
3705
+ ```
3706
+
3707
+ ---
3708
+
3709
+ ## 114. Encoding load order in YAML
3710
+
3711
+ Bad:
3712
+
3713
+ ```text
3714
+ “put provider three lines earlier”
3715
+ ```
3716
+
3717
+ Correct:
3718
+
3719
+ ```ts
3720
+ inject = ['provider']
3721
+ ```
3722
+
3723
+ ---
3724
+
3725
+ ## 115. Global mutable registry outside lifecycle
3726
+
3727
+ Bad:
3728
+
3729
+ ```ts
3730
+ GLOBAL_TOOLS.push(tool)
3731
+ ```
3732
+
3733
+ with no inverse.
3734
+
3735
+ Correct:
3736
+
3737
+ ```ts
3738
+ const remove = registry.register(tool)
3739
+ ctx.effect(() => remove)
3740
+ ```
3741
+
3742
+ or use the framework's lifecycle-aware registry API.
3743
+
3744
+ ---
3745
+
3746
+ ## 116. Detached promises
3747
+
3748
+ Bad:
3749
+
3750
+ ```ts
3751
+ void longRunningWork()
3752
+ ```
3753
+
3754
+ when it outlives activation and mutates state.
3755
+
3756
+ Use:
3757
+
3758
+ - an effect with async cleanup;
3759
+ - cancellation signal;
3760
+ - jobs subsystem for published background tasks;
3761
+ - a child plugin whose Fiber owns the work.
3762
+
3763
+ ---
3764
+
3765
+ ## 117. Tool returns prose instead of data
3766
+
3767
+ Bad:
3768
+
3769
+ ```text
3770
+ "Job started with id job-17"
3771
+ ```
3772
+
3773
+ Better:
3774
+
3775
+ ```json
3776
+ {
3777
+ "kind": "background",
3778
+ "jobId": "job-17"
3779
+ }
3780
+ ```
3781
+
3782
+ Render prose separately.
3783
+
3784
+ ---
3785
+
3786
+ ## 118. Optional capability declared as hard dependency unnecessarily
3787
+
3788
+ If metrics are optional, this:
3789
+
3790
+ ```ts
3791
+ inject = ['metrics']
3792
+ ```
3793
+
3794
+ can disable an otherwise useful plugin.
3795
+
3796
+ Use optional lookup or a small injected sub-plugin.
3797
+
3798
+ ---
3799
+
3800
+ ## 119. Required capability treated as optional
3801
+
3802
+ Opposite problem:
3803
+
3804
+ ```ts
3805
+ const shell = ctx.get('shell')
3806
+ if (!shell) return
3807
+ ```
3808
+
3809
+ for a plugin whose sole purpose requires shell.
3810
+
3811
+ This hides misconfiguration.
3812
+
3813
+ Use `inject = ['shell']` and let `PENDING` express the dependency contract.
3814
+
3815
+ ---
3816
+
3817
+ ## 120. Treating isolation as security
3818
+
3819
+ `ctx.isolate('shell')` prevents service resolution collisions.
3820
+
3821
+ It does not stop arbitrary plugin code from:
3822
+
3823
+ ```ts
3824
+ import fs from 'node:fs'
3825
+ ```
3826
+
3827
+ Security requires sandbox/process/permission boundaries from the appropriate subsystem/OS layer.
3828
+
3829
+ ---
3830
+
3831
+ ## 121. Assuming effect cleanup can undo external history
3832
+
3833
+ A disposer can close a socket.
3834
+
3835
+ It cannot retract:
3836
+
3837
+ - packets already sent;
3838
+ - messages already published externally;
3839
+ - money already transferred;
3840
+ - durable session events already committed;
3841
+ - files overwritten without a saved inverse.
3842
+
3843
+ For those domains, use compensation/idempotency/versioning/transaction protocols appropriate to the external system.
3844
+
3845
+ ---
3846
+
3847
+ # Part XIX - Designing self-updatable systems with Cordis
3848
+
3849
+ ## 122. What Cordis makes dynamically replaceable
3850
+
3851
+ Cordis is especially strong for **in-process higher layers**:
3852
+
3853
+ ```text
3854
+ agent behavior
3855
+ model adapters
3856
+ tools
3857
+ policies
3858
+ memory/context services
3859
+ prompt contributors
3860
+ workflows
3861
+ runtime registries
3862
+ UI/plugin adapters
3863
+ configuration-selected providers
3864
+ ```
3865
+
3866
+ These can be represented as plugin/service/effect surfaces and reconciled at runtime.
3867
+
3868
+ ---
3869
+
3870
+ ## 123. What Cordis does not magically hot-swap
3871
+
3872
+ Some layers remain host/bootstrap concerns:
3873
+
3874
+ ```text
3875
+ Node/Electron executable
3876
+ native ABI changes
3877
+ OS entitlements
3878
+ code signing
3879
+ preload security boundary
3880
+ Chromium runtime flags
3881
+ native .node modules with incompatible ABI
3882
+ installer/updater itself
3883
+ process-level crashes
3884
+ ```
3885
+
3886
+ A self-updating application should separate:
3887
+
3888
+ ```text
3889
+ small stable bootstrap / host
3890
+ +
3891
+ large Cordis-managed dynamic layer
3892
+ ```
3893
+
3894
+ The dynamic layer can evolve aggressively while the bootstrap owns restart, binary replacement, code-signing, and rollback when a process restart is unavoidable.
3895
+
3896
+ ---
3897
+
3898
+ ## 124. Safe self-modification rule
3899
+
3900
+ An agent that edits a Cordis plugin should not immediately mutate arbitrary live global state.
3901
+
3902
+ Preferred loop:
3903
+
3904
+ ```text
3905
+ 1. edit plugin source/config
3906
+ 2. build/typecheck/test candidate
3907
+ 3. Loader/HMR imports candidate
3908
+ 4. reconcile old → candidate
3909
+ 5. await lifecycle settlement
3910
+ 6. observe health checks
3911
+ 7. keep candidate or restore previous composition
3912
+ ```
3913
+
3914
+ DeepSeek Harness's transactional Loader patches are useful here, but they are only one part of the safety story.
3915
+
3916
+ ---
3917
+
3918
+ # Part XX - Testing Cordis components
3919
+
3920
+ ## 125. Minimum lifecycle test matrix
3921
+
3922
+ Every serious plugin should be tested under more than startup.
3923
+
3924
+ ```text
3925
+ [ ] initial mount
3926
+ [ ] invalid config
3927
+ [ ] required provider missing
3928
+ [ ] provider appears later
3929
+ [ ] provider disappears
3930
+ [ ] provider replaced by compatible implementation
3931
+ [ ] plugin config update
3932
+ [ ] source HMR/restart
3933
+ [ ] explicit fiber.dispose()
3934
+ [ ] parent disposal
3935
+ [ ] async work aborted during unload
3936
+ [ ] repeated mount/unmount cycles
3937
+ [ ] no duplicate registrations after N cycles
3938
+ ```
3939
+
3940
+ **Wait for the fiber, never for a guessed time, and await dependencies first.** `await ctx.plugin(x)` waits only while the fiber has work in flight. A fiber whose injected service is not provided yet is PENDING with nothing in flight, so awaiting it returns at once, before the plugin has even started. A fixed `setTimeout` wait hides this on a fast machine and fails on a slow CI runner (fixed real instance: `@acryldev/node-server`'s tests waited 20 ms for a server that scans for a free port, and failed on Windows; one of its tests only passed because its fiber was still PENDING when it was checked). So await each dependency's fiber first, then the consumer's, then assert the state you expect: `ACTIVE`, the service present, or the rejection a failing plugin settles with (an awaited fiber that fails rejects with its startup error). When a plugin's readiness is later than its fiber (work deferred past `apply`, such as `@acryldev/plugin-context`'s startup pass), wait on the signal the plugin provides for it (`pluginContext.startupSettled`) and fail with what it reports, not with a polling deadline.
3941
+
3942
+ ---
3943
+
3944
+ ## 126. Effect leak test
3945
+
3946
+ Record baseline counts:
3947
+
3948
+ ```text
3949
+ listeners
3950
+ registered tools
3951
+ open watchers
3952
+ active timers
3953
+ provider entries
3954
+ child Fibers
3955
+ ```
3956
+
3957
+ Then:
3958
+
3959
+ ```text
3960
+ mount → activate → dispose
3961
+ ```
3962
+
3963
+ Repeat many times.
3964
+
3965
+ Final state should equal baseline for everything the plugin owned.
3966
+
3967
+ This is the engineering approximation of recovery/observational equivalence.
3968
+
3969
+ ---
3970
+
3971
+ ## 127. Provider replacement test
3972
+
3973
+ Given:
3974
+
3975
+ ```text
3976
+ consumer injects myCap
3977
+ ```
3978
+
3979
+ Test:
3980
+
3981
+ ```text
3982
+ provider A mount
3983
+ consumer ACTIVE
3984
+ call → A
3985
+
3986
+ replace A with B
3987
+ consumer unload/reload
3988
+ call → B
3989
+
3990
+ assert A no longer receives calls
3991
+ assert consumer registration count stays 1
3992
+ ```
3993
+
3994
+ ---
3995
+
3996
+ ## 128. Waterfall contract test
3997
+
3998
+ Test both delegation and veto.
3999
+
4000
+ ```ts
4001
+ ctx.on('my/request', async (req, next) => {
4002
+ trace.push('outer-before')
4003
+ const result = await next()
4004
+ trace.push('outer-after')
4005
+ return result
4006
+ })
4007
+ ```
4008
+
4009
+ Assert order around downstream execution.
4010
+
4011
+ Then add a veto listener and assert the default handler did not run.
4012
+
4013
+ ---
4014
+
4015
+ ## 129. Tool contract tests
4016
+
4017
+ At minimum:
4018
+
4019
+ ```text
4020
+ [ ] valid args execute
4021
+ [ ] invalid args rejected before body
4022
+ [ ] semantic validation errors clear
4023
+ [ ] canonical output matches output.schema
4024
+ [ ] renderer produces expected model content
4025
+ [ ] cancellation reaches operation
4026
+ [ ] tool unregisters on plugin unload
4027
+ [ ] policy hooks still run
4028
+ [ ] Code Mode receives canonical value
4029
+ [ ] replay/UI presenter is pure if provided
4030
+ ```
4031
+
4032
+ ---
4033
+
4034
+ # Part XXI - Practical reference: “what should I use?”
4035
+
4036
+ ## 130. Plugin vs Service vs Tool vs Event
4037
+
4038
+ ```text
4039
+ Plugin
4040
+ = lifecycle/replacement unit
4041
+
4042
+ Service
4043
+ = direct named capability consumed by code
4044
+
4045
+ Tool
4046
+ = model-callable operation registered in Harness tools service
4047
+
4048
+ Event
4049
+ = open runtime notification/interception contract
4050
+ ```
4051
+
4052
+ A single feature may involve all four:
4053
+
4054
+ ```text
4055
+ Plugin: Git provider plugin
4056
+ Service: ctx.git
4057
+ Tool: git_status
4058
+ Events: git/pre-operation, git/result
4059
+ ```
4060
+
4061
+ Do not make one concept impersonate another.
4062
+
4063
+ ---
4064
+
4065
+ ## 131. Service vs event decision examples
4066
+
4067
+ ### Need current database result
4068
+
4069
+ ```ts
4070
+ await ctx.database.query(...)
4071
+ ```
4072
+
4073
+ Service.
4074
+
4075
+ ### Notify plugins that session title changed
4076
+
4077
+ ```ts
4078
+ ctx.emit('session/title-changed', ...)
4079
+ ```
4080
+
4081
+ Event.
4082
+
4083
+ ### Allow policies to wrap model request
4084
+
4085
+ ```ts
4086
+ ctx.waterfall('agent/request', ..., next)
4087
+ ```
4088
+
4089
+ Waterfall event.
4090
+
4091
+ ### Allow model to query database
4092
+
4093
+ ```ts
4094
+ ctx.tools.register(defineTool(...))
4095
+ ```
4096
+
4097
+ Tool consumer over database Service.
4098
+
4099
+ ---
4100
+
4101
+ # Part XXII - Coding-agent rules: MUST / SHOULD / MUST NOT
4102
+
4103
+ ## 132. MUST
4104
+
4105
+ 1. **MUST declare every hard service dependency.**
4106
+ 2. **MUST make every activation-owned resource disposable.**
4107
+ 3. **MUST assume a plugin can activate more than once in one process.**
4108
+ 4. **MUST validate deployment configuration before using it.**
4109
+ 5. **MUST use service/capability boundaries rather than concrete provider imports when replacement is intended.**
4110
+ 6. **MUST call `next()` in waterfall listeners unless intentionally vetoing/replacing downstream behavior.**
4111
+ 7. **MUST honor cancellation in tools/LLM/provider operations where the contract supplies a signal.**
4112
+ 8. **MUST keep canonical tool data separate from model/UI formatting.**
4113
+ 9. **MUST inspect the local vendored API/types before relying on upstream examples.**
4114
+ 10. **MUST test unload/reload, not only startup.**
4115
+
4116
+ ---
4117
+
4118
+ ## 133. SHOULD
4119
+
4120
+ 1. **SHOULD use function plugins by default.**
4121
+ 2. **SHOULD use a `Service` class when exposing a direct capability.**
4122
+ 3. **SHOULD use stable config row IDs.**
4123
+ 4. **SHOULD keep order-dependent cleanup inside one disposer.**
4124
+ 5. **SHOULD namespace custom service and event names to avoid collisions.**
4125
+ 6. **SHOULD keep provider-specific logic behind a capability definition.**
4126
+ 7. **SHOULD use generated subsystem surfaces as the source of truth for Harness events/services.**
4127
+ 8. **SHOULD make configuration defaults safe and unsurprising.**
4128
+ 9. **SHOULD use durable session events for replay/model-visible facts.**
4129
+ 10. **SHOULD keep the bootstrap smaller and less dynamic than the Cordis-managed layer in self-updating systems.**
4130
+
4131
+ ---
4132
+
4133
+ ## 134. MUST NOT
4134
+
4135
+ 1. **MUST NOT rely on `cordis.yml` line order for dependency readiness.**
4136
+ 2. **MUST NOT leave raw timers/watchers/listeners outside ownership.**
4137
+ 3. **MUST NOT cache required provider references across activation episodes.**
4138
+ 4. **MUST NOT treat `PENDING` as automatically erroneous.**
4139
+ 5. **MUST NOT assume `INACTIVE` is a current Fiber enum state.**
4140
+ 6. **MUST NOT invent `ctx.fork()` for generic Context branching.**
4141
+ 7. **MUST NOT treat service isolation as a sandbox.**
4142
+ 8. **MUST NOT let a logging waterfall hook omit `next()`.**
4143
+ 9. **MUST NOT make programmatic callers parse rendered tool prose for IDs/fields.**
4144
+ 10. **MUST NOT assume plugin disposal reverses irreversible external history.**
4145
+
4146
+ ---
4147
+
4148
+ # Part XXIII - Architecture review template for coding agents
4149
+
4150
+ ## 135. Before implementing a Cordis feature, write this mini-design
4151
+
4152
+ ```md
4153
+ ## Capability
4154
+ What domain does this belong to?
4155
+
4156
+ ## Plugin boundary
4157
+ Why should this behavior have independent lifecycle/config/replacement?
4158
+
4159
+ ## Provides
4160
+ Which service(s), tool(s), event(s), or session facts does it provide?
4161
+
4162
+ ## Injects
4163
+ Which required services must exist before activation?
4164
+
4165
+ ## Optional dependencies
4166
+ Which capabilities improve behavior but are not required?
4167
+
4168
+ ## Effects
4169
+ List every process-local side effect created while active.
4170
+
4171
+ ## Disposal
4172
+ How does each effect quiesce?
4173
+
4174
+ ## Config
4175
+ Which deployment-dependent values are validated fields?
4176
+
4177
+ ## Events
4178
+ Which event mode is used and why?
4179
+
4180
+ ## HMR/replacement
4181
+ What happens when this plugin or one of its providers changes?
4182
+
4183
+ ## Durable state
4184
+ Does anything model-visible or replay-critical need a session event?
4185
+
4186
+ ## Tests
4187
+ How do we prove mount → use → unload → remount is clean?
4188
+ ```
4189
+
4190
+ A coding agent should be able to answer every section before merging a new core capability.
4191
+
4192
+ ---
4193
+
4194
+ # Part XXIV - Applying the model to an ACRYL-style agent platform
4195
+
4196
+ ## 136. Recommended Cordis decomposition
4197
+
4198
+ For an agent-agnostic runtime, treat major swappable systems as capability seams rather than hardwired imports.
4199
+
4200
+ Example conceptual tree:
4201
+
4202
+ ```text
4203
+ ACRYL / agent runtime
4204
+ ├── session store service
4205
+ ├── agent adapter registry
4206
+ │ ├── Codex provider
4207
+ │ ├── Claude provider
4208
+ │ └── Pi provider
4209
+ ├── context compaction service
4210
+ │ ├── provider A
4211
+ │ └── provider B
4212
+ ├── memory service
4213
+ │ ├── local
4214
+ │ └── remote
4215
+ ├── codebase graph service
4216
+ │ ├── graph provider A
4217
+ │ └── graph provider B
4218
+ ├── shell / filesystem realm
4219
+ ├── approval policy
4220
+ ├── handoff/relay workflow
4221
+ ├── tool families
4222
+ ├── UI/TUI surface plugins
4223
+ └── telemetry/trace observers
4224
+ ```
4225
+
4226
+ Each provider should be selectable by composition, not by editing consumers.
4227
+
4228
+ ---
4229
+
4230
+ ## 137. Example: agent adapter seam
4231
+
4232
+ Definition:
4233
+
4234
+ ```ts
4235
+ abstract class CodingAgentService extends Service {
4236
+ abstract startSession(spec: StartSpec): Promise<AgentSession>
4237
+ abstract resumeSession(id: string): Promise<AgentSession>
4238
+ abstract stopSession(id: string): Promise<void>
4239
+ }
4240
+ ```
4241
+
4242
+ Providers:
4243
+
4244
+ ```text
4245
+ CodexAdapter
4246
+ ClaudeAdapter
4247
+ PiAdapter
4248
+ OpenCodeAdapter
4249
+ ```
4250
+
4251
+ Consumers:
4252
+
4253
+ ```text
4254
+ relay workflow
4255
+ session UI
4256
+ handoff tool
4257
+ multi-agent orchestrator
4258
+ ```
4259
+
4260
+ Consumers inject a stable capability. They should not import each provider package directly.
4261
+
4262
+ ---
4263
+
4264
+ ## 138. Example: optional memory
4265
+
4266
+ If an agent runtime works without memory:
4267
+
4268
+ ```ts
4269
+ export function apply(ctx: Context) {
4270
+ const memory = ctx.get('memory')
4271
+ // enhance if present
4272
+ }
4273
+ ```
4274
+
4275
+ If a particular plugin is specifically a “memory-grounded planner,” then memory is required:
4276
+
4277
+ ```ts
4278
+ export const inject = ['memory']
4279
+ ```
4280
+
4281
+ The dependency semantics should express product truth.
4282
+
4283
+ ---
4284
+
4285
+ ## 139. Example: hot-swapping context graph provider
4286
+
4287
+ A context graph consumer should depend on:
4288
+
4289
+ ```text
4290
+ ctx.codeGraph
4291
+ ```
4292
+
4293
+ not:
4294
+
4295
+ ```text
4296
+ OmniGraph SDK concrete client
4297
+ Lat.md concrete implementation
4298
+ ```
4299
+
4300
+ Then composition can choose provider per workspace/agent realm.
4301
+
4302
+ If the provider is replaced, consumers' active episodes restart cleanly against the new provider.
4303
+
4304
+ That is exactly the kind of system Cordis is designed to make tractable.
4305
+
4306
+ ---
4307
+
4308
+ # Part XXV - Source-reading guide for coding agents
4309
+
4310
+ ## 140. Read docs in this order
4311
+
4312
+ For a new coding agent entering the codebase:
4313
+
4314
+ ```text
4315
+ 1. docs/cordis-primer.md
4316
+ 2. docs/cordis-tutorial/index.md
4317
+ 3. docs/cordis-tutorial/01-first-plugin.md
4318
+ 4. 02-lifecycle-and-effects.md
4319
+ 5. 03-services.md
4320
+ 6. 04-events.md
4321
+ 7. 05-config.md
4322
+ 8. 06-composition-and-hmr.md
4323
+ 9. 07-into-the-harness.md
4324
+ 10. docs/architecture.md
4325
+ 11. owning docs/subsystems/<domain>.md
4326
+ 12. owning package README/types/source
4327
+ 13. vendor/cordis source only when behavior remains unclear
4328
+ ```
4329
+
4330
+ For tool work also read:
4331
+
4332
+ ```text
4333
+ docs/cookbook/adding-a-tool.md
4334
+ packages/core/tools/README.md
4335
+ ```
4336
+
4337
+ For LLM work:
4338
+
4339
+ ```text
4340
+ docs/user/develop/practice/llm-adapter.md
4341
+ packages/llm/llm*/
4342
+ ```
4343
+
4344
+ ---
4345
+
4346
+ ## 141. Inspect implementation before guessing
4347
+
4348
+ High-value files:
4349
+
4350
+ ```text
4351
+ vendor/cordis/src/context.ts
4352
+ vendor/cordis/src/fiber.ts
4353
+ vendor/cordis/src/registry.ts
4354
+ vendor/cordis/src/service.ts
4355
+ vendor/cordis/src/events.ts
4356
+ vendor/README.md
4357
+ ```
4358
+
4359
+ These answer questions such as:
4360
+
4361
+ - what exact Fiber states exist;
4362
+ - when config is resolved;
4363
+ - how dependencies trigger activation;
4364
+ - what an effect can return;
4365
+ - what `dispose()` waits for;
4366
+ - how event modes actually dispatch;
4367
+ - which behavior differs from upstream Cordis.
4368
+
4369
+ ---
4370
+
4371
+ # Part XXVI - Compact master reference
4372
+
4373
+ ## 142. Cordis primitive cheat sheet
4374
+
4375
+ | Primitive | Meaning | Most common use |
4376
+ |---|---|---|
4377
+ | `Context` | scoped runtime environment | service lookup + registrations |
4378
+ | `ctx.plugin()` | mount child lifecycle | compose behavior from code |
4379
+ | `ctx.inject()` | gated child behavior | conditional behavior on services |
4380
+ | `Fiber` | mounted plugin instance | lifecycle state/cleanup/debugging |
4381
+ | `Service` | named capability | provider abstraction |
4382
+ | `inject` | required service set | dependency-driven activation |
4383
+ | `ctx.get()` | optional service lookup | optional enhancement |
4384
+ | `ctx.effect()` | own custom side effect | timer/socket/watcher cleanup |
4385
+ | `ctx.on()` | lifecycle-owned listener | event observation/interception |
4386
+ | `emit` | sync broadcast | notification |
4387
+ | `parallel` | await all listeners | fan-out completion |
4388
+ | `serial` | ordered async bail | decision chain |
4389
+ | `bail` | ordered sync bail | synchronous decision |
4390
+ | `waterfall` | around-middleware | policy/interception |
4391
+ | `ctx.extend()` | child context metadata | scoped context derivation |
4392
+ | `ctx.isolate()` | new service realm | multiple providers of same name |
4393
+ | `ctx.intercept()` | scoped service config | service-specific overrides |
4394
+ | `ctx.registry` | plugin runtime registry | introspection/debugging |
4395
+
4396
+ ---
4397
+
4398
+ ## 143. Fiber state cheat sheet
4399
+
4400
+ | State | Meaning | Coding implication |
4401
+ |---|---|---|
4402
+ | `PENDING` | mounted, requirements not ready | do not expect `apply()` yet |
4403
+ | `LOADING` | activation running | setup/effects may be in progress |
4404
+ | `ACTIVE` | current activation live | dependencies and registrations valid |
4405
+ | `FAILED` | config/apply failed | inspect error/log and candidate rollback |
4406
+ | `UNLOADING` | cleanup in progress | do not register new effects |
4407
+ | `DISPOSED` | permanently removed | Fiber cannot simply reactivate |
4408
+
4409
+ ---
4410
+
4411
+ ## 144. Event mode cheat sheet
4412
+
4413
+ | Mode | Awaited? | Order | Stops early? | Typical use |
4414
+ |---|---:|---|---:|---|
4415
+ | `emit` | no | registration | no | notification |
4416
+ | `parallel` | yes | concurrent | no | fan-out work |
4417
+ | `serial` | yes | registration | yes | async decision |
4418
+ | `bail` | no | registration | yes | sync decision |
4419
+ | `waterfall` | depends on handlers | nested registration order | yes by omitting `next()` | policy/wrapping |
4420
+
4421
+ ---
4422
+
4423
+ ## 145. Harness extension cheat sheet
4424
+
4425
+ | Goal | Mechanism |
4426
+ |---|---|
4427
+ | Add LLM provider | `ctx.llm.registerAdapter(...)` |
4428
+ | Add model-facing capability | `ctx.tools.register(defineTool(...))` |
4429
+ | Add execution policy | tool/agent capability events |
4430
+ | Add shell provider | shell service seam |
4431
+ | Add filesystem provider | fs service seam |
4432
+ | Add process confinement | sandbox service seam |
4433
+ | Add background work | jobs service |
4434
+ | Add human command | commands service |
4435
+ | Add model context | agent/context APIs under owning subsystem |
4436
+ | Observe durable facts | `session/event` + event type |
4437
+ | Add replay-critical model-visible state | extend durable session event model |
4438
+ | Give sessions/agents separate provider instances | isolated service realm/preset composition |
4439
+
4440
+ ---
4441
+
4442
+ # Part XXVII - Final operating principles
4443
+
4444
+ ## 146. The Cordis discipline
4445
+
4446
+ A Cordis system remains comprehensible when every dynamic contribution can answer four questions:
4447
+
4448
+ ```text
4449
+ 1. Who owns me?
4450
+ 2. What do I require?
4451
+ 3. How do I leave?
4452
+ 4. What happens when my provider changes?
4453
+ ```
4454
+
4455
+ If any answer is “some global singleton probably handles it,” the design is incomplete.
4456
+
4457
+ ---
4458
+
4459
+ ## 147. The most important invariants
4460
+
4461
+ ### Ownership invariant
4462
+
4463
+ Every live registration/resource has one lifecycle owner.
4464
+
4465
+ ### Dependency invariant
4466
+
4467
+ Every hard capability dependency is declared and reactively tracked.
4468
+
4469
+ ### Re-entry invariant
4470
+
4471
+ A plugin may activate repeatedly without accumulating stale state.
4472
+
4473
+ ### Replacement invariant
4474
+
4475
+ A consumer does not retain a retired provider across activation episodes.
4476
+
4477
+ ### Event invariant
4478
+
4479
+ Waterfall delegation is explicit; observation cannot accidentally suppress core behavior.
4480
+
4481
+ ### Tool invariant
4482
+
4483
+ Programmatic value, model-facing rendering, and UI presentation remain distinct.
4484
+
4485
+ ### Durability invariant
4486
+
4487
+ Model-visible/replay-critical facts come from durable session state, not ephemeral callbacks alone.
4488
+
4489
+ ### Security invariant
4490
+
4491
+ Cordis composition/isolation is not mistaken for OS-level sandboxing.
4492
+
4493
+ ---
4494
+
4495
+ ## 148. The one paragraph a coding agent should remember
4496
+
4497
+ When adding behavior to a Cordis system, make it a plugin only if it benefits from independent lifecycle or composition. Declare every required capability with `inject`; access providers through stable service names rather than concrete implementations. Treat every registration and resource as an owned effect, using lifecycle-aware Cordis/Harness registries when available and `ctx.effect()` for everything else. Expect provider loss, config updates, HMR, and repeated activation. Use services for direct capabilities, events for open observation/interception, waterfalls only with deliberate `next()` semantics, tools for model-callable APIs with canonical typed values, and durable session events for facts that must survive replay. Then test not only whether the component starts, but whether it can leave and return without leaving a trace it does not own.
4498
+
4499
+ ---
4500
+
4501
+ # Appendix A - Practical source map
4502
+
4503
+ ## DeepSeek Harness development tutorials
4504
+
4505
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/basic/
4506
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/basic/tool
4507
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/basic/config
4508
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/basic/publish
4509
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/framework/
4510
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/framework/service
4511
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/framework/events
4512
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/practice/
4513
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/practice/llm-adapter
4514
+
4515
+ ## Hands-on Cordis tutorial
4516
+
4517
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/
4518
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/01-first-plugin
4519
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/02-lifecycle-and-effects
4520
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/03-services
4521
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/04-events
4522
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/05-config
4523
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/06-composition-and-hmr
4524
+ - https://deepseek-harness.github.io/deepseek-harness/en/develop/cordis-tutorial/07-into-the-harness
4525
+
4526
+ ## Parsed Markdown in repository
4527
+
4528
+ - https://github.com/deepseek-ai/deepseek-harness/tree/master/docs/cordis-tutorial
4529
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/cordis-primer.md
4530
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/architecture.md
4531
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/cookbook/adding-a-tool.md
4532
+
4533
+ ## Vendored implementation
4534
+
4535
+ - https://github.com/deepseek-ai/deepseek-harness/tree/master/vendor/cordis
4536
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/vendor/cordis/src/context.ts
4537
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/vendor/cordis/src/fiber.ts
4538
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/vendor/cordis/src/registry.ts
4539
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/vendor/cordis/src/service.ts
4540
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/vendor/cordis/src/events.ts
4541
+ - https://github.com/deepseek-ai/deepseek-harness/blob/master/vendor/README.md
4542
+
4543
+ ## Upstream Cordis
4544
+
4545
+ - https://github.com/cordiverse/cordis
4546
+
4547
+ ## Paper
4548
+
4549
+ - https://github.com/cordiverse/paper
4550
+ - https://github.com/cordiverse/paper/blob/main/paper.pdf
4551
+
4552
+ Title:
4553
+
4554
+ > *A Programming Paradigm for Spatiotemporal Composability*
4555
+
4556
+ The repository marks the paper as a **preprint under active revision**, draft dated 2026-08-13. Treat specific formal claims as draft research and verify the latest revision before citing them academically.
4557
+
4558
+ ## Supplemental explanatory articles
4559
+
4560
+ - https://redreamality.com/blog/cordis-spatiotemporal-composability-deepseek-harness/
4561
+ - https://jeffxiong.substack.com/p/everything-is-a-plugin
4562
+
4563
+ Use articles as explanation, not as the implementation source of truth. For code, prefer current Harness docs, current vendored source, and generated TypeScript surfaces.
4564
+
4565
+ ---
4566
+
4567
+ # Appendix B - Coding-agent completion checklist
4568
+
4569
+ Before declaring a Cordis feature complete:
4570
+
4571
+ ```text
4572
+ ARCHITECTURE
4573
+ [ ] Correct owning subsystem chosen
4574
+ [ ] Plugin boundary justified
4575
+ [ ] Service/provider/consumer roles separated only where useful
4576
+
4577
+ DEPENDENCIES
4578
+ [ ] Hard dependencies in inject
4579
+ [ ] Optional dependencies intentionally optional
4580
+ [ ] No YAML-order dependency
4581
+ [ ] No concrete provider import where a seam is intended
4582
+
4583
+ LIFECYCLE
4584
+ [ ] Every raw resource has cleanup
4585
+ [ ] No detached long-running promise
4586
+ [ ] Cleanup quiesces async work
4587
+ [ ] Order-dependent teardown is inside one disposer
4588
+ [ ] Repeated activation does not accumulate state
4589
+
4590
+ CONFIG
4591
+ [ ] Runtime schema exported
4592
+ [ ] Defaults validated
4593
+ [ ] Deployment tunables configurable
4594
+ [ ] Stable row id used
4595
+ [ ] Patch semantics understood
4596
+
4597
+ EVENTS
4598
+ [ ] Correct dispatch mode chosen
4599
+ [ ] Waterfall observers call next()
4600
+ [ ] Listener registration is lifecycle-owned
4601
+ [ ] Durable fact vs live event distinction is correct
4602
+
4603
+ TOOLS
4604
+ [ ] Parameters typed/validated
4605
+ [ ] Canonical output schema is useful programmatically
4606
+ [ ] Renderer contains prose, canonical value contains data
4607
+ [ ] Cancellation signal honored
4608
+ [ ] Tool disappears on plugin unload
4609
+ [ ] Policy pipeline not bypassed
4610
+
4611
+ LLM
4612
+ [ ] Provider-neutral request mapping correct
4613
+ [ ] StreamChunk ordering valid
4614
+ [ ] block-start/block-end pairs valid
4615
+ [ ] usage before finish
4616
+ [ ] signal forwarded
4617
+ [ ] stable LlmError used for provider failures
4618
+
4619
+ HMR / REPLACEMENT
4620
+ [ ] Source reload tested
4621
+ [ ] Config reload tested
4622
+ [ ] Provider swap tested
4623
+ [ ] Missing provider → PENDING tested
4624
+ [ ] Candidate failure/rollback behavior understood
4625
+ [ ] No duplicate listener/tool/provider after repeated reload
4626
+
4627
+ SECURITY / DURABILITY
4628
+ [ ] Cordis isolation not treated as sandbox
4629
+ [ ] External irreversible effects explicitly considered
4630
+ [ ] Model-visible replay-critical state persisted through session model
4631
+
4632
+ DIAGNOSTICS
4633
+ [ ] Useful plugin name
4634
+ [ ] Errors fail loud enough to diagnose
4635
+ [ ] Fiber state can be inspected
4636
+ [ ] Effect leaks can be audited
4637
+ ```
4638
+
4639
+ ---
4640
+
4641
+ # Appendix C - 30-second onboarding prompt for another coding agent
4642
+
4643
+ Use this when delegating Cordis work to a sub-agent:
4644
+
4645
+ ```text
4646
+ This repository uses DeepSeek Harness's vendored @deepseek-ai/cordis.
4647
+ Treat vendor/cordis and generated subsystem types/docs as authoritative over generic
4648
+ upstream examples. Cordis plugins are lifecycle units. Hard service requirements go
4649
+ in inject and are live: consumers unload/re-activate when provider implementations
4650
+ change. Every registration/resource must be owned by the current Fiber; ctx.on,
4651
+ ctx.plugin, service provisioning, ctx.tools.register and ctx.llm.registerAdapter are
4652
+ lifecycle-aware, while raw timers/watchers/connections must be wrapped in ctx.effect
4653
+ with cleanup. PENDING is a valid missing-dependency state. Current Fiber states are
4654
+ PENDING, LOADING, ACTIVE, FAILED, UNLOADING, DISPOSED; there is no public INACTIVE
4655
+ enum. Use services for direct capabilities, events for open extension points, and
4656
+ always call next() in waterfall observers unless intentionally vetoing. A Harness
4657
+ tool is not a Cordis primitive: it is registered into ctx.tools and should return a
4658
+ canonical typed value separate from model/UI rendering. Assume plugins can be hot-
4659
+ reloaded and activated repeatedly. Test provider removal/replacement and disposal,
4660
+ not only startup. Before coding, inspect the owning docs/subsystems page and local
4661
+ package types.
4662
+ ```
4663
+
4664
+ ---
4665
+
4666
+ **End of guide.**