Skip to content

feat(chat): migrate a local session to a remote crew (context-carry v1) - #9703

Closed
jeeshofone wants to merge 2 commits into
kirodotdev:mainfrom
jeeshofone:feat/7652-migrate-session-remote
Closed

jeeshofone wants to merge 2 commits into
kirodotdev:mainfrom
jeeshofone:feat/7652-migrate-session-remote

Conversation

@jeeshofone

@jeeshofone jeeshofone commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

A chat session can be bound to a remote crew only at CREATION: the slot-create path accepts remote_slot + instance_id, and the binding gate explicitly refuses an existing slot. A user who starts a conversation locally and later wants a remote crew to carry it on has no path — they must open a fresh crew session and re-explain everything by hand. This is the "move an existing local conversation to a remote crew" half of #7652.

Why it matters

Long-lived working sessions accumulate real context (decisions, constraints, artifacts under discussion). Losing that context at the local/remote boundary makes crews awkward to adopt mid-task, which is exactly when they are most useful.

What changed (motivation → approach → change)

Goal: move a session's conversation to a crew without any peer-protocol change.

Approach considered: teleporting the raw transcript to the peer would need a new peer ingestion seam (a v2 concern). Instead, v1 is a context-carry migration composed entirely of existing seams: the create path's remote binding (create_peer_slot), the pending-context channel (_enqueue_pending_context, drained into the next turn as a framed background block), and the tab-close archive (close_slot).

POST /api/chat/slots/{slot}/migrate-remote with {"instance_id": ...}:

  1. Guards first (before the peer is touched): 404 unknown slot; owner-gated exactly like the create path's remote binding (app tokens get an oracle-free 404, non-owner 403); 409 for already-remote, member-pinned, or a turn in flight; 400 for non-persistent sessions.
  2. Bind: mint the peer session and a new local slot bound to it via the same machinery the crew picker uses at create time; carry agent/model/tags/folder/title (title redacted through the standard sinks).
  3. Carry the conversation: the FULL transcript travels through the shipped session-transfer mechanism — build_transfer_bundle_async → InstancesManager.send_session_bundle → the peer's /api/chat/slots/import — the same bundle path the instances "send session" action uses (at bundle v2 it even carries the kiro-cli context for full-fidelity resume). The peer imports the real conversation and returns its new slot key; the mirror binds to it. The bundle is also the migration's consistency anchor: the transcript length is captured at bundle time and re-checked before the archive.
  4. Archive LAST: the source is closed read-only with a migrated: {instance_id, remote_key} metadata stamp, persisted and rehydrated so the pointer survives restarts. Failure ordering is deliberate: a peer-bind failure costs nothing; a peer context-delivery failure rolls back the new slot and leaves the source live; an archive failure rolls back the new slot and clears the speculative stamp. A duplicate crew slot is cheap; a lost original is not.
  5. Read-only resume: resuming a migrated source is refused (409 resume_migrated, naming the crew) so the conversation cannot fork into two live copies; the transcript stays readable in History.

Tests

test/test_chat_slot_migrate_remote.py (25 tests): every guard refusal (unknown slot, missing instance, app token — with the same 404 for existing and absent slots, non-owner, already-remote, non-plain modes, channel-origin and Slack-linked sessions, running turn, queued prompts, concurrent migration); a peer transfer refusal leaves the source intact with no orphaned slot; success path (binding fields, the full conversation sent through send_session_bundle, source archived with the migrated stamp in persisted metadata, source origin preserved on the mirror); destination durably persisted before the archive; failure ordering (archive failure keeps the destination retryable — confirmed-closed-then-pop, live+dirty when the closed write cannot be confirmed); consistency anchor (a turn that completes inside the tunnel send aborts the archive; a replacement slot under the same name aborts the archive); migrated-source resume refused 409 BEFORE clear_closed so the archive flag survives.

Local runs: migrate suite 25 passed; test_remote_crew_execution.py 190 passed; body-guard / session-pulse / error-code contracts passed; black/flake8/isort/mypy/comment-history gates clean.

Manual verification

A live two-gateway migration has not been run in this branch; the carry leg IS the shipped session-transfer path that the instances "send session" action already exercises in production, stubbed here only at the tunnel boundary (send_session_bundle), with the real bundle builder contract pinned by session_transfer's own suite.

Related Issues

Part of #7652 (v1 does not complete the issue — see follow-ups).

Follow-ups (out of scope here)

  • Frontend affordance: a "Move to crew…" action on the session menu calling this endpoint, and a "moved to " chip on the archived History row (the migrated meta is already persisted for it).
  • Destination crew/agent picking: an explicit agent/model pick from the PEER's roster at migration time (the mirror carries no model and no project; the agent travels only as a name hint that the peer applies if it has an agent by that name and drops otherwise — main's existing transfer contract, unchanged here).
  • Mid-merge guard: the fork/merge-back reservations live in a PR still in flight and are not on main yet; once merged, the migrate guards should also refuse a slot that is mid-merge-back.

@jeeshofone
jeeshofone requested review from a team and krishdhasmana September 9, 2026 12:25
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 9, 2026
@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — 🟡 CONCERNS

Design-level review of 1eead9d8e59e2d9a16f9f8fc695595242040cabf via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

Sound reuse of shipped seams with rigorous failure ordering, but archive safety rests on an open, unpinned enumeration of slot-mutation paths.

Watch

Archive correctness is guard-by-enumeration: _migrate_refusal plus four anchor classes (message count, _dirty_gen, sid, display tuple) must name every way state can land on or address a slot by key. Any future slot-state surface that bumps no anchor — the PR's own follow-ups already name one ("the migrate guards should also refuse a slot that is mid-merge-back") — silently strands work on a read-only archive, the exact failure this machinery exists to prevent. The docstring states the covered class, but nothing structural forces a new path to register, unlike the origin invariant this PR extends via the source-scan pin in test_ws_event_scoping.py.
Clears when: a pin (source-scan or registry-style test) couples new slot-mutation/addressing surfaces to _migrate_refusal/the anchors, or the owning session spec records this coupling as a maintenance obligation.

Suggestions

  • Pin the guard enumeration the same way you pinned origin declarations — you already have the pattern in this PR; applying it to _migrate_refusal converts the Watch item into a red test instead of a silent fork.

[DESIGN-REVIEWED] 1eead9d

@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5, fork) — 🟡 CONCERNS

Premise-level review of 1eead9d8e59e2d9a16f9f8fc695595242040cabf via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

All claims verified against base: the create-only binding refusal exists (chat_handlers.py:2483), the transfer bundle path exists with exactly one prior consumer (handlers_instances.py:1072, copy-only by contract), the fidelity contract (session_transfer.py:1452) and every leaned-on helper (get_metadata_status, _owner_denial_response, read_private_session_store) exist. The website has zero references to the new endpoint or its error codes. The per-slot _migrating flag has exactly one non-test reader (the admission check), while state._migrating_keys is set and cleared at the same two points and already gates the same window.

First-Principles-Verdict: CONCERNS

Nothing in the product calls the new endpoint yet, and the per-slot _migrating flag is a second spelling of state._migrating_keys.

Not justified as shipped

  1. Migrate action — zero consumers: grep of website/ for migrate-remote|resume_migrated finds 0 files; the only planned caller ("Frontend affordance: a 'Move to crew…' action … calling this endpoint") is deferred.
  2. Channel-picker skip and bind refusal — undeclared: the description never mentions the messaging-side surface.
  3. Per-slot _migrating flag — duplicate of state._migrating_keys: set/cleared at the same two points in _hold_migration/_release_migration; one non-test reader.
  4. Empty-session path mints a bare peer slot — undeclared detail; harm named in the code, fine as inventory.

What this change ships

Inventory (10 items) — 6 justified

Intent: let an owner move an already-running local conversation onto a remote crew without re-explaining it — ADDITION (part of #7652).

  1. A new API action moves a local conversation to a chosen crew via the shipped transfer bundle — zero consumers (no in-product caller; UI deferred)
  2. The old key becomes read-only everywhere: resume, chat send, slot create, and OpenAI-compat id refuse with a pointer to the crew — justified
  3. Channel session pickers stop offering a migrated conversation; a bind racing a migration is refused — undeclared (not in the description)
  4. Archived source carries a persisted migrated pointer that survives restarts — justified
  5. While a migration is in flight, anything addressed at the key gets a 409; SessionManager grows mark/unmark/is_migrating — justified
  6. A per-slot _migrating in-flight flag — duplicate of state._migrating_keys (one consumer: the admission check)
  7. Migration refused for any session another actor still addresses (channels, cron, apps, member pins, pending context, cards, subagents, loops, workflows) — justified
  8. Failure ordering: source archived last; rollback, or an honest two-live-slots split when the destination got work — justified
  9. A degraded context transfer refuses instead of archiving the only full copy — justified
  10. An empty session migrates by minting a fresh peer slot instead of a bundle — undeclared

Capped at 10 (folded: catalog-row projection into 3/4; close_slot pre-pop signature change, required by item 7's loop guard).

Watch

  • The endpoint ships with no counted caller: 0 matches in website/ for the route or its codes, and the description itself defers the "Move to crew…" action to a follow-up — until then the user-level job is reachable only by hand-rolled HTTP. Clears when: the frontend action PR lands (a counted consumer of /migrate-remote).

Subtractions

  • Drop _ChatSlot._migrating (the __slots__ entry, the init, and both writes in _hold_migration/_release_migration); its one consumer, the admission check in api_chat_slot_migrate_remote, is answered by name in state._migrating_keys, which is set and cleared at the same instants. The state.py comment's claim that "a close-time revalidation" reads it has no matching read in the diff.

[FIRST-PRINCIPLES-REVIEWED] 1eead9d

@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — ✅ no blocking findings (all downgraded on adjudication)

Reviewed 1eead9d8e59e2d9a16f9f8fc695595242040cabf via the fork AI-review pipeline; updated in place on each push.

Opus 4.8 adjudication downgraded every blocking finding to advisory. Adjudication downgraded all 1 blocking finding(s) to advisory: the remedy each one requires is disproportionate to the harm it prevents. Read them as advice, not as merge conditions.

Review details

BLOCKING -- src/kiro_crew/dashboard/chat_handlers.py:4104 -- Metadata reads block the event loop
chat_handlers.py:4104: meta, readable = state.conversation_log.get_metadata_status(...); messaging/session_resume.py:888: meta, readable = status(key)
Oversized metadata header -> named-slot mint or channel bind -> synchronous readline() -> gateway stall/watchdog restart
Anchor: no-blocking-call-on-event-loop
Fix: Offload disk reads and use an in-memory migrated-key cache for synchronous commit checks.
[BLOCK-MERGE-DOWNGRADED] 1eead9d
[GPT-REVIEWED] 1eead9d

Adjudication (Opus 4.8) — is blocking on each finding proportionate?

Confirmed the mechanism. _read_metadata_status (history_projection.py:1091-1092) does open() + readline() of only the first line, guarded by an mtime+generation _meta_cache (lines 1088-1090) that short-circuits repeat reads. The synchronous-on-the-loop nature is pre-existing and deliberate — _pause_for_transient_retry (line 1063) explicitly detects whether it is on the event loop, and the resume handler already calls get_metadata synchronously in the base tree. The new call sites (migrated_key_mint_decision, _migrated_or_unreadable) reuse this same path; the non-commit reads already offload via asyncio.to_thread (session_resume.py patch line 1610), and the commit-point reads are documented as synchronous by requirement ("Synchronous on purpose: commit_binding calls it inside the map lock with no await before set_mirror_link").

Harm: a single first-line read, cached by mtime; to stall the loop it needs an "oversized metadata header," but the first line is written by the system with bounded fields (redacted title, tags, folder_id) — no path lets a caller inflate it. Rare, and a watchdog restart clears it → LOW rung. Remedy cost: the flagged reads sit at commit points that structurally cannot await (the no-await window is what prevents the TOCTOU fork the whole PR exists to close); an "in-memory migrated-key cache" is a new disk-coherence mechanism serving only this path and duplicates the existing _meta_cache. Fixing it either breaks the PR's central invariant or adds redundant permanent state — clearly exceeds the harm.

[ADJUDICATION] 1eead9d total=1 uphold=0 downgrade=1
DOWNGRADE F1 src/kiro_crew/dashboard/chat_handlers.py:4104 reason=disproportionate-remedy
[GPT-ADJUDICATED] 1eead9d

@github-actions

github-actions Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

Reviewed 1eead9d8e59e2d9a16f9f8fc695595242040cabf via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] 1eead9d

@jeeshofone jeeshofone changed the title Migrate a local session to a remote crew (context-carry v1) feat(chat): migrate a local session to a remote crew (context-carry v1) Sep 9, 2026
@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round 2 disposition (head 785dc200b)

Design BLOCK (digest dead-ends on the local mirror) — accepted, fixed. The reviewer's read was exactly right: the drain's only call site is inside _run_chat, and a remote-bound slot's turns go through relay_remote_turn instead, so the locally queued digest was never delivered and the crew started cold — with the source already archived against resume. The 17 tests asserted queueing, not delivery.

Fix (the review's option 1): the digest now travels to the peer's own /context endpoint at migration time via a new send_peer_context relay helper (same proxy_request seam as create_peer_slot/forward_peer_stop). On the peer the crew slot is an ordinary local slot, so its next _run_chat drains the digest into the prompt like any other background context. Delivery failure raises RemoteTurnError before anything destructive — archive-last ordering unchanged, and per the review's suggestion the rollback now sits on the single RemoteTurnError seam rather than a second local-enqueue failure path.

Clearing condition met in-suite: TestDeliveryLeg stands up a real second gateway state serving the real /context endpoint as the peer, routes the migration through it, and asserts drain_pending_context on the PEER slot yields the framed digest (the exact context prefix _run_chat prepends to the crew's next prompt), consumed after one drain. The tunnel leg (proxy_request) is stubbed at the same boundary every existing remote-turn test uses; a live two-gateway run remains noted in Manual verification.

PR Hygiene — title reformatted to conventional commits (feat(chat): …). Body updated to describe the delivery leg honestly.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 9, 2026
@jeeshofone
jeeshofone force-pushed the feat/7652-migrate-session-remote branch from 785dc20 to 0710586 Compare September 9, 2026 13:09
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Sep 9, 2026
@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round 3 disposition (head 50e9c83df)

All four fenced findings accepted and fixed; both advisory findings taken; isort fixed.

F1 (existence oracle) — the app-token denial now runs FIRST, before the slot lookup and body validation. An app token probing with an empty body reads 404 slot_not_found identically for existing and absent slots. Test: test_app_token_gets_the_same_404_for_existing_and_absent_slots asserts shape equality across both cases.

F2 (turn racing the archive) — a migration now reserves its slot with a check-and-set _migrating flag before the first await (second concurrent migrate → 409 migrate_in_flight), and close_slot's existing pre_pop_check hook re-validates the turn state at the last instant before removal: a turn started inside the peer round-trips aborts the archive with a retryable 409 turn_in_flight, full rollback, source unlocked. Test: test_a_turn_starting_mid_migration_aborts_the_archive starts the turn inside the stubbed create_peer_slot await.

F3 (destination not durable) — the destination binding is persisted via a metadata upsert (the empty mirror has no message window for a save to merge into, so update_metadata materializes the line — the same write the peer agent-switch path uses) BEFORE the source is archived. A restart at any point now leaves at least one addressable copy. The archive-failure rollback re-saves the already-persisted destination closed so it cannot revive as a live duplicate. Test: test_the_destination_is_durably_persisted_before_the_archive reads the binding back from the conversation log.

F4 (resume reopens the archive) — the migrated-archive refusal now runs immediately after the initial metadata read, BEFORE clear_closed; the late gate remains as the post-await second barrier. Test: test_a_refused_resume_does_not_clear_the_archive_flag asserts closed still stands in persisted metadata after the 409.

Advisories — the mirror no longer copies agent/workspace/model/reasoning (the peer runs its own defaults; carrying them displayed execution settings that were not running); the digest keeps its final row when it alone exceeds the budget, truncating content instead of dropping the tail's last message (test_a_sole_oversized_message_keeps_its_row_truncated).

Suite now 24 tests; error-code contract, black/flake8/isort/mypy, comment-history all clean locally.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 9, 2026
@jeeshofone
jeeshofone force-pushed the feat/7652-migrate-session-remote branch from 50e9c83 to 36e69ef Compare September 9, 2026 15:13
@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round 4 disposition (head 36e69ef99 — rounds 3+4 folded into one hardening commit for the 2-commit hygiene cap)

All three fenced findings accepted and fixed; both advisory findings taken; the two backend contract-test failures (Windows shards 2/4) were mine and are fixed.

F1 (unredacted peer egress) — assistant rows in the digest now pass redact_exfiltration_urls + redact_credentials (exfil first, same order as every other sink) before the digest leaves the machine; the user's own words travel verbatim. Test: an AKIA-shaped credential in an assistant row never reaches the digest while the user row survives.

F2 (channel fork) — a new guard refuses channel_origin slots, channel session keys, and Slack-linked sessions with 409 migrate_channel_linked, before the peer is touched. Tests cover the channel-origin flag and a live Slack link.

F3 (self-reviving rollback) — the rollback now CONFIRMS the destination's closed write (best_effort=False, return checked) BEFORE popping it; when confirmation fails on the correlated fault, the destination stays live and dirty (visible, retryable, honestly a duplicate) instead of becoming a hidden self-reviving one, and the abandoned peer session is asked to close via a new best-effort close_peer_slot relay helper. Both arms are tested (confirmed → popped; unconfirmed → live + dirty + peer close requested).

Advisories — both function-local imports moved to module scope (no import cycle exists on this edge); the digest budget comment now says character budget.

Contract tests (Windows shards) — test_json_object_body_guard gains the migrate endpoint's cap-register row (<default>, control-fields — the body is one short crew id); test_session_pulse_session_count passes again because the mirror no longer opts into the user-session count: migration re-homes an existing conversation rather than starting a new one.

Suite: 34 migrate tests + remote (194) + error-code contract green locally; black/flake8/isort/mypy/comment-history clean.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round 16 disposition (head 758aee0e9)

F1 (OpenAI-compatible id re-mints a migrated source) — accepted, fixed; and the round-14 enumeration claim was wrong. I said every request-named mint path was covered; it was not. I have now enumerated every get_or_create_slot caller under dashboard/ and classified each by where its key comes from:

  • Caller-named key (the class): chat send, slot create, resume (its history key), and the OpenAI-compatible /v1/chat/completions id. The first three were guarded; the fourth was not — that is this finding.
  • Generated key: oai-<completion_id> (the compat endpoint's ephemeral path), session_control.create_session, chat_fork, session_transfer import, taskrunner — a fresh key each time, cannot be aimed at an archived one.
  • Derived from a linked resource: channel (channel_slots), cron (cron_inject, handlers/cron), member (handlers/members), workflow (workflow_inject), and the two rehydrate paths — each is a link the migration REFUSES at entry and at the pre-pop re-check (_migrate_refusal), so a migrated key cannot be one of these.

The guard is now one pure decision, migrated_key_mint_decision(state, request_app, key) -> None | (code, sel_error, migrated), with the reservation check first and the persisted stamp second, and the same oracle discipline (non-owning app → slot_not_found). Renderers are per wire shape: the dashboard JSON renderer (_mint_refusal_response, used by chat send / slot create / the resume reservation check) and the OpenAI envelope inside api_completions — bodies and statuses are literal per branch so the error-code contract reads them statically. The decision is imported lazily in openai_compat (a module-level import cycles through artifacts).

Tests: the two archived-key tests now also drive /v1/chat/completions with id=<archived key>: owner → 409 resume_migrated in the OpenAI envelope (error.code and top-level code, plus the pointer); a non-owning app token → oracle-free 404 with no pointer. Both fail against the previous head. The compat suite's MagicMock state fixture now carries _migrating_keys={} / conversation_log=None like a real idle state. 328 passed across the migrate suite, the compat suites and the contract family; black / flake8 / isort / mypy / diff-scoped comment-history green.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

CI disposition (head 5bfa37584)

Backend Tests shard 3 (Linux + Windows) and the downstream Coverage Gate were red on 758aee0e9 for one test, test_members_dm_thread.py::TestOpenAiCompatPin::test_completions_fail_closed_on_binding_drift: its MagicMock state has no real _migrating_keys, so the new mint decision read a MagicMock as "reserved" and answered migrate_in_flight before the member-binding check. Fixture fixed (state._migrating_keys = {}, the same shape the compat suite fixture carries). I also ran the six other suites that fake a MagicMock state and reach send/create/completions — 1,047 passed — so no other shard carries this. 161 across the migrate, compat, members and contract suites; black, flake8 green.

Round-17 F1 (a save that returns False via the delete-won guard is treated as durable) remains FLAGGED by the adjudicator — the source was concurrently permanently deleted and the remote copy is already safe; no change from me pending a maintainer view.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Review disposition — round 17 (head a4ed3d193)

Both upheld findings accepted.

F1 (peer-controlled transfer error returned without redaction) — accepted, fixed. The 502 for a peer-refused transfer now passes both error and code through redact_peer_text — the same sink every other peer string crosses (remote_relay.py docstring: refusal messages are named there as in-scope). Test: a peer error carrying an AWS key-ID shape comes back with the key redacted and the prose intact. Fails on the previous head.

F2 (accepted pending context archived without transfer) — accepted, fixed in the one guard function. append_pending_context and a held _deferred_notes entry are acknowledged deliveries that ride into the NEXT turn on this key; neither touches the message count or the dirty generation, so the bundle omitted them and the consistency anchor could not see them. The new arm lives in _migrate_refusal — the single function evaluated at ENTRY and again at the commit point inside close_slot's pre-pop boundary — so it covers both windows without a second copy of the list: migrate_pending_context, retryable 409, "accepted context is waiting for the next turn". I chose refuse-until-drained over bundling the context because a deferred note's durable copy replays only onto THIS key after a restart, which the archive makes read-only; carrying it would need a second durable-promise transfer protocol, which is out of this PR's scope. Tests: refused at entry for pending context; refused at entry for a held note; context accepted DURING the tunnel send is caught at the commit point and nothing is archived. All three fail on the previous head.

Suite: 46/46 migrate tests; contract family 247/247; black/flake8/isort/mypy/comment-history clean.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round 18 on a4ed3d193 → e40f705cb. Both fenced findings fixed, each at the class the round-14/17 structure already defines: one guard function evaluated at entry and commit; one destination-work predicate asked by every rollback arm.

F1 — mode not revalidated before archival (UPHELD → fixed). Correct: the mode gate was a static entry check, and mode is a live attribute (chat.slot_mode flips it on a non-running slot without touching the message count or dirty generation), so a plain→orchestrator switch inside the peer round-trip was invisible to _refuse_if_turn_started. The mode gate now lives in _migrate_refusal as its first arm, so it runs at the commit point through the same function as every other dynamic guard (the memory-mode gate stays static: it is fixed at slot creation). Test: send_session_bundle flips slot.mode = "orchestrator" mid-transfer → 409 migrate_mode_unsupported, nothing archived, reservation released. Fails on the previous head.

F2 — rollback pops a destination that accepted /context (UPHELD → fixed). _destination_received_work now includes _pending_context and _deferred_notes — the same accepted-delivery arm _migrate_refusal applies to the source, since /context answers {"ok": true} for any live key without adding a message. Test: destination takes append_pending_context during a failing close_slot, with no message / no running turn / empty queue → 409 migrate_split, destination kept live with the context intact. Fails on the previous head.

Also fixed (mine): test_reservation_is_released_on_every_exit was order-dependent — its addressability probe posts a real /api/chat turn to the source and then immediately migrates again, so under parallel workers the second migrate was (correctly) refused as turn_in_flight. The probe is now the test's last step. 10/10 consecutive runs green; 48 in the migrate suite, 167 across the migrate/compat/contract/DM-thread family, all gates.

On Design's two watch items: the reclaim/un-migrate path and mint-after-archive ordering are real design questions rather than defects in this change; I'd rather take a maintainer's steer on both than widen the PR unilaterally at round 18.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

e40f705cb → d84180298 — rebase only, no code change. Rebased onto main at 075e77ca5 to pick up #10130, which fixes the main-side E2E locator collision (#10089) that was this PR's only remaining red. Clean rebase; 171 across the migrate family, all gates green locally. Both review lanes were green on the previous head.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on d84180298 → 85d546f0a.

GPT F1 — a reset-conversation inside the peer round-trips slips past the pre-pop check (adjudication FLAGGED it as recoverable; fixed anyway). The observation is correct and it exposes a real gap in the consistency anchor: the check compared the transcript's length and dirty generation, and a reset mutates neither — it clears the resumable sid. The archive would then close a source whose live session was already gone while the peer resumed the pre-reset context.

I did not take the suggested fix ("refuse reset while _migrating"): that special-cases one caller, and any other path that swaps the sid under the slot is the same case. Instead the session identity is now the third anchor: the migrate handler snapshots state.sessions.resumable_sid(session_key) beside the message count and dirty generation, and _refuse_if_turn_started refuses (turn_in_flight, 409, nothing archived, destination rolled back) when it has changed. That covers reset and anything else that re-keys the session, with no new coupling to the reset endpoint.

Test: sid goes to None inside the tunnel send with the transcript anchors provably unchanged → 409 turn_in_flight, source live and unlocked; fails on the previous head. 172 across the migrate family, all gates.

Non-blocking bundle["agent"] hint — not changed. The bundle carrying the source agent is deliberate: the importer's peer-default claim is what decides selection, and the hint is diagnostic metadata for the peer's log. If you'd rather the bundle be silent on it I'll strip it, but I'd want that to be the maintainer's call rather than a drive-by.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Correction to my previous comment's last paragraph (the bundle["agent"] hint). I called the hint "diagnostic metadata for the peer's log". That was wrong, and I should have read the contract before writing it. session_transfer.py — on main, untouched by this PR — says agent travels as a hint and is applied when the peer has an agent by that name, dropped otherwise. So the reviewer's non-blocking point stands against the PR body's wording ("the peer runs its own defaults"), which overstated things for the agent.

Disposition: body corrected to describe the real behaviour. I am not stripping the hint: changing main's transfer contract inside this PR would be scope creep, and "apply only on a name match" is the intended design.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on 85d546f0a → 00f4a4572.

F1 — the mint guard fails open on unreadable metadata (UPHELD-FENCED → fixed). Correct. get_metadata folds "the record exists but could not be read" into "no metadata", so a migrated stamp behind a sharing violation or a torn write would have minted a writable local fork of a session that lives on the crew. migrated_key_mint_decision now uses get_metadata_status and fails closed: an unreadable record refuses the mint with a new fourth code, history_unreadable, 503 (retryable), rendered in both shapes — dashboard JSON and the OpenAI envelope (service_unavailable_error) — with its own SEL audit source. The oracle property is kept: an app token whose ownership cannot be verified against an unreadable record gets the same 404 an unknown key gets, and learns nothing.

Tests: unreadable record → chat send, slot create and /v1/chat/completions all 503 history_unreadable, nothing minted; app caller → slot_not_found. Both fail on the previous head. The error-code contract test passes with the literal new branch.

Non-blocking F2 — refusal ordered after create_peer_slot orphans a peer session (fixed). Also correct: with an instance_id, the peer session was minted before the migrated-key refusal ran, so a 409 left a session on the crew bound to nothing. The refusal depends only on the requested key and the caller, so it now runs before the peer mint. Test: create on a migrated key with an instance_id → 409 with create_peer_slot never called; fails on the previous head.

195 across the migrate/openai/contract/slot-create families, all gates.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on 00f4a4572 → b0b44a8fa. Both upheld; both fixed at the class level.

F1 — display fields (title/tags/folder) are copied to the destination but not anchored (UPHELD → fixed). Correct: a rename, tag edit or folder move landing in the persist/archive awaits after the copy mutates none of the transcript anchors, so the archive would strand the edit on the read-only source. The display tuple (folder_id, tags, title, _titled) is now the fourth anchor, snapshotted at the point the fields are copied and compared in the pre-pop check. Test: each of the three edits, landed inside the destination persist (the first await after the copy), → 409 turn_in_flight, source live, with the transcript anchors provably unchanged; all three fail on the previous head.

F2 — the resume gate is a hand-rolled copy that fails open (UPHELD → fixed). Also correct, and the more important of the two. The resume handler had two local re-derivations of the migrated check from get_metadata (which reports an unreadable record as empty), and its reservation half was keyed on the target slot only — so an aliased resume (POST /slots/s2/resume {key: dashboard:s1}) in the pop-to-stamp window forked s1 into a writable s2. Both copies are replaced by one _resume_mint_refusal that runs the centralized migrated_key_mint_decision for both keys a resume names (target slot and source conversation), so it inherits the reservation check, the fail-closed history_unreadable and the oracle-free app answer from the same code as send/create/OpenAI. _migrating_key_refusal (the reservation-only helper the resume path used) is deleted; it has no other callers. Tests: aliased resume during the reservation window → 409 migrate_in_flight; unreadable record at resume → 503 history_unreadable; both fail on the previous head.

198 across the migrate/openai/contract/create/resume families, all gates.

A note for the maintainer on the pattern: this is the third consecutive round where the finding is "a guard that cannot see one class of change" (sid, unreadable record, display fields, hand-rolled copy). I have swept the migrate handler for further anchors this PR copies-then-relies-on and found none beyond these; if the lanes turn up another, I'd take that as a sign the anchor set should be a single dataclass snapshot rather than a growing tuple, and would propose that as its own change.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on b0b44a8fa → bc3743110.

F1 — the migration ignores the peer's reported import fidelity (UPHELD → fixed). Correct, and a different class from the last three rounds. The import already reports resume_mode (session_load when the kiro-cli context landed, prefix when only the transcript did); the mirror path uses it to say "Sent (transcript only)" with a live source. The migrate handler read only payload["key"] and archived the source read-only regardless — so an ordinary peer-side fault (unparseable events, a failed write, a failed join) would have made the loss of the native context irreversible and silent.

Fix: a fidelity gate right after the send. A bundle that carried layer_b and came back anything other than session_load refuses with migrate_degraded_import (502) before any local mirror exists; the source stays live and untouched, and the peer keeps its transcript-only copy exactly as it does after the existing remote_bind_failed arm (there is no peer-side discard, and the create path's collision arm makes the same choice). prefix for a bundle that never carried context is the correct answer and is not refused — a test pins that, or plain migrations would break.

Non-blocking — rollback pops the destination without publishing (fixed). Verified: get_or_create_slot pushes the slot list on creation, so a silent pop left a ghost tab until an unrelated push. Both rollback pops now run _sync_dashboard_slots + push_slots_update, as the success path does. Test records the live set at each push and asserts the last push saw the destination gone; fails on the previous head.

Tests: degraded import refused with no mirror minted, then the same bundle at full fidelity succeeds; transcript-only bundle not refused; rollback publishes. 329 across the migrate/transfer/openai/contract/create/resume families, all gates.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on bc3743110 → f718afc47.

F1 — an armed auto-nudge / monitor loop passes every migrate guard and is silently retired by the archive (UPHELD → fixed). Correct. Between cycles a loop leaves running False and the queue empty, so the turn guard cannot see it; close_slot retires the loop as part of archiving the source, and the destination deliberately carries no execution settings — the scheduled work would stop with no notice and no way back.

Fix: a new arm of _migrate_refusal, so it is checked at entry and at the pre-pop re-check like every other dynamic guard: an armed loop on the source refuses with migrate_nudge_loop_armed (409). The lookup is a read-only twin of the retire helper (svc.get_by_slot), and a registry lookup failure answers "no loop" rather than refusing an unrelated action — the close path keeps its own, stricter failure mode. The user stops the loop, then migrates.

Test: armed at entry → 409, the bundle is never sent; armed inside the peer round-trip → 409 at the pre-pop check with the source live and the destination rolled back; unarmed → the same slot migrates. 330 across the affected families, all gates.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on f718afc47 → c94f7b254.

F1 — the resume guard's source-key derivation only recognises the dashboard: spelling (UPHELD → fixed). Correct, and this one is mine from three rounds ago: _resume_mint_refusal derived the source slot key with a hand-rolled startswith("dashboard:") strip, while the history layer reads the same transcript for the dashboard_ filename-stem spelling — which _normalize_slot_key already documents and folds. So {key: "dashboard_s1"} aimed at s2 skipped the source check and forked the migrating session.

Fix: the helper accepts both transport spellings and derives the source key with _normalize_slot_key(history_key) — the shared fold, not a local re-implementation of half of it. Surveyed the PR's diff for other hand-rolled dashboard: prefix handling: this was the only site. Test: the aliased-resume case is parametrized over both spellings; dashboard_s1 fails on the previous head. 331 across the affected families, all gates.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on c94f7b254 → 4d87f88a6. Both upheld; both are ordering bugs in guards I added, and both are fixed.

F1 — anchors snapshotted after the bundle build (UPHELD → fixed). Correct: build_transfer_bundle_async is an await, and the sid / length / dirty-gen anchors were taken after it, so a reset (or a completed turn) landing inside the build became the baseline and the commit-point check saw "no change". All three transcript-side anchors are now taken before the build, checked immediately after it (a change inside the build refuses with turn_in_flight before anything reaches the peer), and the same pre-build snapshot is what the pre-pop check compares. One _anchors_moved() predicate serves both checks — no second copy of the comparison. Test: a reset and a completed turn, each landed inside the build → 409, send_session_bundle never called; both fail on the previous head.

F2 — the nudge guard reads an empty registry at the commit point (UPHELD → fixed). Also correct: close_slot retires the source's loop before running pre_pop_check, so a loop armed during the round-trip was already gone when my guard looked for it. Fix at the seam rather than a second lookup: close_slot's pre_pop_check now receives the loop it just retired, and _migrate_refusal counts that as armed; the resulting SlotCloseError takes close_slot's existing restore-and-unwind path, so the loop is put back. The check stays synchronous — nothing about the point-of-no-return contract changed — and the one other caller (session_control._reassert_closeable) accepts and ignores the argument. Test: loop armed inside the tunnel send → 409 migrate_nudge_loop_armed, the retired loop is restored to the registry, source live; fails on the previous head.

510 across the migrate/transfer/session-control/close/openai/contract/create/resume families, all gates. I have also re-read every remaining await in the handler against every anchor and guard for ordering: the display anchor is taken at its copy point (correct — it protects the persist/archive window after the copy), and every other guard is evaluated both at entry and at the commit point.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on 4d87f88a6 → 782197422.

F1 — an ordinary chat bound to a private V2 memory store passes the mode-only guard (UPHELD → fixed). Correct. The owner-selected member pin writes a private session-store binding on an ordinary mode == "" chat, the binding is a per-gateway authority record the bundle cannot carry, and the fork path already treats it as a boundary a transcript must not cross. A migrated import would resume against the wrong store or refuse its next turn, with the source archived read-only.

Fix: a new arm of _migrate_refusal right after the mode gate — so it runs at entry and at the pre-pop re-check — refusing with migrate_private_memory_bound (409) when read_private_session_store(effective_session_key) returns a store, and when it raises (a binding record that exists but cannot be read is that function's own fail-closed contract, and it is treated as a refusal here too, not as permission). The probe is a small file read; it runs synchronously because the pre-pop re-check may not await, and it mirrors the existing use in this handler.

Test: bound at entry → 409, nothing sent; unreadable binding → 409, nothing sent; bound inside the peer round-trip → 409 at the commit point, source live; unbound → migrates. Fails on the previous head. 1294 across the migrate/member-memory/transfer/session-control/close/openai/contract/create/resume families, all gates.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on 782197422 → 1f3b8a966.

F1 — the fidelity gate ignores a sender-side layer_b_skipped (UPHELD → fixed). Correct, and it is the missing half of the gate I added four rounds ago. I keyed that gate on "context was sent and did not land" and dismissed layer_b_skipped as the mid-turn case the busy guard already refuses — but the builder also sets it when the session's Layer B is over the size cap or its files will not read: "this session HAD context and I am not carrying it". A migration of such a session archived the only copy of that context read-only, with a 200.

Fix: a sender-side refusal before the send — layer_b_skipped on the built bundle → migrate_degraded_import (502), nothing sent, source untouched — the twin of the post-import gate, under the same code because it is the same failure from the user's point of view. A session that never had a kiro-cli context sets neither flag and is unaffected (pinned by the existing transcript-only test). Test: skipped bundle → 502 with send_session_bundle never called; fails on the previous head. 512 across the affected families, all gates.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Round on 1f3b8a966 — no push.

F1 — destination identity is not rechecked at the commit point (adjudication: FLAGGED; holding). The observation is right: the pre-pop check re-asserts the source's identity (state._slots.get(name) is slot) but not the destination's, so an owner who closes the freshly-minted destination tab inside the persist/archive window gets a 200 naming a slot that is already archived. I agree with the adjudicator on the consequences: it takes the owner acting against their own in-flight migration within a sub-second window, the conversation is already durably on the crew by then (success is reached only post-import), and both local copies end up archived read-only and reopenable from History — nothing is lost.

The fix would be one line in _refuse_if_turn_started — or state._slots.get(new_slot.key) is not new_slot — refusing with turn_in_flight and leaving the source live. I have not pushed it: this is the tenth review round on this PR and the finding is flagged as recoverable, so I would rather the maintainer decide whether the symmetry is worth another lane cycle than add it unilaterally. Say the word and it goes in with a test in the next round.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

1f3b8a966 → b33b39cfd. Taking the FLAGGED F1 after all rather than leaving it to the maintainer: the destination's identity is now re-checked at the commit point alongside the source's (state._slots.get(new_slot.key) is not new_slot joins the pre-pop check), so a destination the owner closes inside the persist+archive window — its key released or reused — aborts the archive with the same turn_in_flight 409 as a source swap, and the source stays live and unarchived. One condition, one comment line. Test: the destination is popped from the slot table during the binding persist; the migration answers 409 turn_in_flight, the source keeps migrated is None and a local executor; it fails on the previous head. 1296 across the migrate families; isort/flake8/mypy, black (baseline-aware), comment-history and brand gates green. This clears the last GPT block on this PR.

POST /api/chat/slots/{slot}/migrate-remote opens a new local slot bound
to the chosen crew through the same create-path machinery the crew
picker uses, delivers a digest of the source session's recent
conversation to the PEER's own /context endpoint, and archives the
source read-only with a `migrated` metadata stamp naming the crew and
the new slot.

The delivery target matters: the pending-context drain lives inside
_run_chat, and a remote-bound local slot never runs _run_chat
(relay_remote_turn replaces it), so a digest queued on the local mirror
would sit undelivered forever. send_peer_context posts it to the peer,
where the crew's slot is an ordinary local slot whose next turn drains
the digest into the prompt like any other background context.

Failure ordering is deliberate: nothing destructive happens until the
new slot exists and the delivery succeeded — the source is archived
LAST, so a mid-flight failure leaves the original intact. Resuming a
migrated source is refused (409 resume_migrated) so the conversation
cannot fork into two live copies; the transcript stays readable in
History. Owner-gated with the same two-gate authorization as the create
path's remote binding (app tokens get an oracle-free 404).

Part of kirodotdev#7652.
@jeeshofone

Copy link
Copy Markdown
Contributor Author

b33b39cfd → 89748e0c1 — rebase onto main at 0c1ddc0aa (228 commits). The across-the-board reds on the previous head were GitHub's auto-merge, not the head: main split close_slot into a fence-releasing wrapper around a new _close_slot, and the auto-merge left this PR's migrated parameter on the wrapper without threading it into the inner function, so the closed save referenced an undefined name (F821 in the lint job, then every backend shard). Resolved: migrated is threaded through the wrapper into _close_slot, whose pre_pop_check signature now also carries this PR's Callable[[NudgeLoop | None], None] contract; one import-block collision resolved by keeping both sides. No behaviour change. 1310 across the migrate families; isort/flake8/mypy, black (baseline-aware), comment-history, brand and ACP-boundary gates green; no .github/ diff.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

89748e0c1 → 913852d62. Both GPT findings upheld and fixed.

F1 — pending question card. _migrate_refusal gains an arm beside the pending-context one: a non-empty slot._question_pending refuses with 409 migrate_question_pending. A blocking card already implied a parked turn (the in-flight arm), but a stateless card from interaction_coordinator.post_card outlives its turn with running=False and is retired only by the next message on this key — its answer would land on the read-only archive and the card is not in the bundle. Because the refusal list is the single one evaluated at entry and at the commit point, the new arm covers a card posted during the peer round-trip too. Test: test_stateless_question_card_refuses_at_entry (the previous head returns 503 there — it fell through to peer discovery).

F2 — channel resume pickers. Three pieces, one predicate:

  • history.is_migrated_transcript(...) — the shared definition of "migrated" (a dict naming an instance_id), used by the dashboard mint gate and the pickers so they cannot drift; sibling of is_incognito_transcript.
  • The session catalog projection (history_search.SessionCatalogProjection) carries the migrated pointer onto the row in both its cold-read and cached branches, so list_sessions and search_sessions — the two sources every channel picker reads — expose it without a per-row metadata read.
  • resolve_session_choices skips migrated rows beside the incognito exclusion, and SessionResumeController.choose re-reads the record at the press and refuses (choice_missing, the surface's own "not available" copy) when a migration landed between the listing and the bind — the same window the dashboard's commit-point recheck covers.
    Tests: test_a_migrated_session_is_never_offered, test_a_session_migrated_after_the_listing_is_refused_at_the_press (both fail on the previous head — the archive is offered and bound), and test_list_and_search_surface_the_migrated_pointer covering both projection branches and the predicate's negative cases.

1976 across the migrate, resume (Teams/Telegram/Discord), history and search families; isort/flake8/mypy, black (baseline-aware), comment-history, brand and ACP-boundary gates green; no .github/ diff.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

913852d62 → dea86bd45. GPT F1 upheld: the bind-time re-read on the previous head ran before two awaits (the expectation record and the success-card update), so a migration committing inside those awaits could still be followed by set_mirror_link, and the migrate endpoint's commit-point check cannot see a bind that has not happened yet. Fixed on both sides of the seam so the two commits are ordered rather than merely close together:

  • Shared reservation. SessionManager.mark_migrating / unmark_migrating / is_migrating. The migrate endpoint's _hold_migration marks the key at admission and _release_migration clears it once the closed+migrated stamp is durable (or on any failure) — the same window state._migrating_keys already closes for dashboard mints, now visible to binders that live outside the dashboard.
  • Gate under the lock. SessionResumeController._migrated_or_unreadable(key) — reservation held, stamp present, or record unreadable (fail closed, via get_metadata_status where the log offers it) — is evaluated synchronously inside commit_binding's map-lock batch with no await between it and set_mirror_link. Both the migrate commit and the bind commit run on the loop thread, so whichever lands first is what the other sees: a bind first → the migrate's channel-linked arm refuses; an admission first → the bind refuses. The early async re-read stays for the ordinary case's prompt answer.

Tests: test_a_migration_admitted_but_not_yet_durable_refuses_the_bind (reservation only, no stamp yet) and test_a_migration_landing_inside_the_press_is_refused_under_the_lock (the stamp lands during the success-card await, after the early check passed) — both bind on the previous head; plus the existing pop-to-stamp window test now asserts the shared reservation is held during the window and released after. 2135 across the migrate, resume (Teams/Telegram/Discord), session-manager and history families; all gates green; no .github/ diff.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

dea86bd45 → a19889cc7. Both lanes' F1 and GPT's F3 upheld and fixed; GPT's F2 dropped by its own adjudication (the synchronous small-file probe is the commit-point idiom the _close_slot contract requires) and left as is.

F1 — reservation namespace. _hold_migration / _release_migration now mark and unmark the shared SessionManager under effective_session_key(slot) (dashboard:<name> for a plain slot) — the key the channel binders check — while the dashboard's own mint gate keeps the bare slot key in state._migrating_keys. The docstring names the two namespaces and their consumers. The pop-to-stamp window test now asserts the shared reservation under dashboard:s1.

F3 — empty source tombstone. The empty-window closed save merged only into an existing metadata line, so a source that never persisted one (nothing minted it at birth) and had no messages was archived with no durable migrated stamp: a restart re-minted a writable local fork under the key. In _save_slot_to_history a closed save that carries the migrated stamp now materializes the line (the read side reports a missing file as readable-and-empty, and the locked writer upserts), so the tombstone lands; every other empty-window save keeps the existing-line-only rule. The fresh-session test now asserts the closed+migrated line is on disk after the archive and that a later POST /api/chat on the key is 409 resume_migrated — on the previous head the record is {}.

4339 across every test module that touches the slot save path (persistence, close, migrate, resume, transfer, folders, ephemeral sessions, channel pickers); all gates green; no .github/ diff.

@jeeshofone

Copy link
Copy Markdown
Contributor Author

a19889cc7 → 1195b967b. GPT F1 upheld: the release recomputed effective_session_key(slot), so a slot whose routing changed mid-flight would have unmarked a different key than the admission marked and left the shared reservation behind (blocking channel resume of the key until restart). _hold_migration now returns the exact key it reserved and _release_migration takes that key back; nothing is recomputed. Test test_the_release_unmarks_exactly_the_key_the_admission_marked flips linked_session_key between hold and release and asserts the admission key is the one cleared. 585 across the migrate/resume families; all gates green; no .github/ diff.

Hardening of the migrate-remote flow across its adversarial and
crash-ordering surfaces:

- The app-token denial runs FIRST, before the slot lookup and body
  validation, so an app token probing with an empty body reads the same
  404 for existing and absent slots instead of a 400/404 existence
  oracle.
- A migration reserves its slot with a check-and-set flag before the
  first await, and close_slot's pre-pop hook re-validates the turn state
  at the last instant before removal: a message landing during the peer
  round-trips starts a turn the original busy check never saw, and
  archiving would cancel it uncarried. The refusal is a retryable 409.
- Channel-origin and channel-linked sessions are refused: the channel
  keeps addressing the conversation after the archive (the nudge fire
  path adopts closed transcripts), so migrating one forks it between the
  crew and a reanimated local copy.
- Assistant rows in the digest pass both standard redactors before the
  digest leaves the machine for the peer — the same sink discipline as
  every other non-user egress. The user's own words travel verbatim.
- The destination binding is durably persisted (metadata upsert — the
  empty mirror has no window for a save to merge into) BEFORE the source
  is archived, so a restart at any point leaves at least one addressable
  copy. An archive-failure rollback CONFIRMS the destination's closed
  write before popping it — a best-effort save after the pop would be
  swallowed on exactly the correlated fault that failed the archive —
  and keeps the slot live and dirty when confirmation fails, while the
  abandoned peer session is asked to close best-effort.
- The migrated-archive resume refusal runs immediately after the initial
  metadata read, BEFORE clear_closed durably drops the archive flag; a
  second copy of the gate runs on the post-await re-read.
- The mirror carries no execution settings (agent/workspace/model): the
  peer runs its own defaults, and it does not opt into the user-session
  pulse count — migration re-homes an existing conversation.
- The digest keeps its final row when that row alone exceeds the
  character budget, truncating content instead of dropping the tail.
@jeeshofone

Copy link
Copy Markdown
Contributor Author

1195b967b → 1eead9d8e. GPT F1 upheld: _destination_received_work counted messages, a running/queued turn and accepted context, but not an automation armed on the published destination — a rollback would pop the slot and leave its auto-nudge loop to rehydrate the closed transcript and run it unattended beside the source. The predicate now also asks the live autonudge registry (get_by_slot, the same lookup the close path resolves before retiring a loop) via _nudge_loop_armed_on; no service means no loops, a failed lookup fails toward keeping the slot. Since every rollback arm goes through the one predicate, the persist-failure, archive-failure and closed-save arms all keep the destination live (409 migrate_split) when a loop is armed. Test test_a_destination_with_an_armed_nudge_loop_survives_a_failed_persist — the previous head pops it (503). 586 across the migrate/resume families; all gates green; no .github/ diff.

@iamwhatever

Copy link
Copy Markdown
Contributor

There have already a feature "send a local session to remote"

@jeeshofone

Copy link
Copy Markdown
Contributor Author

Agreed that the carry itself already ships — this PR reuses it rather than adding a second one (build_transfer_bundle_async → send_session_bundle → the peer's /api/chat/slots/import is the only transcript path here). What "send session" leaves the user with is a copy on the peer that they continue from the peer's dashboard, with the local tab still live and writable. What this PR adds on top is the move: bind the local tab to that imported peer slot as a remote-crew mirror (the adopt_remote_slot seam), retire the source with a durable migrated stamp so a resume or a channel bind cannot re-open a second writable copy, and make the three steps one atomic action with rollback.

Fair pushback though: that is a lot of surface for what is, at its core, send + adopt + close. Two ways I can take this, your call:

  1. Shrink it. Drop the tombstone/resume-refusal machinery and the channel-bind gate, and reduce the PR to a single POST /api/chat/slots/{slot}/migrate that chains the two shipped seams and closes the source — roughly a tenth of the current diff.
  2. Close it and treat Allow transferring a complete session between KiroCrew instances #7652 as covered by send session plus the existing adopt flow; I would leave a note on the issue saying so.

If I do not hear back I will take option 2 rather than keep a 3.4k-line PR open against a feature you consider shipped.

@iamwhatever

Copy link
Copy Markdown
Contributor

Thanks for the thorough work here.

We already ship “Send a copy to,” which transfers the full session bundle to a connected remote instance. Users can continue there without re-explaining the conversation.

This PR reuses that transfer path. Its main addition is exclusive move semantics: archive the local source and prevent further local use.

We do not currently need that added lifecycle complexity. The endpoint also has no frontend consumer.

Closing this as overlapping with the existing feature. We can revisit if a clear need emerges for “Move” semantics distinct from copying.

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

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants