Skip to content

fix(server): persist swarm completion report on CommReport - #1750

Draft
nkcodec wants to merge 28 commits into
1jehuang:masterfrom
nkcodec:fork/turnstart
Draft

nkcodec wants to merge 28 commits into
1jehuang:masterfrom
nkcodec:fork/turnstart

Conversation

@nkcodec

@nkcodec nkcodec commented Oct 7, 2026

Copy link
Copy Markdown

Problem

swarm(action=report, ...) updated latest_completion_report in memory and broadcast ServerEvent::SwarmStatus to live clients, but never persisted to ~/.jcode/state/swarm/session_*.json. The persisted record was only refreshed by heartbeats, salvage, removal, and orphan-reparent, so a worker that reported back could lose its report when the idle worker reaper overwrote its status to stopped.

On 2026-10-07 at 21:36-21:38 UTC, two spawned workers (cricket, crocodile) called swarm action=report status=completed and status=ready with full completion reports. Their persisted JSON files still showed latest_completion_report=null ~30 minutes later when the reaper overwrote status, so the coordinator never saw the reports on resume.

Change

update_member_status_with_report_tldr (crates/jcode-app-core/src/server/swarm.rs:1427) gains swarm_plans and swarm_coordinators parameters and, after broadcast_swarm_status returns, persists the swarm state once per turn when a new completion report is actually recorded. The two existing Request::CommReport callers (client_lifecycle.rs, client_lightweight_control.rs) now pass the two maps that are already in scope at their callsites.

Status-only transitions (no completion report) skip the persist path. The reaper, heartbeat, salvage, removal, and orphan-reparent paths are unchanged.

Test

comm_report_persists_completion_report_to_disk in crates/jcode-app-core/src/server/swarm.rs::tests exercises the full path: an IsolatedRuntimeDir RAII guard redirects persistence to a tempfile::TempDir via JCODE_RUNTIME_DIR; the test sets up a swarm with one plan and a coordinator, calls update_member_status_with_report_tldr with status "completed" and a non-empty report, then reads back the JSON and asserts latest_completion_report and status are correct.

Verified end-to-end:

  • Test FAILS without the gate (file not written, os error 2 on read).
  • Test PASSES with the gate.
  • Full swarm::tests:: module: 30/30 pass.
  • Workspace cargo check: clean.

Note

The pre-existing member_in_status_broadcast already retains terminal members for 15 minutes (default JCODE_SWARM_STATUS_BROADCAST_TERMINAL_SECS), so the live ServerEvent::SwarmStatus broadcast still surfaces the completed worker to the coordinator during that window. The bug was only the on-disk persistence. No broadcast-pacing change ships here.

emilio and others added 28 commits October 6, 2026 21:43
Add run_turn_start_collecting() (hooks.rs): sync dispatch of turn_start
hooks with stdout captured, capped at 4000 chars, never fails the turn.

turn_execution.rs: append non-empty output as [HOOK TURN_START] block to
the turn system reminder, giving hooks a dynamic context channel.

Live-verified on this box 2026-09-24: daemon runs this as
versions/0.88.0-turnstart; alerts written to ~/.jcode/ALERTS/ surface in
every session banner.
run_once (used by 'jcode run', ambient cycle agents, and debug exec) went
through run_turn without setting current_turn_system_reminder, so hook
stdout never reached those sessions. Extract run_once_with_optional_hook_
banner and fire run_turn_start_collecting() there too, matching the
streaming entry point's behavior.

Live-verified: 'jcode run' with an ALERTS marker now reports the
[HOOK TURN_START] banner; without a marker it correctly reports none.
…json, ambient, swarm)

1a8ab2b7a only covered run_once (print path). run_once_capture_with_display_role
is what run_single_message_command_capture_with_auto_poke (jcode run --json),
ambient cycles (run_once_capture), debug exec, and swarm workers use; those
consumers never saw the [HOOK TURN_START] banner. Extract
fire_turn_start_hook_into_reminder shared by both non-streaming entries.
Ambient runner built a bare Registry for cycle/guardian agents, so scheduled
work never saw any mcp__* tools (e.g. mcp__jev__* judgment tools) unlike
interactive, headless-run, and swarm sessions. Register MCP at all three
runner sites: direct-delivered items, spawned scheduled sessions (both via
register_mcp_tools_for_dir so project-local config resolves against the
item working_dir), and the headless cycle agent.
fingerprint_config covers connection config only, so description-only
server updates never reached new sessions (stale tool text served from
cache forever). Mirrors the 1jehuang#206 Phase 2 cache-sync block from the
spawn path into reload_config. Found via laya v3.14 description-only
deploy; tests: schema_cache 8/8, test_reload_empty_config green.
The streaming turn path ran the hook twice: once via the fork's collecting
dispatch (stdout into system reminder, no session metadata) and once via
the legacy stock fire-and-forget observer (with metadata). Side effects
executed twice per turn (double stamp advances, double ntfy pushes).

- run_turn_start_collecting now takes session_id, cwd, source and exports
  JCODE_HOOK_SESSION_ID / JCODE_HOOK_CWD / JCODE_HOOK_SOURCE (chat=streaming
  interactive, run_once=ambient/headless/swarm) so hooks can attribute fires
- legacy fire_turn_start_hook('chat') removed; collecting dispatch is the
  single turn_start dispatch on all paths
ScheduledItem/ScheduleRequest gain recurse_minutes (serde default None).
pop_ready re-arms due recurring items in place: clone with same id,
scheduled_for = now + N so missed-interval backlog collapses to one
pending copy. Fix: re-arm must run AFTER self.items = remaining or the
assignment wipes the clones (caught by new unit tests, 5 cases).

schedule_ambient + end_ambient_cycle next_schedule accept the field;
schema property added; opt_i64 coerce helper added to serde_coerce.

Motivation: guardian re-arm relied on model discipline; two silent
guardian deaths on 2026-09-24 (first disk-guardian pair died after one
run). Structural re-arm survives mid-run kills.

Tests: fork_recurse_tests 5/5; ambient surface 61/61 excluding
scheduled_live_delivery_reaches_subscribed_client, which now VERIFIED
pre-existing: fails alone on clean HEAD worktree (re-verified 2026-09-30).
Live smoke (2026-09-30, worker microbe) fell back to the generic
schedule tool because only schedule_ambient had the schema property.
Both create tools now accept and map recurse_minutes.
take_ready_direct_items consumed session-targeted recurring items
without re-arming: a per-session guardian died after one fire.
Live-caught 2026-09-30 with smoke item sched_d9eae4bf (session
target, recurse_minutes=2: popped, never re-queued). Mirrors
pop_ready's rearm; same-id clone scheduled from now.

Test: direct_delivery_recurring_item_is_rearmed (fork_recurse 6/6).
When a background await_members times out but its workers are alive, the
watcher now re-arms itself instead of finalizing and relying on the
coordinator to remember. Guards:

- Progress gate: last_progress_ms (persisted on every swarm event for the
  wait's swarm) must be newer than the current round's start; a hung worker
  finalizes immediately instead of looping.
- Hard cap: MAX_AUTO_REARMS = 3, then finalize as timeout.
- Backoff: base x 1/2/4, capped at 1h. Base recorded from the caller's
  timeout on first arm. A manual re-arm after a FINALIZED timeout resets
  counters (fresh budget by explicit request).
- Background waits notify the requester on re-arm (wake=false).

Also fixes a wart found while designing: a duplicate await_members on an
already-active key previously hung until client timeout; it now answers
"deduped" immediately (waiter still receives the completion).

Regression caught during dev: the progress probe originally saved the
watcher's stale in-memory state, clobbering prefs a duplicate request had
upgraded on disk (background delivery lost). Probe now read-modify-writes
the disk copy. Caught by await_upgrade_background test; suite 74/74.

Decision logic unit-tested in await_auto_rearm (6 cases: progress re-arm,
backoff doubling, cap, hung guard, 1h ceiling, serde back-compat).
… cap

The full-suite token-cap test caught the parallel session's recurse_minutes
schema text at ~33 tokens. Shortened both schedule tool variants; meaning
unchanged (structural re-arm, same id, omit for one-shot).
Models sometimes pass the dispatch alias (mcp__<server>__<tool>) as the
bare tool name to mcp_call; remote servers then answer -32602 'Tool
mcp__... not found' and the agent burns a retry round-trip. Strip a
matching self-prefix before dispatch.

Observed in live logs 2026-10-01: 'MCP error -32602: Tool
mcp__jev__jev_audit not found' with the tool actually present.
A long-lived session's MCP child can die while the session lives on
(CBM daemon idle-exit, serena crash). The manager kept the closed
handle in its map, and since connect-on-first-call only triggers when
the server is absent, every subsequent call failed with 'exited
(stdout closed)' until a manual mcp reload.

- McpHandle/McpClient: expose is_closed()
- Manager::call_tool: check both fast paths, prune dead entries
  (release pool handles / shutdown owned client), then fall through
  to the existing reconnect path
- McpServerConfig: derive Default (test convenience)
- unit test: is_closed flips false->true across child EOF
Backing models behind the omni mux periodically emit mangled tool
names (live evidence: 119 failures across 3 sessions since Sep 19):
CamelCase forms (Agentgrep, McpCall, SkillManage, Ls, Bg) and bare
MCP tool names missing the mcp__server__ prefix (get_architecture).
Each one burned a failed round-trip; the corrective error usually
recovered but wasted tokens and occasionally spiraled.

Add a tolerant registry fallback in jcode-tool-types (kept dependency-
light and unit-testable there; app-core delegates):
1. separator/case-insensitive exact match (Agentgrep -> agentgrep,
   McpCall -> mcp_call)
2. unique mcp__ suffix match (get_architecture ->
   mcp__codebase_memory__get_architecture)

Ambiguous matches still fail with the available-tools list so the
model can self-correct; genuinely unknown names behave as before.
…P tools in fuzzy test

- turn_start banner injection (streaming + non-streaming entries) skipped
  under cfg(test): unit tests must not execute the developer's real
  turn_start hook; its [HOOK TURN_START] reminder leaked into provider
  prompts and broke fable_guardrail_reconsideration_recovers_the_streaming_turn
  and retention_readiness_scorecard on machines with a real hook installed
- run_turn_start_collecting honors JCODE_HOOKS_DISABLED like every other
  hook path (consistent suppression semantics)
- fuzzy_resolve test: seed mcp_call/mcp_search/skill_manage explicitly -
  they register lazily (MCP activation), not in the bare base registry

Validation: jcode-base hooks+storage 25/25; app-core lib 1453 pass,
1 known load-flake (background_task_wake, passes alone); upstream
worktree control run confirms the 2 hook-leak failures were fork-only
run_turn_start_collecting must return None without executing the hook
while JCODE_HOOKS_DISABLED is set, and collect trimmed stdout when not.
Uses the JCODE_HOOK_TURN_START env override surface. First direct test
of the collector.

TEST-ONLY commit: no production code changed; deployed binary
(da0eb94d @ 20261003T080612Z) stays current.
ACP clients (Desktop) have no skill picker or slash popup, so a typed
`/name` previously reached the model as plain text. Resolve it in
start_processing_message against the same registry the CLI repl uses:
registered names activate the skill (SKILL.md becomes the system prompt,
trailing text becomes the turn prompt) and unregistered or path-like
slash text passes through untouched. Explicit client-sent active_skill
still wins.
Idle soft-interrupt turns reuse start_processing_message with the queued
payload as content. Their text is machine-generated, so a leading /name
must not be reinterpreted as a skill invocation. Thread an internal
resolve_skill flag through ProcessingMessage: true for client messages,
false for the idle-interrupt path. Wire format unchanged.
…are unchanged

The completion-confidence gate poked 'Double-checking confidence for you...'
on every turn end when any completed todo's completion_confidence was below
validated. Unlike the ownership gate it had no unchanged-assessment dedup,
so an agent that re-verified and kept its honest scores got poked again and
again (user-visible: 3+ identical popups in a row). The continuation message
itself asks the model to keep todos up to date, so each re-verify turn
rewrote the todo file and defeated the existing unchanged-state guards.

Fix: fingerprint the completed todos' (id, completion_confidence,
confidence_history). If a poke already fired and the fingerprint is
unchanged, log AUTO_POKE_DECISION action=idle
reason=unchanged_completion_confidence and fall through to the clean
completion handoff with the honest confidence label. The fingerprint resets
when todos change, when the circuit breaker trips, and when new open work
begins, so genuinely new work still gets gated. Fingerprint survives client
reload via the restore blob.
…fix rebase test drift

- test_completion_gate_nudges_stop_after_budget_exhausted: now asserts the
  new behavior (gate fires once, falls through to the clean final-response
  handoff on attempt 1, fully idle from attempt 2).
- helpers_tests.rs: 3 upstream ScheduleRequest initializers lacked the fork's
  recurse_minutes field (0.91 rebase drift).
The fingerprint dedup added in 7a4c199 was silent: a suppressed poke
left no trace, so observability of the dedup path required reading code.
Add an else branch logging AUTO_POKE_DECISION action=idle
reason=unchanged_completion_confidence with a 32-char fingerprint
preview and completed count, matching the existing idle-decision log
lines. Behavior unchanged; logging only.
Three defects found by the new regression test:

1. The fingerprint serialized a Vec of (id, confidence, history)
   tuples whose byte representation was not stable across calls for
   identical todo states, so the dedup comparison could spuriously
   mismatch. Sort tuples by id before serializing.

2. The fire branch never advanced the fingerprint, so a second call
   with unchanged todos compared equal against the stale baseline,
   mismatched, and fired again every turn (the user-reported repeat
   poke). Assign the fingerprint inside the fire branch.

3. The regression test asserted attempts stay at 1 after dedup, but
   the clean final handoff resets attempts to 0 by design. Assert the
   reset instead.

test_completion_gate_dedup_suppresses_unchanged_todos proves: turn 1
fires (attempts 1), turn 2 with identical todos routes to the clean
final handoff (continuation queued, attempts reset to 0), no repeat
'Double-checking confidence' popup.
The dedup does not re-fire when todos change after the final handoff:
todo_final_response_requested latches true at the clean handoff, and the
schedule function returns false on every later call while latched. The
prior turn's summary claimed the fingerprint alone governed re-firing;
this test pins the actual semantics: one poke per completion cycle,
then permanent idle until a new cycle begins.
…off latch

Turn 1 fires gate with Speculative todo. Turn 2 saves a new history entry
but confidence is still below threshold. Fingerprint changes and the gate
fires again within budget. Turn 3 (unchanged todos) dedups and the clean
final handoff latches. Turn 4 fully idle.

Asserts: budget advances on refire (1->2), resets on handoff, poke count
matches distinct below-threshold states fired. Coalesced display: two
back-to-back identical system messages become one row with [x2] suffix.
Pure read-only CLI, no server round-trip or model call. Reads persisted
sessions and git commits from discovered project roots over a time window,
groups by day, and prints human-readable or JSON output.

Flags:
  --since         Time window: 30m, 2h, 1d, 3d, 1w (default: 1d)
  --working-dir   Filter sessions by project root
  --no-git        Sessions only
  --json          Structured JSON output

Session output: title, working_dir, msg counts, first user prompt.
Commit output: short hash, subject, author, repo.
Both grouped by local date. Discovered repos: ~/src/*, ~/app/projects/*, cwd.
jcode digest: authored-work summaries grouped by day from recent sessions
  and commits. Supports --working-dir, --days, --format (text/json).

jcode decisions: decision trail extracted from session tool/intent pairs.
  Supports --session, --format (tsv/text/json). Uses Session::load (not
  load_startup_stub) so decisions are actually extracted.

jcode pr: PR guardian using gh CLI. Checks mergeable state, review
  decision, and status check rollup. Exit 0 = all green, exit 1 =
  needs attention. --notify posts to ntfy.sh.

jcode recall: project state snapshot — git branch, recent commits, open
  sessions, open todos, project memories, open PR count. Defaults to cwd.
  Supports --working-dir, --since-days, --format.

Fixes (recall): Todo files are top-level Vec, not wrapped objects.
Priority field accepts serde_json::Value (string or object). Session
loading uses Session::load to avoid load_startup_stub schema mismatch.

Fixes (tests): Session IDs in CLI integration tests matched file names
incorrectly (stripped 'session_' prefix that was present in filenames).

Unit tests: 8 recall tests covering git_state, todos (empty/missing/priority
variants), and project memories. All pass.
`Request::CommReport` updated `latest_completion_report` in memory and
broadcast `ServerEvent::SwarmStatus` to live clients, but never persisted
to `~/.jcode/state/swarm/session_*.json`. The persisted record was only
refreshed by heartbeats, salvage, removal, and orphan-reparent, so a
worker's completion report could be lost when the in-memory state was
later reaped by the idle worker reaper.

Croc and cricket on 2026-10-07 completed and reported back; their JSON
still showed `latest_completion_report=null` until the reaper overwrote
status to `stopped`.

Persist once per turn inside `update_member_status_with_report_tldr`
when a new completion report is recorded.

Signed-off-by: Jcode Subagent <emilio@Hetzner>
xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
Save changed report text even when no assigned plan task closes. Port 1jehuang#1750.

Co-authored-by: nkcodec <[email protected]>
xenking added a commit to xenking/jcode that referenced this pull request Nov 22, 2026
Upstream-PR: 1jehuang#1357
Upstream-PR-Commit: 1jehuang#1357 0da5e81
Upstream-PR: 1jehuang#1362
Upstream-PR-Commit: 1jehuang#1362 5962058
Upstream-PR: 1jehuang#1486
Upstream-PR-Commit: 1jehuang#1486 fadc624
Upstream-PR: 1jehuang#1733
Upstream-PR-Commit: 1jehuang#1733 01f3415
Upstream-PR: 1jehuang#1750
Upstream-PR-Commit: 1jehuang#1750 1ac0c82
Upstream-PR: 1jehuang#1822
Upstream-PR-Commit: 1jehuang#1822 73f85fc
Upstream-PR: 1jehuang#1912
Upstream-PR-Commit: 1jehuang#1912 36d7682
Upstream-PR: 1jehuang#1978
Upstream-PR-Commit: 1jehuang#1978 0f55643
Upstream-PR: 1jehuang#2007
Upstream-PR-Commit: 1jehuang#2007 638f87c
Upstream-PR: 1jehuang#2213
Upstream-PR-Commit: 1jehuang#2213 c5e1487
Upstream-PR: 1jehuang#2234
Upstream-PR-Commit: 1jehuang#2234 0d4d5d4
Upstream-PR: 1jehuang#2266
Upstream-PR-Commit: 1jehuang#2266 217ddc2
Upstream-PR: 1jehuang#2267
Upstream-PR-Commit: 1jehuang#2267 e98c40b

This branch has not been deployed

No deployments
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.

1 participant