Skip to content

docs(architecture): COMMAND-INFRASTRUCTURE field manual — codify substrate work as authoring guide - #1493

Merged
joelteply merged 1 commit into
canaryfrom
docs/command-infrastructure-field-manual
May 31, 2026
Merged

joelteply merged 1 commit into
canaryfrom
docs/command-infrastructure-field-manual

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Per Joel 2026-05-30:

"Let's make sure we have detailed designs for this command infrastructure into modules and properly built from the ground up by using our own generators."

Existing architecture docs cover the doctrine (MODULE-ARCHITECTURE.md), the runtime contract (CBAR-SUBSTRATE-ARCHITECTURE.md), and the concerns catalog (MODULE-CATALOG.md). Missing: the field manual for a module author sitting down to write code today, with substrate work from PRs #1483–#1492 codified into reusable shape.

This PR adds that one document. No code touched.

What the manual covers

§ Topic Sources from
1 The system in one sentence (Commands + Events + Persona in Rust) Joel 2026-05-30 doctrinal statement
2 Substrate primitives quick reference PRs #1483 / #1484 / #1485 / #1486 / #1487 / #1491 with real code snippets
3 Module Design Template (mod.rs + types.rs canonical shape) Distilled from chat/, generator/, data, airc
4 Concurrency doctrine (per-resource locks, multi-thread tests, dual-write partial-failure) PRs #1489 / #1490 / #1491 / #1492 — the two real bugs caught this session pinned as doctrine
5 Migration playbook (Joel's "rethink, don't port" rule) Memory: rethink-dont-port-commands-to-rust
6 Generator usage + v2 roadmap PR #1487 (current) + proposed enhancements
7 Acceptance criteria (7-point bar for "module-ready") Synthesis
8 / 9 See-also + every-PR reference table Cross-refs

Why this matters now

Doctrinal docs answer why. The catalog answers which. Neither answers how: where do I find the envelope API? what's the per-resource lock pattern? what shape does the generator expect? what counts as a concurrency stress test? The substrate is coherent enough now to be reduced to a single reference an author reads once and starts writing clean modules from.

What this does NOT do

  • Does NOT re-derive doctrine — defers to MODULE-ARCHITECTURE.md for the why.
  • Does NOT re-survey the module space — defers to MODULE-CATALOG.md.
  • Does NOT change any code — pure documentation.
  • Does NOT ship Generator v2 — flagged in §6.1 as separate follow-up. This PR establishes the template v2 will emit.

Follow-up PRs (proposed, not included here)

  1. Generator v2: emit modules matching the Module Design Template in §3. Includes types.rs scaffold with envelope boilerplate, tests skeleton with the multi-thread concurrency stress-test primer, DESIGN.md scaffold, per-resource lock scaffold when --stateful is set.
  2. Per-module DESIGN.md pages next to each migrated module's mod.rs (chat, data, airc, generator). ~150-200 lines each, pinning the module's role, command surface, state model, concurrency contract, kinks found.

Length + scope

480 lines. Tight by design — a manual the author reads in one sitting before authoring, then references when stuck. The longer the manual, the less anyone reads it.

Test plan

Stacks on

canary directly — pure documentation PR, no code dependency on the open chain.

References

…trate work as authoring guide

Per Joel 2026-05-30:
> "Let's make sure we have detailed designs for this command
>  infrastructure into modules and properly built from the ground
>  up by using our own generators."

Existing docs cover the **doctrine** (MODULE-ARCHITECTURE.md), the
**runtime contract** (CBAR-SUBSTRATE-ARCHITECTURE.md), and the
**concerns catalog** (MODULE-CATALOG.md). What was missing: the
**field manual** for a module author sitting down to write code
today.

This document codifies the substrate work from PRs #1483–#1492 into
reusable shape:

# What this manual covers

- **§1 The system in one sentence** — Commands + Events + Persona,
  in Rust, with airc handling grid. The doctrinal reduction Joel
  named on 2026-05-30.

- **§2 Substrate primitives quick reference** — ServiceModule trait,
  CommandRequest/Response envelopes, HandleRef + four cell shapes,
  HandleRef::expect_owned_by, CommandRequest::handle_id_or_legacy,
  interceptor chain, cross-module call pattern. Each with a code
  snippet pulled from the actual landed PRs.

- **§3 Module Design Template** — the canonical mod.rs + types.rs
  shape every ServiceModule follows. What the GeneratorModule
  scaffolds; what humans fill in. Rules for ts-rs annotations,
  serde camelCase, optional field handling, executor injection
  for tests.

- **§4 Concurrency doctrine** — per-resource locks (not module-wide),
  std::sync vs tokio::sync, the multi-thread test discipline
  (worker_threads=4), partial-failure semantics for dual-write
  composition. Pins the two real bugs caught this session
  (PR #1490 cursor race; PR #1487 generator same-name race) as
  doctrine, not anecdote.

- **§5 Migration playbook** — Joel's "rethink, don't port" rule
  with a pre-migration checklist + substrate checklist + a worked
  example for chat/analyze (the next chat migration).

- **§6 Generator usage** — how to scaffold a module via
  `./jtag generate/module`; v2 roadmap for the richer scaffold
  matching the Module Design Template.

- **§7 Acceptance criteria** — the 7-point bar for
  "concurrency-clean, wire-clean, ready for the headless integration
  test."

- **§8/§9 See also + PR references** — cross-refs to every
  substrate PR by surface, plus the existing architecture docs.

# Why a field manual now

The doctrinal docs answer the **why**. The catalog answers the
**which**. Neither answers the **how**: where do I find the
envelope API? what's the per-resource lock pattern? what shape
does the generator expect? what counts as a concurrency stress
test? The substrate is now coherent enough to be reduced to a
single reference an author can read once and start writing
clean modules from.

# What this does NOT do

- **Does NOT re-derive doctrine** — defers to MODULE-ARCHITECTURE.md
  for the architectural why.
- **Does NOT re-survey the module space** — defers to
  MODULE-CATALOG.md for what modules exist.
- **Does NOT change any code** — pure documentation, no Rust touched.
- **Does NOT propose v2 of the generator** in this PR — flagged in
  §6.1 as a separate follow-up. This PR establishes the template
  the v2 generator will emit.

# Follow-up PRs

- **Generator v2**: emit modules matching the Module Design Template
  (types.rs scaffold, tests skeleton with concurrency primer,
  DESIGN.md scaffold, per-resource lock scaffold when --stateful).
- **Per-module DESIGN.md pages** living next to mod.rs for each
  migrated module (chat, data, airc, generator). Each documents
  the module's role, command surface, state model, concurrency
  contract, kinks found.

# Length + scope

~440 lines. Tight by design — a manual the author reads in one
sitting before authoring, then references when stuck. The longer
the manual, the less anyone reads it.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 3be3022 into canary May 31, 2026
2 checks passed
@joelteply
joelteply deleted the docs/command-infrastructure-field-manual branch May 31, 2026 00:21
joelteply added a commit that referenced this pull request May 31, 2026
…/cursors, airc/realtime-store (#1495)

Step 2 of the doc set Joel approved on 2026-05-30 ("Yeah let's do it. In order"):

1. ✅ Field manual codifying substrate (PR #1493)
2. ✅ Generator v2 emitting modules per the template (PR #1494)
3. **This PR**: per-module design pages for everything we've built
4. (Next) MODULE-CATALOG.md update marking which modules are alive in Rust

Each doc follows the canonical 8-section template from the field
manual (Role / Command surface / Cross-module deps / State model /
Events emitted / Concurrency contract / Migration notes / Kinks found).

# What this PR adds

| Doc | Lines | Status of subject |
|---|---|---|
| `CHAT-MODULE.md` | 125 | chat/poll + chat/send shipped Rust (PR #1489); analyze/export still TS |
| `GENERATOR-MODULE.md` | 127 | v1 + v2 (PRs #1487 + #1494) — recursive bootstrap |
| `DATA-CURSORS-MODULE.md` | 164 | data/query-{open,next,close} migrated to HandleRef (PR #1490) |
| `AIRC-REALTIME-STORE-MODULE.md` | 142 | In-memory store + 4 moment-of-truth concurrency tests (PR #1492) |
| **Total** | **558** | |

# Why under `docs/architecture/` (not next to mod.rs)

The field manual §3 prescribes "DESIGN.md next to mod.rs" for the
canonical directory-module pattern. For this PR:

- chat/ and generator/ ARE directory modules, but only exist on
  unmerged PR branches (#1489 / #1487). Putting their DESIGN.md
  there would couple this PR to that chain.
- data and airc/realtime_store are single-file modules — no
  natural "next to mod.rs" location.

Resolution: all four go under `docs/architecture/` following the
existing convention (PERSONA-COGNITION-CONTRACT.md, ORM-PHASE-2-DESIGN.md
style). When the open PR chain merges, future PRs CAN move
chat/DESIGN.md + generator/DESIGN.md into their respective
directories if the team prefers — content stays the same; only the
file path changes. Single-file module docs stay under
`docs/architecture/` indefinitely (no natural directory home).

# What each doc captures

## CHAT-MODULE.md

- The chat/send dual-write semantics + the warning-field degraded-
  success pattern
- All 11 concurrency tests pinning multi-persona invariants
- The TS→Rust rethink table (resolved UUIDs only, no name resolution
  in kernel)
- Three flagged substrate kinks waiting for second consumers before
  distillation (envelope builder, typed cross-module call, dual-write
  macro)

## GENERATOR-MODULE.md

- The recursive bootstrap doctrine + v1→v2 evolution
- The two same-name race bugs the per-name lock caught (silent
  "already exists" silencing; torn-state writes with force=true)
- Why std::sync::Mutex over tokio::sync::Mutex here (sync filesystem
  critical section)

## DATA-CURSORS-MODULE.md

- The read-then-async-then-write race story (the "page 1 served 8
  times" bug)
- The dual-shape (handle OR queryId) resolver + the additive
  migration story
- All seven HandleRef migration tests pinning invariants
- The substrate refinements distilled to PR #1491 (expect_owned_by,
  handle_id_or_legacy)

## AIRC-REALTIME-STORE-MODULE.md

- The module-wide mutex + correctness-vs-throughput rationale
- The four moment-of-truth concurrency tests
- The flagged per-room sharding refinement (when persona count grows)
- The known stale-cursor + replay-bound limitation (out of scope but
  flagged)

# What this PR explicitly does NOT do

- **Does NOT touch any code** — pure documentation.
- **Does NOT move chat/ or generator/ DESIGN.md into their module
  directories** — see "Why under docs/architecture/" above.
- **Does NOT cover the full data module** — only the cursor surface.
  CRUD / vector / migration / batch each get their own design page
  as they migrate.
- **Does NOT cover the broader airc module** — only the in-memory
  realtime store. queue-scan / daemon transport / file transport
  get their own audit when they become hot.
- **Does NOT ship a MODULE-CATALOG.md update** — that's step 4 of
  the doc set, separate PR.

# References

- PR #1493 — Field manual (canonical 8-section template)
- PR #1494 — Generator v2 (emits the same template skeleton)
- PRs #1487, #1489, #1490, #1492 — the modules being documented

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…in Rust (step 4 of 4) (#1496)

Final step of the doc set Joel approved on 2026-05-30 ("Yeah let's do it. In order"):

1. ✅ Field manual codifying substrate (PR #1493)
2. ✅ Generator v2 emitting modules per the template (PR #1494)
3. ✅ Per-module design pages for what we've built (PR #1495)
4. **This PR**: MODULE-CATALOG.md update marking which modules are alive in Rust

# What this PR adds

A new `§0. Currently Live In Rust` section near the top of the
catalog with three sub-tables:

## Sub-table 1: Live modules

| Module | What ships | PR | Design doc | Concurrency proven |
|---|---|---|---|---|
| `chat` | chat/poll + chat/send | #1489 | CHAT-MODULE.md | 4 tests |
| `generator` | generate/module + v2 scaffold | #1487 + #1494 | GENERATOR-MODULE.md | 3 tests |
| `data` cursors | data/query-* with HandleRef | #1490 | DATA-CURSORS-MODULE.md | 7 tests |
| `airc/realtime-store` | in-process realtime store | (pre-session) + #1492 tests | AIRC-REALTIME-STORE-MODULE.md | 4 tests |

## Sub-table 2: Substrate primitives

The kernel-level work the four modules ride on — `ServiceModule`
trait, interceptor chain (PR #1483/#1484), HandleRef + cell shapes
(#1485), envelopes (#1486), expect_owned_by + handle_id_or_legacy
(#1491), field manual (#1493), generator v2 (#1494).

## Sub-table 3: Three-primitive map

Per Joel 2026-05-30, mapping the live modules to Commands / Events
/ Persona — showing chat + generator + data are Commands; airc/realtime
is Events; Persona is the next migration target.

# Why minimal restructure

The catalog is 1133 lines of design-proposal entries for every
Continuum concern. Restructuring individual entries to mark which
are live would scatter the live-vs-proposal signal across dozens
of sections. Putting it in one top-of-doc §0 section gives readers
the live-status at a glance without disturbing the rest of the
catalog's design-proposal framing.

# Doctrine the §0 establishes

Modules earn a row in §0 when they clear ALL THREE of the field
manual's acceptance criteria:

1. Rust implementation merged
2. Per-module design doc capturing role / surface / state /
   concurrency / migration / kinks
3. Multi-thread concurrency tests pinning per-resource invariants

This makes the catalog dual-purpose:
- **Design proposal repository** (§I–§IX, unchanged) — what we
  intend to build
- **Implementation status board** (§0, new) — what we've actually
  built + proven

Future migrations grow §0; the proposal sections shrink as their
entries get promoted.

# Updates to the header

- Cross-ref added to COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md
  (joining CBAR / GENOME-FOUNDRY-SENTINEL / PERSONA-COGNITION-CONTRACT)
- Status line updated: "Most entries are design proposals … Some
  are now live in Rust — see §0 below"

# Net diff

+41 lines, -2 lines. Surgical addition that doesn't disturb the
existing catalog content.

# What this PR does NOT do

- **Does NOT migrate any module** — pure documentation
- **Does NOT restructure §I–§IX entries** — each concern stays in
  design-proposal form until it migrates to Rust + earns a §0 row
- **Does NOT add new module concerns to the catalog** — chat,
  generator, data cursors, and airc/realtime-store are already
  represented implicitly in the existing concerns sections; §0 is
  the live-status index, not a new concern listing

# References

- PR #1493 — Field manual (acceptance criteria the §0 table inherits)
- PR #1494 — Generator v2 (eats own dogfood)
- PR #1495 — Per-module design pages linked from §0
- PRs #1487, #1489, #1490, #1492 — the live modules
- Memory: `three-primitives-commands-events-persona`,
  `headless-rust-must-work-soon`

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…+ envelope dispatch + concurrency test (#1499)

Per Joel 2026-05-30:
> "Let's make sure we have detailed designs for this command
>  infrastructure into modules and properly built from the ground up
>  by using our own generators."

Builds on the field manual (PR #1493) which codified the Module
Design Template. This PR makes the GeneratorModule emit modules
that MATCH that template — eat own dogfood, no future hand-rolled
scaffolds.

# Before vs after

**v1 scaffold (PR #1487)** produced 2 files:
- `mod.rs` — ServiceModule with raw-Err dispatch arms
- `README.md` — author-facing summary

The author had to hand-author types.rs, the typed envelope wiring,
the test module, the concurrency stress-test scaffold, and the
DESIGN.md. Every migration repeated the same boilerplate.

**v2 scaffold** produces 4 files:
- `mod.rs` — ServiceModule with typed envelope dispatch + handler
  methods + concurrency test scaffold (multi-thread tokio,
  `worker_threads = 4`)
- `types.rs` — `<Cmd>Params` + `<Cmd>Result` per declared command,
  with `#[derive(TS)]`, `serde(rename_all = "camelCase")`,
  `export_to "../../../shared/generated/<name>/<Cmd>Params.ts"`
- `DESIGN.md` — canonical per-module design skeleton with required
  section headers (Role / Command surface / Cross-module deps /
  State model / Events emitted / Concurrency contract / Migration
  notes / Kinks found)
- `README.md` — author-facing summary referencing all four files +
  cross-refs to the field manual

# New `--stateful` flag

When `params.stateful = true`, the generator additionally emits:

- `use dashmap::DashMap;` import
- `ResourceState` placeholder struct
- `resource_locks: DashMap<String, Arc<tokio::sync::Mutex<ResourceState>>>`
  field on the module struct
- `fn resource_lock(&self, id: &str)` get-or-create helper
- A second concurrency test
  (`resource_locks_stay_parallel_across_distinct_ids`) pinning the
  "different ids stay parallel" invariant

Authors who set `stateful = true` get the per-resource lock pattern
(per field manual §4.1) without writing any of the boilerplate.

# Generated `mod.rs` shape (the substantive change)

Each declared command now emits:

```rust
// Dispatch arm:
"<cmd>" => {
    let req = CommandRequest::<<CmdName>Params>::from_value(params)?;
    let result = self.handle_<verb>(req.params).await?;
    CommandResponse::ok(result).into_command_result()
}

// Typed handler method (scaffolded stub):
pub async fn handle_<verb>(
    &self,
    params: <CmdName>Params,
) -> Result<<CmdName>Result, String> {
    Err("<cmd>: not yet implemented in this scaffolded module".to_string())
}
```

Authors replace ONE line — the `Err(...)` body — to fill in real
logic. The envelope wiring is already in place; the typed params
flow through to the handler; the typed result materializes
through the response envelope automatically.

# Naming helpers

- `command_to_type_stem("chat", "chat/poll")` → `"Poll"`
- `command_to_type_stem("chat", "chat/analyze/findings")` →
  `"AnalyzeFindings"`
- `command_to_handler_name("chat", "chat/poll")` → `"handle_poll"`
- `command_to_handler_name("chat", "chat/analyze/findings")` →
  `"handle_analyze_findings"`

Strips the leading `<module>/` prefix when present; falls back to
the full command path (PascalCase / snake_case).

# Tests (39/39 pass — 22 new + 17 pre-existing)

## New template tests (14)
- `mod_rs_contains_struct_definition_and_trait_impl`
- `mod_rs_uses_typed_envelope_dispatch_for_each_command` ← v2 core
- `mod_rs_emits_typed_handler_methods_for_each_command` ← v2 core
- `mod_rs_imports_envelope_types_from_runtime`
- `mod_rs_includes_with_executor_constructor_for_tests`
- `mod_rs_emits_concurrency_stress_test_with_multi_thread_runtime`
- `mod_rs_for_stateless_module_omits_resource_lock_scaffold`
- `mod_rs_for_stateful_module_emits_per_resource_lock_scaffold` ← --stateful
- `types_rs_emits_params_and_result_for_each_command`
- `types_rs_annotates_for_ts_rs_export_with_camel_case`
- `types_rs_for_command_less_module_emits_no_params_structs`
- `design_md_includes_all_required_sections`
- `design_md_lists_each_command_in_the_surface_table`
- `design_md_state_section_reflects_stateful_flag`
- `command_to_type_stem_strips_module_prefix_and_pascals`
- `command_to_handler_name_strips_module_prefix_and_snakes`

## New filesystem dogfood (1)
- `stateful_multi_command_scaffold_has_consistent_cross_references` —
  scaffolds a stateful 3-command module to a tempdir, then verifies
  every dispatch arm has a matching typed handler, every handler
  has a matching Params/Result type in types.rs, and the stateful
  lock scaffold cross-references match. Closest unit-level proof
  that a real consumer can `cargo check` the scaffold untouched.

## Pre-existing (all still pass)
- All v1 generator tests + the per-name concurrency tests landed
  in PR #1487 still green. The `--stateful` flag is additive; the
  default `stateful: false` preserves v1 behavior at the dispatch
  level.

# What this PR does NOT do

- **Does NOT auto-wire the generated module** into
  `modules/mod.rs` at the parent or register at runtime startup.
  The README + next_step message both spell out the manual steps.
  A future `generate/refresh` command can automate this.
- **Does NOT generate aliases** for legacy command prefixes
  (e.g., `collaboration/chat/*` → `chat/*`). The chat module's
  hand-written alias dispatch is the reference pattern; authors
  wire aliases manually until a `--alias` flag is added.
- **Does NOT enforce specific Params/Result fields** — only
  scaffolds empty structs with the right derives. Authors add
  typed fields per the field manual's ts-rs annotation rules.
- **Does NOT add `generate/command`** (add a new command to an
  existing module). That's a separate follow-up — flagged in
  field manual §6.1.

# Migration story: next chat-analyze migration

With v2 in place, the chat-analyze migration (the worked example
from field manual §5.3) becomes:

```bash
./jtag generate/module \
  --name "chat_analyze" \
  --description "Long-running chat analysis with HandleRef + event streaming" \
  --commands "chat/analyze,chat/analyze/findings,chat/analyze/complete,chat/analyze/cancel" \
  --events-published "chat:analyze:finding,chat:analyze:complete,chat:analyze:cancelled" \
  --priority normal \
  --stateful   # mints + tracks per-run state
```

Output: 4 files, all the boilerplate done. Author opens mod.rs,
implements 4 handler bodies, opens types.rs, fills in 4
Params/Result pairs, opens DESIGN.md, writes the rationale.
That's it — concurrency tests already primed, envelope wiring
already correct, ts-rs bindings already declared.

# References

- [docs/architecture/COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md](docs/architecture/COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md)
  §3 (Module Design Template) — what this PR makes the generator
  emit
- §4 (Concurrency doctrine) — what `--stateful` mode scaffolds
- §6 (Generator usage) — the v2 invocation pattern
- PR #1493 (field manual)
- PR #1487 (v1 generator)

Co-authored-by: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant