Skip to content

Split ai-chat into an abstract base with ai-chat-native and ai-chat-pty subtypes (closes #3446) - #3472

Merged
malibio merged 1 commit into
mainfrom
issue-3446-ai-chat-subtypes
Oct 1, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-3446-ai-chat-subtypes

Conversation

@malibio

@malibio malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator

Closes #3446. Implements ADR-088 §1–§2 on the ADR-086 registry.

What changes

ai-chat becomes an abstract base; a chat is always one of two core subtypes. Each AI-chat type is defined once, in nodespace-types; core's copy (models/ai_chat_node.rs) is deleted.

Type Kind / category Fields (bucket = type id)
ai-chat abstract base, flat agent (required, no default), model, summary, last_active
ai-chat-native core subtype, structured while messages[] is nested provider (native | openai-compat), turn_status (idle | processing), context_tokens, messages
ai-chat-pty core subtype, flat session_status (active | ended), session_id (local_only), transcript (local_only), exit_code

Removed: created_nodes (nothing wrote it), the stale messages[] item-field declarations, the pty provider, session_status on native chats, archived as a session value, every capture: key, and model as a harness name.

Rules (all inherited from the base through the registry): not embedded, not mentionable, no inbound references, children allowed, title required. No relationships added.

Backend

  • Registry / wire: CoreNodeType::{AiChatNative, AiChatPty}; AiChatNativeNode and AiChatPtyNode embed the envelope and AiChatBase, with closed enums for provider, turn status and session status. Each subtype promotes its whole chain, so properties carries extension fields only. flatten_properties_for_api reads a core subtype's chain from the registry.
  • Behaviours: the base keeps the title rule and no-embedding; a behaviour per subtype adds to it. Enum vocabularies are the schema's to enforce.
  • Capture writes bare session_id, transcript, summary, exit_code, last_active and session_status: ended through the validated, versioned update (retrying a version conflict). It no longer writes started_at, ended_at or agent_type.
  • Daemon agent loop: watches ai-chat-native only; turn-status and message writes are patches of the fields they change instead of a rebuilt bucket.
  • Mention containers query: resolved 'task', 'ai-chat' by literal, so no chat (and no task subtype) was its own container once instances stopped being exactly ai-chat. It now goes through the ancestry table.

Frontend

  • A plugin and page-level viewer per subtype (AiChatNativeNodeViewer, AiChatPtyNodeViewer) sharing one title header; no plugin for the abstract base.
  • A new chat is created as ai-chat-native with agent: nodespace. Picking a terminal harness retypes it to ai-chat-pty, sets agent to the harness and clears model; the pane re-resolves its viewer from the node's current type.
  • The AI Chats sidebar queries the base type and lists both subtypes.
  • The PTY view reads typed sessionStatus / sessionId / summary / transcript / agent; "ended" is sessionStatus === 'ended'.
  • hasTypedCoreFields is split: hasTypedUpdate now names only the types with a typed update command, since the chat subtypes promote fields but are written as property patches.

Not in this PR

Docs

The AI-chat sheets in nodespace-docs/components/node-types.md and architecture/ai-chat-node.md already describe these types and fields. A follow-on docs commit adjusts the creation flow ("created as ai-chat-native, retyped when a harness is picked") and notes that retyping between chat subtypes is allowed.

No migration: reset the database.

Tests

  • bun run test:changed: frontend (303 files / 5578 tests), browser, scripts and the Rust workspace all pass.
  • New core/tests/it/ai_chat_subtypes_test.rs: abstract base refused on every create and retype path; buckets, defaults and typed structs per subtype; closed buckets reject the other subtype's and the retired keys; closed enums; a base query returns both subtypes; no inbound references; retype only between chat types; children; title rule.
  • Capture tests: exact key set per content level, ended, the validated write on a real ai-chat-pty node, and refusal on a node that is not a terminal chat.

🤖 Generated with Claude Code

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3472

Review Type: Initial Review (no prior reviews or comments on the PR; reviewed at 5cdede29)

Summary: The split is done the way ADR-088 §1–§2 and ADR-086 describe it. There is one definition per chat type in nodespace-types, core's copy is deleted, the schemas are closed, and rules resolve through the registry. I found no Critical issue and none of the node-type reject conditions (undeclared key, literal node_type comparison, lifecycle_status read, second wire definition, ids-as-relationships, non-UUID id, compatibility code). Two Important items should be fixed in this PR: the eval harness no longer excludes its own chat nodes, and the docs change the PR describes has not landed.

What I ran: scripts/check-node-type-literals.ts and scripts/check-pro-boundary.ts (both clean), 7 targeted frontend test files (239 tests, pass), scripts/aichat.test.ts (19 pass). I did not re-run the Rust workspace or the full test:changed.


Requirements Check (issue #3446 acceptance criteria)

  • ✅ ai-chat is abstract; subtypes have typed structs (tests). core_type.rs marks AiChat abstract with AiChatNative / AiChatPty as children. ai_chat_subtypes_test.rs refuses the base on create_node, create_node_with_parent, bulk_create, bulk_create_hierarchy and on retype. AiChatNativeNode / AiChatPtyNode have wire-contract tests and proptests.
  • ✅ A query for ai-chat returns both subtypes; the sidebar lists both (tests). a_query_for_ai_chat_returns_both_subtypes (real store) and ai-chats.test.ts "lists both chat subtypes" (the store queries the base type and keeps each item's subtype).
  • ✅ Capture writes bare names through the validated update; no capture: key, started_at or ended_at (test). capture_writes_exactly_the_declared_bare_names, finalize_capture_backfills_a_real_terminal_chat (per-bucket assertions, version advances) and the refusal test on a native chat. The conflict retry itself is untested (finding 3).
  • ✅ session_status is active | ended; the PTY viewer reads ended. Closed enum from AiChatSessionStatus::ALL; archived is rejected on write; ai-chat-pty-session.svelte:81 reads sessionStatus === 'ended'.
  • ✅ agent holds the harness or nodespace; model holds only a model id. Native create writes agent: nodespace; the retype writes the harness to agent and clears model; the PTY view pre-selects from agent. Nothing reads model as a harness any more.
  • ✅ No AI-chat type in packages/core/src/models/ai_chat_node.rs. The file and its test file are deleted; models/mod.rs re-exports from nodespace-types.
  • ❌ Follows node-type-sequence.md; node-types.md sheets updated in the same PR. The sheets already describe the three types and their fields. Two gaps:
    • The "follow-on docs commit" the PR description promises (created as ai-chat-native, retyped when a harness is picked; retyping between chat subtypes is allowed) is not on nodespace-docs origin/main as of e06d63f (finding 2).
    • The sequence's "TypeScript regenerated" step cannot be met: the repo has no generator (no ts-rs dependency in any Cargo.toml), so ai-chat-node.ts, typed-core-fields.ts and core-node-types.ts are hand-mirrored, as every other core type on main is. This predates the PR and I am not counting it against it.
  • ✅ bun run test:changed passes; quality:fix clean. Taken from the PR description; I verified only the subset listed above.

Code Review Findings

🟡 Important

1. The eval harness no longer excludes its own chat nodes from graph snapshots
📁 scripts/eval/graph.ts:103 and :273-275

  • What is wrong: SCAFFOLDING_TYPES = ["ai-chat", "date"] is applied as an exact match (!SCAFFOLDING_TYPES.includes(t)) over every schema id from schema list. That list now contains ai-chat-native and ai-chat-pty, and scripts/aichat.ts (changed in this PR) creates the harness's chat as ai-chat-native. So captureSnapshot now queries and returns the harness's own chat node.
  • Effect: the chat exists before the before snapshot and gains two messages during the scored turn, so it shows up in diff.changedNodes. end-state.ts:406-418 fails expectNoWrites on any changed node, so every read-only scenario would report a false failure. This is the case the comment above the constant says the exclusion exists to prevent.
  • How I verified: by reading graph.ts, runner.ts:1052-1086 and end-state.ts. I did not run the eval (it needs the model). No test covers the filter: there is no graph.test.ts, which is why test:scripts stayed green.
  • Recommendation: exclude the whole family, either by listing the two subtype ids or by dropping any schema whose extends chain reaches ai-chat. Add a small bun:test for the filter.
  • Principle: this is the same "instances typed exactly ai-chat" assumption the PR removes everywhere else; the literal checker cannot see it because it is an array membership test, not a comparison.

2. The docs change the PR relies on has not landed
📁 nodespace-docs: components/node-types.md:65, architecture/ai-chat-node.md:29

  • What is wrong: the PR adds a creation flow that neither ADR-088 nor the sheets describe: a chat is always created as ai-chat-native, and picking a harness retypes it in place to ai-chat-pty (ai-chat-native-node-viewer.svelte:160-178, allowed by crud.rs:59-81). The docs (checked at nodespace-docs e06d63f) say only that "no node can be retyped into a chat" and that retyping into ai-chat-native / ai-chat-pty from another type is refused; nothing says a chat may be retyped between chat subtypes or that this is how a terminal chat comes to exist. The PR description defers this to a follow-on commit.
  • Related drift: the sheet gives agent examples as claude, codex; the code and schema description write claude-code. Stored names are user-visible keys, so the sheet should show the real values.
  • Recommendation: push the docs commit before merge and link it in the PR description (the sequence asks the description to link the docs change).
  • Principle: node-type-sequence.md: docs change in the same change, and reviewers reject a type change that leaves its sheet behind.

🟢 Suggestions

3. The capture conflict retry has no test
📁 packages/daemon/src/services/capture_service.rs:84-120

  • Every capture test passes with the loop replaced by a single read and write: none of them produces a VersionConflict. The path matters because capture is fire-and-forget, so a dropped write loses session_status: ended with only a log line.
  • Recommendation: add one test that bumps the node's version between capture's read and write (or races a rename on a multi_thread runtime) and asserts the backfill lands and the rename survives. Confirm it fails with the retry removed.
  • Principle: a test should fail without the change it covers.

4. AiChatPtyNodeBehavior restates the base's rules instead of inheriting them
📁 packages/core/src/behaviors/mod.rs:1704-1730 (and the same four methods at 1665-1702)

  • NodeBehaviorRegistry::resolve (:2455) returns the nearest registered behaviour in the chain, and the trait default for get_embeddable_content embeds the node's content (:266). The "chats are not embedded" rule therefore holds for a subtype only because each subtype behaviour copies get_embeddable_content, get_parent_contribution, can_have_children and supports_markdown by hand.
  • AiChatPtyNodeBehavior validates nothing; if it were not registered, resolve(["ai-chat-pty", "ai-chat"]) would fall through to the base and behave identically.
  • Recommendation: drop the PTY behaviour, or have the subtype behaviours delegate those four methods to AiChatNodeBehavior. The next subtype (ai-chat-acp) should not be able to become embeddable by omission.
  • Principle: DRY; rules compose from the base (ADR-086 §5) rather than being re-declared per subtype.

5. A non-message child of a chat is still not its own embedding root
📁 packages/core/src/db/sqlite_store/embedding_roots.rs:77-125; packages/core/src/behaviors/mod.rs:1640

  • ADR-088 §1, node-types.md (line 105 and the ai-chat sheet) and participation.md:62 say a non-message child of a chat is its own embedding root so it stays searchable. embedding_root_id only re-roots at a filed (member_of) descendant, so a note under a root chat resolves to the chat, which is never embedded, and the note is absent from semantic search.
  • This is not a regression (children under a chat were accepted before), but this PR is where "a chat may hold children" becomes a stated, tested rule (a_chat_may_hold_children).
  • Recommendation: implement it here if small, or list it under "Not in this PR" so the gap between the sheet and the code is recorded.

6. A terminal chat only becomes ended when capture is enabled
📁 packages/daemon/src/services/capture_service.rs:70-72

  • finalize_capture returns before writing anything when capture.enabled is false, which is the default. session_status is now a required core field meaning "is the session running", yet in the default configuration a finished session stays active in the store, and on reopen the viewer re-attaches a terminal to a dead session id (ai-chat-pty-session.svelte:86-88).
  • Same behaviour as before the PR (then archived), so not a regression.
  • Recommendation: write session_status, exit_code and last_active at every session end, and gate only summary / transcript / session_id on the capture setting.

Nitpicks

  • Nit: packages/desktop-app/src/lib/types/core-node-types.ts:40-43: subtypeEntry hardcodes mentionable: false while its comment says the value follows the ancestor. Correct for the chat family, wrong for the next subtype of a mentionable parent (tool-native). Derive it from the parent entry or take it as a parameter.
  • Nit: packages/desktop-app/src/lib/components/viewers/ai-chat-native-node-viewer.svelte:173: the retype patch sends session_status: 'active', which is the schema default the backend applies on retype (a_chat_can_be_retyped_only_from_another_chat_type shows it without the key). The schema default is meant to be the only default.
  • Nit: packages/desktop-app/src/lib/plugins/core-plugins.ts:561: the shared chat plugin config keeps canHaveChildren: false while the backend now says chats hold children. Acceptable while the viewer question is open, but worth a comment saying it is a UI choice, not the structural rule.

Checked and found sound (areas the brief asked for scrutiny on)

  • Leftovers: no remaining read or write of capture:*, created_nodes, the archived session value or provider: 'pty' as a stored value. The one 'pty' left is ModelSelection.provider in ai-chat-model-selector.svelte:24, a UI event value that the viewer turns into a retype.
  • Mention containers: mention_containers_query() now uses is_a_sql over the ancestry table; the plan regression test runs the same function, and the container test covers both subtypes.
  • Daemon writes: turn-status and message writes are field patches at the read version with conflict retry; only ai-chat-native is watched and recovered.
  • Retype path: the model selector is locked once a user message exists, so a chat cannot be retyped mid-turn from the UI. The optimistic update promotes by the target type (shared-node-store.svelte.ts:1948, tested), and the pane resolves the viewer from the node's current type.

Recommendation: REQUEST CHANGES

Small in scope: fix finding 1 and land the docs commit (finding 2). Findings 3–6 and the nits are for /address-review to triage; none blocks.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary (commit cbebd1a3)

Addressed

  1. 🟡 Eval snapshots counted the harness's own chat. SCAFFOLDING_TYPES now lists the whole chat family; the filter is extracted as snapshotQueryTypes and covered by a new scripts/eval/graph.test.ts, including a test that reads the type aichat.ts creates so the two cannot drift.
  2. 🟡 Docs. Landed in nodespace-docs 0f5dc29: node-types.md §1.4 and the ai-chat sheet (agent is required and holds claude-code / codex; retyping between chat subtypes is allowed), architecture/ai-chat-node.md (creation flow: created as ai-chat-native, retyped when a harness is picked; session end vs capture), and the agent example in ADR-088.
  3. 🟢 Capture conflict retry had no test. The retry loop is now write_at_current_version, which takes the version read as a parameter; a_version_conflict_is_retried_and_the_other_write_survives hands it an overtaken version and asserts one conflict, one retry, the session ended and the concurrent rename kept.
  4. 🟢 Subtype behaviours restated the base's rules. Both subtype behaviours take can_have_children, supports_markdown, get_embeddable_content and get_parent_contribution from AiChatNodeBehavior through one macro. The PTY behaviour stays registered: the registry requires a behaviour per core type.
  5. 🟢 A session only became ended with capture enabled. finalize_capture now always writes session_status: ended, exit_code and last_active; session_id, summary and transcript stay behind the capture setting and its content level. Covered by a_session_ends_on_its_node_even_when_capture_is_off. This is a behaviour change beyond the issue's text, folded in because the default configuration otherwise leaves every finished session active and re-attaches a terminal to a dead session.
  • Nit: subtypeEntry derives mentionable from its parent entry.
  • Nit: the retype patch no longer restates the session_status schema default.
  • Nit: canHaveChildren: false on the chat plugins now says it is an editor choice, not the structural rule.

Skipped

  1. 🟢 A non-message child of a chat is not its own embedding root. This is an acceptance criterion of Declare and enforce children and parent rules per node type #3447 ("A non-message child of a chat is embedded as its own root (test)"), which also replaces can_have_children() in embedding aggregation with the declared children rule. Doing it here would duplicate that work in the same files.

Verification: bun run test:changed passes on all tiers (frontend, browser, scripts, Rust workspace); quality:fix clean; push check passed.

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: finding 6 changes what a session end writes (a behaviour change in capture_service.rs, with a new retry seam), and finding 4 changes how the subtype behaviours resolve their rules. Both are small but are logic changes the first review did not see.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3472 (re-review)

Review Type: Re-Review (commit cbebd1a3, ten files, against the initial review at 5cdede29)

Previous Review Summary: 6 findings and 3 nits. 5 findings and all 3 nits addressed, 1 finding skipped with a valid reason, 0 not addressed. New issues found: 0 Critical, 0 Important, 2 Suggestions, 2 nits.

What I ran on cbebd1a3:

  • bun test scripts/eval/graph.test.ts: 3 pass.
  • bun run test -- src/tests/types/core-node-types.test.ts src/tests/components/ai-chat-native-viewer-pty-retype.test.ts: 11 pass.
  • cargo-nextest -p nodespace-daemon capture_service: 7 pass.
  • cargo-nextest -p nodespace-core --lib behaviors:: -E 'test(chat)': 6 pass.

I did not re-run the full test:changed, and I did not mutate the code to watch a test fail (reviewer is read-only); where I say a test would fail, that is from reading it.


Status of the first review's findings

# Finding Status
1 🟡 Eval snapshots counted the harness's own chat Addressed. SCAFFOLDING_TYPES lists the whole family, the filter is extracted as snapshotQueryTypes, and graph.test.ts covers it.
2 🟡 Docs change had not landed Addressed. Read in nodespace-docs: node-types.md §1.4 now says a chat may be retyped between chat subtypes and how a terminal chat comes to exist; the ai-chat sheet shows agent as required with claude-code / codex; the ai-chat-pty sheet says ended is set whenever the session exits. architecture/ai-chat-node.md "Creating a conversation" describes create-as-native then retype, and the ai-chat-pty section describes session end versus capture. ADR-088 uses claude-code. One sentence there is inaccurate for session_id (new finding 1).
3 🟢 Capture conflict retry had no test Addressed. a_version_conflict_is_retried_and_the_other_write_survives hands the first read a version a rename has already overtaken. With the retry removed (or MAX_WRITE_ATTEMPTS = 1) the first write returns VersionConflict as an Err and the .expect panics, so the test does fail without the code it covers. The reads == 2 assertion also pins that the conflict really occurred.
4 🟢 Subtype behaviours restated the base's rules Addressed. inherit_ai_chat_rules! delegates the four methods to AiChatNodeBehavior. Keeping the PTY behaviour registered is right: the registry tests hold the behaviour list to CoreNodeType::ALL.
5 🟢 A non-message child of a chat is not its own embedding root Skipped, reason valid. #3447 lists "A non-message child of a chat is embedded as its own root (test)" as an acceptance criterion, and its item 4 replaces can_have_children() in embedding aggregation with the declared children rule, in the same files. Doing it here would be duplicated work.
6 🟢 A session only became ended with capture enabled Addressed. finalize_capture always writes session_status, exit_code and last_active; covered by a_session_ends_on_its_node_even_when_capture_is_off, which asserts the exact ai-chat-pty bucket.
Nit subtypeEntry hardcoded mentionable: false Addressed. Derived as mentionable && parent.mentionable. The registry-parity test (core-node-types.test.ts, "matches the Rust registry on parent, abstract and mentionable") still pins it against the Rust source.
Nit Retype patch restated the session_status default Addressed. The optimistic node is still correct before the backend responds: the PTY view only tests sessionStatus === 'ended', and the store's optimistic promotion fills sessionStatus: 'active' from typed-core-fields.ts:123. No UI path retypes a PTY chat back to native, so a dormant ended bucket cannot be revived by the shorter patch.
Nit canHaveChildren: false on the chat plugins Addressed with a comment that it is an editor choice.

Requirements Check (issue #3446 acceptance criteria)

  • ✅ ai-chat is abstract; creating one directly is refused; the subtypes are core subtypes with typed structs (tests). Unchanged by this commit.
  • ✅ A query for ai-chat returns both subtypes, and the sidebar lists both (tests). Unchanged.
  • ✅ Capture writes bare session_id, transcript, summary, exit_code and session_status: ended through the validated update; no capture: key, started_at or ended_at (test). a_finished_session_writes_exactly_the_declared_bare_names now covers capture off as well as the three content levels.
  • ✅ session_status is active | ended; the PTY viewer reads ended.
  • ✅ agent holds the harness or nodespace; model holds only a model id.
  • ✅ No AI-chat type is defined in packages/core/src/models/ai_chat_node.rs.
  • ✅ Follows node-type-sequence.md; the node-types.md AI-chat sheets are updated (was ❌ in the first review). The docs live in a separate repo, so "same PR" is met as a paired docs commit, which the address-review comment names.
  • ✅ bun run test:changed passes; quality:fix clean. Taken from the address-review comment; I verified the targeted subset above.

No node-type reject condition is introduced by this commit: no undeclared key, literal node_type comparison, lifecycle_status read, second wire definition or compatibility code.


Code Review Findings (new in cbebd1a3)

🟢 Suggestions

1. session_id is described as capture-gated, but the viewer writes it at every launch
📁 packages/daemon/src/services/capture_service.rs:158-181; packages/desktop-app/src/lib/components/viewers/ai-chat-pty-session.svelte:216-226; docs: nodespace-docs/architecture/ai-chat-node.md:95

  • What is wrong: the commit moves session_id behind config.enabled and the doc comment, the module header and the docs sentence now say the session id is written "only when capture is enabled". The desktop viewer's launch() writes session_id (with session_status: 'active') to the node as soon as the session starts, whatever the capture setting, because re-attach needs it. On the only path that passes a node_id, the node therefore carries session_id with capture off, and the daemon's gate changes nothing.
  • Effect: no wrong behaviour; a misleading contract. a_session_ends_on_its_node_even_when_capture_is_off asserts session_id == None and the exact bucket {session_status, exit_code}, which holds only because the test node never went through the viewer's launch write. A reader who trusts the docs would believe capture-off leaves no session id on the node.
  • Recommendation: treat session_id as the session's own state, like session_status: write it in the always-written set (or leave it to the launch write) and drop it from the "capture's" list in the comment and in ai-chat-node.md. Capture then gates exactly summary and transcript, which is the content.
  • Principle: one statement of a rule, and it must match what the system does; a test should model the real precondition.

2. The always-on write now reaches a node that is not a chat, if a caller passes one
📁 packages/daemon/src/services/capture_service.rs:67-108; packages/daemon/src/services/agent_session_service.rs:187; packages/core/src/services/node_service/crud.rs:2664-2700

  • What is wrong: LaunchSession accepts any node_id and does not check its type. finalize_capture relies on the closed schema to refuse a wrong node, and the test comment says "a node that is not a terminal chat declares none of the session fields, so the write is refused". That is true for core types only: reject_undeclared_core_keys skips non-core scopes ("a user-defined type stays open"). A node_id naming a node of a user-defined type would get session_status, exit_code and last_active written into its bucket. Before this commit that needed capture switched on; it now happens in the default configuration.
  • How I verified: by reading crud.rs; I did not run a test against a user-defined type. Not reachable from the desktop app (it passes the PTY chat's own id, and a chat can only be retyped to another chat type) or the CLI (passes no node). It needs a direct gRPC caller with a wrong id.
  • The other cases are correct: a deleted node fails in current_version with "not found" and is logged at warn; a session with no node returns Ok(None) before any read; a native chat is refused by the closed bucket and left untouched (tested).
  • Recommendation: in current_version (it already has the node), refuse unless type_is_a(node.node_type, CoreNodeType::AiChatPty), or reject the id in launch_session before spawning. Add the user-defined-type case next to the existing refusal test.
  • Principle: validate at the boundary rather than depend on a property (closed schema) the target may not have.

Nitpicks

  • Nit: scripts/eval/graph.test.ts:35-41: the test reads the created type out of aichat.ts with /"--type",\s*"([a-z-]+)"/. It is sound today (one --type in the file, and toBeDefined makes a miss fail loudly), but it takes the first match, so a second --type added above cmdNew would silently test the wrong type. aichat.ts is already import-safe (import.meta.main guard, and decision-roundtrip.test.ts imports from it): export a CHAT_NODE_TYPE constant, use it in cmdNew and import it in the test.
  • Nit: packages/daemon/src/services/agent_session_service.rs:193 and :223: the log lines still say "capture: failed to read config, skipping" and "session capture failed (non-fatal)". Nothing is skipped on a config read failure any more (the default config still ends the session), and the failing write is now the session end. Same for "capture skips when node_id is absent" in packages/cli/src/commands/session.rs:82.

Checked and found sound (areas the brief asked about)

  • write_at_current_version seam: a private function generic over the version read is a small cost for a deterministic conflict test; the alternative, racing a rename on a multi-thread runtime, would be timing-dependent. The production call passes current_version, which the three finalize_capture tests on a real store exercise, so the wiring is covered. Non-conflict errors return at once, and the last attempt's conflict is returned as an error rather than swallowed.
  • inherit_ai_chat_rules!: correct. The base overrides exactly those four methods beyond type_name and validate; validation composes through validate_node over for_chain, so the title rule needs no delegation. test_ai_chat_node_capabilities and test_ai_chat_node_never_embeddable hold the rules for both subtypes. A macro is proportionate here: a default-method supertrait or a wrapper struct would be more machinery for two impls.
  • Config read failure: falls back to CaptureConfig::default() (capture off), and the session still ends on its node.
  • Proto comment on enabled now describes what the flag gates.

Recommendation: APPROVE

Both Important findings from the first review are fixed, the skipped finding belongs to #3447, and this commit introduces no Critical or Important issue. The two suggestions and two nits are small and none blocks the merge.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (re-review): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary, round 2 (commits 6fd16117, f6c91d6f)

Addressed (from the re-review)

  1. 🟢 session_id described as capture-gated while the viewer writes it at launch. session_id is now part of the session's own state, written at every session end with session_status, exit_code and last_active. Capture gates the content only: summary and transcript. Comments, the proto comment and the tests follow.
  2. 🟢 The always-on write could reach a node that is not a chat. finalize_capture now refuses a node unless its type is ai-chat-pty or extends it, before any write. finalize_capture_refuses_a_node_that_is_not_a_terminal_chat covers a native chat and a node of a user-defined type, whose open schema would otherwise have taken the fields.
  • Nit: aichat.ts exports CHAT_NODE_TYPE; graph.test.ts imports it instead of scraping the source.
  • Nit: log lines and the CLI comment say what is written when.

Nothing skipped.

Also in this push: merge with main (f6c91d6f), which brought in generated TypeScript (#3440) and the single task definition (#3441). The conflicts were all on the chat types:

  • The chat wire types (AiChatBase, AiChatNativeNode, AiChatPtyNode, the three enums) carry the ts-rs derives and are registered with the generator; ai-chat-node.ts on the frontend is now guards and default-filling converters over the generated types.
  • core_promoted_fields returns main's PromotedField; the chat arms state their shapes (context_tokens / exit_code numbers, messages an array; last_active and context_tokens read-only).
  • The generated registry entry gains typedUpdate, from WireShape::Typed { update: true }. hasTypedUpdate reads it, replacing the hand-kept list of typed-update types the first frontend pass added.

Verification: bun run test:changed passes on the merged branch: frontend, browser, scripts, types:check (generated TypeScript drift) and the Rust workspace. quality:fix clean; push check passed.

Docs: the nodespace-docs sentence that still lists session_id as capture-gated is corrected in a follow-on docs commit with the merge.

Re-Review Decision

Decision: RE-REVIEW NEEDED

Rationale: the terminal-chat guard is new logic on the session-end path, and the merge resolution re-expressed the chat types in main's generation scheme and extended the generated registry entry. Small, but not seen by a reviewer.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review: PR #3472 (re-review 2)

Review Type: Re-Review (commits 6fd16117 and the merge f6c91d6f, against the re-review at cbebd1a3)

Previous Review Summary: the re-review made 2 suggestions and 2 nits. All 4 are addressed, 0 not addressed, 0 skipped. New issues found in the two new commits: 0 Critical, 0 Important, 2 Suggestions, 3 nits. For the merge I reviewed the resolution (git show f6c91d6f --remerge-diff, 30 files, all on the chat types), not main's own changes.

What I ran on f6c91d6f:

  • bun run types:check: generated TypeScript is up to date (55 files).
  • bun run --cwd packages/desktop-app quality:check (eslint without --fix, design tokens, svelte-check): 2516 files, 0 errors, 0 warnings.
  • bun run test -- on typed-core-fields, ai-chat-node, core-node-types, node-normalize, extension-api-surface, ai-chat-native-viewer-pty-retype, ai-chats: 7 files, 103 tests pass.
  • bun test scripts/eval/graph.test.ts scripts/aichat.test.ts: 22 pass.
  • cargo-nextest -p nodespace-daemon capture_service: 7 pass. -p nodespace-types: 123 pass. -p nodespace-core --test it ai_chat_subtypes_test::: 15 pass. -p nodespace-core --lib core_schemas: 36 pass; --lib -E 'test(chat)': 14 pass.
  • scripts/check-node-type-literals.ts and scripts/check-pro-boundary.ts: both clean.

I did not re-run the full test:changed, and I did not mutate code to watch a test fail (reviewer is read-only).


Status of the re-review's findings

# Finding Status
1 🟢 session_id described as capture-gated while the viewer writes it at launch Addressed in code. build_session_end_properties (capture_service.rs:187-192) writes session_id with session_status, exit_code and last_active at every session end; config.enabled now gates only summary and transcript. The module header, the function comment and the settings_service.proto comment agree. a_finished_session_writes_exactly_the_declared_bare_names and a_session_ends_on_its_node_even_when_capture_is_off assert the new key set. The docs sentence is still open on my copy of the docs (new finding 2).
2 🟢 The always-on write could reach a node that is not a chat Addressed. current_version (capture_service.rs:102-122) refuses unless type_is_a(node.node_type, CoreNodeType::AiChatPty). finalize_capture_refuses_a_node_that_is_not_a_terminal_chat covers a native chat and a node of a user-defined invoice type, with capture off, and asserts version and properties are unchanged. See "Checked and found sound" for the placement and the caller.
Nit graph.test.ts scraped the chat type from aichat.ts Addressed. scripts/aichat.ts:40 exports CHAT_NODE_TYPE, cmdNew uses it, and graph.test.ts imports it. aichat.ts stays import-safe (the import.meta.main guard is unchanged).
Nit Log and comment wording Addressed in agent_session_service.rs:193 and :223 and cli/src/commands/session.rs:81-82. A few sibling comments still use the old wording (nit below).

Requirements Check (issue #3446 acceptance criteria)

  • ✅ ai-chat is abstract; creating one directly is refused; the subtypes are core subtypes with typed structs (tests). ai_chat_subtypes_test passes on the merged tree (15 tests); the generated registry shows ai-chat as abstract: true with both subtypes parented to it.
  • ✅ A query for ai-chat returns both subtypes, and the sidebar lists both (tests). ai-chats.test.ts passes after the merge.
  • ✅ Capture writes bare session_id, transcript, summary, exit_code and session_status: ended through the validated update; no capture: key, started_at or ended_at (test).
  • ✅ session_status is active | ended; the PTY viewer reads ended. The generated AiChatSessionStatus is 'active' | 'ended'.
  • ✅ agent holds the harness or nodespace; model holds only a model id.
  • ✅ No AI-chat type is defined in packages/core/src/models/ai_chat_node.rs. The file and its test stay deleted through the merge; main's edit to it was two doc-comment lines, so nothing was lost. No Rust reference to an AiChatNode struct or an ai_chat_node module remains.
  • ✅ Follows node-type-sequence.md; node-types.md AI-chat sheets updated. The sequence's "TypeScript regenerated" step, which the first review could not hold the PR to, is now met: the chat wire types derive ts_rs::TS, are listed in the generator, and types:check is clean. One docs sentence is unconfirmed (finding 2).
  • ✅ bun run test:changed passes; quality:fix clean. Taken from the address-review comment; I verified the subset listed above.

No node-type reject condition is introduced: no undeclared key, no literal node_type comparison (checker clean), no lifecycle_status read (the converter's envelope() copies the field through, as main's did), no second wire definition, no hand-copied generated TypeScript (the hand-kept TYPED_CORE_FIELDS, CORE_NODE_TYPES and chat interfaces on the branch are replaced by the generated files), no compatibility code.


Code Review Findings (new in 6fd16117 and f6c91d6f)

🟢 Suggestions

1. The chat arms' read_only flags follow no stated rule, and no test pins them or their shapes
📁 packages/nodespace-types/src/convert.rs:353-390; packages/core/src/models/core_schemas.rs:1762-1806

  • What is wrong: main's typed_wire_shapes_promote_their_schemas_fields pins two things for a typed type: the promoted shape follows the schema's field type, and read_only == (protection == System). Both assertions sit inside the WireShape::Typed { update: true } arm, so the chat family (Typed { update: false }) is checked for neither. test_ai_chat_wire_structs_promote_their_whole_chain pins the names only.
  • The shapes are right. I checked each by hand against the schemas with the test's own mapping: context_tokens and exit_code are Number, messages is Array, and the enum, datetime and text fields are Text. They also match the hand-kept table the branch had before the merge, so storageNodeToApiFields behaves as it did.
  • The read_only flags do not follow main's rule. The chat schemas mark six fields System (summary, last_active, context_tokens, session_id, transcript, exit_code); the arms flag two (last_active, context_tokens).
  • Effect today: none. readOnly has one frontend consumer, writableTypedCoreKeys, used only by updateTypedNode, which the store reaches only when hasTypedUpdate is true. On the Rust side read_only is read by the generator and that one test. The frontend never writes last_active or context_tokens (the only references under src/lib are the two reads in ai-chat-node.ts), and chat writes stay properties patches keyed by storage name, so no read or write path for the chat family changed.
  • Why it still matters: the generated table now states that summary and exit_code are client-writable while last_active is not, a distinction nothing chose and nothing checks. If the family gains a typed update, that half-applied flag becomes behaviour.
  • Recommendation: move the shape assertion out of the update: true arm so it runs for every Typed { .. } type over its schema chain (chain_fields). For read_only, either drop it from the chat arms with a line saying the flag only means something for a typed update, or apply the System rule and assert it. Note that the rule as written would flag session_id, which the viewer writes at launch, so decide which before asserting.
  • Principle: one rule per flag, held by a test; the generated table is only as true as the Rust it is generated from.

2. The docs sentence that still lists session_id as capture-gated: not confirmed as landed
📁 nodespace-docs/architecture/ai-chat-node.md:95

  • The address-review comment says this sentence "is corrected in a follow-on docs commit with the merge". The copy of nodespace-docs on this machine still reads: "Saving what the session left behind (session_id, summary, transcript) is opt-in". I read the file only; I did not run git against that repository, so the checkout may simply be behind its remote.
  • Recommendation: confirm the docs commit is pushed before merging. The sentence should say session_id is written with the session's own state, and capture gates summary and transcript.
  • Principle: node-type-sequence.md: the docs change with the code.

Nitpicks

  • Nit: the "capture backfills" wording that 6fd16117 corrected in the CLI comment survives in four siblings: packages/proto/proto/agent_session_service.proto:42-45 ("capture backfills this node ... in which case capture is skipped"), packages/daemon/src/services/agent_session_service.rs:176-178, packages/desktop-app/src/lib/services/tauri-commands.ts:186, and packages/desktop-app/src/lib/components/viewers/ai-chat-pty-session.svelte:209-211 ("Capture backfills the rest at session end (transcript/summary/exit code)"; the exit code is session state now). The session end writes the node whether or not capture is on.
  • Nit: packages/daemon/src/services/capture_service.rs:111-120: the guard accepts "a type extending" ai-chat-pty, and only the refusals are tested. If a user-defined type may extend ai-chat-pty, one accepting case would pin the type_is_a choice over an exact match.
  • Nit: packages/nodespace-types/src/ai_chat.rs:222-223: a stray empty /// after "A single message in an ai-chat conversation." now shows up as a blank line in the generated ai-chat-message.ts doc comment.

Checked and found sound (areas the brief asked about)

  • Where the terminal-chat guard sits. It is in current_version, which the retry loop calls on every attempt, and that is the right place. A retype between the read and the write bumps the version, the write conflicts, and the re-read then refuses the node, so the check and the write are tied to the same version. A check before the loop would not have that property. Non-conflict errors still return at once, and a refusal is not retried (read_version().await?).
  • How the caller handles the refusal. agent_session_service.rs:218-225 logs it at warn with the session id and the error, which names the node id and its type, and teardown is unaffected. That is consistent with every other session-end failure. Rejecting the id in LaunchSession would fail faster for a wrong caller, but the end-of-session check would still be needed (the node can be retyped or deleted while the session runs), and no shipped caller passes a wrong id.
  • Always writing session_id at session end. A session's end write lands milliseconds after the process exits, and the viewer only offers a new session once it has seen the exit, so the end write of an old session overwriting the id of its replacement on the same node needs a relaunch inside that window. I do not consider it reachable by a person.
  • typedUpdate and hasTypedUpdate. The generator computes it as core.wire() == WireShape::Typed { update: true }, the same test typed_update_fields uses, so the frontend's list and the backend's cannot differ. The generated registry marks exactly task, project, person and query. hasTypedUpdate reads it through coreTypeEntry, which returns undefined for a user-defined type, so issue extends task stays on the generic path, as it did under main's exact-key hasTypedCoreFields. No import cycle: typed-core-fields.ts imports core-node-types.ts, which imports only ./generated. No caller of hasTypedCoreFields remains in source or tests; main's two callers (shared-node-store.svelte.ts:1871, schema-authoring.ts:87) both use hasTypedUpdate. CoreTypeEntry is not part of the extension API surface (the surface snapshot test passes), so no EXTENSION_API_VERSION bump is due.
  • ai-chat-node.ts. The converters are called from one place, normalizeNodeData, which is keyed by the exact type, so passing node.nodeType through yields the same value the forced literal did. Nothing discriminated the AiChatNode union on a nodeType literal; the guards use isExactly / isA. AiChatMessage.role as string is main's generated shape; the three readers (chat-message.svelte:20-21, ai-chat-native-node-viewer.svelte:99 and :119-122) compare against string values and filter before casting to DisplayMessage['role']. svelte-check is clean.
  • TYPED_CORE_DEFAULTS with agent: ''. It has one consumer, storageNodeToApiFields (the dev-proxy's storage to wire conversion), where a stored agent overwrites it. For a row with no agent it yields '', which is what the Rust conversion puts on the wire, so the two transports agree. The branch's hand-kept table carried the same value before the merge. It is not used to build a write.
  • Nothing dropped by the resolution. Main's ts-rs derives are on every chat wire type, including the optional = nullable field attributes on the message records. Main's PromotedField shape is used in all three chat arms and in chat_envelope. The app-lib re-export takes main's Priority (main removed TaskPriority) and the branch's two chat structs. The branch's side is intact: the subtype enums, AiChatBase, the registry entries, and the chat arms of the converters. The parity tests the branch had written against the Rust source are gone, correctly: generation plus types:check replaces them.

Recommendation: APPROVE

Both suggestions and both nits from the re-review are fixed, the merge resolution is correct and loses nothing from either side, and neither new commit introduces a Critical or Important issue. Suggestion 1 has no effect on behaviour today; suggestion 2 is a one-sentence docs check to make before merging.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated pragmatic-code-review (re-review 2): APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Address-review summary, round 3 (commit 87684192)

Addressed

  1. 🟢 The chat arms' read_only flags followed no rule, and nothing pinned their shapes. typed_wire_shapes_promote_their_schemas_fields now checks names and shapes over the schema chain for every typed core type, not only those with a typed update. read_only says what a typed update may set: it follows the schema's protection where a typed update exists and must be unset where there is none, so the chat arms no longer carry it. The generated typed-core-fields.ts is regenerated; no frontend path read the flag for the chat family.
  2. 🟢 Docs sentence listing session_id as capture-gated. Corrected in nodespace-docs alongside this push: session_id is written with the session's own state; capture gates summary and transcript.
  • Nit: the four remaining "capture backfills" comments (proto, daemon, tauri-commands.ts, ai-chat-pty-session.svelte) now say the session's end is recorded whether or not capture is on.
  • Nit: a_type_extending_the_terminal_chat_is_written pins the type_is_a choice with an accepting case.
  • Nit: the stray /// on AiChatMessage is gone from the Rust doc and the generated file.

Nothing skipped.

Verification: bun run test:changed passes (frontend, browser, scripts, types:check, Rust workspace); quality:fix clean; push check passed.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: this commit tightens a test, removes a flag the reviewer confirmed has no consumer for the chat family, adds one test and corrects comments. No behaviour changes, and the two prior passes both ended in APPROVE.

@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merge queue: #3472 was taken out of the queue — it conflicts with main in: packages/core/src/models/ai_chat_node.rs, packages/core/src/models/mod.rs, packages/desktop-app/app-lib/src/types.rs, packages/nodespace-types/src/ai_chat.rs, packages/nodespace-types/src/convert.rs, packages/nodespace-types/src/lib.rs. Rebase onto origin/main, push, and re-run bun run merge 3472.

@malibio
malibio force-pushed the issue-3446-ai-chat-subtypes branch from 8768419 to 7063374 Compare October 1, 2026 20:09
@malibio

malibio commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Merge queue: #3472 was taken out of the queue — it conflicts with main in: packages/daemon/src/services/local_agent_service.rs. Rebase onto origin/main, push, and re-run bun run merge 3472.

…ty subtypes (closes #3446)

ai-chat becomes an abstract base (ADR-088 §1-§2); a chat is an ai-chat-native
(NodeSpace's agent loop) or an ai-chat-pty (an external agent in a terminal).
Each chat type is defined once in nodespace-types; core's copy is deleted.

- Base fields: agent (required), model, summary, last_active. Native:
  provider (native | openai-compat), turn_status, context_tokens, messages.
  PTY: session_status (active | ended), session_id, transcript, exit_code.
- A finished terminal session always records its end on its ai-chat-pty node
  through the validated update, under bare field names; capture gates the
  summary and transcript. No capture: keys, started_at, ended_at or agent_type.
- The mention-containers query resolves task and chat through the ancestry
  table instead of type literals.
- Frontend: a plugin and viewer per subtype over the generated chat types; a
  chat is created as ai-chat-native and retyped when a terminal harness is
  picked; the AI Chats list queries the base type.
- The generated registry entry carries typedUpdate.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@malibio
malibio force-pushed the issue-3446-ai-chat-subtypes branch from 62672bb to 02dabb1 Compare October 1, 2026 20:35
@malibio
malibio merged commit 28e5d39 into main Oct 1, 2026
@malibio
malibio deleted the issue-3446-ai-chat-subtypes branch October 1, 2026 20:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Split ai-chat into an abstract base with ai-chat-native and ai-chat-pty subtypes

1 participant