Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
docs(security): record the OpenCode 1.x subagent baton boundary
João Matheus7c983e9237bb
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex d1aed332..2721a9be 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -66,6 +66,7 @@ the legitimate restricted-project control and the failed-query cases.| 4k | The idle-session auto-end (`[sessions] idle_end_after_hours`) never ends a session it does not own: idle-threshold + active-run exclusion at selection, guarded CAS stamp, conditional page write, owner attribution | `ai-memory-store/src/reader.rs` `idle_open_sessions` — ONE statement: the idle-threshold predicate (`ended_at IS NULL` + `COALESCE(MAX(observations.created_at), started_at) < cutoff`), `ORDER BY last_activity ASC` capped at the batch, and a correlated `pages` subquery bound to the session's own `workspace_id`/`project_id` and to the path rendered in SQL from the id blob (`lower(hex(id))` with 8-4-4-4-12 hyphens — byte-for-byte the Rust `format!("sessions/{session_id}.md")`, proven by the selection test with a page present and absent) capturing the latest `sessions/<id>.md` version as the tick's write precondition — a read path, never a write; `active_managed_run_native_session_ids` (only `state = 'active'` managed runs). `ai-memory-store/src/ops.rs` `idle_end_sessions` — per-candidate `UPDATE sessions … WHERE id AND workspace_id AND project_id AND ended_at IS NULL` that also re-verifies the session's observation count (EVERY row of the session — the digest's population, no per-row scope filter) and the latest page version; `ended_at` = the tick's clock (last activity kept in the audit detail), `ended_observation_count` counted at the stamp, one `idle_session_end` audit row in the same transaction, and the consolidation gate: the job is enqueued INSIDE the stamp's transaction (`session_consolidation::enqueue_in_tx`), so a failed enqueue rolls back the stamp, the audit row and the job, while the page the tick already wrote stays as an ordinary version; a lost stamp skips the enqueue and never aborts the batch. The lifecycle-only gate applies the same scope/open guard before any mutation, re-checks substantiveness atomically, reuses `end_lifecycle_only_session_in_tx` (releasing the accepted handoff), and writes its OWN `idle_session_end` audit row distinct from the `release_lifecycle_only_handoff` row. `ai-memory-hooks/src/idle_end.rs` `run_idle_end_tick` — excludes active-run sessions in Rust via `SessionId::from_native` BEFORE the batch bound (the serve loop over-fetches, so an excluded backlog cannot starve the batch), classifies via `session_has_substantive_observation`, builds the page and its count from one digest snapshot (`SessionDigest::load_with_count` — the count the CAS guard re-verifies), writes the page with `Wiki::write_page_if` under `PagePrecondition::Latest(seen)`/`Absent` (`Mismatch` skips the whole session), keeps an agent-written page (`session_page_written_by_agent`), and attributes via `router.rs` `stored_session_identity` (the hook path's own fail-closed parse). The tick creates no additional handoff: the consolidation gate and the lifecycle-only release gate are its only handoff-affecting effects | `store` `tests/suite/idle_session_end.rs` — guard by guard: `idle_end_loses_to_an_already_ended_session` (the `ended_at IS NULL` predicate; fails with it removed), `idle_end_counts_the_same_observation_population_as_the_digest` (a multi-project session ends with `ended_observation_count` = 2; fails if the CAS count's population diverges from the digest/counter's), `idle_end_cas_rejects_a_stale_observation_count` (the count guard; fails with it removed), `idle_end_cas_rejects_a_moved_latest_page` (the page-version guard; fails with it removed), `idle_end_pre_stamp_non_end_observation_in_window_loses_the_cas` / `idle_end_pre_stamp_checkpoint_page_in_window_loses_the_cas` / `idle_end_pre_stamp_real_session_end_in_window_loses_the_cas` (the test-only seam runs on the writer connection BEFORE the candidate's stamp transaction and injects the SQL effects a concurrent writer would leave in the read-to-stamp window — simulated effects, not a run of the hook's `SessionEnd` handler; a `Lost` with the consolidation gate on creates no job; each fails with its guard removed), `idle_end_candidate_cannot_cross_the_project_boundary` (a foreign-scope candidate is refused; same-scope control ends), `idle_end_lifecycle_only_refuses_a_foreign_scope_candidate` (the lifecycle-only scope/open guard: `Lost`, no audit, the claimed handoff stays `Accepted`; fails with the guard removed), `idle_end_lifecycle_only_refuses_an_already_ended_session_with_control` (dedicated already-ended case: `Lost` with no audit and no handoff release, next to the open control in the same fixture that ends and releases), `idle_end_lifecycle_only_loses_to_a_substantive_race` (the atomic substantiveness re-check), `idle_end_reopens_the_handoff_a_lifecycle_only_session_claimed` (exactly one `idle_session_end` row, distinct from the release row), `idle_end_watermark_converges_a_late_real_session_end` (a late real `SessionEnd` converges through `AlreadyEnded`/`ReEnd`), `idle_end_batch_stamps_every_candidate_in_one_command`, `idle_selection_is_cutoff_scoped_ordered_and_bounded` (threshold, order, bound; `seen_page_id` captured with a page present and `None` without — the `session_page_path` rendering), `idle_end_stamps_watermark_audit_page_and_consolidation`, `idle_end_consolidation_enqueue_shares_the_callers_transaction` + `idle_end_consolidation_enqueue_failure_rolls_back_and_retries` (the in-transaction enqueue; fails out-of-transaction), `session_observation_count_refuses_foreign_and_missing_scopes` (foreign workspace / foreign project / missing id each count 0; the right tuple counts — the raw-id reader's scope join), `enqueue_in_tx_refuses_a_foreign_scope_and_leaves_the_foreign_queue` (a foreign tuple enqueues nothing and the foreign project's queue is unchanged; the right tuple enqueues — the job INSERT's scope binding). `hooks` `tests/suite/idle_end.rs` + `src/synth.rs` `load_with_count_scopes`: `foreign_and_missing_tuples_load_nothing_the_right_tuple_loads` (`SessionDigest::load_with_count` refuses a foreign tuple and a missing id as `SessionCollision`; the right tuple loads and counts — the tuple validation; fails with it removed), `idle_tick_skips_a_session_ended_by_a_real_session_end_between_selection_and_write` (a real `/hook` `SessionEnd` landing between selection and page write leaves the hook's page as the only version and no additional handoff from the tick; fails with the conditional write removed — the CAS itself is proven by the store tests above), `idle_tick_late_real_session_end_with_new_work_reends_with_handoff` (the late real end re-ends with exactly one handoff), `idle_tick_excludes_active_managed_run_sessions` (+control after `cancel_managed_run`), `idle_tick_excluded_backlog_cannot_starve_the_batch` (25 excluded sessions cannot consume the batch), `idle_tick_ends_idle_substantive_session_with_page_job_and_no_handoff` (owner attribution via `last_modified_by.username`; no additional handoff from the tick), `idle_tick_lifecycle_only_ends_without_page_or_job_and_creates_no_handoff`, `idle_tick_skips_active_sessions_and_respects_the_batch`, `idle_tick_keeps_a_session_page_written_by_the_agent`; `cli` `serve.rs` `idle_end_tick_does_not_start_when_disabled_or_maintenance_off` and `idle_end_tick_ends_an_idle_session_on_the_first_pass` (tick-clock `ended_at`, paused `tokio::time`), `config.rs` `sessions_idle_end_defaults_off_loads_from_toml_and_rejects_out_of_range` | STRONG || 4l | The cut-off-session pointer (session-start notice, `memory_briefing` `recent_sessions`, `memory_handoff_list` `newer_unended_session`) names only the caller's own or shared sessions, carries no captured text, and claims nothing; `memory_read_session_observations` without a `session_id` defaults through the same owner-filtered, scope-bound ordering | `ai-memory-store/src/reader.rs` `recent_session_activity` applies the same `OwnerFilter` clause on the session row as `sessions_for_scope` (`actor_user IS NULL OR = :actor`, or `IS NULL` for an unattributed caller) inside the resolved, authorized `(workspace, project)`; `ai-memory-hooks/src/router.rs` `render_continuity_notice` renders only the stored agent kind, the session UUID, an age and the scope's server-side names (the `render_handoff_notice`/`render_inbox_notice` bar) and is computed after `authorize_resolved`; the MCP fields reuse the tool's own resolved scope and owner filter | router `session_start_never_names_another_operators_cut_off_session` (adversarial: with registered users, bob's cut-off session is not named to alice; control: bob's next session is pointed at it; fails with the owner clause removed), `session_start_names_a_session_cut_off_without_ending` (the notice carries none of the session's prompt, command or output text); store `session_activity.rs` `the_owner_filter_hides_another_operators_sessions`; MCP `memory_read_session_observations_default_never_crosses_owner_or_project` (adversarial: bob's newer open session in alice's cwd and alice's newer session in another project are never alice's default; control: alice's own older session is, and bob's default is his own; fails with the owner filter set to `Any`); CLI `harness_switch_e2e.rs` (real server and hook binary; no captured text in the notice) | STRONG || 4o | An OMP subagent session never claims a handoff or leaves one behind | `ai-memory-hooks/src/router.rs` SessionEnd `child_session`: an OpenCode or OMP end whose body carries a subagent marker (`payload.rs` `body_is_subagent`) closes and summarizes the session without a baton. The generated OMP extension (`ai-memory-cli/src/commands/install_hooks.rs` `build_omp_extension`) records a subagent session from `ctx.agent.kind` on the session's own `session_start`, `before_agent_start` and `session_shutdown`, never on a tool event (an advisor's tool calls reach the session they advise as `kind: "sub"` under that session's id), skips `fetchHandoff` for it and posts its events with `agent_id`. Pi reports no `ctx.agent`, so every Pi session stays top-level | router `omp_subagent_session_end_closes_and_summarizes_without_baton` (a marked OMP end leaves no baton; control: a top-level OMP session in the same project still leaves one), beside `opencode_child_session_end_closes_and_summarizes_without_baton`, and `drop_subagent_captures_drops_an_omp_subagent_session` (an opted-in project drops the marked session through its end; control: the top-level session is stored); `install_hooks.rs` `omp_extension_marks_subagent_sessions_and_skips_their_handoff` and, running the generated OMP extension in Node, `slow_generated_handoff_runtime::omp_extension_keeps_subagent_sessions_off_the_baton` (a task subagent, a `/tan` clone and a revived subagent never request `/handoff` and carry `agent_id` on every event, their ends included; controls: the top-level session and a session without `ctx.agent` claim, and the advisor's tool calls leave the top-level session unmarked). Each fails with its guard removed | STRONG |+| 4p | An OpenCode 1.x subagent session never claims a handoff or leaves one behind | `ai-memory-cli/src/commands/install_hooks.rs` `build_opencode_plugin`: the generated V1 plugin records a child session's parent from its `session.created` and from the `session.updated` OpenCode publishes on every prompt before the model call (a child the task tool resumes by `task_id` in a later process), skips `fetchHandoff` in `experimental.chat.system.transform` for it, and `endSession` posts its end with `agent_id` on every close path, the `dispose` at exit included, so the router's SessionEnd `child_session` gate (row 4o) closes and summarizes it without a baton | `install_hooks.rs` `opencode_plugin_skips_the_handoff_for_a_subagent_session` (the parent comes from both session events, only from a string `parentID`, and the transform returns for a child before `fetchHandoff`) and `opencode_plugin_marks_a_subagent_session_end` (`dispose` ends sessions through `endSession`, which adds `agent_id` for a recorded child); running the generated plugin in Node, `slow_generated_handoff_runtime::opencode_plugin_keeps_task_subagents_off_the_baton` (a `task` subagent and one resumed by `task_id` never request `/handoff`, and their ends from `dispose` carry `agent_id`; controls: a top-level session and one continued from an earlier process claim and stay unmarked). Each fails with its guard removed | STRONG || 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` lets every session vote whatever its owner (the owner filter only withholds the observation excerpt and ids, never the vote or the page) | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation); `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (B still gets A's session page ranked by A's observation, with the page's own snippet) | STRONG || 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain; read side: `reader.rs` `page_versions` lists every row at the path, with no `is_latest` filter, for `/web/w/…/h/*path` and `/api/v1/…/history/*path`. It does apply TTL expiry (`reader.rs` `history_visible`): a version whose own `expires_at` passed is neither listed nor readable by id, a path whose live version expired shows no history at all (the forget sweep hard-deletes every row there), and a `supersedes` link to a hidden version reads as `null`. Expiry is the only thing that hides a superseded version; a concurrent write never does | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs`; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope`; `ai-memory-web` `history_replay.rs` `history_keeps_both_sides_of_a_concurrent_divergent_write` (two attributed writers on one base: all three versions and both authors listed, one `is_latest`, the two writers' versions diff by id) and `history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest`; bite: an `is_latest = 1` filter in `page_versions` fails both; `history_hides_expired_versions_and_expired_pages` (an expired superseded version and every version of a page whose live version expired answer 404 by path and by id on HTML and JSON, and the live successor's `supersedes` is `null`; control: a TTL in the future is listed and diffable; bites with the per-row predicate removed, with the live-version clause disabled, and with the `supersedes` hiding removed) | STRONG || 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` and `restore_page_from_checkpoint` use the same page mutex and `apply_batch` retains sorted, deduplicated locks; restore reads current frontmatter under the guard and rolls back its installed file if the store refuses the version; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `restore_page_lock_waits_before_conformance_and_allows_another_path` (a queued writer wins first, its timestamp is preserved, another path progresses; fails without the restore page guard or with conformance before it), `restore_page_collision_keeps_disk_and_store_unchanged` and `restore_page_store_failure_rolls_back_replacement_and_new_file` (rejected historical alias and injected upsert failures preserve disk and SQL, ordinary restore succeeds after removing the fault; fail without restore rollback). `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |