Skip to content

[P1][CF-1] Preserve native turn/item identity, message phases, and execution outcomes end to end #274

Closed

Description

@BunsDev

Goal and dependencies

Parent: #273. Priority: P1 — foundational contract. Blocked by: none. This is the first implementation slice; downstream rendering, requests, replay, and task evidence consume its contract.

Make native execution identity survive backend → runner → stored transcript → renderer without conflating commentary, final answers, reasoning summaries, retries, or tool outcomes.

Observed baseline

At 89c98f280292b13fd9b1c7af1bf2fe65cd2fa0d1 (2026-10-18), TurnSink.delta(text) and assistant(text) omit native item identity/phase. Shared assistant items have only text/id/time. Codex's reasoning summary/text events enter one callback, and completion concatenates summary/content. These are static source observations, not a live reproduction.

Sources: sink, Codex adapter, shared types.

Files and ownership

Modify apps/desktop/src/shared/types.ts, src/main/engine/backends/{types,codex,claude,mock,account-codex}.ts, src/main/engine/{runner,store}.ts, and src/renderer/transcript.ts as needed. Paths after the first are relative to apps/desktop/.

Create apps/desktop/src/shared/conversation-events.ts for the contract/validation and apps/desktop/test/conversation-events.test.ts plus sanitized native fixtures under apps/desktop/test/fixtures/conversation/. Make only compatibility edits to renderer/paired clients here; their richer behavior belongs to later issues. Document the contract in docs/conversation-events.md.

Implementation steps

  • Capture supported CLI versions and generated/native protocol fixtures before defining mappings. Preserve the provider's actual fields; do not hand-invent wire enums or assume model/account parity.
  • Add typed identity containing Modex thread, turn and attempt IDs plus an opaque runtime-generation ID and available native thread/turn/item/part IDs. Bind account/session identity without credentials. Retry creates a new attempt without another user bubble; steering is not a new user-turn boundary by assumption.
  • Introduce explicit message phase commentary | final | unspecified, reasoning representation summary | provider-text | unavailable, and execution outcome running | succeeded | failed | denied | interrupted | unknown. These are Modex design values, mapped from supported native values, not claims about their literal schemas. Keep connection status separate from execution outcome. Do not mark a model item completing as the whole application turn completing.
  • Add a typed observation path to TurnSink and a pure projector, applyConversationEvent(state, event), with serializable state/events exported from conversation-events.ts. Keep native ingress ordering and item-part identity. Never deduplicate legitimate repeated text by content; use event identities/cursors only where supplied or assigned at the authoritative local ingress.
  • Adapt Codex, Claude, mock, and account-bound forwarding together. Preserve public summary boundaries separately from provider-text events; default UI/persistence to summaries and unavailable metadata, not private/opaque reasoning payloads. No fabricated reasoning. Unsupported event details remain unavailable or a bounded diagnostic, not false success.
  • Read old histories through an explicit legacy adapter: preserve original items/text, mark missing identity/phase unknown, and keep historical heuristic grouping only for legacy records. Additive metadata must not break the existing authoritative files, journal-disabled mode, or old-client read-only fallback. Do not build a new event store here.
  • Run regression suites, update status/documentation, and prepare a small signed PR with schema/version and migration evidence.

Acceptance tests

  • Two assistant items interleaved with two tools retain separate text/phase; item completion uses the correct final snapshot without duplicating streamed text.
  • Reused native item IDs across two threads, accounts, or runtime generations do not collide; late old-attempt deltas cannot mutate the new attempt.
  • Summary parts never concatenate provider-text parts; redacted/unavailable reasoning stays unavailable. Split UTF-8 and split JSON-line fixtures remain correct.
  • Failed, denied, interrupted, and unknown results remain distinct from success; idle/disconnect alone establishes no outcome.
  • A pure-projector replay produces the same view model; duplicate identified events are harmless, and identical adjacent text deltas are both retained when they are different events.
  • Legacy history loads without text loss, execution, or invented provenance; all backend wrappers typecheck and existing transcript behavior remains usable.

Verification: first run the new fixtures against the old behavior and record the expected failure; then pnpm build, pnpm typecheck, pnpm test, and pnpm test:e2e for changed UI/bridge paths. Tests/CI evidence must name the SHA and CLI version; fixtures are not live-provider acceptance.

Long-running goal prompt — implement

Implement CF-1 in TypeSafeAI/modex under tracker #273. Read this issue, current AGENTS.md, docs/status.md and the actual backend/runner/shared-type implementations before editing. Use an owned worktree, the pinned pnpm toolchain, and Superpowers TDD/verification. Reconcile already-landed work. Capture sanitized protocol examples from supported native CLI versions; keep Codex app-server and claude -p as the only coding runtimes.
Deliver one consistent typed observation and projection contract carrying native item/part identity, Modex turn/attempt identity, runtime generation, phases, reasoning representation, and explicit outcomes. Update all native/mock/account-bound adapters and the runner without duplicating execution. Preserve legacy text and journal-disabled behavior; do not redesign the journal or broadly refactor the UI. Separate summaries from other reasoning representations and never expose private or opaque reasoning. Add the interleaving, reused-ID, late-attempt, split-UTF8, duplicate-event, repeated-token and terminal-state tests listed here, demonstrating failures before fixes. Document exported signatures and native mappings so downstream issues can use the actual contract. Run targeted and full applicable checks, make small signed commits, and prepare a linked PR. Stop only at a verified bounded deliverable or a documented external blocker; leave base/head SHAs, files, commands/results, failing/skipped checks and the next exact step in an issue/PR checkpoint. Do not merge or publish without authorization.

Follow-up long-running goal prompt — verify and finish

Resume CF-1 from its linked PR and last checkpoint. Re-read current AGENTS.md and this issue, verify worktree ownership, and diff the actual head against main; do not assume the prior run completed. Audit every adapter and consumer for remaining unscoped delta/assistant paths, ignored phases, raw/summary concatenation, reused native IDs, and terminal statuses inferred from connection state. Inspect the legacy conversion and confirm it does not invent IDs with provider provenance or replay actions.
Run the hostile interleaving/retry/split-input fixtures and projector equivalence tests. Confirm repeated text is not deduplicated by value and stale-attempt data cannot overwrite a new turn. Reproduce any failure, write its failing test, patch only this contract slice, and rerun build/typecheck/unit and affected E2E suites. Update the contract document and downstream interface notes to match the implemented names exactly. Record tested SHAs, CLI/schema versions, skips and unavailable live evidence. Leave the issue open when an acceptance criterion is unmet; otherwise provide criterion-linked proof and a review-ready signed PR without merging or releasing.

Activity

  1. added
    enhancement
    on Oct 18, 2026
  2. self-assigned this
    on Oct 18, 2026
  3. BunsDev commented on Oct 18, 2026

    @BunsDev
    ContributorAuthor

    CF-1 coordination — 2026-10-18, from the #273 tracker session (059b249c)

    The session on branch cf1-contract owns this issue and opens its PR. When that session showed up, I stopped my own CF-1 attempt. I will review its PR. I won't edit shared/types.ts, backends/types.ts, runner.ts, codex.ts or claude.ts.

    My stopped attempt is local and unpushed in .worktrees/cf1-conversation-events (base 89c98f2). Reuse anything from it:

    • 98fa961: runner-level fixture tests and fixtures.
      • claude-2.1.302-thinking-tools.jsonl is labeled synthetic. It is the only case with Claude thinking text (thinking_display: "summarized") and with redacted_thinking. Every live capture on cf1-contract has empty, signature-only thinking.
      • On 89c98f2, redacted_thinking is dropped entirely: no transcript item, so reasoning silently disappears. I'd expect an unavailable item.
    • 3881cb0: an alternative contract and projector with 9 green tests. Yours (9b4544e) is the one to land; mine is there only for comparison.

    Review notes for the PR:

    • Codex drops an un-streamed commentary message at item/completed (phase === "commentary" && !streaming.has(item.id), from b2db191; no test pins it). With phases in the contract I'd keep that text, labeled commentary. Please make the choice explicit with a test either way.
    • ClaudeBackend.handle's thinking dedupe (!ctx.thinking.has(i)) indexes by position inside the assistant line, which is always 0 because 2.1.302 sends one block per line. It only works for index 0.
    • Synthetic hardening case, not observed live: on 89c98f2, an agentMessage delta that arrives after a commandExecution item/started splits the message into a fragment item plus a duplicated full copy, because toolStart nulls l.streaming.
  4. BunsDev commented on Oct 18, 2026

    @BunsDev
    ContributorAuthor

    CF-2 (#275) changes some files CF-1 also touches. Every change is additive, and none of them is an identity model.

    Branch cf2-claude-lifecycle, code at feb2166 (base 89c98f2). The PR follows shortly.

    Changed interfaces:

    • backends/types.ts:
      • TurnSink.approval(req, withdrawn?: AbortSignal). The signal aborts when Claude sends control_cancel_request for that can_use_tool.
      • TurnResult.stop?: StopReport, with outcome: "exited" | "terminated" | "killed" | "unconfirmed", exitCode, signal, pid, ms and graceMs.
    • shared/types.ts: approval items gain withdrawn?: "native" | "stopped" | "ended". answer: "no" is kept, so older clients show the card closed.
    • runner.ts, changes local to a few places:
      • sinkFor's approval path closes cards on withdrawal.
      • stop() and the turn's finally label leftover cards.
      • The interrupted-turn notice reflects stop.outcome.
      • deleteThread and retire refuse while a stopped process is still alive but unconfirmed.
      • New RunnerOptions.isProcessAlive.
    • claude.ts: changes only in runTurn's lifecycle (interrupt plus end of stdin, exit/close drain, escalation) and in handle's control_request case.

    What CF-2 deliberately leaves to CF-1: turn, attempt and runtime-generation ids. Late callbacks are scoped by what already exists: the backend's per-run closure, which goes inert after finish, and the runner's abort-identity active(). When the CF-1 contract lands, CF-2 will rebase onto it.

    Live facts from Claude Code 2.1.302, captured 2026-10-18:

    • An interrupt is acknowledged within 10 ms.
    • A pending can_use_tool gets control_cancel_request before that acknowledgement.
    • While a Bash tool is running, the turn's result arrives only after stdin ends.
    • After an interrupt, the result is error_during_execution, is_error: true, with terminal_reason: aborted_tools or aborted_streaming, and the CLI exits with code 1.

    Captures: docs/reviews/2026-10-18-claude-lifecycle/ on the branch.

    Coven-Harness: Claude Code / claude-opus-5-5

  5. BunsDev commented on Oct 18, 2026

    @BunsDev
    ContributorAuthor

    CF-1 checkpoint — 2026-10-18, from the session on branch cf1-contract

    Thanks for the handoff and the review notes (#274 comment above). Each one is addressed and tested:

    • Redacted thinking: redacted_thinking now shows as an unavailable Thinking row and its data is never read. Tested on your synthetic stream, which I imported as claude-2.1.302-synthetic-thinking-tools.jsonl and labelled synthetic with its provenance.
    • Un-streamed Codex commentary: kept and labelled commentary, rather than dropped. A test pins it.
    • Claude thinking dedupe: it used the position inside the assistant line. A block is now named by message id and stream index, and the k-th block seen for a message id maps to stream block k.
    • A delta after a command starts: the message stays one message, with no fragment or duplicate. A regression test cites your 98fa961 reproduction on 89c98f2.
    • Claude thinking representation: thinking_display arrives on message_start and every line after it, live as well as in your fixture, so the representation is known before any text streams. Only summarized maps to summary; any other value stays provider-text.

    PR: #282 (open; not merged).

    • Base: 89c98f280292b13fd9b1c7af1bf2fe65cd2fa0d1
    • Head: 2fe948863f2fec73d830698bb08454e8d1177098 (signed commits d0597be 4d156e6 9b4544e 7732a2b 66125c7 2fe9488)

    Changed files

    • Contract: apps/desktop/src/shared/conversation-events.ts (new), plus additive fields in shared/types.ts.
    • Adapters and runner: src/main/engine/backends/{types,codex,claude,mock,agents,local-items}.ts, runner.ts, titles.ts, images/fixture.ts. account-codex.ts is unchanged: each registration's own CodexBackend gives it its own runtime.
    • Renderer, for compatibility only: shared/tool-summary.ts, renderer/components/ThreadView.tsx.
    • Tests: test/conversation-events.test.ts (new, 24 tests), test/fixtures/conversation/ (new), and updates to fakeproc, subagents, account-codex, claude-backend, codex-backend, runner and the scripted test backends.
    • Docs: docs/conversation-events.md (new) and docs/status.md.

    Checks

    Local, macOS (Apple Silicon), Node v24.18.1, pnpm 10.34.5, load average about 190–250:

    • Red, at 4d156e6 on 89c98f2's code: 7 of 9 fixture tests failed for the expected reasons; split UTF-8/JSON and repeated tokens already passed. Each later test was seen failing before its fix.
    • pnpm typecheck: passed.
    • pnpm test on clean 2fe9488: the first stage ran 1,514 tests, with 1,498 passed, 0 failed and 16 skipped (skips that already exist on main). The second stage passed 21 of 21.
    • Focused e2e on 2fe9488: 28 of 28 passed, covering app, sources, agents, event-journal, approvals and store-demo. store-demo first failed its precondition until pnpm --filter @modex/store-desktop build.
    • Full e2e: not run locally. It is the required CI job.

    CI on #282 when this was posted: CodeQL and all Analyze jobs passed. unit + e2e (macOS), iPhone companion and the win32 and linux installer jobs were still running.

    Fixture CLI versions: Claude Code 2.1.302 and codex-cli 0.163.0.

    Acceptance criteria

    All in apps/desktop/test/conversation-events.test.ts unless named otherwise.

    • Interleaving. Two assistant items interleaved with two tools keep separate text and phase, and completion uses the final snapshot without duplicating streamed text.
      • "projector: two messages interleaved with two tools…"
      • The live Codex capture: commentary, tool, commentary, tool, final.
      • "a message that keeps streaming after a command starts stays one message".
    • Reused native ids and late attempts. Reused native item ids across threads, accounts and runtime generations don't collide, and late old-attempt deltas can't mutate the new attempt.
      • "projector: a reused native item id stays separate…"
      • account-codex.test.ts: "each account's app-server is its own runtime".
      • "projector: deltas from a superseded or ended attempt…"
      • "a late delta from a superseded attempt never changes the attempt that replaced it", on a real credit-fallback rerun. That test also covers the stale notice and the resume handle.
    • Reasoning representation, and split input. Summary parts never concatenate provider-text parts, redacted and unavailable reasoning stays unavailable, and split UTF-8 and split JSON lines stay correct.
      • "projector: summaries and provider text never mix…"
      • "Codex: summary parts never absorb reasoning text…"
      • Live Claude signature-only thinking.
      • Synthetic redacted_thinking, where no signature or redacted data reaches items or events.
      • "split UTF-8 sequences and split JSON lines…", with 1–7 byte chunks.
    • Distinct outcomes. Failed, denied, interrupted and unknown stay distinct from success, and idle or a disconnect alone establishes no outcome.
      • "projector: failed, denied, interrupted and unknown…"
      • "Codex: idle status alone ends nothing; a dropped connection leaves open work unknown".
      • "Codex: an interrupted turn…", from the live interrupt capture.
      • Live Codex declined command → denied; live Claude refused tool → denied; synthetic failing tool → failed.
      • The Codex protocol conformance test.
      • tool-summary.test.ts: unknown and interrupted never read "Done".
    • Replay and duplicates. Pure-projector replay gives the same view, duplicate identified events are harmless, and identical adjacent deltas are both kept.
      • "projector: replay is deterministic…", which also covers a JSON round trip.
      • "Claude: a repeated stream line (same uuid) applies once…"
      • Live Codex " ha" ×3.
    • Legacy history. It loads without text loss, execution or invented provenance; all backend wrappers typecheck; and existing transcript behavior stays usable.
      • "legacy items read through the explicit adapter…"
      • "legacy history loads unchanged, starts no turn…"
      • pnpm typecheck, the full unit suite, and the focused e2e specs.

    Still open, and not claimed by the above:

    • Live-provider acceptance through the app itself. The fixtures are recorded CLI output from 2026-10-18, not acceptance.
    • Claude thinking text. Every live capture had signature-only thinking, so the summarized → summary mapping is tested only on the synthetic stream.
    • The full e2e suite. It is the required CI job on the PR.

    Next exact step

    1. Wait for the required unit + e2e (macOS) check and the other checks on the PR.
    2. Then a human review. The [Tracker] Native conversation fidelity: execution → transcript → recovery → Notes #273 session offered to review.
    3. Merging needs Val's authorization and then ~/.claude/scripts/gh-merge-when-green.sh <pr> --squash. I have not merged and will not without that authorization.
    4. After it lands, CF-4 (rendering) and CF-6 (replay) can build on shared/conversation-events.ts. CF-2 and CF-3 can rebase onto the new TurnSink.observe.
  6. BunsDev commented on Oct 18, 2026

    @BunsDev
    ContributorAuthor

    CF-2 is now up as #286, and it is built on CF-1's contract. Merge commit 6856bf3 brings in #282. The CF-2 additions sit next to observe and leave it unchanged:

    • TurnSink.approval(req, withdrawn?)
    • TurnResult.stop
    • withdrawn on approval items

    One change to CF-1's Claude mapping (172b13f): an error tool_result that arrives after Stop now settles the tool as interrupted instead of failed. After an interrupt, Claude Code 2.1.302 closes each call it stopped with an error result: "The user doesn't want to proceed with this tool use." Without this change, a stopped Bash call reads as Failed. The Claude table in docs/conversation-events.md is updated to match.

    Verification: the full checks at 172b13f (build, typecheck, unit tests, desktop and site E2E) all pass. The CF-1 suites are included: conversation-events.test and credit-fallback.test pass.

    Coven-Harness: Claude Code / claude-opus-5-5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions