Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge main fixes into release/3.3
AkitaOnRails66721cd004bc
diff --cc CHANGELOG.mdindex 1de0fc27,62e4cd18..a5d7e615--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -11,212 -11,163 +11,367 @@@ version in [`docs/changelog/`](docs/cha## [Unreleased]+### Added++- Added `ai-memory run --no-exit-prompt`, `[run] exit_prompt = false`, and+ `AI_MEMORY_RUN_EXIT_PROMPT=false` to skip the switch/rerun menu after a+ successful interactive session. The menu remains enabled by default (#1776).++- `ai-memory merge-project --workspace <w> --from <source> --into <target>`+ losslessly joins two project identities inside one workspace. Its default is+ an exact dry run; `--confirm` re-stamps page history, sessions, observations,+ handoffs, embeddings and managed workstreams in one writer transaction, then+ removes the source project. Same-path pages get a new target version that+ appends the source body behind an `ai-memory:merged-from` marker while both+ prior histories remain restorable. The target frontmatter wins, a one-sided+ expiry is removed, and the combined page is flagged stale for consolidation.+ `restore-page --page-id <uuid>` restores either retained history even after+ the source identity is removed. Open sessions and live managed runs refuse+ the merge (#1645).+- `audit-contamination` now reports projects in one workspace whose names+ collide after Unicode compatibility decomposition, case folding, and+ removal of non-spacing marks. Findings distinguish case from accent+ differences and include page/session counts plus last activity (#1645).++- Cross-project messages can carry an optional epistemic `nature` (`unknown`,+ `measured`, `reported`, or `inferred`) and bounded supporting `evidence`.+ The server refuses a `measured` send without non-empty evidence; existing+ messages and callers remain `unknown` by default (#1428).++- Added `memory_patch_page` for atomic, heading-anchored edits to an existing+ Markdown page without re-emitting its body or metadata. It requires the+ page's current `page_id`; section replacement additionally requires the+ bounded SHA-256 token returned by `memory_read_page`. Missing, duplicate or+ fenced-code headings, stale tokens, conflicting edits, failed admission and+ concurrent writes leave the page unchanged. The typed TypeScript client+ exposes the same contract as `pages.patch` (#1697).++- Added an offline `ai-memory-eval abstention` benchmark with versioned+ clean-room answerable, hard-negative, conflicting, partial and+ missing-channel fixtures; raw lexical/score/density/belief signals;+ FSR/FAR/coverage threshold sweeps with undefined denominators preserved;+ optional reuse of pinned LongMemEval `*_abs` cases; and optional structured+ LLM answerability through the existing QA provider path. Conflicting and+ partial cases remain separate from binary ground truth, no threshold is+ presented as calibrated, and production runtime behavior is unchanged.+ The retrieval evaluator now also parses production's structured+ `{text,citations}` answer shape instead of a stale string (#1717).++- Added `[briefing] inject_on_subagent_start` to `.ai-memory.toml`. A project+ that sets it hands each `claude-code` subagent the project brief when the+ subagent starts: the same pinned, `_rules/` and `_slots/` brief that+ `inject_on_session_start` adds at session start, kept within `max_chars` and+ within the 10,000-character limit of that agent's hook context. The hook+ reads it from a new read-only `GET /brief`, which resolves and authorizes the+ project as `/handoff` does but never reads or claims a handoff, so a subagent+ cannot take its parent session's baton. A server without the route answers+ 404 and the subagent starts as before. The native hook and the+ `hooks/claude-code` shell and PowerShell scripts deliver it, and every marker+ parser treats the key as a settings boundary. It is off by default (#1715).++- Added an optional `[query_answer] max_context_tokens` admission budget for+ answer synthesis. It preserves retrieval hits, reports omitted or clipped+ evidence, prioritizes known newer corrections, prefers whole snippets and+ clips only complete trailing sentences or statements into leftover space. It+ skips the model when no meaningful evidence fits. The default+ remains disabled (#1684).++- `GET /admin/status` and `ai-memory status --json` now carry a+ `consolidation` block: the queue counts plus up to 20 `failed_sessions`+ (`session_id`, `attempts`, `failed_at_us`, scrubbed `last_error`), newest+ first. A consolidation run that gives up after its retries now has a+ machine-readable record with the session ids needed to re-run it, instead of+ only a journal line and the `/health` panel's count — which also resets with+ the process. The web health panel's own view stays counts-only, and an older+ server's status shape is unchanged (#1692).++- Added the bundled `coding-v1` retrieval-evaluation corpus for offline checks+ of decision rationale, resolved-error causes, correction evidence, and late+ session details. It reuses the existing scorer and A/B reports; it measures+ evidence retrieval, not semantic answer correctness or handoff behavior (#1686).++- `[auto_improve.eval] builtin = "structure"` runs the eval gate's structural+ checks in process, so the gate needs no interpreter, no scorer script inside+ the container and no timeout to hit. It checks an H1, an upper-case+ `TODO`/`TBD` placeholder (a hard failure), a `##` section and a list of steps+ for `procedures/`, and text beyond the heading within 2,400 characters for+ `_rules/` — never a section name or a wording, so the wiki's language does+ not matter. `eval_results` records `checker_name = "builtin:structure"`.+ `builtin` and `command` are mutually exclusive; `command` is unchanged for+ project-specific scorers (#1638).++- `ai-memory llm-test --server` probes the server's own configured provider+ instead of building one from the caller's environment, through a new+ root-only `POST /admin/llm-test`. The retry hint that `status` and the health+ panel print now names it: with the server in a container or on another host+ its keys exist only there, so the old client-side hint failed with "no API+ key" or a provider `400` while the server was healthy. The probe runs one+ fixed short prompt, reports provider, model, latency and the error class, and+ scrubs the provider's message before printing it (#1639).++- Added `[handoff] deliver_on_session_start = false` to `.ai-memory.toml`. A+ project that sets it no longer gets its handoff, or the continuity notice, at+ session start; the handoff is still created when the session ends and stays+ open for `memory_handoff_accept`. The native hook, the shell and PowerShell+ scripts and the generated TypeScript integrations send `handoff=0` only when+ the value is explicitly falsy (#1621).++- Added first-party Qoder CLI/IDE lifecycle and MCP support. Both installers+ merge into `~/.qoder/settings.json`: `install-mcp --client qoder` writes a+ sessionless stdio bridge, while `install-hooks --agent qoder` registers the+ eight documented memory-bearing events as native commands. Session start+ delivers a pending handoff through `hookSpecificOutput.additionalContext`,+ prompt/tool capture uses Qoder's Claude-shaped payloads, and a missing hook+ `cwd` falls back only to `QODER_PROJECT_DIR`. Setup detects `~/.qoder`,+ uninstall removes both entries, and agent backups include its settings and+ shared AGENTS-compatible skills/instructions (#1611).++- Profile writes now return `digest_warning` when the selected summary,+ abstract, or prose statement exceeds the 240-byte session-start digest+ limit. The write still succeeds, but its author can shorten the summary+ instead of discovering the truncation only in a later session (#1609).++- Added project routing for the named profiles of a multiplexing Hermes+ gateway. The gateway exports only the default profile's `terminal.cwd`, so+ every other profile's events used to fall back to the gateway's own working+ directory and all its bots landed in one project. A gateway event of a named+ profile now routes by an `.ai-memory.toml` placed in that profile's Hermes+ home (`~/.hermes/profiles/<name>`, or under the gateway's `HERMES_HOME`), and+ that marker's capture exclusions and server profile apply. A profile without+ such a marker keeps the old behavior. The profile name is checked against+ Hermes' profile-id pattern before it is used as a path (#1597).++- Added Hermes Agent hook consent to `ai-memory doctor`. Hermes runs a shell+ hook only when that exact command is approved in the home's+ `shell-hooks-allowlist.json`, and each profile under+ `~/.hermes/profiles/<name>` keeps its own allowlist. A profile with the+ ai-memory hooks in `config.yaml` but no approvals captured nothing, and its+ gateway only logged `not allowlisted — skipped` for each event. `doctor` now+ reads the root home and every profile, reports which ai-memory hook events+ each one wires, and warns about every profile whose events are not+ allowlisted (unless `hooks_auto_accept` is on), with the `hermes -p <name>+ --accept-hooks` command that approves them. The JSON output gains a `hermes`+ array. It never writes either file and never prints the hook commands,+ which can embed a bearer token (#1598).++- Added `AI_MEMORY_RERANK_TIMEOUT_SECS` (`rerank_timeout_secs` in+ `config.toml`) to set the `memory_query` reranker budget, which was fixed at+ 20 seconds. The default stays 20 and zero is rejected at startup. A hosted+ provider behind an LLM fallback chain can spend the whole fixed budget on one+ slow 503 before the next candidate answers, and every such query then keeps+ its pre-rerank order. ([#1614](https://github.com/akitaonrails/ai-memory/issues/1614))++- `ai-memory status` now shows the client's version next to the server's: a+ `ai-memory X (client)` line under `ai-memory X (server)`, and `version` in+ the JSON `client` object. In a split install (native client and hooks, the+ server in a container or on another host) the two drift apart when only one+ side is upgraded, and nothing showed it. When they differ in major version,+ the text report adds a warning to upgrade the older side (#1644).++### Changed++- `memory_lint` now reports embedding-band pairs as+ `similarity_candidate` instead of `contradiction`, and no longer infers that+ a newer page supersedes an older one from timestamps alone. Explicit+ `contradicts` edges remain `contradiction` findings (#1685).++- `move-project` now refuses the **copy+purge merge** — the path taken when the+ destination workspace already holds a project of the same name — unless+ `--allow-lossy-merge` is passed as well as `--confirm`. That path keeps only+ the source's latest pages and deletes the project with its sessions,+ observations, handoffs and older page versions, which `--confirm` written for+ "move this project" did not say; the refusal answers `409` with the counts it+ would discard. A true-move (fresh destination, everything preserved) is+ unchanged, and `merge-workspace`, whose command already says merge, keeps+ working without the extra flag (#1713).++- `memory_install_self_routing(compact: true)` and `ai-memory+ install-instructions --compact` now return a block that is actually compact:+ 2.1 KB instead of 5.9 KB, close to the 7.9 KB full block it was supposed to+ replace. It keeps the rules a session needs without reading anything else+ (scope selection for session-aware and static clients, managed-run resume,+ capture, the untrusted-memory trust rule, and where rules belong) and points+ at the installed `ai-memory-*` Agent Skills for the rest, which it already+ required to be installed (#1672).++- When the native session linked to a workstream is missing from its store,+ an interactive `ai-memory run <harness>` now also names the newest session+ this checkout still holds for that harness and the native selector that+ resumes it, such as `resume <id>` for Codex. The launch still starts fresh+ as before; running the same command again with that selector right after+ the harness name links that session instead (#1654).++- Managed-workstream startup packets now render completed tool calls and+ results as compact provenance stubs instead of spending the 30,000-character+ resume budget on raw command output or generated file content. Conversation,+ checkpoints, compactions, and annotations remain inline; the complete+ sanitized tool evidence stays searchable in the ledger (#1607).++- The LLM fallback chain now logs its own events. A transient candidate+ failure logs a warning with that candidate's provider, model, chain+ position, error class, HTTP status and cooldown, and an info line records+ each change of the answering candidate. Before, the chain logged nothing,+ and callers such as the reranker named only the first candidate, so a log+ could blame the primary for a timeout another candidate caused. Response+ bodies are never logged (#1628).++ ### Changed++ - Documented the settings that `config.default.toml` had left out, and added+ `docs/config-properties.md`, a reference table of every key `config.toml`+ accepts with its default, environment variable and purpose. The template now+ describes the `llm_*` keys (including `llm_compat_strict` and+ `[[llm_fallbacks]]`), the embedding endpoint and prefix keys,+ `tcp_keepalive_secs`, `base_path`, `release_base_url`, `cors_allow_origins`,+ `consolidate_on_session_end`, `backfill_on_start`, `run_autowire`,+ `claude_true_yolo`, the `contradiction_band_*` keys, and the `[run]`,+ `[hook_spool]`, `[handoff]`, `[maintenance]`, `[dream]`, `[retrieval]`,+ `[search.fts]`, `[profile]` and `[[admission_webhooks]]` sections. It also+ lists the remaining keys of `[decay]` (including `[decay.half_life_days]`),+ `[consolidation]`, `[auto_improve]`, `[auto_scope]` and `[auth]`, and the+ `[auto_improve.scheduler.experience_entropy_filter]` table. The new entries+ are all commented examples, and keys with a built-in default show that+ default. `AGENTS.md` now requires a new config key to land in both files.+### Fixed+ - Updated `libz-sys` to 1.1.31 so its build probe no longer records the build+ environment, including possible secrets, in Cargo target artifacts+ (RUSTSEC-2026-0418).+ - Imported every Claude transcript left behind by `/clear`, oldest first,+ before finalizing the managed run on the newest session. Pre-clear turns now+ retain their native-session provenance instead of disappearing from the+ workstream ledger (#1797).+ - Kept purge-session tombstones out of automatic hollow-project cleanup, so+ an old otherwise-empty project cannot lose replay protection immediately+ after its session is purged (GHSA-pphw-hm98-3wh4).+ - Made Crush transcript cursors revision-aware within their one-second native+ timestamp bucket. Same-second inserts and edits are now imported exactly+ once, while captured recovery endpoints still exclude later revisions+ (#1813).+ - Made TypeScript SDK capability initialization client-owned with independently+ cancellable waits, so one caller cannot abort another caller's shared probe+ and a later caller observes its own cancellation promptly (#1815).+ - Initialized MCP sessions in the document and agentmemory importer routes,+ retaining validated session IDs and sending `notifications/initialized`, so+ conditional imports work with both stateless and `--http-stateful` servers+ (#1836).+ - Explicit `ai-memory run --fresh claude` launches now expose the previously+ linked Claude session through `AI_MEMORY_PREVIOUS_SESSION_HISTORY`, including+ when the two sessions live under different Claude config homes (#1789).+ - Replaced the misleading hook-refresh-only warning after a linked Codex run+ fails to acknowledge context with a `/new`-specific ownership warning. The+ wrapper does not adopt the unlinked thread because Codex supplies no trusted+ parent relationship (#1788).++ - Sorted recent page lists by timestamp rather than RFC3339 text, so updates+ with different fractional-second precision appear in chronological order+ in the legacy recent API, project activity, folder previews and namespace+ listings. Kept title-sort and equal-timestamp path tie-breaks (#1247).++ - Fixed `restore` replacing live data when a backup without `config.toml`+ contains API keys that the configured pepper cannot verify. It now refuses+ before the swap, preserving the live wiki, database and config, and names+ the original configuration as the remedy (#1495).++ - Preserved explicit DOCX/PPTX line breaks and DOCX tabs in document imports+ when XML uses paired tags, including formatted PowerPoint breaks in slides+ and speaker notes. DOCX carriage returns now also keep adjacent text runs+ on separate lines instead of joining their words. Paragraph tab-stop+ definitions no longer insert spurious tabs into the extracted text (#1786).++ - Kept a wiki-sync server page when its repository file was recreated after+ the sync planned a deletion. `sync --propagate-deletes --apply` now rechecks+ local absence before sending the delete, preserves the page's baseline and+ reports the changed file for the next sync, including with `--prefer repo`+ (#1787).+ - Transcript imports (`backfill`, the `run` ledger, `recover`) now drop Codex+ memory-writing agent runs by the same signals the live hook uses: the+ checkout cwd, an event's recorded cwd, or a Codex user prompt that opens+ with `## Memory Writing Agent`. A custom `CODEX_HOME` whose last path+ component is not `.codex` previously reimported those sessions (#1790).+ - Admission webhook HTTP requests now follow redirects only within the+ configured `scheme://host:port` origin (up to 10 hops) and fail on+ cross-origin redirects without forwarding page payloads or applying foreign+ response mutations, surfacing the redirect refusal cause in logs and+ `reject`-policy errors (#1794).+ - `ai-memory project access` and `ai-memory project grants` now refuse empty+ or whitespace-only `--workspace`, `--project`, and (for access) `--mode`+ values before sending any request to the server. These commands take+ required names and never call `resolve_scope`, so the #1774 choke point+ did not cover them (#1791).+ - `ai-memory user grant` and `ai-memory user revoke` now refuse empty or+ whitespace-only `--user`, `--workspace`, `--project`, and (for grant)+ `--level` values before sending any request to the server. These commands+ take required names and never call `resolve_scope`, so the #1774 choke+ point did not cover them (#1792).+ - Stopped the lifecycle relay from treating an oversized HTTP response as a+ transport failure and immediately resending its batch. A response beyond the+ 64 KiB acknowledgement cap now retains its HTTP status, stops the flush, and+ keeps unacknowledged events pending, including on HTTP 429 backpressure (#1799).+ - Decoded WebVTT cue character references before document-import sanitization,+ preserving literal escaped tags and applying the existing text-size limit+ to the decoded text. SRT extraction is unchanged (#1800).+ - Preserved native OIDC hook-spool entries when the POSIX or PowerShell script+ bundle drained the shared queue. Scripts now leave those entries for native+ credential resolution instead of posting them anonymously and retiring them+ on a 2xx or 401 response; static, anonymous and legacy entries still drain+ normally (#1801).+ - Refused backup restores with a missing or invalid gzip trailer before+ replacing live data, even when all tar entries were readable (#1805).+ - Kept separate pre-migration archives when installations share a backup+ destination and start in the same second, instead of overwriting an+ existing installation's snapshot (#1806).+ - Restored the previous wiki file when `restore-page` could not commit its+ SQLite update, including a rejected case-colliding historical path. Restores+ now share the page writer's lock through conformance, file replacement and+ indexing so a concurrent write to that same path cannot leave disk and+ SQLite disagreeing (#1807).+ - Kept concurrent page edits current during opt-in cold-cluster dedup and dream+ merges. Each write batch now skips if a selected source version changed,+ preserving the newer body, tier and pin along with unchanged peers (#1808).+ - Dropping the final store writer handle now finishes when its command queue+ is full. Accepted writes still drain before the writer thread exits, including+ when callers have cancelled their waits (#1809).++ - Scheduled empty-project cleanup now preserves projects that have sent or+ received agent messages, including claimed/cancelled history, so it cannot+ silently delete their inbox/outbox through a project cascade (#1810).++ - Fixed `server add` rejecting valid inline tables in `servers.toml`, including+ token rotations and URL changes. Updates now accept the same table forms as+ reads and removal, preserving registered roots and other profiles (#1812).+ - Kept OpenCode V1 failed tool results in the managed workstream ledger,+ including their visible error text and error status, instead of importing+ only the call and silently dropping the failure reason (#1814).+ - Initialized the TypeScript SDK's MCP session before the first `callTool`,+ fixing HTTP 422 responses with `--http-stateful`. Raw calls still skip+ schema checks, and later wrapped calls reuse the session (#1816).+ - Preserved literal reasoning tags and their contents inside structured JSON+ strings when parsing OpenAI-compatible tolerant replies and Anthropic text+ replies. Reasoning blocks outside the JSON are still removed, including+ when a strict OpenAI-compatible request falls back to tolerant parsing (#1817).+ - Disabled HTTP redirect following on the native hook client (`build_client`)+ so 3xx responses from SSO gateways, captive portals, or proxies fail closed+ instead of following to a 200 OK login page, which dropped spooled hook events+ and injected login HTML into agent handoff context (#1818).+ - Supported singular units (`day`, `week`, `month`) and weeks in+ `parse_since_to_epoch` for git commit filtering during consolidation+ bootstrapping, trimmed surrounding whitespace, rejected negative intervals,+ and used checked arithmetic to prevent integer overflow panics (#1820).+ - Kept OpenCode 2 failed tool results in the managed workstream ledger,+ including their visible error text and error status, instead of importing+ only the call and recording a status-error loss (#1823).+ - Imported OpenCode 2 compaction session messages into the managed workstream+ ledger (`summary`, or `error.message` on a failed compaction) instead of+ dropping them with no event and no loss (#1824).+ - `memory_query(global=false)` now overrides a project's+ `[recall] default_global` marker and uses the resolved project's normal+ search. Previously the explicit opt-out still returned cross-project+ `global_hits` and disabled project-only query options (#1835).+ - Honored `base_path` from `config.toml` when mounting the HTTP server, so+ thin clients and the web UI use the same prefix. Explicit flag and environment+ overrides, including an empty value to serve at the root, kept their precedence (#1837).- Refused empty and whitespace-only `--workspace` and `--project` flags at theshared CLI scope-resolution choke point (`resolve_scope`,`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, anddiff --cc companions/ai-memory-ts/CHANGELOG.mdindex 89c2d3ea,3d27abe6..ceb5d753--- a/companions/ai-memory-ts/CHANGELOG.md+++ b/companions/ai-memory-ts/CHANGELOG.md@@@ -8,10 -8,18 +8,20 @@@ and this project adheres to [Semantic V## [Unreleased]+ ### Fixed++ - Capability initialization is owned by the client rather than its first+ caller. Concurrent callers now wait with independent abort signals and+ deadlines; cancelling one does not fail or delay the others. (#1815)++ - Initialized the MCP session before the first `callTool`, so raw tool calls+ work with `--http-stateful` without a preceding wrapped call. Raw calls+ still skip `tools/list` and schema checks. (#1816)+### Added+- Decoded optional query-answer context admission receipts as `answerContext` (#1684).+- `query` takes the server's `memory_query` page filters: `kind`, `tier`,`pathPrefix` and `tag`, in every search mode.diff --cc crates/ai-memory-cli/src/commands/run.rsindex 1829771d,6e932c6a..ac96d3aa--- a/crates/ai-memory-cli/src/commands/run.rs+++ b/crates/ai-memory-cli/src/commands/run.rs@@@ -16,9 -16,9 +16,9 @@@ use ai_memory_workstream::AmbiguousNativeSession, ClaudeContinuation, ExportedTranscript, FORWARDED_ENV_NAMES,JailChecklistItem, JailHostFacts, JailSupport, JailToggleChoice, JailToggleKind, LaunchMode,LaunchPlan, LaunchRoots, ManagedHarness, NativeSessionCandidate, ai_jail_support,- allows_native_session_adoption, apply_claude_true_yolo, apply_yolo, build_ai_jail_invocation,- build_launch_plan, build_launch_plan_with_env_lookup, claude_continued_session,+ allows_native_session_adoption, apply_claude_true_yolo, apply_jail_process_isolation,+ apply_yolo, build_ai_jail_invocation, build_launch_plan, build_launch_plan_with_env_lookup,- claude_continued_session, claude_live_background_attach_id, claude_session_ran_in_background,+ claude_continued_sessions, claude_live_background_attach_id, claude_session_ran_in_background,clean_path, crush_global_config_path, discover_native_session, export_transcript,has_native_session_selector, inside_ai_jail_here, inspect_repository,is_interactive_session_invocation, jail_checklist, jail_toggle, kiro_explicit_session_id,diff --cc crates/ai-memory-wiki/src/wiki.rsindex 1c880cec,8c0682d6..44e7719f--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@@ -1273,94 -974,36 +1273,98 @@@ impl Wikipath.as_str())))})?;- let mut md = parse(&raw)?;+ let md = parse(&raw)?;+ self.restore_page_markdown(workspace_id, project_id, path, md, true)+ .await+ }++ /// Restore one retained SQLite page version as the new latest version.+ /// This complements checkpoint restore for histories that moved from+ /// another project path during `merge-project`.+ pub async fn restore_page_from_version(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: PagePath,+ version_id: PageId,+ ) -> WikiResult<PageId> {+ let reader = self+ .store_reader+ .as_ref()+ .ok_or_else(|| ai_memory_wiki_error("page-version restore requires a store reader"))?;+ let version = reader+ .page_version_body(+ workspace_id,+ project_id,+ path.as_str().to_owned(),+ version_id,+ )+ .await?+ .ok_or_else(|| {+ WikiError::Store(ai_memory_store::StoreError::NotFound(+ "page version not found in the requested scope".into(),+ ))+ })?;+ let tier = version+ .tier+ .parse::<Tier>()+ .map_err(|error| ai_memory_wiki_error(&error.to_string()))?;+ let frontmatter = canonicalize_index_frontmatter(version.frontmatter, tier, version.pinned);+ self.restore_page_markdown(+ workspace_id,+ project_id,+ path,+ Markdown {+ frontmatter,+ body: version.body,+ },+ true,+ )+ .await+ }++ async fn restore_page_markdown(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: PagePath,+ mut md: Markdown,+ keep_own_generated_at: bool,+ ) -> WikiResult<PageId> {- // Conform like the three sibling write paths (`write_page_inner`,- // `apply_batch`, `approve_auto_improve_proposal`) do: the row this- // upserts is conformed at the store's write choke point either way,- // so writing the historical bytes verbatim left the file behind the- // row. Restoring the pre-OKF checkpoint every migrated install- // carries then failed `export-okf` for the whole project with "run- // the server once to migrate" — which the one-shot wiki migration- // never does again — and made each `serve` boot re-archive the data- // dir once the migration archive was deleted. Conformance is- // idempotent modulo `generated.at`. When the file on disk already- // holds the same content, its timestamp still wins, so the file keeps- // matching the row the store's idempotent upsert reuses. Otherwise- // the disk holds a newer version and would leave only `now()`; an- // already-conformant checkpoint keeps its own `generated.at` instead,- // so it restores byte-exact whatever the clock.- conform_frontmatter_for_disk_keeping(- &self.abs_path(workspace_id, project_id, &path),- path.as_str(),- &mut md,- keep_own_generated_at,- );- let raw = emit(&md)?;- let title = derive_title(&md.frontmatter, &md.body, &path);- let links = crate::markdown::extract_all_links(&md.frontmatter, &md.body, &path);- let meta = derive_index_metadata(&path, &md.frontmatter)?;- let body = md.body.clone();- let abstract_text = frontmatter_abstract(&md.frontmatter).map(str::to_owned);-- let id = {+ let (id, body, abstract_text) = {let _guard = self.mutation_lock.read().await;+ // Restore shares the writer/reindex lock, including the disk read+ // that chooses generated.at and any rollback after a refused upsert.+ let _page_guard = self.lock_page(workspace_id, project_id, &path).await;+ let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;+ // Conform like the three sibling write paths (`write_page_inner`,+ // `apply_batch`, `approve_auto_improve_proposal`) do: the row this+ // upserts is conformed at the store's write choke point either way,+ // so writing the historical bytes verbatim left the file behind the+ // row. Restoring the pre-OKF checkpoint every migrated install+ // carries then failed `export-okf` for the whole project with "run+ // the server once to migrate" — which the one-shot wiki migration+ // never does again — and made each `serve` boot re-archive the data+ // dir once the migration archive was deleted. Conformance is+ // idempotent modulo `generated.at`. When the file on disk already+ // holds the same content, its timestamp still wins, so the file keeps+ // matching the row the store's idempotent upsert reuses. Otherwise+ // the disk holds a newer version and would leave only `now()`; an+ // already-conformant checkpoint keeps its own `generated.at` instead,+ // so it restores byte-exact whatever the clock.- conform_frontmatter_for_disk_keeping(&abs, path.as_str(), &mut md, true);++ conform_frontmatter_for_disk_keeping(++ &abs,++ path.as_str(),++ &mut md,++ keep_own_generated_at,++ );+ let raw = emit(&md)?;+ let title = derive_title(&md.frontmatter, &md.body, &path);+ let links = crate::markdown::extract_all_links(&md.frontmatter, &md.body, &path);+ let meta = derive_index_metadata(&path, &md.frontmatter)?;+ let body = md.body.clone();+ let abstract_text = frontmatter_abstract(&md.frontmatter).map(str::to_owned);+self.ensure_project_workspace(workspace_id, project_id).await?;let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Parents)?;diff --cc docs/lifecycle-ops.mdindex f9c7677b,7aae2938..262eafdd--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@@ -1070,11 -1028,11 +1070,12 @@@ What happens2. Server validates the page path.3. Server checkpoints the current wiki tree first (`pre-restore-page ...`) whenthere are uncommitted changes.-4. Server reads the exact markdown blob for that project/page from git at- `--from`, parses it, writes it back to the live wiki tree, and upserts a new- latest page row in SQLite so search, links, and `/web` agree with disk.- It shares the same-path lock with writes and watcher reindexing, including- the read of current frontmatter used to preserve `generated.at`.+4. Server reads either the exact markdown blob for that project/page from git+ at `--from`, or the retained SQLite version identified by `--page-id` after- verifying that it now belongs to the requested project and path. It writes- that content to the live wiki tree and upserts a new latest page row so- search, links, and `/web` agree with disk.++ verifying that it now belongs to the requested project and path. It shares++ the same-path lock with writes and watcher reindexing, including the read of++ current frontmatter used to preserve `generated.at`, then writes the content++ and upserts a new latest page row so search, links, and `/web` agree with disk.5. Server writes a post-restore checkpoint (`restore-page ...`) when the livetree changed.@@@ -1084,10 -1042,12 +1085,14 @@@ Failure modes- **Invalid page path** → 422, no mutation.- **Checkpoint or file not found** → 500 with the git/libgit2 error; anypre-restore checkpoint remains as an audit breadcrumb.+- **Page-version UUID is malformed** → 400 before a checkpoint or mutation.+- **Page version is absent or belongs to another project/path** → 404.- **Historical markdown is malformed or non-UTF-8** → 500, live file is notreplaced.+ - **SQLite rejects the restored version** (for example, the historical path+ collides with a current page under case folding) → 500, the previous file is+ restored or a newly created file is removed. If that rollback also fails,+ the error explicitly reports an inconsistent state requiring repair.What it does not recover:diff --cc docs/managed-workstreams.mdindex 590a4ed2,f6a0b1b5..a6d2f06a--- a/docs/managed-workstreams.md+++ b/docs/managed-workstreams.md@@@ -500,17 -464,18 +500,27 @@@ it. The compressed copy counts as the land the transcript import reads it like the plain file. Use`ai-memory run --fresh <harness>` to deliberately skip the linkedsession and the adoption chooser. `--fresh` cannot be combined with a native- resume, continue, session, or fork selector.+ resume, continue, session, or fork selector. A fresh interactive launch still+ exports the linked session as `AI_MEMORY_PREVIOUS_SESSION_HISTORY` when it is+ available locally. This matters when Claude's new session uses a different+ configuration home: the harness can read the bounded, checkout-validated old+ session without ai-memory copying it into the server.++ Codex's in-session `/new` command does not expose a trustworthy parent-thread+ relationship. ai-memory therefore never guesses that the new thread owns the+ managed workstream. If the linked thread exits without acknowledging its+ context after `/new`, the wrapper explains that the intended thread must be+ selected explicitly on the next managed run.+When the linked session is missing and the checkout still holds another+session of that harness, an interactive launch that names its harness still+starts fresh but also names the newest one and the native selector that+resumes it, such as `resume <id>` for Codex. Running the same command again+with that selector right after the harness name is an explicit selector, so+that session is linked instead. The launcher never picks it on its own, and+it cannot tell whether that session is open in another terminal or linked to+another workstream; adoption stays a bootstrap operation.+## What happens on each run1. The host client resolves the normal workspace/project scope and a stablediff --cc docs/marker-file.mdindex b8134b86,841a836e..5b66b0fb--- a/docs/marker-file.md+++ b/docs/marker-file.md@@@ -312,17 -293,11 +312,19 @@@ values are ignored and behave like thefalsy (`false` / `0` / `no` / `off`, quoted or bare). A marker that sets only`[profile]` keys is a settings boundary, like one with `[briefing]` keys.+`[handoff] deliver_on_session_start` is on unless the value is explicitly falsy+(`false` / `0` / `no` / `off`, quoted or bare). Clients send `handoff=0` on the+session-start fetch only when the marker turns it off, so the server reads+nothing, claims nothing and adds no handoff or continuity notice for that+project. A marker that sets only `[handoff]` is a settings boundary, like one+with `[briefing]` or `[profile]` keys. Use it for projects whose automatic+handoffs are mostly noise, such as a bot fleet driven by routines and webhooks.+`[recall] default_global` applies to an agent's unscoped `memory_query` and- `memory_recent` calls. A `memory_query` with `as_of` is not broadened: it- reads the current project as it stood at that instant, and an explicit+ `memory_recent` calls. On `memory_query`, an explicit `global: false` keeps+ the resolved project, even when the marker enables global recall. Explicit+ `workspace` + `project` or `scopes` also override the marker. A query with+ `as_of` reads the current project as it stood at that instant, and an explicit`global=true` with `as_of` is refused. The `ai-memory search` and`ai-memory recent` terminal commands do not read it: those commands stayscoped to the current project and cover every project only when you pass